code
stringlengths
4
1.01M
language
stringclasses
2 values
<?php /** * This is the model class for table "message". * * The followings are the available columns in table 'message': * @property integer $msg_id * @property string $subject * @property string $msg_content * @property string $msg_uploads * @property integer $user_id * @property string $msg_time * @property string $msg_date * @property integer $is_read */ class Message extends CActiveRecord { /* PROPERTY FOR RECEIVING THE FILE FROM FORM*/ public $msg_uploads; public $to; public $attribute_id; /** * Returns the static model of the specified AR class. * @return Message the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'message'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('subject, msg_content, msg_time, msg_date,to', 'required'), array('user_id, is_read, sender_id, user_id, is_task, is_deleted', 'numerical', 'integerOnly'=>true), array('subject, msg_uploads', 'length', 'max'=>120), array('msg_content', 'length'), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('msg_id, subject, msg_content, msg_uploads, user_id, msg_time, msg_date, is_read', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'msg_id' => 'Msg', 'subject' => 'Subject', 'msg_content' => 'Msg Content', 'msg_uploads' => 'Msg Uploads', 'user_id' => 'User', 'msg_time' => 'Msg Time', 'msg_date' => 'Msg Date', 'is_read' => 'Is Read', 'is_task' => 'Is Task' ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('msg_id',$this->msg_id); $criteria->compare('subject',$this->subject,true); $criteria->compare('msg_content',$this->msg_content,true); $criteria->compare('msg_uploads',$this->msg_uploads,true); $criteria->compare('user_id',$this->user_id); $criteria->compare('msg_time',$this->msg_time,true); $criteria->compare('msg_date',$this->msg_date,true); $criteria->compare('is_read',$this->is_read); return new CActiveDataProvider(get_class($this), array( 'criteria'=>$criteria, )); } public function actionSearch($term) { if(Yii::app()->request->isAjaxRequest && !empty($term)) { $variants = array(); $criteria = new CDbCriteria; $criteria->select='tag'; $criteria->addSearchCondition('tag',$term.'%',false); $tags = tagsModel::model()->findAll($criteria); if(!empty($tags)) { foreach($tags as $tag) { $variants[] = $tag->attributes['tag']; } } echo CJSON::encode($variants); } else throw new CHttpException(400,'Invalid request. Please do not repeat this request again.'); } // functions public function setMsg() { $connection = Yii::app()->db; $sql="SELECT * FROM user"; $command = $connection->createCommand($sql); $results = $command->queryAll(); return $results; } public function setGroup() { $connection = Yii::app()->db; $sql="SELECT * FROM groups"; $command = $connection->createCommand($sql); $results = $command->queryAll(); return $results; } public function getMsg($id) { $i=0; $connection = Yii::app()->db; $sql="SELECT t1.message_id,t1.user_id FROM message_user AS t1 INNER JOIN message AS t2 ON t1.message_id = t2.msg_id WHERE t2.is_task IS NULL ORDER BY t2.msg_id DESC"; $command = $connection->createCommand($sql); $results = $command->queryAll(); $data=array(); foreach($results as $temp) { //print_r($temp['user_id']); $msg=$temp['message_id']; $value1 = explode(",",$temp['user_id']); //print_r($value1); foreach($value1 as $value2) { //print_r($value2); if($value2==$id) { //echo 'message'; //print_r($msg); $data[$i]=$msg; $i++; } } } return $data; } public function getTasks($id,$status) { $i=0; $connection = Yii::app()->db; $sql="SELECT t1.message_id,t1.user_id FROM message_user AS t1 INNER JOIN message AS t2 ON t1.message_id = t2.msg_id WHERE t2.is_task IS NOT NULL ORDER BY t2.msg_id DESC"; $command = $connection->createCommand($sql); $results = $command->queryAll(); $data=array(); foreach($results as $temp) { //print_r($temp['user_id']); $msg=$temp['message_id']; $task=TaskAssignToPatients::model()->findByAttributes(array('id'=>$msgids->is_task,'status'=>$status)); if($task != NULL ) { $value1 = explode(",",$temp['user_id']); //print_r($value1); foreach($value1 as $value2) { //print_r($value2); if($value2==$id) { $data[$i]=$msg; $i++; } } } else if($status=='T') {$value1 = explode(",",$temp['user_id']); //print_r($value1); foreach($value1 as $value2) { //print_r($value2); if($value2==$id) { $data[$i]=$msg; $i++; } } } } return $data; } public function getMsgcontent($msgid) { $connection = Yii::app()->db; $sql="SELECT * FROM message WHERE msg_id =".$msgid; $command = $connection->createCommand($sql); $users= $command->queryAll(); return $users; } public function getMsgvalue($msgid) { $connection = Yii::app()->db; $sql="SELECT t1.subject, t1.msg_id, t1.msg_date,t1.user_id,t1.sender_id FROM message AS t1,message_user AS t2 WHERE t1.msg_id=t2.message_id AND t1.user_id=113 AND t1.is_task IS NULL"; $command = $connection->createCommand($sql); $users= $command->queryAll(); return $users; } public function getTaskvalue($msgid) { $connection = Yii::app()->db; $sql="SELECT * FROM message WHERE msg_id =".$msgid." AND is_task!='NULL'"; $command = $connection->createCommand($sql); $users= $command->queryAll(); return $users; } // TO set Isread public function setRead($msgid) { $connection = Yii::app()->db; $sql="UPDATE message SET is_read = 1 WHERE msg_id =".$msgid; $command = $connection->createCommand($sql); $command->queryAll(); } public function getUnreadMessages() { /* $command = Yii::app()->dbadvert->createCommand() ->select ('*') ->from('message') ->where('is_read=0') ->limit(14,0) ->order('msg_date desc') ->queryAll(); return $command;*/ $connection = Yii::app()->db; $sql = 'SELECT * FROM `message` WHERE `is_read`=0 ORDER BY `message`.`msg_date` ASC LIMIT 0 , 30'; $command = $connection->createCommand($sql); $uread_messages = $command->queryAll(); //For getting total number of messages $sql = 'SELECT * FROM `message` WHERE `is_read`=0'; $command = $connection->createCommand($sql); $total = $command->queryAll(); $total = sizeof($total); return array ($uread_messages,$total); } public function getSysMessages() { /* $command = Yii::app()->dbadvert->createCommand() ->select ('*') ->from('message') ->where('is_read=0') ->limit(14,0) ->order('msg_date desc') ->queryAll(); return $command;*/ $connection = Yii::app()->sys_db; $sql = 'SELECT * FROM `messages` WHERE `is_read`=0 ORDER BY `messages`.`date` ASC LIMIT 0 , 30'; $command = $connection->createCommand($sql); $uread_messages = $command->queryAll(); //For getting total number of messages $sql = 'SELECT * FROM `messages` WHERE `is_read`=0'; $command = $connection->createCommand($sql); $total = $command->queryAll(); $total = sizeof($total); return array ($uread_messages,$total); } // For Message Forward public function messageForward() { $model=new Message; if(isset($_POST['Message'])) { $model->attributes=$_POST['Message']; if($model->save()) { $insert_id = Yii::app()->db->getLastInsertID(); $list = implode(",", $_POST['msg']); //DB Insertion $connection = Yii::app()->db; $command = $connection->createCommand(); $results = $command->insert('message_user',array('user_id'=>$list,'message_id'=>$insert_id)); } } } //To Delete user id from List of Message-User public function deleteMessage($uid,$mid) { $connection = Yii::app()->db; $sql="SELECT user_id FROM message_user WHERE message_id =".$mid; $command = $connection->createCommand($sql); $results = $command->queryAll(); foreach($results as $temp) { //print_r($temp['user_id'); //$msg=$temp['message_id']; $list=''; $value1 = explode(",",$temp['user_id']); foreach($value1 as $value2) { if($value2!=$uid) { $list .=$value2.','; }} $list1=trim($list,','); $connection = Yii::app()->db; $sql="UPDATE message_user SET user_id = '".$list1."' WHERE message_id =".$mid; $command = $connection->createCommand($sql); $command->execute(); } } // To get message Contents field by field public function getMsgcontentView($msgid,$variable) { $connection = Yii::app()->db; $sql="SELECT * FROM message WHERE msg_id =".$msgid; $command = $connection->createCommand($sql); $users= $command->queryAll(); foreach($users as $users1) return $users1[$variable]; } //To get Patient Name for Message public function getName($id) { $users = Yii::app()->dbadvert->createCommand() ->select('patient_lname') ->from('patients') ->where('patient_id='.$id) ->queryAll(); foreach($users as $users1) return $users1['patient_lname']; } //For Sent Message List public function getSentmessage() { $connection = Yii::app()->db; $sql="SELECT * FROM message_user ORDER BY id DESC"; $command = $connection->createCommand($sql); $results = $command->queryAll(); return $results; } public function getUserName($id) { $connection = Yii::app()->db; $sql="SELECT username FROM blog_user WHERE id=".$id; $command = $connection->createCommand($sql); $results = $command->queryAll(); foreach($results as $users1) return $users1['username']; } public function getPhoto($id) { $connection = Yii::app()->db; $sql="SELECT photo FROM user_details WHERE user_id =".$id; $command = $connection->createCommand($sql); $result=$command->queryAll(); if(count($result) == 0) return '<img src="users/user.jpg" width="48" height="51" />'; else return '<img src="users/'.$id.'/'.$result[0]['photo'].'.jpg" width="48" height="51" />'; } public function getPhototask($id) { $connection = Yii::app()->db; $sql="SELECT photo FROM user_details WHERE user_id =".$id; $command = $connection->createCommand($sql); $result=$command->queryAll(); if(count($result) == 0) return '<img src="users/user.jpg" width="48" height="51" />'; else return '<img src="users/'.$id.'/'.$result[0]['photo'].'.jpg" width="100" height="100" />'; } public function getUserPhototask($id) { $connection = Yii::app()->db; $sql="SELECT photo FROM user_details WHERE user_id =".$id; $command = $connection->createCommand($sql); $result=$command->queryAll(); if(count($result) == 0) return '<img src="users/user.jpg" width="43" height="43" />'; else return '<img src="users/'.$id.'/'.$result[0]['photo'].'.jpg" width="43" height="43" />'; } // Reccurssive Function For Reply Ajax Link and disply Div, Rajith public function getReply1($rid) { $next = Reply::model()->findByAttributes(array('uid'=>Yii::app()->user->id,'rid'=>$rid)); if($next!=NULL) { $details = Message::model()->findByAttributes(array('msg_id'=>$next->mid)); echo '<div >'; echo CHtml::ajaxLink('From &nbsp; ::- '.Message::model()->getUserName($details->sender_id).' &nbsp; &nbsp; Subject &nbsp; ::- '.$details->subject,Yii::app()->createUrl('Message/message_details' ), array('type' =>'GET','data' => array('msg'=>$next->mid), 'dataType' => 'text','update' =>'#'.$next->mid)); echo '</div>'; echo '<div id='.$next->mid.'></div>'; Message::model()->getReply($next->mid); } else { return ; } } public function getReply($mid) { $next = Reply::model()->findAll(array('order'=>'rid DESC', 'condition'=>'(uid=:x or sid=:y) and mid=:z', 'params'=>array(':x'=>Yii::app()->user->id,':y'=>Yii::app()->user->id,':z'=>$mid))); if($next!=NULL) { $i=0; foreach($next as $next1) { if($i!=0) { $details = Message::model()->findByAttributes(array('msg_id'=>$next1['rid'])); echo '<div class="msgacc_Con">'; echo CHtml::ajaxLink('&nbsp;<strong>From</strong> &nbsp;:&nbsp;'.Message::model()->getUserName($details->sender_id).'<br/><strong>Subject</strong> &nbsp;:&nbsp'.$details->subject,Yii::app()->createUrl('Message/message_details' ), array('type' =>'GET','data' => array('msg'=>$next1['rid']), 'dataType' => 'text','update' =>'#'.$next1['rid'])); echo '</div>'; echo '<div id='.$next1['rid'].'></div>'; } $i++; } $details = Message::model()->findByAttributes(array('msg_id'=>$mid)); echo '<div class="msgacc_Con">'; echo CHtml::ajaxLink('&nbsp;<strong>From</strong> &nbsp;:&nbsp;'.Message::model()->getUserName($details->sender_id).' <br/><strong>Subject</strong> &nbsp;:&nbsp;'.$details->subject,Yii::app()->createUrl('Message/message_details' ), array('type' =>'GET','data' => array('msg'=>$mid), 'dataType' => 'text','update' =>'#'.$mid)); echo '</div>'; echo '<div id='.$mid.'></div>'; } else { return ; } } // Reccurssive Function For Reply ID, Rajith public function getReplyid1($mid) { $next = Reply::model()->findByAttributes(array('uid'=>Yii::app()->user->id,'mid'=>$mid)); if($next!=NULL) { $rid=Message::model()->getReplyid($next->rid); return $rid; } return $mid; } public function getReplycount($mid) { $next = Reply::model()->findAll(array('order'=>'rid DESC', 'condition'=>'(uid=:x or sid=:y) and mid=:z', 'params'=>array(':x'=>Yii::app()->user->id,':y'=>Yii::app()->user->id,':z'=>$mid))); if($next!=NULL) { return count($next); } else { return 0; } } public function getReplyid($mid) { $next = Reply::model()->findAll(array('order'=>'rid DESC', 'condition'=>'(uid=:x or sid=:y) and mid=:z', 'params'=>array(':x'=>Yii::app()->user->id,':y'=>Yii::app()->user->id,':z'=>$mid))); if($next!=NULL) { return $next[0]['rid']; } else { return $mid; } } // Sort for task- Rajith public function sorts($t,$status,$page) { switch($t) { case 0: $subject='msg_id DESC'; break; case 1: $subject='subject'; break; case 2: $subject='subject DESC'; break; } $i=0; $messageids=NULL; $connection = Yii::app()->db; $sql="SELECT t1.msg_id,t1.is_task FROM message AS t1 INNER JOIN message_user AS t2 ON t1.msg_id = t2.message_id WHERE t1.is_task IS NOT NULL AND t2.user_id =".Yii::app()->user->id." ORDER BY t1.".$subject; $command = $connection->createCommand($sql); $msgids = $command->queryAll(); if($msgids!=NULL) { foreach($msgids as $msgids1) { //only for T if($status=='T') { $messageids[$i]=$msgids1['msg_id']; $i++; } else { $task=TaskAssignToPatients::model()->findByAttributes(array('id'=>$msgids1['is_task'],'status'=>$status)); if($task != NULL ) { $messageids[$i]=$msgids1['msg_id']; $i++; } } } } return $messageids; } public function sortsUsertask($t,$status,$user_id) { switch($t) { case 0: $subject='msg_id DESC'; break; case 1: $subject='subject'; break; case 2: $subject='subject DESC'; break; } $i=0; $messageids=NULL; $connection = Yii::app()->db; $sql="SELECT t1.msg_id,t1.is_task FROM message AS t1 INNER JOIN message_user AS t2 ON t1.msg_id = t2.message_id WHERE t1.is_task IS NOT NULL AND t2.user_id =".$user_id." ORDER BY t1.".$subject; $command = $connection->createCommand($sql); $msgids = $command->queryAll(); if($msgids!=NULL) { foreach($msgids as $msgids1) { //only for T if($status=='T') { $messageids[$i]=$msgids1['msg_id']; $i++; } else { $task=TaskAssignToPatients::model()->findByAttributes(array('id'=>$msgids1['is_task'],'status'=>$status)); if($task != NULL ) { $messageids[$i]=$msgids1['msg_id']; $i++; } } } } return $messageids; } public function sortsAgencytask($t,$status) { switch($t) { case 0: $subject='id DESC'; break; case 1: $subject='subject'; break; case 2: $subject='id DESC'; break; } $i=0; $messageids=NULL; //$msgids=TaskAssignToPatients::model()->findAll(array('order'=>$subject, 'condition'=>'is_task!=:z', 'params'=>array(':z'=>''))); $msgids=TaskAssignToPatients::model()->findAll(array('order'=>$subject)); return $msgids; } }
Java
<?php class NFe_APIChildResource { // @var string Parent Keys private $_parentKeys; // @var string Fabricator private $_fabricator; function __construct( $parentKeys = array(), $className ) { $this->_fabricator = $className; $this->_parentKeys = $parentKeys; } function mergeParams( $attributes ) { return array_merge( $attributes, $this->_parentKeys ); } private function configureParentKeys($object) { foreach ($this->_parentKeys as $key => $value) { $object[$key] = $value; } return $object; } public function create( $attributes = array() ) { $result = call_user_func_array( $this->_fabricator . '::create', array( $this->mergeparams($attributes), $this->_parentKeys ) ); if ($result) { $this->configureParentKeys( $result ); } return $result; } public function search( $options = array() ) { $results = call_user_func_array($this->_fabricator . '::search', array( $this->mergeParams($options), $this->_parentKeys )); if ( $results && $results->total() ) { $modifiedResults = $results->results(); for ( $i = 0; $i < count($modifiedResults); $i++ ) { $modifiedResults[$i] = $this->configureParentKeys( $modifiedResults[$i] ); } $results->set($modifiedResults, $results->total()); } return $results; } public function fetch( $key = array() ) { if ( is_string($key) ) { $key = array( "id" => $key ); } $result = call_user_func_array($this->_fabricator . '::fetch', array( $this->mergeParams($key), $this->_parentKeys )); if ( $result ) { $this->configureParentKeys( $result ); } return $result; } }
Java
# Copyright (C) 2019 Fassio Blatter from stopeight import analyzer version=analyzer.version from stopeight.util.editor.data import ScribbleData def legal_segments(data): from stopeight.matrix import Vectors from stopeight.analyzer import legal_segments return legal_segments(Vectors(data)).__array__().view(ScribbleData) legal_segments.__annotations__ = {'data':ScribbleData,'return':ScribbleData}
Java
<?php if (is_category('stem')) { get_template_part('templates/content', 'stem'); } else { get_template_part('templates/content', 'category'); } ?>
Java
/* CMTP implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2002-2003 Marcel Holtmann <marcel@holtmann.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ #include <linux/export.h> #include <linux/types.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/skbuff.h> #include <linux/socket.h> #include <linux/ioctl.h> #include <linux/file.h> #include <linux/compat.h> #include <linux/gfp.h> #include <linux/uaccess.h> #include <net/sock.h> #include <linux/isdn/capilli.h> #include "cmtp.h" static int cmtp_sock_release(struct socket *sock) { struct sock *sk = sock->sk; BT_DBG("sock %p sk %p", sock, sk); if (!sk) return 0; sock_orphan(sk); sock_put(sk); return 0; } static int cmtp_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct cmtp_connadd_req ca; struct cmtp_conndel_req cd; struct cmtp_connlist_req cl; struct cmtp_conninfo ci; struct socket *nsock; void __user *argp = (void __user *)arg; int err; BT_DBG("cmd %x arg %lx", cmd, arg); switch (cmd) { case CMTPCONNADD: if (!capable(CAP_NET_ADMIN)) return -EACCES; if (copy_from_user(&ca, argp, sizeof(ca))) return -EFAULT; nsock = sockfd_lookup(ca.sock, &err); if (!nsock) return err; if (nsock->sk->sk_state != BT_CONNECTED) { sockfd_put(nsock); return -EBADFD; } err = cmtp_add_connection(&ca, nsock); if (!err) { if (copy_to_user(argp, &ca, sizeof(ca))) err = -EFAULT; } else sockfd_put(nsock); return err; case CMTPCONNDEL: if (!capable(CAP_NET_ADMIN)) return -EACCES; if (copy_from_user(&cd, argp, sizeof(cd))) return -EFAULT; return cmtp_del_connection(&cd); case CMTPGETCONNLIST: if (copy_from_user(&cl, argp, sizeof(cl))) return -EFAULT; if (cl.cnum <= 0) return -EINVAL; err = cmtp_get_connlist(&cl); if (!err && copy_to_user(argp, &cl, sizeof(cl))) return -EFAULT; return err; case CMTPGETCONNINFO: if (copy_from_user(&ci, argp, sizeof(ci))) return -EFAULT; err = cmtp_get_conninfo(&ci); if (!err && copy_to_user(argp, &ci, sizeof(ci))) return -EFAULT; return err; } return -EINVAL; } #ifdef CONFIG_COMPAT static int cmtp_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { if (cmd == CMTPGETCONNLIST) { struct cmtp_connlist_req cl; uint32_t uci; int err; if (get_user(cl.cnum, (uint32_t __user *) arg) || get_user(uci, (u32 __user *) (arg + 4))) return -EFAULT; cl.ci = compat_ptr(uci); if (cl.cnum <= 0) return -EINVAL; err = cmtp_get_connlist(&cl); if (!err && put_user(cl.cnum, (uint32_t __user *) arg)) err = -EFAULT; return err; } return cmtp_sock_ioctl(sock, cmd, arg); } #endif static const struct proto_ops cmtp_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = cmtp_sock_release, .ioctl = cmtp_sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = cmtp_sock_compat_ioctl, #endif .bind = sock_no_bind, .getname = sock_no_getname, .sendmsg = sock_no_sendmsg, .recvmsg = sock_no_recvmsg, .poll = sock_no_poll, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .mmap = sock_no_mmap }; static struct proto cmtp_proto = { .name = "CMTP", .owner = THIS_MODULE, .obj_size = sizeof(struct bt_sock) }; static int cmtp_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &cmtp_proto); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sock->ops = &cmtp_sock_ops; sock->state = SS_UNCONNECTED; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = protocol; sk->sk_state = BT_OPEN; return 0; } static const struct net_proto_family cmtp_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = cmtp_sock_create }; int cmtp_init_sockets(void) { int err; err = proto_register(&cmtp_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_CMTP, &cmtp_sock_family_ops); if (err < 0) goto error; return 0; error: BT_ERR("Can't register CMTP socket"); proto_unregister(&cmtp_proto); return err; } void cmtp_cleanup_sockets(void) { if (bt_sock_unregister(BTPROTO_CMTP) < 0) BT_ERR("Can't unregister CMTP socket"); proto_unregister(&cmtp_proto); }
Java
/* * * function: Á¬Ïß½Ó¿Ú * * Date:2015-12-05 * * Author: Bill Wang */ #ifndef _LOGIC_WH_PORT_H_ #define _LOGIC_WH_PORT_H_ #include <assert.h> typedef struct structPort { int moduleId; int paraId; bool operator < (const structPort &port) const { if( moduleId < port.moduleId ) { //СÓÚÖ±½Ó·µ»Øtrue return true; }else if( moduleId > port.moduleId ) { //´óÓÚ·µ»Øfalse return false; }else { //Èç¹ûmoduleIdÒ»Ñù£¬¼ÌÐø±È½ÏparaId£¬²»¿ÉÄܶ¼Ò»Ñù if( paraId < port.paraId ) return true; else if (paraId > port.paraId) return false; else return false; } } }whPort; //Ò»¸ö³ö¿Ú¶¨Ò壬ÍêÈ«¶¨ÒåÒ»¸öport #endif
Java
/* NicEdit - Micro Inline WYSIWYG * Copyright 2007-2008 Brian Kirchoff * * NicEdit is distributed under the terms of the MIT license * For more information visit http://nicedit.com/ * Do not remove this copyright message */ var bkExtend = function(){ var args = arguments; if (args.length == 1) args = [this, args[0]]; for (var prop in args[1]) args[0][prop] = args[1][prop]; return args[0]; }; function bkClass() { } bkClass.prototype.construct = function() {}; bkClass.extend = function(def) { var classDef = function() { if (arguments[0] !== bkClass) { return this.construct.apply(this, arguments); } }; var proto = new this(bkClass); bkExtend(proto,def); classDef.prototype = proto; classDef.extend = this.extend; return classDef; }; var bkElement = bkClass.extend({ construct : function(elm,d) { if(typeof(elm) == "string") { elm = (d || document).createElement(elm); } elm = $BK(elm); return elm; }, appendTo : function(elm) { elm.appendChild(this); return this; }, appendBefore : function(elm) { elm.parentNode.insertBefore(this,elm); return this; }, addEvent : function(type, fn) { bkLib.addEvent(this,type,fn); return this; }, setContent : function(c) { this.innerHTML = c; return this; }, pos : function() { var curleft = curtop = 0; var o = obj = this; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } var b = (!window.opera) ? parseInt(this.getStyle('border-width') || this.style.border) || 0 : 0; return [curleft+b,curtop+b+this.offsetHeight]; }, noSelect : function() { bkLib.noSelect(this); return this; }, parentTag : function(t) { var elm = this; do { if(elm && elm.nodeName && elm.nodeName.toUpperCase() == t) { return elm; } elm = elm.parentNode; } while(elm); return false; }, hasClass : function(cls) { return this.className.match(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)')); }, addClass : function(cls) { if (!this.hasClass(cls)) { this.className += " nicEdit-"+cls }; return this; }, removeClass : function(cls) { if (this.hasClass(cls)) { this.className = this.className.replace(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)'),' '); } return this; }, setStyle : function(st) { var elmStyle = this.style; for(var itm in st) { switch(itm) { case 'float': elmStyle['cssFloat'] = elmStyle['styleFloat'] = st[itm]; break; case 'opacity': elmStyle.opacity = st[itm]; elmStyle.filter = "alpha(opacity=" + Math.round(st[itm]*100) + ")"; break; case 'className': this.className = st[itm]; break; default: //if(document.compatMode || itm != "cursor") { // Nasty Workaround for IE 5.5 elmStyle[itm] = st[itm]; //} } } return this; }, getStyle : function( cssRule, d ) { var doc = (!d) ? document.defaultView : d; if(this.nodeType == 1) return (doc && doc.getComputedStyle) ? doc.getComputedStyle( this, null ).getPropertyValue(cssRule) : this.currentStyle[ bkLib.camelize(cssRule) ]; }, remove : function() { this.parentNode.removeChild(this); return this; }, setAttributes : function(at) { for(var itm in at) { this[itm] = at[itm]; } return this; } }); var bkLib = { isMSIE : (navigator.appVersion.indexOf("MSIE") != -1), addEvent : function(obj, type, fn) { (obj.addEventListener) ? obj.addEventListener( type, fn, false ) : obj.attachEvent("on"+type, fn); }, toArray : function(iterable) { var length = iterable.length, results = new Array(length); while (length--) { results[length] = iterable[length] }; return results; }, noSelect : function(element) { if(element.setAttribute && element.nodeName.toLowerCase() != 'input' && element.nodeName.toLowerCase() != 'textarea') { element.setAttribute('unselectable','on'); } for(var i=0;i<element.childNodes.length;i++) { bkLib.noSelect(element.childNodes[i]); } }, camelize : function(s) { return s.replace(/\-(.)/g, function(m, l){return l.toUpperCase()}); }, inArray : function(arr,item) { return (bkLib.search(arr,item) != null); }, search : function(arr,itm) { for(var i=0; i < arr.length; i++) { if(arr[i] == itm) return i; } return null; }, cancelEvent : function(e) { e = e || window.event; if(e.preventDefault && e.stopPropagation) { e.preventDefault(); e.stopPropagation(); } return false; }, domLoad : [], domLoaded : function() { if (arguments.callee.done) return; arguments.callee.done = true; for (i = 0;i < bkLib.domLoad.length;i++) bkLib.domLoad[i](); }, onDomLoaded : function(fireThis) { this.domLoad.push(fireThis); if (document.addEventListener) { document.addEventListener("DOMContentLoaded", bkLib.domLoaded, null); } else if(bkLib.isMSIE) { document.write("<style>.nicEdit-main p { margin: 0; }</style><scr"+"ipt id=__ie_onload defer " + ((location.protocol == "https:") ? "src='javascript:void(0)'" : "src=//0") + "><\/scr"+"ipt>"); $BK("__ie_onload").onreadystatechange = function() { if (this.readyState == "complete"){bkLib.domLoaded();} }; } window.onload = bkLib.domLoaded; } }; function $BK(elm) { if(typeof(elm) == "string") { elm = document.getElementById(elm); } return (elm && !elm.appendTo) ? bkExtend(elm,bkElement.prototype) : elm; } var bkEvent = { addEvent : function(evType, evFunc) { if(evFunc) { this.eventList = this.eventList || {}; this.eventList[evType] = this.eventList[evType] || []; this.eventList[evType].push(evFunc); } return this; }, fireEvent : function() { var args = bkLib.toArray(arguments), evType = args.shift(); if(this.eventList && this.eventList[evType]) { for(var i=0;i<this.eventList[evType].length;i++) { this.eventList[evType][i].apply(this,args); } } } }; function __(s) { return s; } Function.prototype.closure = function() { var __method = this, args = bkLib.toArray(arguments), obj = args.shift(); return function() { if(typeof(bkLib) != 'undefined') { return __method.apply(obj,args.concat(bkLib.toArray(arguments))); } }; } Function.prototype.closureListener = function() { var __method = this, args = bkLib.toArray(arguments), object = args.shift(); return function(e) { e = e || window.event; if(e.target) { var target = e.target; } else { var target = e.srcElement }; return __method.apply(object, [e,target].concat(args) ); }; } /* START CONFIG */ var nicEditorConfig = bkClass.extend({ buttons : { 'bold' : {name : __('Click to Bold'), command : 'Bold', tags : ['B','STRONG'], css : {'font-weight' : 'bold'}, key : 'b'}, 'italic' : {name : __('Click to Italic'), command : 'Italic', tags : ['EM','I'], css : {'font-style' : 'italic'}, key : 'i'}, 'underline' : {name : __('Click to Underline'), command : 'Underline', tags : ['U'], css : {'text-decoration' : 'underline'}, key : 'u'}, 'left' : {name : __('Left Align'), command : 'justifyleft', noActive : true}, 'center' : {name : __('Center Align'), command : 'justifycenter', noActive : true}, 'right' : {name : __('Right Align'), command : 'justifyright', noActive : true}, 'justify' : {name : __('Justify Align'), command : 'justifyfull', noActive : true}, 'ol' : {name : __('Insert Ordered List'), command : 'insertorderedlist', tags : ['OL']}, 'ul' : {name : __('Insert Unordered List'), command : 'insertunorderedlist', tags : ['UL']}, 'subscript' : {name : __('Click to Subscript'), command : 'subscript', tags : ['SUB']}, 'superscript' : {name : __('Click to Superscript'), command : 'superscript', tags : ['SUP']}, 'strikethrough' : {name : __('Click to Strike Through'), command : 'strikeThrough', css : {'text-decoration' : 'line-through'}}, 'removeformat' : {name : __('Remove Formatting'), command : 'removeformat', noActive : true}, 'indent' : {name : __('Indent Text'), command : 'indent', noActive : true}, 'outdent' : {name : __('Remove Indent'), command : 'outdent', noActive : true}, 'hr' : {name : __('Horizontal Rule'), command : 'insertHorizontalRule', noActive : true} }, iconsPath : '../nicEditorIcons.gif', buttonList : ['save','bold','italic','underline','left','center','right','justify','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','upload','link','unlink','forecolor','bgcolor'], iconList : {"xhtml":1,"bgcolor":2,"forecolor":3,"bold":4,"center":5,"hr":6,"indent":7,"italic":8,"justify":9,"left":10,"ol":11,"outdent":12,"removeformat":13,"right":14,"save":25,"strikethrough":16,"subscript":17,"superscript":18,"ul":19,"underline":20,"image":21,"link":22,"unlink":23,"close":24,"arrow":26,"upload":27} }); /* END CONFIG */ var nicEditors = { nicPlugins : [], editors : [], registerPlugin : function(plugin,options) { this.nicPlugins.push({p : plugin, o : options}); }, allTextAreas : function(nicOptions) { var textareas = document.getElementsByTagName("textarea"); for(var i=0;i<textareas.length;i++) { nicEditors.editors.push(new nicEditor(nicOptions).panelInstance(textareas[i])); } return nicEditors.editors; }, findEditor : function(e) { var editors = nicEditors.editors; for(var i=0;i<editors.length;i++) { if(editors[i].instanceById(e)) { return editors[i].instanceById(e); } } } }; var nicEditor = bkClass.extend({ construct : function(o) { this.options = new nicEditorConfig(); bkExtend(this.options,o); this.nicInstances = new Array(); this.loadedPlugins = new Array(); var plugins = nicEditors.nicPlugins; for(var i=0;i<plugins.length;i++) { this.loadedPlugins.push(new plugins[i].p(this,plugins[i].o)); } nicEditors.editors.push(this); bkLib.addEvent(document.body,'mousedown', this.selectCheck.closureListener(this) ); }, panelInstance : function(e,o) { e = this.checkReplace($BK(e)); var panelElm = new bkElement('DIV').setStyle({width : (parseInt(e.getStyle('width')) || e.clientWidth)+'px'}).appendBefore(e); this.setPanel(panelElm); return this.addInstance(e,o); }, checkReplace : function(e) { var r = nicEditors.findEditor(e); if(r) { r.removeInstance(e); r.removePanel(); } return e; }, addInstance : function(e,o) { e = this.checkReplace($BK(e)); if( e.contentEditable || !!window.opera ) { var newInstance = new nicEditorInstance(e,o,this); } else { var newInstance = new nicEditorIFrameInstance(e,o,this); } this.nicInstances.push(newInstance); return this; }, removeInstance : function(e) { e = $BK(e); var instances = this.nicInstances; for(var i=0;i<instances.length;i++) { if(instances[i].e == e) { instances[i].remove(); this.nicInstances.splice(i,1); } } }, removePanel : function(e) { if(this.nicPanel) { this.nicPanel.remove(); this.nicPanel = null; } }, instanceById : function(e) { e = $BK(e); var instances = this.nicInstances; for(var i=0;i<instances.length;i++) { if(instances[i].e == e) { return instances[i]; } } }, setPanel : function(e) { this.nicPanel = new nicEditorPanel($BK(e),this.options,this); this.fireEvent('panel',this.nicPanel); return this; }, nicCommand : function(cmd,args) { if(this.selectedInstance) { this.selectedInstance.nicCommand(cmd,args); } }, getIcon : function(iconName,options) { var icon = this.options.iconList[iconName]; var file = (options.iconFiles) ? options.iconFiles[iconName] : ''; return {backgroundImage : "url('"+((icon) ? this.options.iconsPath : file)+"')", backgroundPosition : ((icon) ? ((icon-1)*-18) : 0)+'px 0px'}; }, selectCheck : function(e,t) { var found = false; do{ if(t.className && t.className.indexOf('nicEdit') != -1) { return false; } } while(t = t.parentNode); this.fireEvent('blur',this.selectedInstance,t); this.lastSelectedInstance = this.selectedInstance; this.selectedInstance = null; return false; } }); nicEditor = nicEditor.extend(bkEvent); var nicEditorInstance = bkClass.extend({ isSelected : false, construct : function(e,options,nicEditor) { this.ne = nicEditor; this.elm = this.e = e; this.options = options || {}; newX = parseInt(e.getStyle('width')) || e.clientWidth; newY = parseInt(e.getStyle('height')) || e.clientHeight; this.initialHeight = newY-8; var isTextarea = (e.nodeName.toLowerCase() == "textarea"); if(isTextarea || this.options.hasPanel) { var ie7s = (bkLib.isMSIE && !((typeof document.body.style.maxHeight != "undefined") && document.compatMode == "CSS1Compat")) var s = {width: newX+'px', border : '1px solid #ccc', borderTop : 0, overflowY : 'auto', overflowX: 'hidden' }; s[(ie7s) ? 'height' : 'maxHeight'] = (this.ne.options.maxHeight) ? this.ne.options.maxHeight+'px' : null; this.editorContain = new bkElement('DIV').setStyle(s).appendBefore(e); var editorElm = new bkElement('DIV').setStyle({width : (newX-8)+'px', margin: '4px', minHeight : newY+'px'}).addClass('main').appendTo(this.editorContain); e.setStyle({display : 'none'}); editorElm.innerHTML = e.innerHTML; if(isTextarea) { editorElm.setContent(e.value); this.copyElm = e; var f = e.parentTag('FORM'); if(f) { bkLib.addEvent( f, 'submit', this.saveContent.closure(this)); } } editorElm.setStyle((ie7s) ? {height : newY+'px'} : {overflow: 'hidden'}); this.elm = editorElm; } this.ne.addEvent('blur',this.blur.closure(this)); this.init(); this.blur(); }, init : function() { this.elm.setAttribute('contentEditable','true'); if(this.getContent() == "") { this.setContent('<br />'); } this.instanceDoc = document.defaultView; this.elm.addEvent('mousedown',this.selected.closureListener(this)).addEvent('keypress',this.keyDown.closureListener(this)).addEvent('focus',this.selected.closure(this)).addEvent('blur',this.blur.closure(this)).addEvent('keyup',this.selected.closure(this)); this.ne.fireEvent('add',this); }, remove : function() { this.saveContent(); if(this.copyElm || this.options.hasPanel) { this.editorContain.remove(); this.e.setStyle({'display' : 'block'}); this.ne.removePanel(); } this.disable(); this.ne.fireEvent('remove',this); }, disable : function() { this.elm.setAttribute('contentEditable','false'); }, getSel : function() { return (window.getSelection) ? window.getSelection() : document.selection; }, getRng : function() { var s = this.getSel(); if(!s || s.rangeCount === 0) { return; } return (s.rangeCount > 0) ? s.getRangeAt(0) : s.createRange(); }, selRng : function(rng,s) { if(window.getSelection) { s.removeAllRanges(); s.addRange(rng); } else { rng.select(); } }, selElm : function() { var r = this.getRng(); if(!r) { return; } if(r.startContainer) { var contain = r.startContainer; if(r.cloneContents().childNodes.length == 1) { for(var i=0;i<contain.childNodes.length;i++) { var rng = contain.childNodes[i].ownerDocument.createRange(); rng.selectNode(contain.childNodes[i]); if(r.compareBoundaryPoints(Range.START_TO_START,rng) != 1 && r.compareBoundaryPoints(Range.END_TO_END,rng) != -1) { return $BK(contain.childNodes[i]); } } } return $BK(contain); } else { return $BK((this.getSel().type == "Control") ? r.item(0) : r.parentElement()); } }, saveRng : function() { this.savedRange = this.getRng(); this.savedSel = this.getSel(); }, restoreRng : function() { if(this.savedRange) { this.selRng(this.savedRange,this.savedSel); } }, keyDown : function(e,t) { if(e.ctrlKey) { this.ne.fireEvent('key',this,e); } }, selected : function(e,t) { if(!t && !(t = this.selElm)) { t = this.selElm(); } if(!e.ctrlKey) { var selInstance = this.ne.selectedInstance; if(selInstance != this) { if(selInstance) { this.ne.fireEvent('blur',selInstance,t); } this.ne.selectedInstance = this; this.ne.fireEvent('focus',selInstance,t); } this.ne.fireEvent('selected',selInstance,t); this.isFocused = true; this.elm.addClass('selected'); } return false; }, blur : function() { this.isFocused = false; this.elm.removeClass('selected'); }, saveContent : function() { if(this.copyElm || this.options.hasPanel) { this.ne.fireEvent('save',this); (this.copyElm) ? this.copyElm.value = this.getContent() : this.e.innerHTML = this.getContent(); } }, getElm : function() { return this.elm; }, getContent : function() { this.content = this.getElm().innerHTML; this.ne.fireEvent('get',this); return this.content; }, setContent : function(e) { this.content = e; this.ne.fireEvent('set',this); this.elm.innerHTML = this.content; }, nicCommand : function(cmd,args) { document.execCommand(cmd,false,args); } }); var nicEditorIFrameInstance = nicEditorInstance.extend({ savedStyles : [], init : function() { var c = this.elm.innerHTML.replace(/^\s+|\s+$/g, ''); this.elm.innerHTML = ''; (!c) ? c = "<br />" : c; this.initialContent = c; this.elmFrame = new bkElement('iframe').setAttributes({'src' : 'javascript:;', 'frameBorder' : 0, 'allowTransparency' : 'true', 'scrolling' : 'no'}).setStyle({height: '100px', width: '100%'}).addClass('frame').appendTo(this.elm); if(this.copyElm) { this.elmFrame.setStyle({width : (this.elm.offsetWidth-4)+'px'}); } var styleList = ['font-size','font-family','font-weight','color']; for(itm in styleList) { this.savedStyles[bkLib.camelize(itm)] = this.elm.getStyle(itm); } setTimeout(this.initFrame.closure(this),50); }, disable : function() { this.elm.innerHTML = this.getContent(); }, initFrame : function() { var fd = $BK(this.elmFrame.contentWindow.document); fd.designMode = "on"; fd.open(); var css = this.ne.options.externalCSS; fd.write('<html><head>'+((css) ? '<link href="'+css+'" rel="stylesheet" type="text/css" />' : '')+'</head><body id="nicEditContent" style="margin: 0 !important; background-color: transparent !important;">'+this.initialContent+'</body></html>'); fd.close(); this.frameDoc = fd; this.frameWin = $BK(this.elmFrame.contentWindow); this.frameContent = $BK(this.frameWin.document.body).setStyle(this.savedStyles); this.instanceDoc = this.frameWin.document.defaultView; this.heightUpdate(); this.frameDoc.addEvent('mousedown', this.selected.closureListener(this)).addEvent('keyup',this.heightUpdate.closureListener(this)).addEvent('keydown',this.keyDown.closureListener(this)).addEvent('keyup',this.selected.closure(this)); this.ne.fireEvent('add',this); }, getElm : function() { return this.frameContent; }, setContent : function(c) { this.content = c; this.ne.fireEvent('set',this); this.frameContent.innerHTML = this.content; this.heightUpdate(); }, getSel : function() { return (this.frameWin) ? this.frameWin.getSelection() : this.frameDoc.selection; }, heightUpdate : function() { this.elmFrame.style.height = Math.max(this.frameContent.offsetHeight,this.initialHeight)+'px'; }, nicCommand : function(cmd,args) { this.frameDoc.execCommand(cmd,false,args); setTimeout(this.heightUpdate.closure(this),100); } }); var nicEditorPanel = bkClass.extend({ construct : function(e,options,nicEditor) { this.elm = e; this.options = options; this.ne = nicEditor; this.panelButtons = new Array(); this.buttonList = bkExtend([],this.ne.options.buttonList); this.panelContain = new bkElement('DIV').setStyle({overflow : 'hidden', width : '100%', border : '1px solid #cccccc', backgroundColor : '#efefef'}).addClass('panelContain'); this.panelElm = new bkElement('DIV').setStyle({margin : '2px', marginTop : '0px', zoom : 1, overflow : 'hidden'}).addClass('panel').appendTo(this.panelContain); this.panelContain.appendTo(e); var opt = this.ne.options; var buttons = opt.buttons; for(button in buttons) { this.addButton(button,opt,true); } this.reorder(); e.noSelect(); }, addButton : function(buttonName,options,noOrder) { var button = options.buttons[buttonName]; var type = (button['type']) ? eval('(typeof('+button['type']+') == "undefined") ? null : '+button['type']+';') : nicEditorButton; var hasButton = bkLib.inArray(this.buttonList,buttonName); if(type && (hasButton || this.ne.options.fullPanel)) { this.panelButtons.push(new type(this.panelElm,buttonName,options,this.ne)); if(!hasButton) { this.buttonList.push(buttonName); } } }, findButton : function(itm) { for(var i=0;i<this.panelButtons.length;i++) { if(this.panelButtons[i].name == itm) return this.panelButtons[i]; } }, reorder : function() { var bl = this.buttonList; for(var i=0;i<bl.length;i++) { var button = this.findButton(bl[i]); if(button) { this.panelElm.appendChild(button.margin); } } }, remove : function() { this.elm.remove(); } }); var nicEditorButton = bkClass.extend({ construct : function(e,buttonName,options,nicEditor) { this.options = options.buttons[buttonName]; this.name = buttonName; this.ne = nicEditor; this.elm = e; this.margin = new bkElement('DIV').setStyle({'float' : 'left', marginTop : '2px'}).appendTo(e); this.contain = new bkElement('DIV').setStyle({width : '20px', height : '20px'}).addClass('buttonContain').appendTo(this.margin); this.border = new bkElement('DIV').setStyle({backgroundColor : '#efefef', border : '1px solid #efefef'}).appendTo(this.contain); this.button = new bkElement('DIV').setStyle({width : '18px', height : '18px', overflow : 'hidden', zoom : 1, cursor : 'pointer'}).addClass('button').setStyle(this.ne.getIcon(buttonName,options)).appendTo(this.border); this.button.addEvent('mouseover', this.hoverOn.closure(this)).addEvent('mouseout',this.hoverOff.closure(this)).addEvent('mousedown',this.mouseClick.closure(this)).noSelect(); if(!window.opera) { this.button.onmousedown = this.button.onclick = bkLib.cancelEvent; } nicEditor.addEvent('selected', this.enable.closure(this)).addEvent('blur', this.disable.closure(this)).addEvent('key',this.key.closure(this)); this.disable(); this.init(); }, init : function() { }, hide : function() { this.contain.setStyle({display : 'none'}); }, updateState : function() { if(this.isDisabled) { this.setBg(); } else if(this.isHover) { this.setBg('hover'); } else if(this.isActive) { this.setBg('active'); } else { this.setBg(); } }, setBg : function(state) { switch(state) { case 'hover': var stateStyle = {border : '1px solid #666', backgroundColor : '#ddd'}; break; case 'active': var stateStyle = {border : '1px solid #666', backgroundColor : '#ccc'}; break; default: var stateStyle = {border : '1px solid #efefef', backgroundColor : '#efefef'}; } this.border.setStyle(stateStyle).addClass('button-'+state); }, checkNodes : function(e) { var elm = e; do { if(this.options.tags && bkLib.inArray(this.options.tags,elm.nodeName)) { this.activate(); return true; } } while(elm = elm.parentNode && elm.className != "nicEdit"); elm = $BK(e); while(elm.nodeType == 3) { elm = $BK(elm.parentNode); } if(this.options.css) { for(itm in this.options.css) { if(elm.getStyle(itm,this.ne.selectedInstance.instanceDoc) == this.options.css[itm]) { this.activate(); return true; } } } this.deactivate(); return false; }, activate : function() { if(!this.isDisabled) { this.isActive = true; this.updateState(); this.ne.fireEvent('buttonActivate',this); } }, deactivate : function() { this.isActive = false; this.updateState(); if(!this.isDisabled) { this.ne.fireEvent('buttonDeactivate',this); } }, enable : function(ins,t) { this.isDisabled = false; this.contain.setStyle({'opacity' : 1}).addClass('buttonEnabled'); this.updateState(); this.checkNodes(t); }, disable : function(ins,t) { this.isDisabled = true; this.contain.setStyle({'opacity' : 0.6}).removeClass('buttonEnabled'); this.updateState(); }, toggleActive : function() { (this.isActive) ? this.deactivate() : this.activate(); }, hoverOn : function() { if(!this.isDisabled) { this.isHover = true; this.updateState(); this.ne.fireEvent("buttonOver",this); } }, hoverOff : function() { this.isHover = false; this.updateState(); this.ne.fireEvent("buttonOut",this); }, mouseClick : function() { if(this.options.command) { this.ne.nicCommand(this.options.command,this.options.commandArgs); if(!this.options.noActive) { this.toggleActive(); } } this.ne.fireEvent("buttonClick",this); }, key : function(nicInstance,e) { if(this.options.key && e.ctrlKey && String.fromCharCode(e.keyCode || e.charCode).toLowerCase() == this.options.key) { this.mouseClick(); if(e.preventDefault) e.preventDefault(); } } }); var nicPlugin = bkClass.extend({ construct : function(nicEditor,options) { this.options = options; this.ne = nicEditor; this.ne.addEvent('panel',this.loadPanel.closure(this)); this.init(); }, loadPanel : function(np) { var buttons = this.options.buttons; for(var button in buttons) { np.addButton(button,this.options); } np.reorder(); }, init : function() { } }); /* START CONFIG */ var nicPaneOptions = { }; /* END CONFIG */ var nicEditorPane = bkClass.extend({ construct : function(elm,nicEditor,options,openButton) { this.ne = nicEditor; this.elm = elm; this.pos = elm.pos(); this.contain = new bkElement('div').setStyle({zIndex : '99999', overflow : 'hidden', position : 'absolute', left : this.pos[0]+'px', top : this.pos[1]+'px'}) this.pane = new bkElement('div').setStyle({fontSize : '12px', border : '1px solid #ccc', 'overflow': 'hidden', padding : '4px', textAlign: 'left', backgroundColor : '#ffffc9'}).addClass('pane').setStyle(options).appendTo(this.contain); if(openButton && !openButton.options.noClose) { this.close = new bkElement('div').setStyle({'float' : 'right', height: '16px', width : '16px', cursor : 'pointer'}).setStyle(this.ne.getIcon('close',nicPaneOptions)).addEvent('mousedown',openButton.removePane.closure(this)).appendTo(this.pane); } this.contain.noSelect().appendTo(document.body); this.position(); this.init(); }, init : function() { }, position : function() { if(this.ne.nicPanel) { var panelElm = this.ne.nicPanel.elm; var panelPos = panelElm.pos(); var newLeft = panelPos[0]+parseInt(panelElm.getStyle('width'))-(parseInt(this.pane.getStyle('width'))+8); if(newLeft < this.pos[0]) { this.contain.setStyle({left : newLeft+'px'}); } } }, toggle : function() { this.isVisible = !this.isVisible; this.contain.setStyle({display : ((this.isVisible) ? 'block' : 'none')}); }, remove : function() { if(this.contain) { this.contain.remove(); this.contain = null; } }, append : function(c) { c.appendTo(this.pane); }, setContent : function(c) { this.pane.setContent(c); } }); var nicEditorAdvancedButton = nicEditorButton.extend({ init : function() { this.ne.addEvent('selected',this.removePane.closure(this)).addEvent('blur',this.removePane.closure(this)); }, mouseClick : function() { if(!this.isDisabled) { if(this.pane && this.pane.pane) { this.removePane(); } else { this.pane = new nicEditorPane(this.contain,this.ne,{width : (this.width || '270px'), backgroundColor : '#fff'},this); this.addPane(); this.ne.selectedInstance.saveRng(); } } }, addForm : function(f,elm) { this.form = new bkElement('form').addEvent('submit',this.submit.closureListener(this)); this.pane.append(this.form); this.inputs = {}; for(itm in f) { var field = f[itm]; var val = ''; if(elm) { val = elm.getAttribute(itm); } if(!val) { val = field['value'] || ''; } var type = f[itm].type; if(type == 'title') { new bkElement('div').setContent(field.txt).setStyle({fontSize : '14px', fontWeight: 'bold', padding : '0px', margin : '2px 0'}).appendTo(this.form); } else { var contain = new bkElement('div').setStyle({overflow : 'hidden', clear : 'both'}).appendTo(this.form); if(field.txt) { new bkElement('label').setAttributes({'for' : itm}).setContent(field.txt).setStyle({margin : '2px 4px', fontSize : '13px', width: '50px', lineHeight : '20px', textAlign : 'right', 'float' : 'left'}).appendTo(contain); } switch(type) { case 'text': this.inputs[itm] = new bkElement('input').setAttributes({id : itm, 'value' : val, 'type' : 'text'}).setStyle({margin : '2px 0', fontSize : '13px', 'float' : 'left', height : '20px', border : '1px solid #ccc', overflow : 'hidden'}).setStyle(field.style).appendTo(contain); break; case 'select': this.inputs[itm] = new bkElement('select').setAttributes({id : itm}).setStyle({border : '1px solid #ccc', 'float' : 'left', margin : '2px 0'}).appendTo(contain); for(opt in field.options) { var o = new bkElement('option').setAttributes({value : opt, selected : (opt == val) ? 'selected' : ''}).setContent(field.options[opt]).appendTo(this.inputs[itm]); } break; case 'content': this.inputs[itm] = new bkElement('textarea').setAttributes({id : itm}).setStyle({border : '1px solid #ccc', 'float' : 'left'}).setStyle(field.style).appendTo(contain); this.inputs[itm].value = val; } } } new bkElement('input').setAttributes({'type' : 'submit'}).setStyle({backgroundColor : '#efefef',border : '1px solid #ccc', margin : '3px 0', 'float' : 'left', 'clear' : 'both'}).appendTo(this.form); this.form.onsubmit = bkLib.cancelEvent; }, submit : function() { }, findElm : function(tag,attr,val) { var list = this.ne.selectedInstance.getElm().getElementsByTagName(tag); for(var i=0;i<list.length;i++) { if(list[i].getAttribute(attr) == val) { return $BK(list[i]); } } }, removePane : function() { if(this.pane) { this.pane.remove(); this.pane = null; this.ne.selectedInstance.restoreRng(); } } }); var nicButtonTips = bkClass.extend({ construct : function(nicEditor) { this.ne = nicEditor; nicEditor.addEvent('buttonOver',this.show.closure(this)).addEvent('buttonOut',this.hide.closure(this)); }, show : function(button) { this.timer = setTimeout(this.create.closure(this,button),400); }, create : function(button) { this.timer = null; if(!this.pane) { this.pane = new nicEditorPane(button.button,this.ne,{fontSize : '12px', marginTop : '5px'}); this.pane.setContent(button.options.name); } }, hide : function(button) { if(this.timer) { clearTimeout(this.timer); } if(this.pane) { this.pane = this.pane.remove(); } } }); nicEditors.registerPlugin(nicButtonTips); /* START CONFIG */ var nicSelectOptions = { buttons : { 'fontSize' : {name : __('Select Font Size'), type : 'nicEditorFontSizeSelect', command : 'fontsize'}, 'fontFamily' : {name : __('Select Font Family'), type : 'nicEditorFontFamilySelect', command : 'fontname'}, 'fontFormat' : {name : __('Select Font Format'), type : 'nicEditorFontFormatSelect', command : 'formatBlock'} } }; /* END CONFIG */ var nicEditorSelect = bkClass.extend({ construct : function(e,buttonName,options,nicEditor) { this.options = options.buttons[buttonName]; this.elm = e; this.ne = nicEditor; this.name = buttonName; this.selOptions = new Array(); this.margin = new bkElement('div').setStyle({'float' : 'left', margin : '2px 1px 0 1px'}).appendTo(this.elm); this.contain = new bkElement('div').setStyle({width: '90px', height : '20px', cursor : 'pointer', overflow: 'hidden'}).addClass('selectContain').addEvent('click',this.toggle.closure(this)).appendTo(this.margin); this.items = new bkElement('div').setStyle({overflow : 'hidden', zoom : 1, border: '1px solid #ccc', paddingLeft : '3px', backgroundColor : '#fff'}).appendTo(this.contain); this.control = new bkElement('div').setStyle({overflow : 'hidden', 'float' : 'right', height: '18px', width : '16px'}).addClass('selectControl').setStyle(this.ne.getIcon('arrow',options)).appendTo(this.items); this.txt = new bkElement('div').setStyle({overflow : 'hidden', 'float' : 'left', width : '66px', height : '14px', marginTop : '1px', fontFamily : 'sans-serif', textAlign : 'center', fontSize : '12px'}).addClass('selectTxt').appendTo(this.items); if(!window.opera) { this.contain.onmousedown = this.control.onmousedown = this.txt.onmousedown = bkLib.cancelEvent; } this.margin.noSelect(); this.ne.addEvent('selected', this.enable.closure(this)).addEvent('blur', this.disable.closure(this)); this.disable(); this.init(); }, disable : function() { this.isDisabled = true; this.close(); this.contain.setStyle({opacity : 0.6}); }, enable : function(t) { this.isDisabled = false; this.close(); this.contain.setStyle({opacity : 1}); }, setDisplay : function(txt) { this.txt.setContent(txt); }, toggle : function() { if(!this.isDisabled) { (this.pane) ? this.close() : this.open(); } }, open : function() { this.pane = new nicEditorPane(this.items,this.ne,{width : '88px', padding: '0px', borderTop : 0, borderLeft : '1px solid #ccc', borderRight : '1px solid #ccc', borderBottom : '0px', backgroundColor : '#fff'}); for(var i=0;i<this.selOptions.length;i++) { var opt = this.selOptions[i]; var itmContain = new bkElement('div').setStyle({overflow : 'hidden', borderBottom : '1px solid #ccc', width: '88px', textAlign : 'left', overflow : 'hidden', cursor : 'pointer'}); var itm = new bkElement('div').setStyle({padding : '0px 4px'}).setContent(opt[1]).appendTo(itmContain).noSelect(); itm.addEvent('click',this.update.closure(this,opt[0])).addEvent('mouseover',this.over.closure(this,itm)).addEvent('mouseout',this.out.closure(this,itm)).setAttributes('id',opt[0]); this.pane.append(itmContain); if(!window.opera) { itm.onmousedown = bkLib.cancelEvent; } } }, close : function() { if(this.pane) { this.pane = this.pane.remove(); } }, over : function(opt) { opt.setStyle({backgroundColor : '#ccc'}); }, out : function(opt) { opt.setStyle({backgroundColor : '#fff'}); }, add : function(k,v) { this.selOptions.push(new Array(k,v)); }, update : function(elm) { this.ne.nicCommand(this.options.command,elm); this.close(); } }); var nicEditorFontSizeSelect = nicEditorSelect.extend({ sel : {1 : '1&nbsp;(8pt)', 2 : '2&nbsp;(10pt)', 3 : '3&nbsp;(12pt)', 4 : '4&nbsp;(14pt)', 5 : '5&nbsp;(18pt)', 6 : '6&nbsp;(24pt)'}, init : function() { this.setDisplay('Font&nbsp;Size...'); for(itm in this.sel) { this.add(itm,'<font size="'+itm+'">'+this.sel[itm]+'</font>'); } } }); var nicEditorFontFamilySelect = nicEditorSelect.extend({ sel : {'arial' : 'Arial','comic sans ms' : 'Comic Sans','courier new' : 'Courier New','georgia' : 'Georgia', 'helvetica' : 'Helvetica', 'impact' : 'Impact', 'times new roman' : 'Times', 'trebuchet ms' : 'Trebuchet', 'verdana' : 'Verdana'}, init : function() { this.setDisplay('Font&nbsp;Family...'); for(itm in this.sel) { this.add(itm,'<font face="'+itm+'">'+this.sel[itm]+'</font>'); } } }); var nicEditorFontFormatSelect = nicEditorSelect.extend({ sel : {'p' : 'Paragraph', 'pre' : 'Pre', 'h6' : 'Heading&nbsp;6', 'h5' : 'Heading&nbsp;5', 'h4' : 'Heading&nbsp;4', 'h3' : 'Heading&nbsp;3', 'h2' : 'Heading&nbsp;2', 'h1' : 'Heading&nbsp;1'}, init : function() { this.setDisplay('Font&nbsp;Format...'); for(itm in this.sel) { var tag = itm.toUpperCase(); this.add('<'+tag+'>','<'+itm+' style="padding: 0px; margin: 0px;">'+this.sel[itm]+'</'+tag+'>'); } } }); nicEditors.registerPlugin(nicPlugin,nicSelectOptions); /* START CONFIG */ var nicLinkOptions = { buttons : { 'link' : {name : 'Add Link', type : 'nicLinkButton', tags : ['A']}, 'unlink' : {name : 'Remove Link', command : 'unlink', noActive : true} } }; /* END CONFIG */ var nicLinkButton = nicEditorAdvancedButton.extend({ addPane : function() { this.ln = this.ne.selectedInstance.selElm().parentTag('A'); this.addForm({ '' : {type : 'title', txt : 'Add/Edit Link'}, 'href' : {type : 'text', txt : 'URL', value : 'http://', style : {width: '150px'}}, 'title' : {type : 'text', txt : 'Title'}, 'target' : {type : 'select', txt : 'Open In', options : {'' : 'Current Window', '_blank' : 'New Window'},style : {width : '100px'}} },this.ln); }, submit : function(e) { var url = this.inputs['href'].value; if(url == "http://" || url == "") { alert("You must enter a URL to Create a Link"); return false; } this.removePane(); if(!this.ln) { var tmp = 'javascript:nicTemp();'; this.ne.nicCommand("createlink",tmp); this.ln = this.findElm('A','href',tmp); } if(this.ln) { this.ln.setAttributes({ href : this.inputs['href'].value, title : this.inputs['title'].value, target : this.inputs['target'].options[this.inputs['target'].selectedIndex].value }); } } }); nicEditors.registerPlugin(nicPlugin,nicLinkOptions); /* START CONFIG */ var nicColorOptions = { buttons : { 'forecolor' : {name : __('Change Text Color'), type : 'nicEditorColorButton', noClose : true}, 'bgcolor' : {name : __('Change Background Color'), type : 'nicEditorBgColorButton', noClose : true} } }; /* END CONFIG */ var nicEditorColorButton = nicEditorAdvancedButton.extend({ addPane : function() { var colorList = {0 : '00',1 : '33',2 : '66',3 :'99',4 : 'CC',5 : 'FF'}; var colorItems = new bkElement('DIV').setStyle({width: '270px'}); for(var r in colorList) { for(var b in colorList) { for(var g in colorList) { var colorCode = '#'+colorList[r]+colorList[g]+colorList[b]; var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems); var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare); var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder); if(!window.opera) { colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent; } } } } this.pane.append(colorItems.noSelect()); }, colorSelect : function(c) { this.ne.nicCommand('foreColor',c); this.removePane(); }, on : function(colorBorder) { colorBorder.setStyle({border : '2px solid #000'}); }, off : function(colorBorder,colorCode) { colorBorder.setStyle({border : '2px solid '+colorCode}); } }); var nicEditorBgColorButton = nicEditorColorButton.extend({ colorSelect : function(c) { this.ne.nicCommand('hiliteColor',c); this.removePane(); } }); nicEditors.registerPlugin(nicPlugin,nicColorOptions); /* START CONFIG */ var nicImageOptions = { buttons : { 'image' : {name : 'Add Image', type : 'nicImageButton', tags : ['IMG']} } }; /* END CONFIG */ var nicImageButton = nicEditorAdvancedButton.extend({ addPane : function() { this.im = this.ne.selectedInstance.selElm().parentTag('IMG'); this.addForm({ '' : {type : 'title', txt : 'Add/Edit Image'}, 'src' : {type : 'text', txt : 'URL', 'value' : 'http://', style : {width: '150px'}}, 'alt' : {type : 'text', txt : 'Alt Text', style : {width: '100px'}}, 'align' : {type : 'select', txt : 'Align', options : {none : 'Default','left' : 'Left', 'right' : 'Right'}} },this.im); }, submit : function(e) { var src = this.inputs['src'].value; if(src == "" || src == "http://") { alert("You must enter a Image URL to insert"); return false; } this.removePane(); if(!this.im) { var tmp = 'javascript:nicImTemp();'; this.ne.nicCommand("insertImage",tmp); this.im = this.findElm('IMG','src',tmp); } if(this.im) { this.im.setAttributes({ src : this.inputs['src'].value, alt : this.inputs['alt'].value, align : this.inputs['align'].value }); } } }); nicEditors.registerPlugin(nicPlugin,nicImageOptions); /* START CONFIG */ var nicSaveOptions = { buttons : { 'save' : {name : __('Save this content'), type : 'nicEditorSaveButton'} } }; /* END CONFIG */ var nicEditorSaveButton = nicEditorButton.extend({ init : function() { if(!this.ne.options.onSave) { this.margin.setStyle({'display' : 'none'}); } }, mouseClick : function() { var onSave = this.ne.options.onSave; var selectedInstance = this.ne.selectedInstance; onSave(selectedInstance.getContent(), selectedInstance.elm.id, selectedInstance); } }); nicEditors.registerPlugin(nicPlugin,nicSaveOptions); /* START CONFIG */ var nicUploadOptions = { buttons : { 'upload' : {name : 'Upload Image', type : 'nicUploadButton'} } }; /* END CONFIG */ var nicUploadButton = nicEditorAdvancedButton.extend({ nicURI : 'http://api.imgur.com/2/upload.json', errorText : 'Failed to upload image', addPane : function() { if(typeof window.FormData === "undefined") { return this.onError("Image uploads are not supported in this browser, use Chrome, Firefox, or Safari instead."); } this.im = this.ne.selectedInstance.selElm().parentTag('IMG'); var container = new bkElement('div') .setStyle({ padding: '10px' }) .appendTo(this.pane.pane); new bkElement('div') .setStyle({ fontSize: '14px', fontWeight : 'bold', paddingBottom: '5px' }) .setContent('Insert an Image') .appendTo(container); this.fileInput = new bkElement('input') .setAttributes({ 'type' : 'file' }) .appendTo(container); this.progress = new bkElement('progress') .setStyle({ width : '100%', display: 'none' }) .setAttributes('max', 100) .appendTo(container); this.fileInput.onchange = this.uploadFile.closure(this); }, onError : function(msg) { this.removePane(); alert(msg || "Failed to upload image"); }, uploadFile : function() { var file = this.fileInput.files[0]; if (!file || !file.type.match(/image.*/)) { this.onError("Only image files can be uploaded"); return; } this.fileInput.setStyle({ display: 'none' }); this.setProgress(0); var fd = new FormData(); // https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/ fd.append("image", file); fd.append("key", "b7ea18a4ecbda8e92203fa4968d10660"); var xhr = new XMLHttpRequest(); xhr.open("POST", this.ne.options.uploadURI || this.nicURI); xhr.onload = function() { try { var res = JSON.parse(xhr.responseText); } catch(e) { return this.onError(); } this.onUploaded(res.upload); }.closure(this); xhr.onerror = this.onError.closure(this); xhr.upload.onprogress = function(e) { this.setProgress(e.loaded / e.total); }.closure(this); xhr.send(fd); }, setProgress : function(percent) { this.progress.setStyle({ display: 'block' }); if(percent < .98) { this.progress.value = percent; } else { this.progress.removeAttribute('value'); } }, onUploaded : function(options) { this.removePane(); var src = options.links.original; if(!this.im) { this.ne.selectedInstance.restoreRng(); var tmp = 'javascript:nicImTemp();'; this.ne.nicCommand("insertImage", src); this.im = this.findElm('IMG','src', src); } var w = parseInt(this.ne.selectedInstance.elm.getStyle('width')); if(this.im) { this.im.setAttributes({ src : src, width : (w && options.image.width) ? Math.min(w, options.image.width) : '' }); } } }); nicEditors.registerPlugin(nicPlugin,nicUploadOptions); var nicXHTML = bkClass.extend({ stripAttributes : ['_moz_dirty','_moz_resizing','_extended'], noShort : ['style','title','script','textarea','a'], cssReplace : {'font-weight:bold;' : 'strong', 'font-style:italic;' : 'em'}, sizes : {1 : 'xx-small', 2 : 'x-small', 3 : 'small', 4 : 'medium', 5 : 'large', 6 : 'x-large'}, construct : function(nicEditor) { this.ne = nicEditor; if(this.ne.options.xhtml) { nicEditor.addEvent('get',this.cleanup.closure(this)); } }, cleanup : function(ni) { var node = ni.getElm(); var xhtml = this.toXHTML(node); ni.content = xhtml; }, toXHTML : function(n,r,d) { var txt = ''; var attrTxt = ''; var cssTxt = ''; var nType = n.nodeType; var nName = n.nodeName.toLowerCase(); var nChild = n.hasChildNodes && n.hasChildNodes(); var extraNodes = new Array(); switch(nType) { case 1: var nAttributes = n.attributes; switch(nName) { case 'b': nName = 'strong'; break; case 'i': nName = 'em'; break; case 'font': nName = 'span'; break; } if(r) { for(var i=0;i<nAttributes.length;i++) { var attr = nAttributes[i]; var attributeName = attr.nodeName.toLowerCase(); var attributeValue = attr.nodeValue; if(!attr.specified || !attributeValue || bkLib.inArray(this.stripAttributes,attributeName) || typeof(attributeValue) == "function") { continue; } switch(attributeName) { case 'style': var css = attributeValue.replace(/ /g,""); for(itm in this.cssReplace) { if(css.indexOf(itm) != -1) { extraNodes.push(this.cssReplace[itm]); css = css.replace(itm,''); } } cssTxt += css; attributeValue = ""; break; case 'class': attributeValue = attributeValue.replace("Apple-style-span",""); break; case 'size': cssTxt += "font-size:"+this.sizes[attributeValue]+';'; attributeValue = ""; break; } if(attributeValue) { attrTxt += ' '+attributeName+'="'+attributeValue+'"'; } } if(cssTxt) { attrTxt += ' style="'+cssTxt+'"'; } for(var i=0;i<extraNodes.length;i++) { txt += '<'+extraNodes[i]+'>'; } if(attrTxt == "" && nName == "span") { r = false; } if(r) { txt += '<'+nName; if(nName != 'br') { txt += attrTxt; } } } if(!nChild && !bkLib.inArray(this.noShort,attributeName)) { if(r) { txt += ' />'; } } else { if(r) { txt += '>'; } for(var i=0;i<n.childNodes.length;i++) { var results = this.toXHTML(n.childNodes[i],true,true); if(results) { txt += results; } } } if(r && nChild) { txt += '</'+nName+'>'; } for(var i=0;i<extraNodes.length;i++) { txt += '</'+extraNodes[i]+'>'; } break; case 3: //if(n.nodeValue != '\n') { txt += n.nodeValue; //} break; } return txt; } }); nicEditors.registerPlugin(nicXHTML); var nicBBCode = bkClass.extend({ construct : function(nicEditor) { this.ne = nicEditor; if(this.ne.options.bbCode) { nicEditor.addEvent('get',this.bbGet.closure(this)); nicEditor.addEvent('set',this.bbSet.closure(this)); var loadedPlugins = this.ne.loadedPlugins; for(itm in loadedPlugins) { if(loadedPlugins[itm].toXHTML) { this.xhtml = loadedPlugins[itm]; } } } }, bbGet : function(ni) { var xhtml = this.xhtml.toXHTML(ni.getElm()); ni.content = this.toBBCode(xhtml); }, bbSet : function(ni) { ni.content = this.fromBBCode(ni.content); }, toBBCode : function(xhtml) { function rp(r,m) { xhtml = xhtml.replace(r,m); } rp(/\n/gi,""); rp(/<strong>(.*?)<\/strong>/gi,"[b]$1[/b]"); rp(/<em>(.*?)<\/em>/gi,"[i]$1[/i]"); rp(/<span.*?style="text-decoration:underline;">(.*?)<\/span>/gi,"[u]$1[/u]"); rp(/<ul>(.*?)<\/ul>/gi,"[list]$1[/list]"); rp(/<li>(.*?)<\/li>/gi,"[*]$1[/*]"); rp(/<ol>(.*?)<\/ol>/gi,"[list=1]$1[/list]"); rp(/<img.*?src="(.*?)".*?>/gi,"[img]$1[/img]"); rp(/<a.*?href="(.*?)".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]"); rp(/<br.*?>/gi,"\n"); rp(/<.*?>.*?<\/.*?>/gi,""); return xhtml; }, fromBBCode : function(bbCode) { function rp(r,m) { bbCode = bbCode.replace(r,m); } rp(/\[b\](.*?)\[\/b\]/gi,"<strong>$1</strong>"); rp(/\[i\](.*?)\[\/i\]/gi,"<em>$1</em>"); rp(/\[u\](.*?)\[\/u\]/gi,"<span style=\"text-decoration:underline;\">$1</span>"); rp(/\[list\](.*?)\[\/list\]/gi,"<ul>$1</ul>"); rp(/\[list=1\](.*?)\[\/list\]/gi,"<ol>$1</ol>"); rp(/\[\*\](.*?)\[\/\*\]/gi,"<li>$1</li>"); rp(/\[img\](.*?)\[\/img\]/gi,"<img src=\"$1\" />"); rp(/\[url=(.*?)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>"); rp(/\n/gi,"<br />"); //rp(/\[.*?\](.*?)\[\/.*?\]/gi,"$1"); return bbCode; } }); nicEditors.registerPlugin(nicBBCode); nicEditor = nicEditor.extend({ floatingPanel : function() { this.floating = new bkElement('DIV').setStyle({position: 'absolute', top : '-1000px'}).appendTo(document.body); this.addEvent('focus', this.reposition.closure(this)).addEvent('blur', this.hide.closure(this)); this.setPanel(this.floating); }, reposition : function() { var e = this.selectedInstance.e; this.floating.setStyle({ width : (parseInt(e.getStyle('width')) || e.clientWidth)+'px' }); var top = e.offsetTop-this.floating.offsetHeight; if(top < 0) { top = e.offsetTop+e.offsetHeight; } this.floating.setStyle({ top : top+'px', left : e.offsetLeft+'px', display : 'block' }); }, hide : function() { this.floating.setStyle({ top : '-1000px'}); } }); /* START CONFIG */ var nicCodeOptions = { buttons : { 'xhtml' : {name : 'Edit HTML', type : 'nicCodeButton'} } }; /* END CONFIG */ var nicCodeButton = nicEditorAdvancedButton.extend({ width : '350px', addPane : function() { this.addForm({ '' : {type : 'title', txt : 'Edit HTML'}, 'code' : {type : 'content', 'value' : this.ne.selectedInstance.getContent(), style : {width: '340px', height : '200px'}} }); }, submit : function(e) { var code = this.inputs['code'].value; this.ne.selectedInstance.setContent(code); this.removePane(); } }); nicEditors.registerPlugin(nicPlugin,nicCodeOptions);
Java
/**************************************************************************** * Ralink Tech Inc. * 4F, No. 2 Technology 5th Rd. * Science-based Industrial Park * Hsin-chu, Taiwan, R.O.C. * (c) Copyright 2002, Ralink Technology, Inc. * * All rights reserved. Ralink's source code is an unpublished work and the * use of a copyright notice does not imply otherwise. This source code * contains confidential trade secret material of Ralink Tech. Any attemp * or participation in deciphering, decoding, reverse engineering or in any * way altering the source code is stricitly prohibited, unless the prior * written consent of Ralink Technology, Inc. is obtained. **************************************************************************** Module Name: rt_profile.c Abstract: Revision History: Who When What --------- ---------- ---------------------------------------------- */ #include "rt_config.h" NDIS_STATUS RTMPReadParametersHook( IN PRTMP_ADAPTER pAd) { PSTRING src = NULL; RTMP_OS_FD srcf; RTMP_OS_FS_INFO osFSInfo; INT retval = NDIS_STATUS_FAILURE; PSTRING buffer; buffer = kmalloc(MAX_INI_BUFFER_SIZE, MEM_ALLOC_FLAG); if(buffer == NULL) return NDIS_STATUS_FAILURE; memset(buffer, 0x00, MAX_INI_BUFFER_SIZE); { #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) { src = STA_PROFILE_PATH; } #endif // CONFIG_STA_SUPPORT // #ifdef MULTIPLE_CARD_SUPPORT src = (PSTRING)pAd->MC_FileName; #endif // MULTIPLE_CARD_SUPPORT // } if (src && *src) { RtmpOSFSInfoChange(&osFSInfo, TRUE); srcf = RtmpOSFileOpen(src, O_RDONLY, 0); if (IS_FILE_OPEN_ERR(srcf)) { DBGPRINT(RT_DEBUG_ERROR, ("Open file \"%s\" failed!\n", src)); } else { retval =RtmpOSFileRead(srcf, buffer, MAX_INI_BUFFER_SIZE); if (retval > 0) { RTMPSetProfileParameters(pAd, buffer); retval = NDIS_STATUS_SUCCESS; } else DBGPRINT(RT_DEBUG_ERROR, ("Read file \"%s\" failed(errCode=%d)!\n", src, retval)); retval = RtmpOSFileClose(srcf); if ( retval != 0) { retval = NDIS_STATUS_FAILURE; DBGPRINT(RT_DEBUG_ERROR, ("Close file \"%s\" failed(errCode=%d)!\n", src, retval)); } } RtmpOSFSInfoChange(&osFSInfo, FALSE); } kfree(buffer); return (retval); }
Java
/* main-rc6-test.c */ /* This file is part of the AVR-Crypto-Lib. Copyright (C) 2006-2015 Daniel Otte (bg@nerilex.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 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/>. */ /* * rc6 test-suit * */ #include "main-test-common.h" #include "rc6.h" #include "performance_test.h" #include "bcal-performance.h" #include "bcal-nessie.h" #include "bcal_rc6.h" #define RC6_ROUNDS 20 char *algo_name = "RC6-32/20/16"; const bcdesc_t *const algolist[] PROGMEM = { (bcdesc_t*)&rc6_desc, NULL }; /***************************************************************************** * additional validation-functions * *****************************************************************************/ void rc6_genctx_dummy(uint8_t *key, uint16_t keysize_b, void *ctx){ rc6_initl(key, keysize_b, RC6_ROUNDS, ctx); } void testrun_nessie_rc6(void){ bcal_nessie_multiple(algolist); } void testrun_performance_rc6(void){ bcal_performance_multiple(algolist); } /***************************************************************************** * main * *****************************************************************************/ const char nessie_str[] PROGMEM = "nessie"; const char test_str[] PROGMEM = "test"; const char performance_str[] PROGMEM = "performance"; const char echo_str[] PROGMEM = "echo"; const cmdlist_entry_t cmdlist[] PROGMEM = { { nessie_str, NULL, testrun_nessie_rc6}, { test_str, NULL, testrun_nessie_rc6}, { performance_str, NULL, testrun_performance_rc6}, { echo_str, (void*)1, (void_fpt)echo_ctrl}, { NULL, NULL, NULL} }; int main (void){ main_setup(); for(;;){ welcome_msg(algo_name); cmd_interface(cmdlist); } }
Java
/* * Copyright (C) 2013-2015 Kay Sievers * Copyright (C) 2013-2015 Greg Kroah-Hartman <gregkh@linuxfoundation.org> * Copyright (C) 2013-2015 Daniel Mack <daniel@zonque.org> * Copyright (C) 2013-2015 David Herrmann <dh.herrmann@gmail.com> * Copyright (C) 2013-2015 Linux Foundation * Copyright (C) 2014-2015 Djalal Harouni * * kdbus is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. */ #include <linux/fs.h> #include <linux/hashtable.h> #include <linux/init.h> #include <linux/module.h> #include <linux/random.h> #include <linux/sched.h> #include <linux/sizes.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/uio.h> #include "bus.h" #include "notify.h" #include "connection.h" #include "domain.h" #include "endpoint.h" #include "handle.h" #include "item.h" #include "match.h" #include "message.h" #include "metadata.h" #include "names.h" #include "policy.h" #include "util.h" static void kdbus_bus_free(struct kdbus_node *node) { struct kdbus_bus *bus = container_of(node, struct kdbus_bus, node); WARN_ON(!list_empty(&bus->monitors_list)); WARN_ON(!hash_empty(bus->conn_hash)); kdbus_notify_free(bus); kdbus_user_unref(bus->creator); kdbus_name_registry_free(bus->name_registry); kdbus_domain_unref(bus->domain); kdbus_policy_db_clear(&bus->policy_db); kdbus_meta_proc_unref(bus->creator_meta); kfree(bus); } static void kdbus_bus_release(struct kdbus_node *node, bool was_active) { struct kdbus_bus *bus = container_of(node, struct kdbus_bus, node); if (was_active) atomic_dec(&bus->creator->buses); } static struct kdbus_bus *kdbus_bus_new(struct kdbus_domain *domain, const char *name, struct kdbus_bloom_parameter *bloom, const u64 *pattach_owner, const u64 *pattach_recv, u64 flags, kuid_t uid, kgid_t gid) { struct kdbus_bus *b; u64 attach_owner; u64 attach_recv; int ret; if (bloom->size < 8 || bloom->size > KDBUS_BUS_BLOOM_MAX_SIZE || !KDBUS_IS_ALIGNED8(bloom->size) || bloom->n_hash < 1) return ERR_PTR(-EINVAL); ret = kdbus_sanitize_attach_flags(pattach_recv ? *pattach_recv : 0, &attach_recv); if (ret < 0) return ERR_PTR(ret); ret = kdbus_sanitize_attach_flags(pattach_owner ? *pattach_owner : 0, &attach_owner); if (ret < 0) return ERR_PTR(ret); ret = kdbus_verify_uid_prefix(name, domain->user_namespace, uid); if (ret < 0) return ERR_PTR(ret); b = kzalloc(sizeof(*b), GFP_KERNEL); if (!b) return ERR_PTR(-ENOMEM); kdbus_node_init(&b->node, KDBUS_NODE_BUS); b->node.free_cb = kdbus_bus_free; b->node.release_cb = kdbus_bus_release; b->node.uid = uid; b->node.gid = gid; b->node.mode = S_IRUSR | S_IXUSR; if (flags & (KDBUS_MAKE_ACCESS_GROUP | KDBUS_MAKE_ACCESS_WORLD)) b->node.mode |= S_IRGRP | S_IXGRP; if (flags & KDBUS_MAKE_ACCESS_WORLD) b->node.mode |= S_IROTH | S_IXOTH; b->id = atomic64_inc_return(&domain->last_id); b->bus_flags = flags; b->attach_flags_req = attach_recv; b->attach_flags_owner = attach_owner; generate_random_uuid(b->id128); b->bloom = *bloom; b->domain = kdbus_domain_ref(domain); kdbus_policy_db_init(&b->policy_db); init_rwsem(&b->conn_rwlock); hash_init(b->conn_hash); INIT_LIST_HEAD(&b->monitors_list); INIT_LIST_HEAD(&b->notify_list); spin_lock_init(&b->notify_lock); mutex_init(&b->notify_flush_lock); ret = kdbus_node_link(&b->node, &domain->node, name); if (ret < 0) goto exit_unref; /* cache the metadata/credentials of the creator */ b->creator_meta = kdbus_meta_proc_new(); if (IS_ERR(b->creator_meta)) { ret = PTR_ERR(b->creator_meta); b->creator_meta = NULL; goto exit_unref; } ret = kdbus_meta_proc_collect(b->creator_meta, KDBUS_ATTACH_CREDS | KDBUS_ATTACH_PIDS | KDBUS_ATTACH_AUXGROUPS | KDBUS_ATTACH_TID_COMM | KDBUS_ATTACH_PID_COMM | KDBUS_ATTACH_EXE | KDBUS_ATTACH_CMDLINE | KDBUS_ATTACH_CGROUP | KDBUS_ATTACH_CAPS | KDBUS_ATTACH_SECLABEL | KDBUS_ATTACH_AUDIT); if (ret < 0) goto exit_unref; b->name_registry = kdbus_name_registry_new(); if (IS_ERR(b->name_registry)) { ret = PTR_ERR(b->name_registry); b->name_registry = NULL; goto exit_unref; } /* * Bus-limits of the creator are accounted on its real UID, just like * all other per-user limits. */ b->creator = kdbus_user_lookup(domain, current_uid()); if (IS_ERR(b->creator)) { ret = PTR_ERR(b->creator); b->creator = NULL; goto exit_unref; } return b; exit_unref: kdbus_node_deactivate(&b->node); kdbus_node_unref(&b->node); return ERR_PTR(ret); } /** * kdbus_bus_ref() - increase the reference counter of a kdbus_bus * @bus: The bus to reference * * Every user of a bus, except for its creator, must add a reference to the * kdbus_bus using this function. * * Return: the bus itself */ struct kdbus_bus *kdbus_bus_ref(struct kdbus_bus *bus) { if (bus) kdbus_node_ref(&bus->node); return bus; } /** * kdbus_bus_unref() - decrease the reference counter of a kdbus_bus * @bus: The bus to unref * * Release a reference. If the reference count drops to 0, the bus will be * freed. * * Return: NULL */ struct kdbus_bus *kdbus_bus_unref(struct kdbus_bus *bus) { if (bus) kdbus_node_unref(&bus->node); return NULL; } /** * kdbus_bus_find_conn_by_id() - find a connection with a given id * @bus: The bus to look for the connection * @id: The 64-bit connection id * * Looks up a connection with a given id. The returned connection * is ref'ed, and needs to be unref'ed by the user. Returns NULL if * the connection can't be found. */ struct kdbus_conn *kdbus_bus_find_conn_by_id(struct kdbus_bus *bus, u64 id) { struct kdbus_conn *conn, *found = NULL; down_read(&bus->conn_rwlock); hash_for_each_possible(bus->conn_hash, conn, hentry, id) if (conn->id == id) { found = kdbus_conn_ref(conn); break; } up_read(&bus->conn_rwlock); return found; } /** * kdbus_bus_broadcast() - send a message to all subscribed connections * @bus: The bus the connections are connected to * @conn_src: The source connection, may be %NULL for kernel notifications * @kmsg: The message to send. * * Send @kmsg to all connections that are currently active on the bus. * Connections must still have matches installed in order to let the message * pass. * * The caller must hold the name-registry lock of @bus. */ void kdbus_bus_broadcast(struct kdbus_bus *bus, struct kdbus_conn *conn_src, struct kdbus_kmsg *kmsg) { struct kdbus_conn *conn_dst; unsigned int i; int ret; lockdep_assert_held(&bus->name_registry->rwlock); /* * Make sure broadcast are queued on monitors before we send it out to * anyone else. Otherwise, connections might react to broadcasts before * the monitor gets the broadcast queued. In the worst case, the * monitor sees a reaction to the broadcast before the broadcast itself. * We don't give ordering guarantees across connections (and monitors * can re-construct order via sequence numbers), but we should at least * try to avoid re-ordering for monitors. */ kdbus_bus_eavesdrop(bus, conn_src, kmsg); down_read(&bus->conn_rwlock); hash_for_each(bus->conn_hash, i, conn_dst, hentry) { if (conn_dst->id == kmsg->msg.src_id) continue; if (!kdbus_conn_is_ordinary(conn_dst)) continue; /* * Check if there is a match for the kmsg object in * the destination connection match db */ if (!kdbus_match_db_match_kmsg(conn_dst->match_db, conn_src, kmsg)) continue; if (conn_src) { /* * Anyone can send broadcasts, as they have no * destination. But a receiver needs TALK access to * the sender in order to receive broadcasts. */ if (!kdbus_conn_policy_talk(conn_dst, NULL, conn_src)) continue; ret = kdbus_kmsg_collect_metadata(kmsg, conn_src, conn_dst); if (ret < 0) { kdbus_conn_lost_message(conn_dst); continue; } } else { /* * Check if there is a policy db that prevents the * destination connection from receiving this kernel * notification */ if (!kdbus_conn_policy_see_notification(conn_dst, NULL, kmsg)) continue; } ret = kdbus_conn_entry_insert(conn_src, conn_dst, kmsg, NULL); if (ret < 0) kdbus_conn_lost_message(conn_dst); } up_read(&bus->conn_rwlock); } /** * kdbus_bus_eavesdrop() - send a message to all subscribed monitors * @bus: The bus the monitors are connected to * @conn_src: The source connection, may be %NULL for kernel notifications * @kmsg: The message to send. * * Send @kmsg to all monitors that are currently active on the bus. Monitors * must still have matches installed in order to let the message pass. * * The caller must hold the name-registry lock of @bus. */ void kdbus_bus_eavesdrop(struct kdbus_bus *bus, struct kdbus_conn *conn_src, struct kdbus_kmsg *kmsg) { struct kdbus_conn *conn_dst; int ret; /* * Monitor connections get all messages; ignore possible errors * when sending messages to monitor connections. */ lockdep_assert_held(&bus->name_registry->rwlock); down_read(&bus->conn_rwlock); list_for_each_entry(conn_dst, &bus->monitors_list, monitor_entry) { if (conn_src) { ret = kdbus_kmsg_collect_metadata(kmsg, conn_src, conn_dst); if (ret < 0) { kdbus_conn_lost_message(conn_dst); continue; } } ret = kdbus_conn_entry_insert(conn_src, conn_dst, kmsg, NULL); if (ret < 0) kdbus_conn_lost_message(conn_dst); } up_read(&bus->conn_rwlock); } /** * kdbus_cmd_bus_make() - handle KDBUS_CMD_BUS_MAKE * @domain: domain to operate on * @argp: command payload * * Return: NULL or newly created bus on success, ERR_PTR on failure. */ struct kdbus_bus *kdbus_cmd_bus_make(struct kdbus_domain *domain, void __user *argp) { struct kdbus_bus *bus = NULL; struct kdbus_cmd *cmd; struct kdbus_ep *ep = NULL; int ret; struct kdbus_arg argv[] = { { .type = KDBUS_ITEM_NEGOTIATE }, { .type = KDBUS_ITEM_MAKE_NAME, .mandatory = true }, { .type = KDBUS_ITEM_BLOOM_PARAMETER, .mandatory = true }, { .type = KDBUS_ITEM_ATTACH_FLAGS_SEND }, { .type = KDBUS_ITEM_ATTACH_FLAGS_RECV }, }; struct kdbus_args args = { .allowed_flags = KDBUS_FLAG_NEGOTIATE | KDBUS_MAKE_ACCESS_GROUP | KDBUS_MAKE_ACCESS_WORLD, .argv = argv, .argc = ARRAY_SIZE(argv), }; ret = kdbus_args_parse(&args, argp, &cmd); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; bus = kdbus_bus_new(domain, argv[1].item->str, &argv[2].item->bloom_parameter, argv[3].item ? argv[3].item->data64 : NULL, argv[4].item ? argv[4].item->data64 : NULL, cmd->flags, current_euid(), current_egid()); if (IS_ERR(bus)) { ret = PTR_ERR(bus); bus = NULL; goto exit; } if (atomic_inc_return(&bus->creator->buses) > KDBUS_USER_MAX_BUSES) { atomic_dec(&bus->creator->buses); ret = -EMFILE; goto exit; } if (!kdbus_node_activate(&bus->node)) { atomic_dec(&bus->creator->buses); ret = -ESHUTDOWN; goto exit; } ep = kdbus_ep_new(bus, "bus", cmd->flags, bus->node.uid, bus->node.gid, false); if (IS_ERR(ep)) { ret = PTR_ERR(ep); ep = NULL; goto exit; } if (!kdbus_node_activate(&ep->node)) { ret = -ESHUTDOWN; goto exit; } /* * Drop our own reference, effectively causing the endpoint to be * deactivated and released when the parent bus is. */ ep = kdbus_ep_unref(ep); exit: ret = kdbus_args_clear(&args, ret); if (ret < 0) { if (ep) { kdbus_node_deactivate(&ep->node); kdbus_ep_unref(ep); } if (bus) { kdbus_node_deactivate(&bus->node); kdbus_bus_unref(bus); } return ERR_PTR(ret); } return bus; } /** * kdbus_cmd_bus_creator_info() - handle KDBUS_CMD_BUS_CREATOR_INFO * @conn: connection to operate on * @argp: command payload * * Return: >=0 on success, negative error code on failure. */ int kdbus_cmd_bus_creator_info(struct kdbus_conn *conn, void __user *argp) { struct kdbus_cmd_info *cmd; struct kdbus_bus *bus = conn->ep->bus; struct kdbus_pool_slice *slice = NULL; struct kdbus_item_header item_hdr; struct kdbus_info info = {}; size_t meta_size, name_len; struct kvec kvec[5]; u64 hdr_size = 0; u64 attach_flags; size_t cnt = 0; int ret; struct kdbus_arg argv[] = { { .type = KDBUS_ITEM_NEGOTIATE }, }; struct kdbus_args args = { .allowed_flags = KDBUS_FLAG_NEGOTIATE, .argv = argv, .argc = ARRAY_SIZE(argv), }; ret = kdbus_args_parse(&args, argp, &cmd); if (ret != 0) return ret; ret = kdbus_sanitize_attach_flags(cmd->attach_flags, &attach_flags); if (ret < 0) goto exit; attach_flags &= bus->attach_flags_owner; ret = kdbus_meta_export_prepare(bus->creator_meta, NULL, &attach_flags, &meta_size); if (ret < 0) goto exit; name_len = strlen(bus->node.name) + 1; info.id = bus->id; info.flags = bus->bus_flags; item_hdr.type = KDBUS_ITEM_MAKE_NAME; item_hdr.size = KDBUS_ITEM_HEADER_SIZE + name_len; kdbus_kvec_set(&kvec[cnt++], &info, sizeof(info), &hdr_size); kdbus_kvec_set(&kvec[cnt++], &item_hdr, sizeof(item_hdr), &hdr_size); kdbus_kvec_set(&kvec[cnt++], bus->node.name, name_len, &hdr_size); cnt += !!kdbus_kvec_pad(&kvec[cnt], &hdr_size); slice = kdbus_pool_slice_alloc(conn->pool, hdr_size + meta_size, false); if (IS_ERR(slice)) { ret = PTR_ERR(slice); slice = NULL; goto exit; } ret = kdbus_meta_export(bus->creator_meta, NULL, attach_flags, slice, hdr_size, &meta_size); if (ret < 0) goto exit; info.size = hdr_size + meta_size; ret = kdbus_pool_slice_copy_kvec(slice, 0, kvec, cnt, hdr_size); if (ret < 0) goto exit; kdbus_pool_slice_publish(slice, &cmd->offset, &cmd->info_size); if (kdbus_member_set_user(&cmd->offset, argp, typeof(*cmd), offset) || kdbus_member_set_user(&cmd->info_size, argp, typeof(*cmd), info_size)) ret = -EFAULT; exit: kdbus_pool_slice_release(slice); return kdbus_args_clear(&args, ret); }
Java
/* ==================================================================== * 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 org.apache.jcc; public class PythonVM { static protected PythonVM vm; static { System.loadLibrary("jcc"); } static public PythonVM start(String programName, String[] args) { if (vm == null) { vm = new PythonVM(); vm.init(programName, args); } return vm; } static public PythonVM start(String programName) { return start(programName, null); } static public PythonVM get() { return vm; } protected PythonVM() { } protected native void init(String programName, String[] args); public native Object instantiate(String moduleName, String className) throws PythonException; }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.commons.math.analysis.interpolation; import org.apache.commons.math.MathException; import org.apache.commons.math.exception.NonMonotonousSequenceException; import org.apache.commons.math.exception.DimensionMismatchException; import org.apache.commons.math.exception.NumberIsTooSmallException; import org.apache.commons.math.TestUtils; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.analysis.polynomials.PolynomialFunction; import org.apache.commons.math.analysis.polynomials.PolynomialSplineFunction; import org.junit.Assert; import org.junit.Test; /** * Test the LinearInterpolator. */ public class LinearInterpolatorTest { /** error tolerance for spline interpolator value at knot points */ protected double knotTolerance = 1E-12; /** error tolerance for interpolating polynomial coefficients */ protected double coefficientTolerance = 1E-6; /** error tolerance for interpolated values */ protected double interpolationTolerance = 1E-12; @Test public void testInterpolateLinearDegenerateTwoSegment() throws Exception { double x[] = { 0.0, 0.5, 1.0 }; double y[] = { 0.0, 0.5, 1.0 }; UnivariateRealInterpolator i = new LinearInterpolator(); UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1d}; TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance); target = new double[]{y[1], 1d}; TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); // Check interpolation Assert.assertEquals(0.0,f.value(0.0), interpolationTolerance); Assert.assertEquals(0.4,f.value(0.4), interpolationTolerance); Assert.assertEquals(1.0,f.value(1.0), interpolationTolerance); } @Test public void testInterpolateLinearDegenerateThreeSegment() throws Exception { double x[] = { 0.0, 0.5, 1.0, 1.5 }; double y[] = { 0.0, 0.5, 1.0, 1.5 }; UnivariateRealInterpolator i = new LinearInterpolator(); UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1d}; TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance); target = new double[]{y[1], 1d}; TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); target = new double[]{y[2], 1d}; TestUtils.assertEquals(polynomials[2].getCoefficients(), target, coefficientTolerance); // Check interpolation Assert.assertEquals(0,f.value(0), interpolationTolerance); Assert.assertEquals(1.4,f.value(1.4), interpolationTolerance); Assert.assertEquals(1.5,f.value(1.5), interpolationTolerance); } @Test public void testInterpolateLinear() throws Exception { double x[] = { 0.0, 0.5, 1.0 }; double y[] = { 0.0, 0.5, 0.0 }; UnivariateRealInterpolator i = new LinearInterpolator(); UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1d}; TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance); target = new double[]{y[1], -1d}; TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); } @Test public void testIllegalArguments() throws MathException { // Data set arrays of different size. UnivariateRealInterpolator i = new LinearInterpolator(); try { double xval[] = { 0.0, 1.0 }; double yval[] = { 0.0, 1.0, 2.0 }; i.interpolate(xval, yval); Assert.fail("Failed to detect data set array with different sizes."); } catch (DimensionMismatchException iae) { // Expected. } // X values not sorted. try { double xval[] = { 0.0, 1.0, 0.5 }; double yval[] = { 0.0, 1.0, 2.0 }; i.interpolate(xval, yval); Assert.fail("Failed to detect unsorted arguments."); } catch (NonMonotonousSequenceException iae) { // Expected. } // Not enough data to interpolate. try { double xval[] = { 0.0 }; double yval[] = { 0.0 }; i.interpolate(xval, yval); Assert.fail("Failed to detect unsorted arguments."); } catch (NumberIsTooSmallException iae) { // Expected. } } /** * verifies that f(x[i]) = y[i] for i = 0..n-1 where n is common length. */ protected void verifyInterpolation(UnivariateRealFunction f, double x[], double y[]) throws Exception{ for (int i = 0; i < x.length; i++) { Assert.assertEquals(f.value(x[i]), y[i], knotTolerance); } } }
Java
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 CoNWeT Lab., Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Wirecloud 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 # along with Wirecloud. If not, see <http://www.gnu.org/licenses/>. from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation import ugettext as _ class Application(models.Model): client_id = models.CharField(_('Client ID'), max_length=40, blank=False, primary_key=True) client_secret = models.CharField(_('Client secret'), max_length=40, blank=False) name = models.CharField(_('Application Name'), max_length=40, blank=False) home_url = models.CharField(_('URL'), max_length=255, blank=False) redirect_uri = models.CharField(_('Redirect URI'), max_length=255, blank=True) def __unicode__(self): return unicode(self.client_id) class Code(models.Model): client = models.ForeignKey(Application) user = models.ForeignKey(User) scope = models.CharField(_('Scope'), max_length=255, blank=True) code = models.CharField(_('Code'), max_length=255, blank=False) creation_timestamp = models.CharField(_('Creation timestamp'), max_length=40, blank=False) expires_in = models.CharField(_('Expires in'), max_length=40, blank=True) class Meta: unique_together = ('client', 'code') def __unicode__(self): return unicode(self.code) class Token(models.Model): token = models.CharField(_('Token'), max_length=40, blank=False, primary_key=True) client = models.ForeignKey(Application) user = models.ForeignKey(User) scope = models.CharField(_('Scope'), max_length=255, blank=True) token_type = models.CharField(_('Token type'), max_length=10, blank=False) refresh_token = models.CharField(_('Refresh token'), max_length=40, blank=True) creation_timestamp = models.CharField(_('Creation timestamp'), max_length=40, blank=False) expires_in = models.CharField(_('Expires in'), max_length=40, blank=True) def __unicode__(self): return unicode(self.token) @receiver(post_save, sender=Application) def invalidate_tokens_on_change(sender, instance, created, raw, **kwargs): if created is False: instance.token_set.all().update(creation_timestamp='0')
Java
/////////////////////////////////////////////////////////////////////////////// // Name: wx/osx/popupwin.h // Purpose: wxPopupWindow class for wxMac // Author: Stefan Csomor // Modified by: // Created: // RCS-ID: $Id: popupwin.h 65680 2010-09-30 11:44:45Z VZ $ // Copyright: (c) 2006 Stefan Csomor // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef _WX_MAC_POPUPWIN_H_ #define _WX_MAC_POPUPWIN_H_ // ---------------------------------------------------------------------------- // wxPopupWindow // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxPopupWindow : public wxPopupWindowBase { public: wxPopupWindow() { } ~wxPopupWindow(); wxPopupWindow(wxWindow *parent, int flags = wxBORDER_NONE) { (void)Create(parent, flags); } bool Create(wxWindow *parent, int flags = wxBORDER_NONE); virtual bool Show(bool show); protected: DECLARE_DYNAMIC_CLASS_NO_COPY(wxPopupWindow) }; #endif // _WX_MAC_POPUPWIN_H_
Java
/* * CPUFreq sakuractive governor * * Copyright (C) 2011 sakuramilk <c.sakuramilk@gmail.com> * * Based on hotplug governor * Copyright (C) 2010 Texas Instruments, Inc. * Mike Turquette <mturquette@ti.com> * Santosh Shilimkar <santosh.shilimkar@ti.com> * * Based on ondemand governor * Copyright (C) 2001 Russell King * (C) 2003 Venkatesh Pallipadi <venkatesh.pallipadi@intel.com>, * Jun Nakajima <jun.nakajima@intel.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/cpufreq.h> #include <linux/cpu.h> #include <linux/jiffies.h> #include <linux/kernel_stat.h> #include <linux/mutex.h> #include <linux/hrtimer.h> #include <linux/tick.h> #include <linux/ktime.h> #include <linux/sched.h> #include <linux/err.h> #include <linux/slab.h> /* greater than 80% avg load across online CPUs increases frequency */ #define DEFAULT_UP_FREQ_MIN_LOAD (85) /* Keep 10% of idle under the up threshold when decreasing the frequency */ #define DEFAULT_FREQ_DOWN_DIFFERENTIAL (10) /* less than 20% avg load across online CPUs decreases frequency */ #define DEFAULT_DOWN_FREQ_MAX_LOAD (17) /* default sampling period (uSec) is bogus; 10x ondemand's default for x86 */ #define DEFAULT_SAMPLING_PERIOD (100000) /* default number of sampling periods to average before hotplug-in decision */ #define DEFAULT_HOTPLUG_IN_SAMPLING_PERIODS (5) /* default number of sampling periods to average before hotplug-out decision */ #define DEFAULT_HOTPLUG_OUT_SAMPLING_PERIODS (10) static void do_dbs_timer(struct work_struct *work); static int cpufreq_governor_dbs(struct cpufreq_policy *policy, unsigned int event); //static int hotplug_boost(struct cpufreq_policy *policy); #ifndef CONFIG_CPU_FREQ_DEFAULT_GOV_SAKURACTIVE static #endif struct cpufreq_governor cpufreq_gov_sakuractive = { .name = "sakuractive", .governor = cpufreq_governor_dbs, .owner = THIS_MODULE, }; struct cpu_dbs_info_s { cputime64_t prev_cpu_idle; cputime64_t prev_cpu_wall; cputime64_t prev_cpu_nice; struct cpufreq_policy *cur_policy; struct delayed_work work; struct work_struct cpu_up_work; struct work_struct cpu_down_work; struct cpufreq_frequency_table *freq_table; int cpu; unsigned int boost_applied; /* * percpu mutex that serializes governor limit change with * do_dbs_timer invocation. We do not want do_dbs_timer to run * when user is changing the governor or limits. */ struct mutex timer_mutex; }; static DEFINE_PER_CPU(struct cpu_dbs_info_s, hp_cpu_dbs_info); static unsigned int dbs_enable; /* number of CPUs using this policy */ /* * dbs_mutex protects data in dbs_tuners_ins from concurrent changes on * different CPUs. It protects dbs_enable in governor start/stop. */ static DEFINE_MUTEX(dbs_mutex); static struct workqueue_struct *khotplug_wq; static struct dbs_tuners { unsigned int sampling_rate; unsigned int up_threshold; unsigned int down_differential; unsigned int down_threshold; unsigned int hotplug_in_sampling_periods; unsigned int hotplug_out_sampling_periods; unsigned int hotplug_load_index; unsigned int *hotplug_load_history; unsigned int ignore_nice; unsigned int io_is_busy; unsigned int boost_timeout; } dbs_tuners_ins = { .sampling_rate = DEFAULT_SAMPLING_PERIOD, .up_threshold = DEFAULT_UP_FREQ_MIN_LOAD, .down_differential = DEFAULT_FREQ_DOWN_DIFFERENTIAL, .down_threshold = DEFAULT_DOWN_FREQ_MAX_LOAD, .hotplug_in_sampling_periods = DEFAULT_HOTPLUG_IN_SAMPLING_PERIODS, .hotplug_out_sampling_periods = DEFAULT_HOTPLUG_OUT_SAMPLING_PERIODS, .hotplug_load_index = 0, .ignore_nice = 0, .io_is_busy = 0, .boost_timeout = 0, }; /* * A corner case exists when switching io_is_busy at run-time: comparing idle * times from a non-io_is_busy period to an io_is_busy period (or vice-versa) * will misrepresent the actual change in system idleness. We ignore this * corner case: enabling io_is_busy might cause freq increase and disabling * might cause freq decrease, which probably matches the original intent. */ static inline cputime64_t get_cpu_idle_time(unsigned int cpu, cputime64_t *wall) { u64 idle_time; u64 iowait_time; /* cpufreq-sakuractive always assumes CONFIG_NO_HZ */ idle_time = get_cpu_idle_time_us(cpu, wall); /* add time spent doing I/O to idle time */ if (dbs_tuners_ins.io_is_busy) { iowait_time = get_cpu_iowait_time_us(cpu, wall); /* cpufreq-sakuractive always assumes CONFIG_NO_HZ */ if (iowait_time != -1ULL && idle_time >= iowait_time) idle_time -= iowait_time; } return idle_time; } /************************** sysfs interface ************************/ /* XXX look at global sysfs macros in cpufreq.h, can those be used here? */ /* cpufreq_sakuractive Governor Tunables */ #define show_one(file_name, object) \ static ssize_t show_##file_name \ (struct kobject *kobj, struct attribute *attr, char *buf) \ { \ return sprintf(buf, "%u\n", dbs_tuners_ins.object); \ } show_one(sampling_rate, sampling_rate); show_one(up_threshold, up_threshold); show_one(down_differential, down_differential); show_one(down_threshold, down_threshold); show_one(hotplug_in_sampling_periods, hotplug_in_sampling_periods); show_one(hotplug_out_sampling_periods, hotplug_out_sampling_periods); show_one(ignore_nice_load, ignore_nice); show_one(io_is_busy, io_is_busy); show_one(boost_timeout, boost_timeout); static ssize_t store_boost_timeout(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; mutex_lock(&dbs_mutex); dbs_tuners_ins.boost_timeout = input; mutex_unlock(&dbs_mutex); return count; } static ssize_t store_sampling_rate(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; mutex_lock(&dbs_mutex); dbs_tuners_ins.sampling_rate = input; mutex_unlock(&dbs_mutex); return count; } static ssize_t store_up_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1 || input <= dbs_tuners_ins.down_threshold) { return -EINVAL; } mutex_lock(&dbs_mutex); dbs_tuners_ins.up_threshold = input; mutex_unlock(&dbs_mutex); return count; } static ssize_t store_down_differential(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1 || input >= dbs_tuners_ins.up_threshold) return -EINVAL; mutex_lock(&dbs_mutex); dbs_tuners_ins.down_differential = input; mutex_unlock(&dbs_mutex); return count; } static ssize_t store_down_threshold(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1 || input >= dbs_tuners_ins.up_threshold) { return -EINVAL; } mutex_lock(&dbs_mutex); dbs_tuners_ins.down_threshold = input; mutex_unlock(&dbs_mutex); return count; } static ssize_t store_hotplug_in_sampling_periods(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; unsigned int *temp; unsigned int max_windows; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; /* already using this value, bail out */ if (input == dbs_tuners_ins.hotplug_in_sampling_periods) return count; mutex_lock(&dbs_mutex); ret = count; max_windows = max(dbs_tuners_ins.hotplug_in_sampling_periods, dbs_tuners_ins.hotplug_out_sampling_periods); /* no need to resize array */ if (input <= max_windows) { dbs_tuners_ins.hotplug_in_sampling_periods = input; goto out; } /* resize array */ temp = kmalloc((sizeof(unsigned int) * input), GFP_KERNEL); if (!temp || IS_ERR(temp)) { ret = -ENOMEM; goto out; } memcpy(temp, dbs_tuners_ins.hotplug_load_history, (max_windows * sizeof(unsigned int))); kfree(dbs_tuners_ins.hotplug_load_history); /* replace old buffer, old number of sampling periods & old index */ dbs_tuners_ins.hotplug_load_history = temp; dbs_tuners_ins.hotplug_in_sampling_periods = input; dbs_tuners_ins.hotplug_load_index = max_windows; out: mutex_unlock(&dbs_mutex); return ret; } static ssize_t store_hotplug_out_sampling_periods(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; unsigned int *temp; unsigned int max_windows; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; /* already using this value, bail out */ if (input == dbs_tuners_ins.hotplug_out_sampling_periods) return count; mutex_lock(&dbs_mutex); ret = count; max_windows = max(dbs_tuners_ins.hotplug_in_sampling_periods, dbs_tuners_ins.hotplug_out_sampling_periods); /* no need to resize array */ if (input <= max_windows) { dbs_tuners_ins.hotplug_out_sampling_periods = input; goto out; } /* resize array */ temp = kmalloc((sizeof(unsigned int) * input), GFP_KERNEL); if (!temp || IS_ERR(temp)) { ret = -ENOMEM; goto out; } memcpy(temp, dbs_tuners_ins.hotplug_load_history, (max_windows * sizeof(unsigned int))); kfree(dbs_tuners_ins.hotplug_load_history); /* replace old buffer, old number of sampling periods & old index */ dbs_tuners_ins.hotplug_load_history = temp; dbs_tuners_ins.hotplug_out_sampling_periods = input; dbs_tuners_ins.hotplug_load_index = max_windows; out: mutex_unlock(&dbs_mutex); return ret; } static ssize_t store_ignore_nice_load(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; unsigned int j; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; if (input > 1) input = 1; mutex_lock(&dbs_mutex); if (input == dbs_tuners_ins.ignore_nice) { /* nothing to do */ mutex_unlock(&dbs_mutex); return count; } dbs_tuners_ins.ignore_nice = input; /* we need to re-evaluate prev_cpu_idle */ for_each_online_cpu(j) { struct cpu_dbs_info_s *dbs_info; dbs_info = &per_cpu(hp_cpu_dbs_info, j); dbs_info->prev_cpu_idle = get_cpu_idle_time(j, &dbs_info->prev_cpu_wall); if (dbs_tuners_ins.ignore_nice) dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice; } mutex_unlock(&dbs_mutex); return count; } static ssize_t store_io_is_busy(struct kobject *a, struct attribute *b, const char *buf, size_t count) { unsigned int input; int ret; ret = sscanf(buf, "%u", &input); if (ret != 1) return -EINVAL; mutex_lock(&dbs_mutex); dbs_tuners_ins.io_is_busy = !!input; mutex_unlock(&dbs_mutex); return count; } define_one_global_rw(sampling_rate); define_one_global_rw(up_threshold); define_one_global_rw(down_differential); define_one_global_rw(down_threshold); define_one_global_rw(hotplug_in_sampling_periods); define_one_global_rw(hotplug_out_sampling_periods); define_one_global_rw(ignore_nice_load); define_one_global_rw(io_is_busy); define_one_global_rw(boost_timeout); static struct attribute *dbs_attributes[] = { &sampling_rate.attr, &up_threshold.attr, &down_differential.attr, &down_threshold.attr, &hotplug_in_sampling_periods.attr, &hotplug_out_sampling_periods.attr, &ignore_nice_load.attr, &io_is_busy.attr, &boost_timeout.attr, NULL }; static struct attribute_group dbs_attr_group = { .attrs = dbs_attributes, .name = "sakuractive", }; /************************** sysfs end ************************/ static void dbs_check_cpu(struct cpu_dbs_info_s *this_dbs_info) { /* combined load of all enabled CPUs */ unsigned int total_load = 0; /* single largest CPU load percentage*/ unsigned int max_load = 0; /* largest CPU load in terms of frequency */ unsigned int max_load_freq = 0; /* average load across all enabled CPUs */ unsigned int avg_load = 0; /* average load across multiple sampling periods for hotplug events */ unsigned int hotplug_in_avg_load = 0; unsigned int hotplug_out_avg_load = 0; /* number of sampling periods averaged for hotplug decisions */ unsigned int periods; struct cpufreq_policy *policy; unsigned int i, j; policy = this_dbs_info->cur_policy; /* * cpu load accounting * get highest load, total load and average load across all CPUs */ for_each_cpu(j, policy->cpus) { unsigned int load; unsigned int idle_time, wall_time; cputime64_t cur_wall_time, cur_idle_time; struct cpu_dbs_info_s *j_dbs_info; j_dbs_info = &per_cpu(hp_cpu_dbs_info, j); /* update both cur_idle_time and cur_wall_time */ cur_idle_time = get_cpu_idle_time(j, &cur_wall_time); /* how much wall time has passed since last iteration? */ wall_time = (unsigned int) cputime64_sub(cur_wall_time, j_dbs_info->prev_cpu_wall); j_dbs_info->prev_cpu_wall = cur_wall_time; /* how much idle time has passed since last iteration? */ idle_time = (unsigned int) cputime64_sub(cur_idle_time, j_dbs_info->prev_cpu_idle); j_dbs_info->prev_cpu_idle = cur_idle_time; if (unlikely(!wall_time || wall_time < idle_time)) continue; /* load is the percentage of time not spent in idle */ load = 100 * (wall_time - idle_time) / wall_time; /* keep track of combined load across all CPUs */ total_load += load; /* keep track of highest single load across all CPUs */ if (load > max_load) max_load = load; } /* use the max load in the OPP freq change policy */ max_load_freq = max_load * policy->cur; /* calculate the average load across all related CPUs */ avg_load = total_load / num_online_cpus(); mutex_lock(&dbs_mutex); /* * hotplug load accounting * average load over multiple sampling periods */ /* how many sampling periods do we use for hotplug decisions? */ periods = max(dbs_tuners_ins.hotplug_in_sampling_periods, dbs_tuners_ins.hotplug_out_sampling_periods); /* store avg_load in the circular buffer */ dbs_tuners_ins.hotplug_load_history[dbs_tuners_ins.hotplug_load_index] = avg_load; /* compute average load across in & out sampling periods */ for (i = 0, j = dbs_tuners_ins.hotplug_load_index; i < periods; i++, j--) { if (i < dbs_tuners_ins.hotplug_in_sampling_periods) hotplug_in_avg_load += dbs_tuners_ins.hotplug_load_history[j]; if (i < dbs_tuners_ins.hotplug_out_sampling_periods) hotplug_out_avg_load += dbs_tuners_ins.hotplug_load_history[j]; if (j == 0) j = periods; } hotplug_in_avg_load = hotplug_in_avg_load / dbs_tuners_ins.hotplug_in_sampling_periods; hotplug_out_avg_load = hotplug_out_avg_load / dbs_tuners_ins.hotplug_out_sampling_periods; /* return to first element if we're at the circular buffer's end */ if (++dbs_tuners_ins.hotplug_load_index == periods) dbs_tuners_ins.hotplug_load_index = 0; /* check if auxiliary CPU is needed based on avg_load */ if (avg_load > dbs_tuners_ins.up_threshold) { /* should we enable auxillary CPUs? */ if (num_online_cpus() < 2 && hotplug_in_avg_load > dbs_tuners_ins.up_threshold) { queue_work_on(this_dbs_info->cpu, khotplug_wq, &this_dbs_info->cpu_up_work); goto out; } } /* check for frequency increase based on max_load */ if (max_load > dbs_tuners_ins.up_threshold) { /* increase to highest frequency supported */ if (policy->cur < policy->max) __cpufreq_driver_target(policy, policy->max, CPUFREQ_RELATION_H); goto out; } /* check for frequency decrease */ if (avg_load < dbs_tuners_ins.down_threshold) { /* are we at the minimum frequency already? */ if (policy->cur <= policy->min) { /* should we disable auxillary CPUs? */ if (num_online_cpus() > 1 && hotplug_out_avg_load < dbs_tuners_ins.down_threshold) { queue_work_on(this_dbs_info->cpu, khotplug_wq, &this_dbs_info->cpu_down_work); } goto out; } } /* * go down to the lowest frequency which can sustain the load by * keeping 30% of idle in order to not cross the up_threshold */ if ((max_load_freq < (dbs_tuners_ins.up_threshold - dbs_tuners_ins.down_differential) * policy->cur) && (policy->cur > policy->min)) { unsigned int freq_next; freq_next = max_load_freq / (dbs_tuners_ins.up_threshold - dbs_tuners_ins.down_differential); if (freq_next < policy->min) freq_next = policy->min; __cpufreq_driver_target(policy, freq_next, CPUFREQ_RELATION_L); } out: mutex_unlock(&dbs_mutex); return; } static void do_cpu_up(struct work_struct *work) { cpu_up(1); } static void do_cpu_down(struct work_struct *work) { cpu_down(1); } static void do_dbs_timer(struct work_struct *work) { struct cpu_dbs_info_s *dbs_info = container_of(work, struct cpu_dbs_info_s, work.work); unsigned int cpu = dbs_info->cpu; int delay = 0; mutex_lock(&dbs_info->timer_mutex); if (!dbs_info->boost_applied) { dbs_check_cpu(dbs_info); /* We want all related CPUs to do sampling nearly on same jiffy */ delay = usecs_to_jiffies(dbs_tuners_ins.sampling_rate); } else { delay = usecs_to_jiffies(dbs_tuners_ins.boost_timeout); dbs_info->boost_applied = 0; if (num_online_cpus() < 2) queue_work_on(cpu, khotplug_wq, &dbs_info->cpu_up_work); } queue_delayed_work_on(cpu, khotplug_wq, &dbs_info->work, delay); mutex_unlock(&dbs_info->timer_mutex); } static inline void dbs_timer_init(struct cpu_dbs_info_s *dbs_info) { /* We want all related CPUs to do sampling nearly on same jiffy */ int delay = usecs_to_jiffies(dbs_tuners_ins.sampling_rate); delay -= jiffies % delay; INIT_DELAYED_WORK_DEFERRABLE(&dbs_info->work, do_dbs_timer); INIT_WORK(&dbs_info->cpu_up_work, do_cpu_up); INIT_WORK(&dbs_info->cpu_down_work, do_cpu_down); if (!dbs_info->boost_applied) delay = usecs_to_jiffies(dbs_tuners_ins.boost_timeout); queue_delayed_work_on(dbs_info->cpu, khotplug_wq, &dbs_info->work, delay); } static inline void dbs_timer_exit(struct cpu_dbs_info_s *dbs_info) { cancel_delayed_work_sync(&dbs_info->work); } static int cpufreq_governor_dbs(struct cpufreq_policy *policy, unsigned int event) { unsigned int cpu = policy->cpu; struct cpu_dbs_info_s *this_dbs_info; unsigned int i, j, max_periods; int rc; this_dbs_info = &per_cpu(hp_cpu_dbs_info, cpu); switch (event) { case CPUFREQ_GOV_START: if ((!cpu_online(cpu)) || (!policy->cur)) return -EINVAL; mutex_lock(&dbs_mutex); dbs_enable++; for_each_cpu(j, policy->cpus) { struct cpu_dbs_info_s *j_dbs_info; j_dbs_info = &per_cpu(hp_cpu_dbs_info, j); j_dbs_info->cur_policy = policy; j_dbs_info->prev_cpu_idle = get_cpu_idle_time(j, &j_dbs_info->prev_cpu_wall); if (dbs_tuners_ins.ignore_nice) { j_dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice; } max_periods = max(DEFAULT_HOTPLUG_IN_SAMPLING_PERIODS, DEFAULT_HOTPLUG_OUT_SAMPLING_PERIODS); dbs_tuners_ins.hotplug_load_history = kmalloc( (sizeof(unsigned int) * max_periods), GFP_KERNEL); if (!dbs_tuners_ins.hotplug_load_history) { WARN_ON(1); return -ENOMEM; } for (i = 0; i < max_periods; i++) dbs_tuners_ins.hotplug_load_history[i] = 50; } this_dbs_info->cpu = cpu; this_dbs_info->freq_table = cpufreq_frequency_get_table(cpu); /* * Start the timerschedule work, when this governor * is used for first time */ if (dbs_enable == 1) { rc = sysfs_create_group(cpufreq_global_kobject, &dbs_attr_group); if (rc) { mutex_unlock(&dbs_mutex); return rc; } } if (!dbs_tuners_ins.boost_timeout) dbs_tuners_ins.boost_timeout = dbs_tuners_ins.sampling_rate * 30; mutex_unlock(&dbs_mutex); mutex_init(&this_dbs_info->timer_mutex); dbs_timer_init(this_dbs_info); break; case CPUFREQ_GOV_STOP: dbs_timer_exit(this_dbs_info); mutex_lock(&dbs_mutex); mutex_destroy(&this_dbs_info->timer_mutex); dbs_enable--; mutex_unlock(&dbs_mutex); if (!dbs_enable) sysfs_remove_group(cpufreq_global_kobject, &dbs_attr_group); kfree(dbs_tuners_ins.hotplug_load_history); /* * XXX BIG CAVEAT: Stopping the governor with CPU1 offline * will result in it remaining offline until the user onlines * it again. It is up to the user to do this (for now). */ break; case CPUFREQ_GOV_LIMITS: mutex_lock(&this_dbs_info->timer_mutex); if (policy->max < this_dbs_info->cur_policy->cur) __cpufreq_driver_target(this_dbs_info->cur_policy, policy->max, CPUFREQ_RELATION_H); else if (policy->min > this_dbs_info->cur_policy->cur) __cpufreq_driver_target(this_dbs_info->cur_policy, policy->min, CPUFREQ_RELATION_L); mutex_unlock(&this_dbs_info->timer_mutex); break; } return 0; } #if 0 static int hotplug_boost(struct cpufreq_policy *policy) { unsigned int cpu = policy->cpu; struct cpu_dbs_info_s *this_dbs_info; this_dbs_info = &per_cpu(hp_cpu_dbs_info, cpu); #if 0 /* Already at max? */ if (policy->cur == policy->max) return; #endif mutex_lock(&this_dbs_info->timer_mutex); this_dbs_info->boost_applied = 1; __cpufreq_driver_target(policy, policy->max, CPUFREQ_RELATION_H); mutex_unlock(&this_dbs_info->timer_mutex); return 0; } #endif static int __init cpufreq_gov_dbs_init(void) { int err; cputime64_t wall; u64 idle_time; int cpu = get_cpu(); idle_time = get_cpu_idle_time_us(cpu, &wall); put_cpu(); if (idle_time != -1ULL) { dbs_tuners_ins.up_threshold = DEFAULT_UP_FREQ_MIN_LOAD; } else { pr_err("cpufreq-sakuractive: %s: assumes CONFIG_NO_HZ\n", __func__); return -EINVAL; } khotplug_wq = create_workqueue("khotplug"); if (!khotplug_wq) { pr_err("Creation of khotplug failed\n"); return -EFAULT; } err = cpufreq_register_governor(&cpufreq_gov_sakuractive); if (err) destroy_workqueue(khotplug_wq); return err; } static void __exit cpufreq_gov_dbs_exit(void) { cpufreq_unregister_governor(&cpufreq_gov_sakuractive); destroy_workqueue(khotplug_wq); } MODULE_AUTHOR("sakuramilk <c.sakuramilk@gmail.com>"); MODULE_DESCRIPTION("'cpufreq_sakuractive' - cpufreq governor for dynamic frequency scaling and CPU hotplug"); MODULE_LICENSE("GPL"); #ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_SAKURACTIVE fs_initcall(cpufreq_gov_dbs_init); #else module_init(cpufreq_gov_dbs_init); #endif module_exit(cpufreq_gov_dbs_exit);
Java
/* SCTP kernel implementation * (C) Copyright IBM Corp. 2001, 2004 * Copyright (c) 1999-2000 Cisco, Inc. * Copyright (c) 1999-2001 Motorola, Inc. * Copyright (c) 2001 Intel Corp. * Copyright (c) 2001 Nokia, Inc. * Copyright (c) 2001 La Monte H.P. Yarroll * * These functions manipulate an sctp event. The struct ulpevent is used * to carry notifications and data to the ULP (sockets). * * This SCTP implementation 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 SCTP implementation 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 GNU CC; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <lksctp-developers@lists.sourceforge.net> * * Or submit a bug report through the following website: * http://www.sf.net/projects/lksctp * * Written or modified by: * Jon Grimm <jgrimm@us.ibm.com> * La Monte H.P. Yarroll <piggy@acm.org> * Ardelle Fan <ardelle.fan@intel.com> * Sridhar Samudrala <sri@us.ibm.com> * * Any bugs reported given to us we will try to fix... any fixes shared will * be incorporated into the next SCTP release. */ #include <linux/slab.h> #include <linux/types.h> #include <linux/skbuff.h> #include <net/sctp/structs.h> #include <net/sctp/sctp.h> #include <net/sctp/sm.h> static void sctp_ulpevent_receive_data(struct sctp_ulpevent *event, struct sctp_association *asoc); static void sctp_ulpevent_release_data(struct sctp_ulpevent *event); static void sctp_ulpevent_release_frag_data(struct sctp_ulpevent *event); /* Initialize an ULP event from an given skb. */ SCTP_STATIC void sctp_ulpevent_init(struct sctp_ulpevent *event, int msg_flags, unsigned int len) { memset(event, 0, sizeof(struct sctp_ulpevent)); event->msg_flags = msg_flags; event->rmem_len = len; } /* Create a new sctp_ulpevent. */ SCTP_STATIC struct sctp_ulpevent *sctp_ulpevent_new(int size, int msg_flags, gfp_t gfp) { struct sctp_ulpevent *event; struct sk_buff *skb; skb = alloc_skb(size, gfp); if (!skb) goto fail; event = sctp_skb2event(skb); sctp_ulpevent_init(event, msg_flags, skb->truesize); return event; fail: return NULL; } /* Is this a MSG_NOTIFICATION? */ int sctp_ulpevent_is_notification(const struct sctp_ulpevent *event) { return MSG_NOTIFICATION == (event->msg_flags & MSG_NOTIFICATION); } /* Hold the association in case the msg_name needs read out of * the association. */ static inline void sctp_ulpevent_set_owner(struct sctp_ulpevent *event, const struct sctp_association *asoc) { struct sk_buff *skb; /* Cast away the const, as we are just wanting to * bump the reference count. */ sctp_association_hold((struct sctp_association *)asoc); skb = sctp_event2skb(event); event->asoc = (struct sctp_association *)asoc; atomic_add(event->rmem_len, &event->asoc->rmem_alloc); sctp_skb_set_owner_r(skb, asoc->base.sk); } /* A simple destructor to give up the reference to the association. */ static inline void sctp_ulpevent_release_owner(struct sctp_ulpevent *event) { struct sctp_association *asoc = event->asoc; atomic_sub(event->rmem_len, &asoc->rmem_alloc); sctp_association_put(asoc); } /* Create and initialize an SCTP_ASSOC_CHANGE event. * * 5.3.1.1 SCTP_ASSOC_CHANGE * * Communication notifications inform the ULP that an SCTP association * has either begun or ended. The identifier for a new association is * provided by this notification. * * Note: There is no field checking here. If a field is unused it will be * zero'd out. */ struct sctp_ulpevent *sctp_ulpevent_make_assoc_change( const struct sctp_association *asoc, __u16 flags, __u16 state, __u16 error, __u16 outbound, __u16 inbound, struct sctp_chunk *chunk, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_assoc_change *sac; struct sk_buff *skb; /* If the lower layer passed in the chunk, it will be * an ABORT, so we need to include it in the sac_info. */ if (chunk) { /* Copy the chunk data to a new skb and reserve enough * head room to use as notification. */ skb = skb_copy_expand(chunk->skb, sizeof(struct sctp_assoc_change), 0, gfp); if (!skb) goto fail; /* Embed the event fields inside the cloned skb. */ event = sctp_skb2event(skb); sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize); /* Include the notification structure */ sac = (struct sctp_assoc_change *) skb_push(skb, sizeof(struct sctp_assoc_change)); /* Trim the buffer to the right length. */ skb_trim(skb, sizeof(struct sctp_assoc_change) + ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t)); } else { event = sctp_ulpevent_new(sizeof(struct sctp_assoc_change), MSG_NOTIFICATION, gfp); if (!event) goto fail; skb = sctp_event2skb(event); sac = (struct sctp_assoc_change *) skb_put(skb, sizeof(struct sctp_assoc_change)); } /* Socket Extensions for SCTP * 5.3.1.1 SCTP_ASSOC_CHANGE * * sac_type: * It should be SCTP_ASSOC_CHANGE. */ sac->sac_type = SCTP_ASSOC_CHANGE; /* Socket Extensions for SCTP * 5.3.1.1 SCTP_ASSOC_CHANGE * * sac_state: 32 bits (signed integer) * This field holds one of a number of values that communicate the * event that happened to the association. */ sac->sac_state = state; /* Socket Extensions for SCTP * 5.3.1.1 SCTP_ASSOC_CHANGE * * sac_flags: 16 bits (unsigned integer) * Currently unused. */ sac->sac_flags = 0; /* Socket Extensions for SCTP * 5.3.1.1 SCTP_ASSOC_CHANGE * * sac_length: sizeof (__u32) * This field is the total length of the notification data, including * the notification header. */ sac->sac_length = skb->len; /* Socket Extensions for SCTP * 5.3.1.1 SCTP_ASSOC_CHANGE * * sac_error: 32 bits (signed integer) * * If the state was reached due to a error condition (e.g. * COMMUNICATION_LOST) any relevant error information is available in * this field. This corresponds to the protocol error codes defined in * [SCTP]. */ sac->sac_error = error; /* Socket Extensions for SCTP * 5.3.1.1 SCTP_ASSOC_CHANGE * * sac_outbound_streams: 16 bits (unsigned integer) * sac_inbound_streams: 16 bits (unsigned integer) * * The maximum number of streams allowed in each direction are * available in sac_outbound_streams and sac_inbound streams. */ sac->sac_outbound_streams = outbound; sac->sac_inbound_streams = inbound; /* Socket Extensions for SCTP * 5.3.1.1 SCTP_ASSOC_CHANGE * * sac_assoc_id: sizeof (sctp_assoc_t) * * The association id field, holds the identifier for the association. * All notifications for a given association have the same association * identifier. For TCP style socket, this field is ignored. */ sctp_ulpevent_set_owner(event, asoc); sac->sac_assoc_id = sctp_assoc2id(asoc); return event; fail: return NULL; } /* Create and initialize an SCTP_PEER_ADDR_CHANGE event. * * Socket Extensions for SCTP - draft-01 * 5.3.1.2 SCTP_PEER_ADDR_CHANGE * * When a destination address on a multi-homed peer encounters a change * an interface details event is sent. */ struct sctp_ulpevent *sctp_ulpevent_make_peer_addr_change( const struct sctp_association *asoc, const struct sockaddr_storage *aaddr, int flags, int state, int error, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_paddr_change *spc; struct sk_buff *skb; event = sctp_ulpevent_new(sizeof(struct sctp_paddr_change), MSG_NOTIFICATION, gfp); if (!event) goto fail; skb = sctp_event2skb(event); spc = (struct sctp_paddr_change *) skb_put(skb, sizeof(struct sctp_paddr_change)); /* Sockets API Extensions for SCTP * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE * * spc_type: * * It should be SCTP_PEER_ADDR_CHANGE. */ spc->spc_type = SCTP_PEER_ADDR_CHANGE; /* Sockets API Extensions for SCTP * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE * * spc_length: sizeof (__u32) * * This field is the total length of the notification data, including * the notification header. */ spc->spc_length = sizeof(struct sctp_paddr_change); /* Sockets API Extensions for SCTP * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE * * spc_flags: 16 bits (unsigned integer) * Currently unused. */ spc->spc_flags = 0; /* Sockets API Extensions for SCTP * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE * * spc_state: 32 bits (signed integer) * * This field holds one of a number of values that communicate the * event that happened to the address. */ spc->spc_state = state; /* Sockets API Extensions for SCTP * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE * * spc_error: 32 bits (signed integer) * * If the state was reached due to any error condition (e.g. * ADDRESS_UNREACHABLE) any relevant error information is available in * this field. */ spc->spc_error = error; /* Socket Extensions for SCTP * 5.3.1.1 SCTP_ASSOC_CHANGE * * spc_assoc_id: sizeof (sctp_assoc_t) * * The association id field, holds the identifier for the association. * All notifications for a given association have the same association * identifier. For TCP style socket, this field is ignored. */ sctp_ulpevent_set_owner(event, asoc); spc->spc_assoc_id = sctp_assoc2id(asoc); /* Sockets API Extensions for SCTP * Section 5.3.1.2 SCTP_PEER_ADDR_CHANGE * * spc_aaddr: sizeof (struct sockaddr_storage) * * The affected address field, holds the remote peer's address that is * encountering the change of state. */ memcpy(&spc->spc_aaddr, aaddr, sizeof(struct sockaddr_storage)); /* Map ipv4 address into v4-mapped-on-v6 address. */ sctp_get_pf_specific(asoc->base.sk->sk_family)->addr_v4map( sctp_sk(asoc->base.sk), (union sctp_addr *)&spc->spc_aaddr); return event; fail: return NULL; } /* Create and initialize an SCTP_REMOTE_ERROR notification. * * Note: This assumes that the chunk->skb->data already points to the * operation error payload. * * Socket Extensions for SCTP - draft-01 * 5.3.1.3 SCTP_REMOTE_ERROR * * A remote peer may send an Operational Error message to its peer. * This message indicates a variety of error conditions on an * association. The entire error TLV as it appears on the wire is * included in a SCTP_REMOTE_ERROR event. Please refer to the SCTP * specification [SCTP] and any extensions for a list of possible * error formats. */ struct sctp_ulpevent *sctp_ulpevent_make_remote_error( const struct sctp_association *asoc, struct sctp_chunk *chunk, __u16 flags, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_remote_error *sre; struct sk_buff *skb; sctp_errhdr_t *ch; __be16 cause; int elen; ch = (sctp_errhdr_t *)(chunk->skb->data); cause = ch->cause; elen = WORD_ROUND(ntohs(ch->length)) - sizeof(sctp_errhdr_t); /* Pull off the ERROR header. */ skb_pull(chunk->skb, sizeof(sctp_errhdr_t)); /* Copy the skb to a new skb with room for us to prepend * notification with. */ skb = skb_copy_expand(chunk->skb, sizeof(struct sctp_remote_error), 0, gfp); /* Pull off the rest of the cause TLV from the chunk. */ skb_pull(chunk->skb, elen); if (!skb) goto fail; /* Embed the event fields inside the cloned skb. */ event = sctp_skb2event(skb); sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize); sre = (struct sctp_remote_error *) skb_push(skb, sizeof(struct sctp_remote_error)); /* Trim the buffer to the right length. */ skb_trim(skb, sizeof(struct sctp_remote_error) + elen); /* Socket Extensions for SCTP * 5.3.1.3 SCTP_REMOTE_ERROR * * sre_type: * It should be SCTP_REMOTE_ERROR. */ sre->sre_type = SCTP_REMOTE_ERROR; /* * Socket Extensions for SCTP * 5.3.1.3 SCTP_REMOTE_ERROR * * sre_flags: 16 bits (unsigned integer) * Currently unused. */ sre->sre_flags = 0; /* Socket Extensions for SCTP * 5.3.1.3 SCTP_REMOTE_ERROR * * sre_length: sizeof (__u32) * * This field is the total length of the notification data, * including the notification header. */ sre->sre_length = skb->len; /* Socket Extensions for SCTP * 5.3.1.3 SCTP_REMOTE_ERROR * * sre_error: 16 bits (unsigned integer) * This value represents one of the Operational Error causes defined in * the SCTP specification, in network byte order. */ sre->sre_error = cause; /* Socket Extensions for SCTP * 5.3.1.3 SCTP_REMOTE_ERROR * * sre_assoc_id: sizeof (sctp_assoc_t) * * The association id field, holds the identifier for the association. * All notifications for a given association have the same association * identifier. For TCP style socket, this field is ignored. */ sctp_ulpevent_set_owner(event, asoc); sre->sre_assoc_id = sctp_assoc2id(asoc); return event; fail: return NULL; } /* Create and initialize a SCTP_SEND_FAILED notification. * * Socket Extensions for SCTP - draft-01 * 5.3.1.4 SCTP_SEND_FAILED */ struct sctp_ulpevent *sctp_ulpevent_make_send_failed( const struct sctp_association *asoc, struct sctp_chunk *chunk, __u16 flags, __u32 error, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_send_failed *ssf; struct sk_buff *skb; /* Pull off any padding. */ int len = ntohs(chunk->chunk_hdr->length); /* Make skb with more room so we can prepend notification. */ skb = skb_copy_expand(chunk->skb, sizeof(struct sctp_send_failed), /* headroom */ 0, /* tailroom */ gfp); if (!skb) goto fail; /* Pull off the common chunk header and DATA header. */ skb_pull(skb, sizeof(struct sctp_data_chunk)); len -= sizeof(struct sctp_data_chunk); /* Embed the event fields inside the cloned skb. */ event = sctp_skb2event(skb); sctp_ulpevent_init(event, MSG_NOTIFICATION, skb->truesize); ssf = (struct sctp_send_failed *) skb_push(skb, sizeof(struct sctp_send_failed)); /* Socket Extensions for SCTP * 5.3.1.4 SCTP_SEND_FAILED * * ssf_type: * It should be SCTP_SEND_FAILED. */ ssf->ssf_type = SCTP_SEND_FAILED; /* Socket Extensions for SCTP * 5.3.1.4 SCTP_SEND_FAILED * * ssf_flags: 16 bits (unsigned integer) * The flag value will take one of the following values * * SCTP_DATA_UNSENT - Indicates that the data was never put on * the wire. * * SCTP_DATA_SENT - Indicates that the data was put on the wire. * Note that this does not necessarily mean that the * data was (or was not) successfully delivered. */ ssf->ssf_flags = flags; /* Socket Extensions for SCTP * 5.3.1.4 SCTP_SEND_FAILED * * ssf_length: sizeof (__u32) * This field is the total length of the notification data, including * the notification header. */ ssf->ssf_length = sizeof(struct sctp_send_failed) + len; skb_trim(skb, ssf->ssf_length); /* Socket Extensions for SCTP * 5.3.1.4 SCTP_SEND_FAILED * * ssf_error: 16 bits (unsigned integer) * This value represents the reason why the send failed, and if set, * will be a SCTP protocol error code as defined in [SCTP] section * 3.3.10. */ ssf->ssf_error = error; /* Socket Extensions for SCTP * 5.3.1.4 SCTP_SEND_FAILED * * ssf_info: sizeof (struct sctp_sndrcvinfo) * The original send information associated with the undelivered * message. */ memcpy(&ssf->ssf_info, &chunk->sinfo, sizeof(struct sctp_sndrcvinfo)); /* Per TSVWG discussion with Randy. Allow the application to * reassemble a fragmented message. */ ssf->ssf_info.sinfo_flags = chunk->chunk_hdr->flags; /* Socket Extensions for SCTP * 5.3.1.4 SCTP_SEND_FAILED * * ssf_assoc_id: sizeof (sctp_assoc_t) * The association id field, sf_assoc_id, holds the identifier for the * association. All notifications for a given association have the * same association identifier. For TCP style socket, this field is * ignored. */ sctp_ulpevent_set_owner(event, asoc); ssf->ssf_assoc_id = sctp_assoc2id(asoc); return event; fail: return NULL; } /* Create and initialize a SCTP_SHUTDOWN_EVENT notification. * * Socket Extensions for SCTP - draft-01 * 5.3.1.5 SCTP_SHUTDOWN_EVENT */ struct sctp_ulpevent *sctp_ulpevent_make_shutdown_event( const struct sctp_association *asoc, __u16 flags, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_shutdown_event *sse; struct sk_buff *skb; event = sctp_ulpevent_new(sizeof(struct sctp_shutdown_event), MSG_NOTIFICATION, gfp); if (!event) goto fail; skb = sctp_event2skb(event); sse = (struct sctp_shutdown_event *) skb_put(skb, sizeof(struct sctp_shutdown_event)); /* Socket Extensions for SCTP * 5.3.1.5 SCTP_SHUTDOWN_EVENT * * sse_type * It should be SCTP_SHUTDOWN_EVENT */ sse->sse_type = SCTP_SHUTDOWN_EVENT; /* Socket Extensions for SCTP * 5.3.1.5 SCTP_SHUTDOWN_EVENT * * sse_flags: 16 bits (unsigned integer) * Currently unused. */ sse->sse_flags = 0; /* Socket Extensions for SCTP * 5.3.1.5 SCTP_SHUTDOWN_EVENT * * sse_length: sizeof (__u32) * This field is the total length of the notification data, including * the notification header. */ sse->sse_length = sizeof(struct sctp_shutdown_event); /* Socket Extensions for SCTP * 5.3.1.5 SCTP_SHUTDOWN_EVENT * * sse_assoc_id: sizeof (sctp_assoc_t) * The association id field, holds the identifier for the association. * All notifications for a given association have the same association * identifier. For TCP style socket, this field is ignored. */ sctp_ulpevent_set_owner(event, asoc); sse->sse_assoc_id = sctp_assoc2id(asoc); return event; fail: return NULL; } /* Create and initialize a SCTP_ADAPTATION_INDICATION notification. * * Socket Extensions for SCTP * 5.3.1.6 SCTP_ADAPTATION_INDICATION */ struct sctp_ulpevent *sctp_ulpevent_make_adaptation_indication( const struct sctp_association *asoc, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_adaptation_event *sai; struct sk_buff *skb; event = sctp_ulpevent_new(sizeof(struct sctp_adaptation_event), MSG_NOTIFICATION, gfp); if (!event) goto fail; skb = sctp_event2skb(event); sai = (struct sctp_adaptation_event *) skb_put(skb, sizeof(struct sctp_adaptation_event)); sai->sai_type = SCTP_ADAPTATION_INDICATION; sai->sai_flags = 0; sai->sai_length = sizeof(struct sctp_adaptation_event); sai->sai_adaptation_ind = asoc->peer.adaptation_ind; sctp_ulpevent_set_owner(event, asoc); sai->sai_assoc_id = sctp_assoc2id(asoc); return event; fail: return NULL; } /* A message has been received. Package this message as a notification * to pass it to the upper layers. Go ahead and calculate the sndrcvinfo * even if filtered out later. * * Socket Extensions for SCTP * 5.2.2 SCTP Header Information Structure (SCTP_SNDRCV) */ struct sctp_ulpevent *sctp_ulpevent_make_rcvmsg(struct sctp_association *asoc, struct sctp_chunk *chunk, gfp_t gfp) { struct sctp_ulpevent *event = NULL; struct sk_buff *skb; size_t padding, len; int rx_count; /* * check to see if we need to make space for this * new skb, expand the rcvbuffer if needed, or drop * the frame */ if (asoc->ep->rcvbuf_policy) rx_count = atomic_read(&asoc->rmem_alloc); else rx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc); if (rx_count >= asoc->base.sk->sk_rcvbuf) { if ((asoc->base.sk->sk_userlocks & SOCK_RCVBUF_LOCK) || (!sk_rmem_schedule(asoc->base.sk, chunk->skb->truesize))) goto fail; } /* Clone the original skb, sharing the data. */ skb = skb_clone(chunk->skb, gfp); if (!skb) goto fail; /* Now that all memory allocations for this chunk succeeded, we * can mark it as received so the tsn_map is updated correctly. */ if (sctp_tsnmap_mark(&asoc->peer.tsn_map, ntohl(chunk->subh.data_hdr->tsn))) goto fail_mark; /* First calculate the padding, so we don't inadvertently * pass up the wrong length to the user. * * RFC 2960 - Section 3.2 Chunk Field Descriptions * * The total length of a chunk(including Type, Length and Value fields) * MUST be a multiple of 4 bytes. If the length of the chunk is not a * multiple of 4 bytes, the sender MUST pad the chunk with all zero * bytes and this padding is not included in the chunk length field. * The sender should never pad with more than 3 bytes. The receiver * MUST ignore the padding bytes. */ len = ntohs(chunk->chunk_hdr->length); padding = WORD_ROUND(len) - len; /* Fixup cloned skb with just this chunks data. */ skb_trim(skb, chunk->chunk_end - padding - skb->data); /* Embed the event fields inside the cloned skb. */ event = sctp_skb2event(skb); /* Initialize event with flags 0 and correct length * Since this is a clone of the original skb, only account for * the data of this chunk as other chunks will be accounted separately. */ sctp_ulpevent_init(event, 0, skb->len + sizeof(struct sk_buff)); sctp_ulpevent_receive_data(event, asoc); event->stream = ntohs(chunk->subh.data_hdr->stream); event->ssn = ntohs(chunk->subh.data_hdr->ssn); event->ppid = chunk->subh.data_hdr->ppid; if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) { event->flags |= SCTP_UNORDERED; event->cumtsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map); } event->tsn = ntohl(chunk->subh.data_hdr->tsn); event->msg_flags |= chunk->chunk_hdr->flags; event->iif = sctp_chunk_iif(chunk); return event; fail_mark: kfree_skb(skb); fail: return NULL; } /* Create a partial delivery related event. * * 5.3.1.7 SCTP_PARTIAL_DELIVERY_EVENT * * When a receiver is engaged in a partial delivery of a * message this notification will be used to indicate * various events. */ struct sctp_ulpevent *sctp_ulpevent_make_pdapi( const struct sctp_association *asoc, __u32 indication, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_pdapi_event *pd; struct sk_buff *skb; event = sctp_ulpevent_new(sizeof(struct sctp_pdapi_event), MSG_NOTIFICATION, gfp); if (!event) goto fail; skb = sctp_event2skb(event); pd = (struct sctp_pdapi_event *) skb_put(skb, sizeof(struct sctp_pdapi_event)); /* pdapi_type * It should be SCTP_PARTIAL_DELIVERY_EVENT * * pdapi_flags: 16 bits (unsigned integer) * Currently unused. */ pd->pdapi_type = SCTP_PARTIAL_DELIVERY_EVENT; pd->pdapi_flags = 0; /* pdapi_length: 32 bits (unsigned integer) * * This field is the total length of the notification data, including * the notification header. It will generally be sizeof (struct * sctp_pdapi_event). */ pd->pdapi_length = sizeof(struct sctp_pdapi_event); /* pdapi_indication: 32 bits (unsigned integer) * * This field holds the indication being sent to the application. */ pd->pdapi_indication = indication; /* pdapi_assoc_id: sizeof (sctp_assoc_t) * * The association id field, holds the identifier for the association. */ sctp_ulpevent_set_owner(event, asoc); pd->pdapi_assoc_id = sctp_assoc2id(asoc); return event; fail: return NULL; } struct sctp_ulpevent *sctp_ulpevent_make_authkey( const struct sctp_association *asoc, __u16 key_id, __u32 indication, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_authkey_event *ak; struct sk_buff *skb; event = sctp_ulpevent_new(sizeof(struct sctp_authkey_event), MSG_NOTIFICATION, gfp); if (!event) goto fail; skb = sctp_event2skb(event); ak = (struct sctp_authkey_event *) skb_put(skb, sizeof(struct sctp_authkey_event)); ak->auth_type = SCTP_AUTHENTICATION_EVENT; ak->auth_flags = 0; ak->auth_length = sizeof(struct sctp_authkey_event); ak->auth_keynumber = key_id; ak->auth_altkeynumber = 0; ak->auth_indication = indication; /* * The association id field, holds the identifier for the association. */ sctp_ulpevent_set_owner(event, asoc); ak->auth_assoc_id = sctp_assoc2id(asoc); return event; fail: return NULL; } /* * Socket Extensions for SCTP * 6.3.10. SCTP_SENDER_DRY_EVENT */ struct sctp_ulpevent *sctp_ulpevent_make_sender_dry_event( const struct sctp_association *asoc, gfp_t gfp) { struct sctp_ulpevent *event; struct sctp_sender_dry_event *sdry; struct sk_buff *skb; event = sctp_ulpevent_new(sizeof(struct sctp_sender_dry_event), MSG_NOTIFICATION, gfp); if (!event) return NULL; skb = sctp_event2skb(event); sdry = (struct sctp_sender_dry_event *) skb_put(skb, sizeof(struct sctp_sender_dry_event)); sdry->sender_dry_type = SCTP_SENDER_DRY_EVENT; sdry->sender_dry_flags = 0; sdry->sender_dry_length = sizeof(struct sctp_sender_dry_event); sctp_ulpevent_set_owner(event, asoc); sdry->sender_dry_assoc_id = sctp_assoc2id(asoc); return event; } /* Return the notification type, assuming this is a notification * event. */ __u16 sctp_ulpevent_get_notification_type(const struct sctp_ulpevent *event) { union sctp_notification *notification; struct sk_buff *skb; skb = sctp_event2skb(event); notification = (union sctp_notification *) skb->data; return notification->sn_header.sn_type; } /* Copy out the sndrcvinfo into a msghdr. */ void sctp_ulpevent_read_sndrcvinfo(const struct sctp_ulpevent *event, struct msghdr *msghdr) { struct sctp_sndrcvinfo sinfo; if (sctp_ulpevent_is_notification(event)) return; /* Sockets API Extensions for SCTP * Section 5.2.2 SCTP Header Information Structure (SCTP_SNDRCV) * * sinfo_stream: 16 bits (unsigned integer) * * For recvmsg() the SCTP stack places the message's stream number in * this value. */ sinfo.sinfo_stream = event->stream; /* sinfo_ssn: 16 bits (unsigned integer) * * For recvmsg() this value contains the stream sequence number that * the remote endpoint placed in the DATA chunk. For fragmented * messages this is the same number for all deliveries of the message * (if more than one recvmsg() is needed to read the message). */ sinfo.sinfo_ssn = event->ssn; /* sinfo_ppid: 32 bits (unsigned integer) * * In recvmsg() this value is * the same information that was passed by the upper layer in the peer * application. Please note that byte order issues are NOT accounted * for and this information is passed opaquely by the SCTP stack from * one end to the other. */ sinfo.sinfo_ppid = event->ppid; /* sinfo_flags: 16 bits (unsigned integer) * * This field may contain any of the following flags and is composed of * a bitwise OR of these values. * * recvmsg() flags: * * SCTP_UNORDERED - This flag is present when the message was sent * non-ordered. */ sinfo.sinfo_flags = event->flags; /* sinfo_tsn: 32 bit (unsigned integer) * * For the receiving side, this field holds a TSN that was * assigned to one of the SCTP Data Chunks. */ sinfo.sinfo_tsn = event->tsn; /* sinfo_cumtsn: 32 bit (unsigned integer) * * This field will hold the current cumulative TSN as * known by the underlying SCTP layer. Note this field is * ignored when sending and only valid for a receive * operation when sinfo_flags are set to SCTP_UNORDERED. */ sinfo.sinfo_cumtsn = event->cumtsn; /* sinfo_assoc_id: sizeof (sctp_assoc_t) * * The association handle field, sinfo_assoc_id, holds the identifier * for the association announced in the COMMUNICATION_UP notification. * All notifications for a given association have the same identifier. * Ignored for one-to-one style sockets. */ sinfo.sinfo_assoc_id = sctp_assoc2id(event->asoc); /* context value that is set via SCTP_CONTEXT socket option. */ sinfo.sinfo_context = event->asoc->default_rcv_context; /* These fields are not used while receiving. */ sinfo.sinfo_timetolive = 0; put_cmsg(msghdr, IPPROTO_SCTP, SCTP_SNDRCV, sizeof(struct sctp_sndrcvinfo), (void *)&sinfo); } /* Do accounting for bytes received and hold a reference to the association * for each skb. */ static void sctp_ulpevent_receive_data(struct sctp_ulpevent *event, struct sctp_association *asoc) { struct sk_buff *skb, *frag; skb = sctp_event2skb(event); /* Set the owner and charge rwnd for bytes received. */ sctp_ulpevent_set_owner(event, asoc); sctp_assoc_rwnd_decrease(asoc, skb_headlen(skb)); if (!skb->data_len) return; /* Note: Not clearing the entire event struct as this is just a * fragment of the real event. However, we still need to do rwnd * accounting. * In general, the skb passed from IP can have only 1 level of * fragments. But we allow multiple levels of fragments. */ skb_walk_frags(skb, frag) sctp_ulpevent_receive_data(sctp_skb2event(frag), asoc); } /* Do accounting for bytes just read by user and release the references to * the association. */ static void sctp_ulpevent_release_data(struct sctp_ulpevent *event) { struct sk_buff *skb, *frag; unsigned int len; /* Current stack structures assume that the rcv buffer is * per socket. For UDP style sockets this is not true as * multiple associations may be on a single UDP-style socket. * Use the local private area of the skb to track the owning * association. */ skb = sctp_event2skb(event); len = skb->len; if (!skb->data_len) goto done; /* Don't forget the fragments. */ skb_walk_frags(skb, frag) { /* NOTE: skb_shinfos are recursive. Although IP returns * skb's with only 1 level of fragments, SCTP reassembly can * increase the levels. */ sctp_ulpevent_release_frag_data(sctp_skb2event(frag)); } done: sctp_assoc_rwnd_increase(event->asoc, len); sctp_ulpevent_release_owner(event); } static void sctp_ulpevent_release_frag_data(struct sctp_ulpevent *event) { struct sk_buff *skb, *frag; skb = sctp_event2skb(event); if (!skb->data_len) goto done; /* Don't forget the fragments. */ skb_walk_frags(skb, frag) { /* NOTE: skb_shinfos are recursive. Although IP returns * skb's with only 1 level of fragments, SCTP reassembly can * increase the levels. */ sctp_ulpevent_release_frag_data(sctp_skb2event(frag)); } done: sctp_ulpevent_release_owner(event); } /* Free a ulpevent that has an owner. It includes releasing the reference * to the owner, updating the rwnd in case of a DATA event and freeing the * skb. */ void sctp_ulpevent_free(struct sctp_ulpevent *event) { if (sctp_ulpevent_is_notification(event)) sctp_ulpevent_release_owner(event); else sctp_ulpevent_release_data(event); kfree_skb(sctp_event2skb(event)); } /* Purge the skb lists holding ulpevents. */ unsigned int sctp_queue_purge_ulpevents(struct sk_buff_head *list) { struct sk_buff *skb; unsigned int data_unread = 0; while ((skb = skb_dequeue(list)) != NULL) { struct sctp_ulpevent *event = sctp_skb2event(skb); if (!sctp_ulpevent_is_notification(event)) data_unread += skb->len; sctp_ulpevent_free(event); } return data_unread; }
Java
/* Miscellaneous utilities for GIMPLE streaming. Things that are used in both input and output are here. Copyright (C) 2009-2015 Free Software Foundation, Inc. Contributed by Doug Kwan <dougkwan@google.com> This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "toplev.h" #include "flags.h" #include "hash-set.h" #include "machmode.h" #include "vec.h" #include "double-int.h" #include "input.h" #include "alias.h" #include "symtab.h" #include "wide-int.h" #include "inchash.h" #include "tree.h" #include "fold-const.h" #include "predict.h" #include "hard-reg-set.h" #include "input.h" #include "function.h" #include "basic-block.h" #include "tree-ssa-alias.h" #include "internal-fn.h" #include "gimple-expr.h" #include "is-a.h" #include "gimple.h" #include "bitmap.h" #include "diagnostic-core.h" #include "hash-map.h" #include "plugin-api.h" #include "ipa-ref.h" #include "cgraph.h" #include "tree-streamer.h" #include "lto-streamer.h" #include "lto-section-names.h" #include "streamer-hooks.h" /* Statistics gathered during LTO, WPA and LTRANS. */ struct lto_stats_d lto_stats; /* LTO uses bitmaps with different life-times. So use a separate obstack for all LTO bitmaps. */ static bitmap_obstack lto_obstack; static bool lto_obstack_initialized; const char *section_name_prefix = LTO_SECTION_NAME_PREFIX; /* Set when streaming LTO for offloading compiler. */ bool lto_stream_offload_p; /* Return a string representing LTO tag TAG. */ const char * lto_tag_name (enum LTO_tags tag) { if (lto_tag_is_tree_code_p (tag)) { /* For tags representing tree nodes, return the name of the associated tree code. */ return get_tree_code_name (lto_tag_to_tree_code (tag)); } if (lto_tag_is_gimple_code_p (tag)) { /* For tags representing gimple statements, return the name of the associated gimple code. */ return gimple_code_name[lto_tag_to_gimple_code (tag)]; } switch (tag) { case LTO_null: return "LTO_null"; case LTO_bb0: return "LTO_bb0"; case LTO_bb1: return "LTO_bb1"; case LTO_eh_region: return "LTO_eh_region"; case LTO_function: return "LTO_function"; case LTO_eh_table: return "LTO_eh_table"; case LTO_ert_cleanup: return "LTO_ert_cleanup"; case LTO_ert_try: return "LTO_ert_try"; case LTO_ert_allowed_exceptions: return "LTO_ert_allowed_exceptions"; case LTO_ert_must_not_throw: return "LTO_ert_must_not_throw"; case LTO_tree_pickle_reference: return "LTO_tree_pickle_reference"; case LTO_field_decl_ref: return "LTO_field_decl_ref"; case LTO_function_decl_ref: return "LTO_function_decl_ref"; case LTO_label_decl_ref: return "LTO_label_decl_ref"; case LTO_namespace_decl_ref: return "LTO_namespace_decl_ref"; case LTO_result_decl_ref: return "LTO_result_decl_ref"; case LTO_ssa_name_ref: return "LTO_ssa_name_ref"; case LTO_type_decl_ref: return "LTO_type_decl_ref"; case LTO_type_ref: return "LTO_type_ref"; case LTO_global_decl_ref: return "LTO_global_decl_ref"; default: return "LTO_UNKNOWN"; } } /* Allocate a bitmap from heap. Initializes the LTO obstack if necessary. */ bitmap lto_bitmap_alloc (void) { if (!lto_obstack_initialized) { bitmap_obstack_initialize (&lto_obstack); lto_obstack_initialized = true; } return BITMAP_ALLOC (&lto_obstack); } /* Free bitmap B. */ void lto_bitmap_free (bitmap b) { BITMAP_FREE (b); } /* Get a section name for a particular type or name. The NAME field is only used if SECTION_TYPE is LTO_section_function_body. For all others it is ignored. The callee of this function is responsible to free the returned name. */ char * lto_get_section_name (int section_type, const char *name, struct lto_file_decl_data *f) { const char *add; char post[32]; const char *sep; if (section_type == LTO_section_function_body) { gcc_assert (name != NULL); if (name[0] == '*') name++; add = name; sep = ""; } else if (section_type < LTO_N_SECTION_TYPES) { add = lto_section_name[section_type]; sep = "."; } else internal_error ("bytecode stream: unexpected LTO section %s", name); /* Make the section name unique so that ld -r combining sections doesn't confuse the reader with merged sections. For options don't add a ID, the option reader cannot deal with them and merging should be ok here. */ if (section_type == LTO_section_opts) strcpy (post, ""); else if (f != NULL) sprintf (post, "." HOST_WIDE_INT_PRINT_HEX_PURE, f->id); else sprintf (post, "." HOST_WIDE_INT_PRINT_HEX_PURE, get_random_seed (false)); return concat (section_name_prefix, sep, add, post, NULL); } /* Show various memory usage statistics related to LTO. */ void print_lto_report (const char *s) { unsigned i; fprintf (stderr, "[%s] # of input files: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, lto_stats.num_input_files); fprintf (stderr, "[%s] # of input cgraph nodes: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, lto_stats.num_input_cgraph_nodes); fprintf (stderr, "[%s] # of function bodies: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, lto_stats.num_function_bodies); for (i = 0; i < NUM_TREE_CODES; i++) if (lto_stats.num_trees[i]) fprintf (stderr, "[%s] # of '%s' objects read: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, get_tree_code_name ((enum tree_code) i), lto_stats.num_trees[i]); if (flag_lto) { fprintf (stderr, "[%s] Compression: " HOST_WIDE_INT_PRINT_UNSIGNED " output bytes, " HOST_WIDE_INT_PRINT_UNSIGNED " compressed bytes", s, lto_stats.num_output_il_bytes, lto_stats.num_compressed_il_bytes); if (lto_stats.num_output_il_bytes > 0) { const float dividend = (float) lto_stats.num_compressed_il_bytes; const float divisor = (float) lto_stats.num_output_il_bytes; fprintf (stderr, " (ratio: %f)", dividend / divisor); } fprintf (stderr, "\n"); } if (flag_wpa) { fprintf (stderr, "[%s] # of output files: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, lto_stats.num_output_files); fprintf (stderr, "[%s] # of output symtab nodes: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, lto_stats.num_output_symtab_nodes); fprintf (stderr, "[%s] # of output tree pickle references: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, lto_stats.num_pickle_refs_output); fprintf (stderr, "[%s] # of output tree bodies: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, lto_stats.num_tree_bodies_output); fprintf (stderr, "[%s] # callgraph partitions: " HOST_WIDE_INT_PRINT_UNSIGNED "\n", s, lto_stats.num_cgraph_partitions); fprintf (stderr, "[%s] Compression: " HOST_WIDE_INT_PRINT_UNSIGNED " input bytes, " HOST_WIDE_INT_PRINT_UNSIGNED " uncompressed bytes", s, lto_stats.num_input_il_bytes, lto_stats.num_uncompressed_il_bytes); if (lto_stats.num_input_il_bytes > 0) { const float dividend = (float) lto_stats.num_uncompressed_il_bytes; const float divisor = (float) lto_stats.num_input_il_bytes; fprintf (stderr, " (ratio: %f)", dividend / divisor); } fprintf (stderr, "\n"); } for (i = 0; i < LTO_N_SECTION_TYPES; i++) fprintf (stderr, "[%s] Size of mmap'd section %s: " HOST_WIDE_INT_PRINT_UNSIGNED " bytes\n", s, lto_section_name[i], lto_stats.section_size[i]); } #ifdef LTO_STREAMER_DEBUG struct tree_hash_entry { tree key; intptr_t value; }; struct tree_entry_hasher : typed_noop_remove <tree_hash_entry> { typedef tree_hash_entry value_type; typedef tree_hash_entry compare_type; static inline hashval_t hash (const value_type *); static inline bool equal (const value_type *, const compare_type *); }; inline hashval_t tree_entry_hasher::hash (const value_type *e) { return htab_hash_pointer (e->key); } inline bool tree_entry_hasher::equal (const value_type *e1, const compare_type *e2) { return (e1->key == e2->key); } static hash_table<tree_hash_entry> *tree_htab; #endif /* Initialization common to the LTO reader and writer. */ void lto_streamer_init (void) { /* Check that all the TS_* handled by the reader and writer routines match exactly the structures defined in treestruct.def. When a new TS_* astructure is added, the streamer should be updated to handle it. */ streamer_check_handled_ts_structures (); #ifdef LTO_STREAMER_DEBUG tree_htab = new hash_table<tree_hash_entry> (31); #endif } /* Gate function for all LTO streaming passes. */ bool gate_lto_out (void) { return ((flag_generate_lto || flag_generate_offload || in_lto_p) /* Don't bother doing anything if the program has errors. */ && !seen_error ()); } #ifdef LTO_STREAMER_DEBUG /* Add a mapping between T and ORIG_T, which is the numeric value of the original address of T as it was seen by the LTO writer. This mapping is useful when debugging streaming problems. A debugging session can be started on both reader and writer using ORIG_T as a breakpoint value in both sessions. Note that this mapping is transient and only valid while T is being reconstructed. Once T is fully built, the mapping is removed. */ void lto_orig_address_map (tree t, intptr_t orig_t) { struct tree_hash_entry ent; struct tree_hash_entry **slot; ent.key = t; ent.value = orig_t; slot = tree_htab->find_slot (&ent, INSERT); gcc_assert (!*slot); *slot = XNEW (struct tree_hash_entry); **slot = ent; } /* Get the original address of T as it was seen by the writer. This is only valid while T is being reconstructed. */ intptr_t lto_orig_address_get (tree t) { struct tree_hash_entry ent; struct tree_hash_entry **slot; ent.key = t; slot = tree_htab->find_slot (&ent, NO_INSERT); return (slot ? (*slot)->value : 0); } /* Clear the mapping of T to its original address. */ void lto_orig_address_remove (tree t) { struct tree_hash_entry ent; struct tree_hash_entry **slot; ent.key = t; slot = tree_htab->find_slot (&ent, NO_INSERT); gcc_assert (slot); free (*slot); tree_htab->clear_slot (slot); } #endif /* Check that the version MAJOR.MINOR is the correct version number. */ void lto_check_version (int major, int minor) { if (major != LTO_major_version || minor != LTO_minor_version) fatal_error ("bytecode stream generated with LTO version %d.%d instead " "of the expected %d.%d", major, minor, LTO_major_version, LTO_minor_version); } /* Initialize all the streamer hooks used for streaming GIMPLE. */ void lto_streamer_hooks_init (void) { streamer_hooks_init (); streamer_hooks.write_tree = lto_output_tree; streamer_hooks.read_tree = lto_input_tree; streamer_hooks.input_location = lto_input_location; streamer_hooks.output_location = lto_output_location; }
Java
/* LinphoneUIControler.h * * Copyright (C) 2011 Belledonne Comunications, Grenoble, France * * 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. */ #import <UIKit/UIKit.h> #include "linphonecore.h" @protocol LinphoneUICallDelegate // UI changes -(void) displayDialerFromUI:(UIViewController*) viewCtrl forUser:(NSString*) username withDisplayName:(NSString*) displayName; -(void) displayCall: (LinphoneCall*) call InProgressFromUI:(UIViewController*) viewCtrl forUser:(NSString*) username withDisplayName:(NSString*) displayName; -(void) displayIncomingCall: (LinphoneCall*) call NotificationFromUI:(UIViewController*) viewCtrl forUser:(NSString*) username withDisplayName:(NSString*) displayName; -(void) displayInCall: (LinphoneCall*) call FromUI:(UIViewController*) viewCtrl forUser:(NSString*) username withDisplayName:(NSString*) displayName; -(void) displayVideoCall:(LinphoneCall*) call FromUI:(UIViewController*) viewCtrl forUser:(NSString*) username withDisplayName:(NSString*) displayName; //status reporting -(void) displayStatus:(NSString*) message; @end @protocol LinphoneUIRegistrationDelegate // UI changes for registration -(void) displayRegisteredFromUI:(UIViewController*) viewCtrl forUser:(NSString*) username withDisplayName:(NSString*) displayName onDomain:(NSString*)domain ; -(void) displayRegisteringFromUI:(UIViewController*) viewCtrl forUser:(NSString*) username withDisplayName:(NSString*) displayName onDomain:(NSString*)domain ; -(void) displayRegistrationFailedFromUI:(UIViewController*) viewCtrl forUser:(NSString*) username withDisplayName:(NSString*) displayName onDomain:(NSString*)domain forReason:(NSString*) reason; -(void) displayNotRegisteredFromUI:(UIViewController*) viewCtrl; @end
Java
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace TtNum1.team_buying { public partial class goods : System.Web.UI.Page { TtNum1.BLL.GoodsInfo bllgoodsinfo = new TtNum1.BLL.GoodsInfo(); TtNum1.Model.GoodsInfo modgoodsinfo = new TtNum1.Model.GoodsInfo(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.QueryString["Goods_ID"] == null) { Response.Write("<script>window.alert('您没有选择公告,无法传值');window.location=index.aspx;</script>"); } else { ViewState["BackUrl"] = Request.UrlReferrer.ToString(); string a = Request.QueryString["Goods_ID"].ToString(); modgoodsinfo = bllgoodsinfo.GetModel(Convert.ToInt16(a)); Goods_ID.Text = modgoodsinfo.Goods_ID.ToString(); DataTable dt = bllgoodsinfo.GetList1(a).Tables[0]; if (dt.Rows.Count > 0) { Goods_ID.Text = dt.Rows[0]["Goods_ID"].ToString(); Goods_name.Text = dt.Rows[0]["Goods_name"].ToString(); Market_price.Text = dt.Rows[0]["Market_price"].ToString(); In_store_price.Text = dt.Rows[0]["In_store_price"].ToString(); Stock.Text = dt.Rows[0]["Stock"].ToString(); Image1.ImageUrl = dt.Rows[0]["Goods_pic"].ToString(); Image2.ImageUrl = dt.Rows[0]["Goods_pic"].ToString(); Goods_info.Text = dt.Rows[0]["Goods_info"].ToString(); Good_Brand.Text = dt.Rows[0]["Good_Brand"].ToString(); Qqp.Text = dt.Rows[0]["Qqp"].ToString(); TextBox12.Text = dt.Rows[0]["Qqp"].ToString(); if (dt.Rows[0]["IN_group_buying"].ToString() == "1") { IN_group_buying.Text = "是"; } else { IN_group_buying.Text = "否"; } Sales_volume.Text = dt.Rows[0]["Sales_volume"].ToString(); TextBox9.Text = dt.Rows[0]["Sales_volume"].ToString(); if (dt.Rows[0]["Group_Buying_Price"].ToString() == "" || dt.Rows[0]["Group_Buying_Price"].ToString() == null) { Group_Buying_Price.Text = "该商品未设置团购信息"; } else { Group_Buying_Price.Text = dt.Rows[0]["Group_Buying_Price"].ToString(); } TextBox10.Text = dt.Rows[0]["Group_Buying_Price"].ToString(); GS1.Text = dt.Rows[0]["Sort_name"].ToString(); GS2.Text = dt.Rows[0]["GS_name1"].ToString(); Image3.ImageUrl = dt.Rows[0]["Img_1"].ToString(); Image4.ImageUrl = dt.Rows[0]["Img_1"].ToString(); Image5.ImageUrl = dt.Rows[0]["Img_2"].ToString(); Image6.ImageUrl = dt.Rows[0]["Img_2"].ToString(); uptime.Text = dt.Rows[0]["uptime"].ToString(); } } } } protected void RadButton2_Click1(object sender, EventArgs e) { // Response.Write("<script>history.back(-1)</script>"); Response.Redirect(ViewState["BackUrl"].ToString()); } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TtNum"].ConnectionString; SqlConnection conn = new SqlConnection(connectionString); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("select * from GoodSort2 where GoodSort2.GS_ID='" + DropDownList1.SelectedValue + "'", conn); DataSet ds = new DataSet(); try { conn.Open(); da.Fill(ds, "GoodSort2"); conn.Close(); } catch (SqlException e2) { Response.Write(e2.ToString()); } PagedDataSource obj = new PagedDataSource(); obj.DataSource = ds.Tables["GoodSort2"].DefaultView; DropDownList2.DataSource = obj; this.DropDownList2.DataTextField = "Sort_name"; this.DropDownList2.DataValueField = "Sort_ID"; DropDownList2.DataBind(); } } }
Java
/* * This file is part of NWFramework. * Copyright (c) InCrew Software and Others. * (See the AUTHORS file in the root of this distribution.) * * NWFramework 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. * * NWFramework 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 NWFramework; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "PchNWStream.h" #include "NWStreamBlockVideo.h" #include <memory.h> //******************************************************************** // //******************************************************************** //-------------------------------------------------------------------- // //-------------------------------------------------------------------- NWStreamBlockVideo::NWStreamBlockVideo() : Inherited(), mFrameBuffer(0), mWidth(0), mHeight(0), mStride(0) { } //******************************************************************** // //******************************************************************** //-------------------------------------------------------------------- // //-------------------------------------------------------------------- bool NWStreamBlockVideo::init() { bool bOK = true; if (!isOk()) { mFrameBuffer = 0; mWidth = 0; mHeight = 0; mStride = 0; bOK = Inherited::init(NWSTREAM_SUBTYPE_MEDIA_VIDEO); } return bOK; } //-------------------------------------------------------------------- // //-------------------------------------------------------------------- void NWStreamBlockVideo::done() { if (isOk()) { DISPOSE_ARRAY(mFrameBuffer); Inherited::done(); } } //-------------------------------------------------------------------- // //-------------------------------------------------------------------- void NWStreamBlockVideo::setFrameBufferData(int _width, int _height, int _stride, unsigned char* _frameBuffer, bool _copy) { if ( _frameBuffer && _copy ) { int frameBufferSize = _height*_stride; ASSERT(_stride >= (_height*3)); mFrameBuffer = NEW unsigned char[frameBufferSize]; memcpy(mFrameBuffer,_frameBuffer,frameBufferSize); } else { mFrameBuffer = _frameBuffer; } mWidth = _width; mHeight = _height; mStride = _stride; }
Java
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :organization t.string :department t.string :name t.string :role t.string :email t.string :password t.binary :picture t.integer :given_chips t.integer :received_chips t.integer :avail_chips t.timestamps end end end
Java
package com.avrgaming.civcraft.structure; import java.sql.ResultSet; import java.sql.SQLException; import java.util.concurrent.locks.ReentrantLock; import org.bukkit.Location; import com.avrgaming.civcraft.config.CivSettings; import com.avrgaming.civcraft.exception.CivException; import com.avrgaming.civcraft.exception.InvalidConfiguration; import com.avrgaming.civcraft.object.Buff; import com.avrgaming.civcraft.object.Town; public class MobGrinder extends Structure { private static final double T1_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t1_chance"); //1% private static final double T2_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t2_chance"); //2% private static final double T3_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t3_chance"); //1% private static final double T4_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t4_chance"); //0.25% private static final double PACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.pack_chance"); //0.10% private static final double BIGPACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.bigpack_chance"); private static final double HUGEPACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.hugepack_chance"); public int skippedCounter = 0; public ReentrantLock lock = new ReentrantLock(); public enum Crystal { T1, T2, T3, T4, PACK, BIGPACK, HUGEPACK } protected MobGrinder(Location center, String id, Town town) throws CivException { super(center, id, town); } public MobGrinder(ResultSet rs) throws SQLException, CivException { super(rs); } @Override public String getDynmapDescription() { return null; } @Override public String getMarkerIconName() { return "minecart"; } public double getMineralChance(Crystal crystal) { double chance = 0; switch (crystal) { case T1: chance = T1_CHANCE; break; case T2: chance = T2_CHANCE; break; case T3: chance = T3_CHANCE; break; case T4: chance = T4_CHANCE; break; case PACK: chance = PACK_CHANCE; break; case BIGPACK: chance = BIGPACK_CHANCE; break; case HUGEPACK: chance = HUGEPACK_CHANCE; } double increase = chance*this.getTown().getBuffManager().getEffectiveDouble(Buff.EXTRACTION); chance += increase; try { if (this.getTown().getGovernment().id.equals("gov_tribalism")) { chance *= CivSettings.getDouble(CivSettings.structureConfig, "mobGrinder.tribalism_rate"); } else { chance *= CivSettings.getDouble(CivSettings.structureConfig, "mobGrinder.penalty_rate"); } } catch (InvalidConfiguration e) { e.printStackTrace(); } return chance; } }
Java
/* * Copyright (c) 2006-2018, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2018.10.30 SummerGift first version * 2019.03.05 whj4674672 add stm32h7 */ #ifndef __DRV_USART_H__ #define __DRV_USART_H__ #include <rtthread.h> #include "rtdevice.h" #include <rthw.h> #include <drv_common.h> #include "drv_dma.h" int rt_hw_usart_init(void); #if defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32F1) || defined(SOC_SERIES_STM32L4) \ || defined(SOC_SERIES_STM32L0) || defined(SOC_SERIES_STM32G0) || defined(SOC_SERIES_STM32G4) #define DMA_INSTANCE_TYPE DMA_Channel_TypeDef #elif defined(SOC_SERIES_STM32F2) || defined(SOC_SERIES_STM32F4) || defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32H7) #define DMA_INSTANCE_TYPE DMA_Stream_TypeDef #endif /* defined(SOC_SERIES_STM32F1) || defined(SOC_SERIES_STM32L4) */ #if defined(SOC_SERIES_STM32F1) || defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F2) \ || defined(SOC_SERIES_STM32F4) || defined(SOC_SERIES_STM32L0) || defined(SOC_SERIES_STM32G0) \ || defined(SOC_SERIES_STM32G4) #define UART_INSTANCE_CLEAR_FUNCTION __HAL_UART_CLEAR_FLAG #elif defined(SOC_SERIES_STM32F7) || defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32H7) #define UART_INSTANCE_CLEAR_FUNCTION __HAL_UART_CLEAR_IT #endif /* stm32 config class */ struct stm32_uart_config { const char *name; USART_TypeDef *Instance; IRQn_Type irq_type; struct dma_config *dma_rx; struct dma_config *dma_tx; }; /* stm32 uart dirver class */ struct stm32_uart { UART_HandleTypeDef handle; struct stm32_uart_config *config; #ifdef RT_SERIAL_USING_DMA struct { DMA_HandleTypeDef handle; rt_size_t last_index; } dma_rx; struct { DMA_HandleTypeDef handle; } dma_tx; #endif rt_uint16_t uart_dma_flag; struct rt_serial_device serial; }; #endif /* __DRV_USART_H__ */
Java
<?php /** * WordPress Roles and Capabilities. * * @package WordPress * @subpackage User */ /** * WordPress User Roles. * * The role option is simple, the structure is organized by role name that store * the name in value of the 'name' key. The capabilities are stored as an array * in the value of the 'capability' key. * * <code> * array ( * 'rolename' => array ( * 'name' => 'rolename', * 'capabilities' => array() * ) * ) * </code> * * @since 2.0.0 * @package WordPress * @subpackage User */ class WP_Roles { /** * List of roles and capabilities. * * @since 2.0.0 * @access public * @var array */ var $roles; /** * List of the role objects. * * @since 2.0.0 * @access public * @var array */ var $role_objects = array(); /** * List of role names. * * @since 2.0.0 * @access public * @var array */ var $role_names = array(); /** * Option name for storing role list. * * @since 2.0.0 * @access public * @var string */ var $role_key; /** * Whether to use the database for retrieval and storage. * * @since 2.1.0 * @access public * @var bool */ var $use_db = true; /** * PHP4 Constructor - Call {@link WP_Roles::_init()} method. * * @since 2.0.0 * @access public * * @return WP_Roles */ function WP_Roles() { $this->_init(); } /** * Setup the object properties. * * The role key is set to the current prefix for the $wpdb object with * 'user_roles' appended. If the $wp_user_roles global is set, then it will * be used and the role option will not be updated or used. * * @since 2.1.0 * @access protected * @uses $wpdb Used to get the database prefix. * @global array $wp_user_roles Used to set the 'roles' property value. */ function _init () { global $wpdb; global $wp_user_roles; $this->role_key = $wpdb->prefix . 'user_roles'; if ( ! empty( $wp_user_roles ) ) { $this->roles = $wp_user_roles; $this->use_db = false; } else { $this->roles = get_option( $this->role_key ); } if ( empty( $this->roles ) ) return; $this->role_objects = array(); $this->role_names = array(); foreach ( (array) $this->roles as $role => $data ) { $this->role_objects[$role] = new WP_Role( $role, $this->roles[$role]['capabilities'] ); $this->role_names[$role] = $this->roles[$role]['name']; } } /** * Add role name with capabilities to list. * * Updates the list of roles, if the role doesn't already exist. * * @since 2.0.0 * @access public * * @param string $role Role name. * @param string $display_name Role display name. * @param array $capabilities List of role capabilities. * @return null|WP_Role WP_Role object if role is added, null if already exists. */ function add_role( $role, $display_name, $capabilities = array() ) { if ( isset( $this->roles[$role] ) ) return; $this->roles[$role] = array( 'name' => $display_name, 'capabilities' => $capabilities ); if ( $this->use_db ) update_option( $this->role_key, $this->roles ); $this->role_objects[$role] = new WP_Role( $role, $capabilities ); $this->role_names[$role] = $display_name; return $this->role_objects[$role]; } /** * Remove role by name. * * @since 2.0.0 * @access public * * @param string $role Role name. */ function remove_role( $role ) { if ( ! isset( $this->role_objects[$role] ) ) return; unset( $this->role_objects[$role] ); unset( $this->role_names[$role] ); unset( $this->roles[$role] ); if ( $this->use_db ) update_option( $this->role_key, $this->roles ); } /** * Add capability to role. * * @since 2.0.0 * @access public * * @param string $role Role name. * @param string $cap Capability name. * @param bool $grant Optional, default is true. Whether role is capable of preforming capability. */ function add_cap( $role, $cap, $grant = true ) { $this->roles[$role]['capabilities'][$cap] = $grant; if ( $this->use_db ) update_option( $this->role_key, $this->roles ); } /** * Remove capability from role. * * @since 2.0.0 * @access public * * @param string $role Role name. * @param string $cap Capability name. */ function remove_cap( $role, $cap ) { unset( $this->roles[$role]['capabilities'][$cap] ); if ( $this->use_db ) update_option( $this->role_key, $this->roles ); } /** * Retrieve role object by name. * * @since 2.0.0 * @access public * * @param string $role Role name. * @return object|null Null, if role does not exist. WP_Role object, if found. */ function &get_role( $role ) { if ( isset( $this->role_objects[$role] ) ) return $this->role_objects[$role]; else return null; } /** * Retrieve list of role names. * * @since 2.0.0 * @access public * * @return array List of role names. */ function get_names() { return $this->role_names; } /** * Whether role name is currently in the list of available roles. * * @since 2.0.0 * @access public * * @param string $role Role name to look up. * @return bool */ function is_role( $role ) { return isset( $this->role_names[$role] ); } } /** * WordPress Role class. * * @since 2.0.0 * @package WordPress * @subpackage User */ class WP_Role { /** * Role name. * * @since 2.0.0 * @access public * @var string */ var $name; /** * List of capabilities the role contains. * * @since 2.0.0 * @access public * @var array */ var $capabilities; /** * PHP4 Constructor - Setup object properties. * * The list of capabilities, must have the key as the name of the capability * and the value a boolean of whether it is granted to the role or not. * * @since 2.0.0 * @access public * * @param string $role Role name. * @param array $capabilities List of capabilities. * @return WP_Role */ function WP_Role( $role, $capabilities ) { $this->name = $role; $this->capabilities = $capabilities; } /** * Assign role a capability. * * @see WP_Roles::add_cap() Method uses implementation for role. * @since 2.0.0 * @access public * * @param string $cap Capability name. * @param bool $grant Whether role has capability privilege. */ function add_cap( $cap, $grant = true ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $this->capabilities[$cap] = $grant; $wp_roles->add_cap( $this->name, $cap, $grant ); } /** * Remove capability from role. * * This is a container for {@link WP_Roles::remove_cap()} to remove the * capability from the role. That is to say, that {@link * WP_Roles::remove_cap()} implements the functionality, but it also makes * sense to use this class, because you don't need to enter the role name. * * @since 2.0.0 * @access public * * @param string $cap Capability name. */ function remove_cap( $cap ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); unset( $this->capabilities[$cap] ); $wp_roles->remove_cap( $this->name, $cap ); } /** * Whether role has capability. * * The capabilities is passed through the 'role_has_cap' filter. The first * parameter for the hook is the list of capabilities the class has * assigned. The second parameter is the capability name to look for. The * third and final parameter for the hook is the role name. * * @since 2.0.0 * @access public * * @param string $cap Capability name. * @return bool True, if user has capability. False, if doesn't have capability. */ function has_cap( $cap ) { $capabilities = apply_filters( 'role_has_cap', $this->capabilities, $cap, $this->name ); if ( !empty( $capabilities[$cap] ) ) return $capabilities[$cap]; else return false; } } /** * WordPress User class. * * @since 2.0.0 * @package WordPress * @subpackage User */ class WP_User { /** * User data container. * * This will be set as properties of the object. * * @since 2.0.0 * @access private * @var array */ var $data; /** * The user's ID. * * @since 2.1.0 * @access public * @var int */ var $ID = 0; /** * The deprecated user's ID. * * @since 2.0.0 * @access public * @deprecated Use WP_User::$ID * @see WP_User::$ID * @var int */ var $id = 0; /** * The individual capabilities the user has been given. * * @since 2.0.0 * @access public * @var array */ var $caps = array(); /** * User metadata option name. * * @since 2.0.0 * @access public * @var string */ var $cap_key; /** * The roles the user is part of. * * @since 2.0.0 * @access public * @var array */ var $roles = array(); /** * All capabilities the user has, including individual and role based. * * @since 2.0.0 * @access public * @var array */ var $allcaps = array(); /** * First name of the user. * * Created to prevent notices. * * @since 2.7.0 * @access public * @var string */ var $first_name = ''; /** * Last name of the user. * * Created to prevent notices. * * @since 2.7.0 * @access public * @var string */ var $last_name = ''; /** * PHP4 Constructor - Sets up the object properties. * * Retrieves the userdata and then assigns all of the data keys to direct * properties of the object. Calls {@link WP_User::_init_caps()} after * setting up the object's user data properties. * * @since 2.0.0 * @access public * * @param int|string $id User's ID or username * @param int $name Optional. User's username * @return WP_User */ function WP_User( $id, $name = '' ) { if ( empty( $id ) && empty( $name ) ) return; if ( ! is_numeric( $id ) ) { $name = $id; $id = 0; } if ( ! empty( $id ) ) $this->data = get_userdata( $id ); else $this->data = get_userdatabylogin( $name ); if ( empty( $this->data->ID ) ) return; foreach ( get_object_vars( $this->data ) as $key => $value ) { $this->{$key} = $value; } $this->id = $this->ID; $this->_init_caps(); } /** * Setup capability object properties. * * Will set the value for the 'cap_key' property to current database table * prefix, followed by 'capabilities'. Will then check to see if the * property matching the 'cap_key' exists and is an array. If so, it will be * used. * * @since 2.1.0 * @access protected */ function _init_caps() { global $wpdb; $this->cap_key = $wpdb->prefix . 'capabilities'; $this->caps = &$this->{$this->cap_key}; if ( ! is_array( $this->caps ) ) $this->caps = array(); $this->get_role_caps(); } /** * Retrieve all of the role capabilities and merge with individual capabilities. * * All of the capabilities of the roles the user belongs to are merged with * the users individual roles. This also means that the user can be denied * specific roles that their role might have, but the specific user isn't * granted permission to. * * @since 2.0.0 * @uses $wp_roles * @access public */ function get_role_caps() { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); //Filter out caps that are not role names and assign to $this->roles if ( is_array( $this->caps ) ) $this->roles = array_filter( array_keys( $this->caps ), array( &$wp_roles, 'is_role' ) ); //Build $allcaps from role caps, overlay user's $caps $this->allcaps = array(); foreach ( (array) $this->roles as $role ) { $role = $wp_roles->get_role( $role ); $this->allcaps = array_merge( $this->allcaps, $role->capabilities ); } $this->allcaps = array_merge( $this->allcaps, $this->caps ); } /** * Add role to user. * * Updates the user's meta data option with capabilities and roles. * * @since 2.0.0 * @access public * * @param string $role Role name. */ function add_role( $role ) { $this->caps[$role] = true; update_usermeta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); } /** * Remove role from user. * * @since 2.0.0 * @access public * * @param string $role Role name. */ function remove_role( $role ) { if ( empty( $this->roles[$role] ) || ( count( $this->roles ) <= 1 ) ) return; unset( $this->caps[$role] ); update_usermeta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); } /** * Set the role of the user. * * This will remove the previous roles of the user and assign the user the * new one. You can set the role to an empty string and it will remove all * of the roles from the user. * * @since 2.0.0 * @access public * * @param string $role Role name. */ function set_role( $role ) { foreach ( (array) $this->roles as $oldrole ) unset( $this->caps[$oldrole] ); if ( !empty( $role ) ) { $this->caps[$role] = true; $this->roles = array( $role => true ); } else { $this->roles = false; } update_usermeta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); } /** * Choose the maximum level the user has. * * Will compare the level from the $item parameter against the $max * parameter. If the item is incorrect, then just the $max parameter value * will be returned. * * Used to get the max level based on the capabilities the user has. This * is also based on roles, so if the user is assigned the Administrator role * then the capability 'level_10' will exist and the user will get that * value. * * @since 2.0.0 * @access public * * @param int $max Max level of user. * @param string $item Level capability name. * @return int Max Level. */ function level_reduction( $max, $item ) { if ( preg_match( '/^level_(10|[0-9])$/i', $item, $matches ) ) { $level = intval( $matches[1] ); return max( $max, $level ); } else { return $max; } } /** * Update the maximum user level for the user. * * Updates the 'user_level' user metadata (includes prefix that is the * database table prefix) with the maximum user level. Gets the value from * the all of the capabilities that the user has. * * @since 2.0.0 * @access public */ function update_user_level_from_caps() { global $wpdb; $this->user_level = array_reduce( array_keys( $this->allcaps ), array( &$this, 'level_reduction' ), 0 ); update_usermeta( $this->ID, $wpdb->prefix.'user_level', $this->user_level ); } /** * Add capability and grant or deny access to capability. * * @since 2.0.0 * @access public * * @param string $cap Capability name. * @param bool $grant Whether to grant capability to user. */ function add_cap( $cap, $grant = true ) { $this->caps[$cap] = $grant; update_usermeta( $this->ID, $this->cap_key, $this->caps ); } /** * Remove capability from user. * * @since 2.0.0 * @access public * * @param string $cap Capability name. */ function remove_cap( $cap ) { if ( empty( $this->caps[$cap] ) ) return; unset( $this->caps[$cap] ); update_usermeta( $this->ID, $this->cap_key, $this->caps ); } /** * Remove all of the capabilities of the user. * * @since 2.1.0 * @access public */ function remove_all_caps() { global $wpdb; $this->caps = array(); update_usermeta( $this->ID, $this->cap_key, '' ); update_usermeta( $this->ID, $wpdb->prefix.'user_level', '' ); $this->get_role_caps(); } /** * Whether user has capability or role name. * * This is useful for looking up whether the user has a specific role * assigned to the user. The second optional parameter can also be used to * check for capabilities against a specfic post. * * @since 2.0.0 * @access public * * @param string|int $cap Capability or role name to search. * @param int $post_id Optional. Post ID to check capability against specific post. * @return bool True, if user has capability; false, if user does not have capability. */ function has_cap( $cap ) { if ( is_numeric( $cap ) ) $cap = $this->translate_level_to_cap( $cap ); $args = array_slice( func_get_args(), 1 ); $args = array_merge( array( $cap, $this->ID ), $args ); $caps = call_user_func_array( 'map_meta_cap', $args ); // Must have ALL requested caps $capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args ); foreach ( (array) $caps as $cap ) { //echo "Checking cap $cap<br />"; if ( empty( $capabilities[$cap] ) || !$capabilities[$cap] ) return false; } return true; } /** * Convert numeric level to level capability name. * * Prepends 'level_' to level number. * * @since 2.0.0 * @access public * * @param int $level Level number, 1 to 10. * @return string */ function translate_level_to_cap( $level ) { return 'level_' . $level; } } /** * Map meta capabilities to primitive capabilities. * * This does not actually compare whether the user ID has the actual capability, * just what the capability or capabilities are. Meta capability list value can * be 'delete_user', 'edit_user', 'delete_post', 'delete_page', 'edit_post', * 'edit_page', 'read_post', or 'read_page'. * * @since 2.0.0 * * @param string $cap Capability name. * @param int $user_id User ID. * @return array Actual capabilities for meta capability. */ function map_meta_cap( $cap, $user_id ) { $args = array_slice( func_get_args(), 2 ); $caps = array(); switch ( $cap ) { case 'delete_user': $caps[] = 'delete_users'; break; case 'edit_user': if ( !isset( $args[0] ) || $user_id != $args[0] ) { $caps[] = 'edit_users'; } break; case 'delete_post': $author_data = get_userdata( $user_id ); //echo "post ID: {$args[0]}<br />"; $post = get_post( $args[0] ); if ( 'page' == $post->post_type ) { $args = array_merge( array( 'delete_page', $user_id ), $args ); return call_user_func_array( 'map_meta_cap', $args ); } $post_author_data = get_userdata( $post->post_author ); //echo "current user id : $user_id, post author id: " . $post_author_data->ID . "<br />"; // If the user is the author... if ( $user_id == $post_author_data->ID ) { // If the post is published... if ( 'publish' == $post->post_status ) $caps[] = 'delete_published_posts'; else // If the post is draft... $caps[] = 'delete_posts'; } else { // The user is trying to edit someone else's post. $caps[] = 'delete_others_posts'; // The post is published, extra cap required. if ( 'publish' == $post->post_status ) $caps[] = 'delete_published_posts'; elseif ( 'private' == $post->post_status ) $caps[] = 'delete_private_posts'; } break; case 'delete_page': $author_data = get_userdata( $user_id ); //echo "post ID: {$args[0]}<br />"; $page = get_page( $args[0] ); $page_author_data = get_userdata( $page->post_author ); //echo "current user id : $user_id, page author id: " . $page_author_data->ID . "<br />"; // If the user is the author... if ( $user_id == $page_author_data->ID ) { // If the page is published... if ( $page->post_status == 'publish' ) $caps[] = 'delete_published_pages'; else // If the page is draft... $caps[] = 'delete_pages'; } else { // The user is trying to edit someone else's page. $caps[] = 'delete_others_pages'; // The page is published, extra cap required. if ( $page->post_status == 'publish' ) $caps[] = 'delete_published_pages'; elseif ( $page->post_status == 'private' ) $caps[] = 'delete_private_pages'; } break; // edit_post breaks down to edit_posts, edit_published_posts, or // edit_others_posts case 'edit_post': $author_data = get_userdata( $user_id ); //echo "post ID: {$args[0]}<br />"; $post = get_post( $args[0] ); if ( 'page' == $post->post_type ) { $args = array_merge( array( 'edit_page', $user_id ), $args ); return call_user_func_array( 'map_meta_cap', $args ); } $post_author_data = get_userdata( $post->post_author ); //echo "current user id : $user_id, post author id: " . $post_author_data->ID . "<br />"; // If the user is the author... if ( $user_id == $post_author_data->ID ) { // If the post is published... if ( 'publish' == $post->post_status ) $caps[] = 'edit_published_posts'; else // If the post is draft... $caps[] = 'edit_posts'; } else { // The user is trying to edit someone else's post. $caps[] = 'edit_others_posts'; // The post is published, extra cap required. if ( 'publish' == $post->post_status ) $caps[] = 'edit_published_posts'; elseif ( 'private' == $post->post_status ) $caps[] = 'edit_private_posts'; } break; case 'edit_page': $author_data = get_userdata( $user_id ); //echo "post ID: {$args[0]}<br />"; $page = get_page( $args[0] ); $page_author_data = get_userdata( $page->post_author ); //echo "current user id : $user_id, page author id: " . $page_author_data->ID . "<br />"; // If the user is the author... if ( $user_id == $page_author_data->ID ) { // If the page is published... if ( 'publish' == $page->post_status ) $caps[] = 'edit_published_pages'; else // If the page is draft... $caps[] = 'edit_pages'; } else { // The user is trying to edit someone else's page. $caps[] = 'edit_others_pages'; // The page is published, extra cap required. if ( 'publish' == $page->post_status ) $caps[] = 'edit_published_pages'; elseif ( 'private' == $page->post_status ) $caps[] = 'edit_private_pages'; } break; case 'read_post': $post = get_post( $args[0] ); if ( 'page' == $post->post_type ) { $args = array_merge( array( 'read_page', $user_id ), $args ); return call_user_func_array( 'map_meta_cap', $args ); } if ( 'private' != $post->post_status ) { $caps[] = 'read'; break; } $author_data = get_userdata( $user_id ); $post_author_data = get_userdata( $post->post_author ); if ( $user_id == $post_author_data->ID ) $caps[] = 'read'; else $caps[] = 'read_private_posts'; break; case 'read_page': $page = get_page( $args[0] ); if ( 'private' != $page->post_status ) { $caps[] = 'read'; break; } $author_data = get_userdata( $user_id ); $page_author_data = get_userdata( $page->post_author ); if ( $user_id == $page_author_data->ID ) $caps[] = 'read'; else $caps[] = 'read_private_pages'; break; default: // If no meta caps match, return the original cap. $caps[] = $cap; } return $caps; } /** * Whether current user has capability or role. * * @since 2.0.0 * * @param string $capability Capability or role name. * @return bool */ function current_user_can( $capability ) { $current_user = wp_get_current_user(); if ( empty( $current_user ) ) return false; $args = array_slice( func_get_args(), 1 ); $args = array_merge( array( $capability ), $args ); return call_user_func_array( array( &$current_user, 'has_cap' ), $args ); } /** * Retrieve role object. * * @see WP_Roles::get_role() Uses method to retrieve role object. * @since 2.0.0 * * @param string $role Role name. * @return object */ function get_role( $role ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); return $wp_roles->get_role( $role ); } /** * Add role, if it does not exist. * * @see WP_Roles::add_role() Uses method to add role. * @since 2.0.0 * * @param string $role Role name. * @param string $display_name Display name for role. * @param array $capabilities List of capabilities. * @return null|WP_Role WP_Role object if role is added, null if already exists. */ function add_role( $role, $display_name, $capabilities = array() ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); return $wp_roles->add_role( $role, $display_name, $capabilities ); } /** * Remove role, if it exists. * * @see WP_Roles::remove_role() Uses method to remove role. * @since 2.0.0 * * @param string $role Role name. * @return null */ function remove_role( $role ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); return $wp_roles->remove_role( $role ); } ?>
Java
# Copyright (C) 2011-2018 Project SkyFire <http://www.projectskyfire.org/ # Copyright (C) 2008-2018 TrinityCore <http://www.trinitycore.org/> # # This file is free software; as a special exception the author gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # This file defines the following macros for developers to use in ensuring # that installed software is of the right version: # # ENSURE_VERSION - test that a version number is greater than # or equal to some minimum # ENSURE_VERSION_RANGE - test that a version number is greater than # or equal to some minimum and less than some # maximum # ENSURE_VERSION2 - deprecated, do not use in new code # # ENSURE_VERSION # This macro compares version numbers of the form "x.y.z" or "x.y" # ENSURE_VERSION( FOO_MIN_VERSION FOO_VERSION_FOUND FOO_VERSION_OK) # will set FOO_VERSION_OK to true if FOO_VERSION_FOUND >= FOO_MIN_VERSION # Leading and trailing text is ok, e.g. # ENSURE_VERSION( "2.5.31" "flex 2.5.4a" VERSION_OK) # which means 2.5.31 is required and "flex 2.5.4a" is what was found on the system # Copyright (c) 2006, David Faure, <faure@kde.org> # Copyright (c) 2007, Will Stephenson <wstephenson@kde.org> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # ENSURE_VERSION_RANGE # This macro ensures that a version number of the form # "x.y.z" or "x.y" falls within a range defined by # min_version <= found_version < max_version. # If this expression holds, FOO_VERSION_OK will be set TRUE # # Example: ENSURE_VERSION_RANGE3( "0.1.0" ${FOOCODE_VERSION} "0.7.0" FOO_VERSION_OK ) # # This macro will break silently if any of x,y,z are greater than 100. # # Copyright (c) 2007, Will Stephenson <wstephenson@kde.org> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # NORMALIZE_VERSION # Helper macro to convert version numbers of the form "x.y.z" # to an integer equal to 10^4 * x + 10^2 * y + z # # This macro will break silently if any of x,y,z are greater than 100. # # Copyright (c) 2006, David Faure, <faure@kde.org> # Copyright (c) 2007, Will Stephenson <wstephenson@kde.org> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # CHECK_RANGE_INCLUSIVE_LOWER # Helper macro to check whether x <= y < z # # Copyright (c) 2007, Will Stephenson <wstephenson@kde.org> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. MACRO(NORMALIZE_VERSION _requested_version _normalized_version) STRING(REGEX MATCH "[^0-9]*[0-9]+\\.[0-9]+\\.[0-9]+.*" _threePartMatch "${_requested_version}") if (_threePartMatch) # parse the parts of the version string STRING(REGEX REPLACE "[^0-9]*([0-9]+)\\.[0-9]+\\.[0-9]+.*" "\\1" _major_vers "${_requested_version}") STRING(REGEX REPLACE "[^0-9]*[0-9]+\\.([0-9]+)\\.[0-9]+.*" "\\1" _minor_vers "${_requested_version}") STRING(REGEX REPLACE "[^0-9]*[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" _patch_vers "${_requested_version}") else (_threePartMatch) STRING(REGEX REPLACE "([0-9]+)\\.[0-9]+" "\\1" _major_vers "${_requested_version}") STRING(REGEX REPLACE "[0-9]+\\.([0-9]+)" "\\1" _minor_vers "${_requested_version}") set(_patch_vers "0") endif (_threePartMatch) # compute an overall version number which can be compared at once MATH(EXPR ${_normalized_version} "${_major_vers}*10000 + ${_minor_vers}*100 + ${_patch_vers}") ENDMACRO(NORMALIZE_VERSION) MACRO(CHECK_RANGE_INCLUSIVE_LOWER _lower_limit _value _upper_limit _ok) if (${_value} LESS ${_lower_limit}) set( ${_ok} FALSE ) elseif (${_value} EQUAL ${_lower_limit}) set( ${_ok} TRUE ) elseif (${_value} EQUAL ${_upper_limit}) set( ${_ok} FALSE ) elseif (${_value} GREATER ${_upper_limit}) set( ${_ok} FALSE ) else (${_value} LESS ${_lower_limit}) set( ${_ok} TRUE ) endif (${_value} LESS ${_lower_limit}) ENDMACRO(CHECK_RANGE_INCLUSIVE_LOWER) MACRO(ENSURE_VERSION requested_version found_version var_too_old) NORMALIZE_VERSION( ${requested_version} req_vers_num ) NORMALIZE_VERSION( ${found_version} found_vers_num ) if (found_vers_num LESS req_vers_num) set( ${var_too_old} FALSE ) else (found_vers_num LESS req_vers_num) set( ${var_too_old} TRUE ) endif (found_vers_num LESS req_vers_num) ENDMACRO(ENSURE_VERSION) MACRO(ENSURE_VERSION2 requested_version2 found_version2 var_too_old2) ENSURE_VERSION( ${requested_version2} ${found_version2} ${var_too_old2}) ENDMACRO(ENSURE_VERSION2) MACRO(ENSURE_VERSION_RANGE min_version found_version max_version var_ok) NORMALIZE_VERSION( ${min_version} req_vers_num ) NORMALIZE_VERSION( ${found_version} found_vers_num ) NORMALIZE_VERSION( ${max_version} max_vers_num ) CHECK_RANGE_INCLUSIVE_LOWER( ${req_vers_num} ${found_vers_num} ${max_vers_num} ${var_ok}) ENDMACRO(ENSURE_VERSION_RANGE)
Java
<!DOCTYPE html> <html> <h1>coca_cola_cherry10</h1> <p> BOLD: 2/2 correct and 0/2false</p> <p> SIFT: 2/2 correct and 0/2false</p><br> <img src = "../../../BVD_M01/coca_cola_cherry/coca_cola_cherry10.jpg" alt = "coca_cola_cherry10.html" style= " width:320px;height:240px;"> <h1> Falsely compared to: </h1><br> </html>
Java
class BitStruct # Class for floats (single and double precision) in network order. # Declared with BitStruct.float. class FloatField < Field # Used in describe. def self.class_name @class_name ||= "float" end def add_accessors_to(cl, attr = name) # :nodoc: unless offset % 8 == 0 raise ArgumentError, "Bad offset, #{offset}, for #{self.class} #{name}." + " Must be multiple of 8." end unless length == 32 or length == 64 raise ArgumentError, "Bad length, #{length}, for #{self.class} #{name}." + " Must be 32 or 64." end offset_byte = offset / 8 length_byte = length / 8 last_byte = offset_byte + length_byte - 1 byte_range = offset_byte..last_byte endian = (options[:endian] || options["endian"]).to_s case endian when "native" ctl = case length when 32; "f" when 64; "d" end when "little" ctl = case length when 32; "e" when 64; "E" end when "network", "big", "" ctl = case length when 32; "g" when 64; "G" end else raise ArgumentError, "Unrecognized endian option: #{endian.inspect}" end cl.class_eval do define_method attr do || self[byte_range].unpack(ctl).first end define_method "#{attr}=" do |val| self[byte_range] = [val].pack(ctl) end end end end end
Java
<?php /** * Core Class to enable hooks and actions for Fonts * @version 1.0 */ if(!class_exists('IOAFont')) { class IOAFont { private $fonts; function __construct() { $fonts = array( ); } /** * Retrives all registered fonts. */ public function getFonts() { return $this->fonts; } public function setFont($font,$key) { global $super_options; $this->fonts[$key] = $font; if(!isset($super_options[SN.$key])) $super_options[SN.$key] = $font['default_font']; } } } $fonts = new IOAFont(); function register_font_class($default='',$defined='',$default_font,$label,$addWeight,$subset) { global $fonts; $fonts->setFont(array( 'default_class' => $default , 'defined_class' => $defined , 'default_font' => $default_font, 'label' => $label, 'fontWeight' => $addWeight, 'subset' => $subset ),trim(str_replace(' ','',$default))); } ?>
Java
/****************************************************************************** * * Copyright(c) 2007 - 2011 Realtek Corporation. 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ //============================================================ // include files //============================================================ #include "mp_precomp.h" #include "phydm_precomp.h" u1Byte ODM_GetAutoChannelSelectResult( IN PVOID pDM_VOID, IN u1Byte Band ) { PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; PACS pACS = &pDM_Odm->DM_ACS; #if (DM_ODM_SUPPORT_TYPE & (ODM_WIN|ODM_CE)) if(Band == ODM_BAND_2_4G) { ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("[ACS] ODM_GetAutoChannelSelectResult(): CleanChannel_2G(%d)\n", pACS->CleanChannel_2G)); return (u1Byte)pACS->CleanChannel_2G; } else { ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("[ACS] ODM_GetAutoChannelSelectResult(): CleanChannel_5G(%d)\n", pACS->CleanChannel_5G)); return (u1Byte)pACS->CleanChannel_5G; } #else return (u1Byte)pACS->CleanChannel_2G; #endif } VOID odm_AutoChannelSelectSetting( IN PVOID pDM_VOID, IN BOOLEAN IsEnable ) { #if (DM_ODM_SUPPORT_TYPE & (ODM_WIN|ODM_CE)) PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; u2Byte period = 0x2710;// 40ms in default u2Byte NHMType = 0x7; ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("odm_AutoChannelSelectSetting()=========> \n")); if(IsEnable) {//20 ms period = 0x1388; NHMType = 0x1; } if(pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) { //PHY parameters initialize for ac series ODM_Write2Byte(pDM_Odm, ODM_REG_NHM_TIMER_11AC+2, period); //0x990[31:16]=0x2710 Time duration for NHM unit: 4us, 0x2710=40ms //ODM_SetBBReg(pDM_Odm, ODM_REG_NHM_TH9_TH10_11AC, BIT8|BIT9|BIT10, NHMType); //0x994[9:8]=3 enable CCX } else if (pDM_Odm->SupportICType & ODM_IC_11N_SERIES) { //PHY parameters initialize for n series ODM_Write2Byte(pDM_Odm, ODM_REG_NHM_TIMER_11N+2, period); //0x894[31:16]=0x2710 Time duration for NHM unit: 4us, 0x2710=40ms //ODM_SetBBReg(pDM_Odm, ODM_REG_NHM_TH9_TH10_11N, BIT10|BIT9|BIT8, NHMType); //0x890[9:8]=3 enable CCX } #endif } VOID odm_AutoChannelSelectInit( IN PVOID pDM_VOID ) { #if (DM_ODM_SUPPORT_TYPE & (ODM_WIN|ODM_CE)) PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; PACS pACS = &pDM_Odm->DM_ACS; u1Byte i; if(!(pDM_Odm->SupportAbility & ODM_BB_NHM_CNT)) return; if(pACS->bForceACSResult) return; ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("odm_AutoChannelSelectInit()=========> \n")); pACS->CleanChannel_2G = 1; pACS->CleanChannel_5G = 36; for (i = 0; i < ODM_MAX_CHANNEL_2G; ++i) { pACS->Channel_Info_2G[0][i] = 0; pACS->Channel_Info_2G[1][i] = 0; } if(pDM_Odm->SupportICType & (ODM_IC_11AC_SERIES|ODM_RTL8192D)) { for (i = 0; i < ODM_MAX_CHANNEL_5G; ++i) { pACS->Channel_Info_5G[0][i] = 0; pACS->Channel_Info_5G[1][i] = 0; } } #endif } VOID odm_AutoChannelSelectReset( IN PVOID pDM_VOID ) { #if (DM_ODM_SUPPORT_TYPE & (ODM_WIN|ODM_CE)) PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; PACS pACS = &pDM_Odm->DM_ACS; if(!(pDM_Odm->SupportAbility & ODM_BB_NHM_CNT)) return; if(pACS->bForceACSResult) return; ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("odm_AutoChannelSelectReset()=========> \n")); odm_AutoChannelSelectSetting(pDM_Odm,TRUE);// for 20ms measurement Phydm_NHMCounterStatisticsReset(pDM_Odm); #endif } VOID odm_AutoChannelSelect( IN PVOID pDM_VOID, IN u1Byte Channel ) { #if (DM_ODM_SUPPORT_TYPE & (ODM_WIN|ODM_CE)) PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; PACS pACS = &pDM_Odm->DM_ACS; u1Byte ChannelIDX = 0, SearchIDX = 0; u2Byte MaxScore=0; if(!(pDM_Odm->SupportAbility & ODM_BB_NHM_CNT)) { ODM_RT_TRACE(pDM_Odm,ODM_COMP_DIG, ODM_DBG_LOUD, ("odm_AutoChannelSelect(): Return: SupportAbility ODM_BB_NHM_CNT is disabled\n")); return; } if(pACS->bForceACSResult) { ODM_RT_TRACE(pDM_Odm,ODM_COMP_DIG, ODM_DBG_LOUD, ("odm_AutoChannelSelect(): Force 2G clean channel = %d, 5G clean channel = %d\n", pACS->CleanChannel_2G, pACS->CleanChannel_5G)); return; } ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("odm_AutoChannelSelect(): Channel = %d=========> \n", Channel)); Phydm_GetNHMCounterStatistics(pDM_Odm); odm_AutoChannelSelectSetting(pDM_Odm,FALSE); if(Channel >=1 && Channel <=14) { ChannelIDX = Channel - 1; pACS->Channel_Info_2G[1][ChannelIDX]++; if(pACS->Channel_Info_2G[1][ChannelIDX] >= 2) pACS->Channel_Info_2G[0][ChannelIDX] = (pACS->Channel_Info_2G[0][ChannelIDX] >> 1) + (pACS->Channel_Info_2G[0][ChannelIDX] >> 2) + (pDM_Odm->NHM_cnt_0>>2); else pACS->Channel_Info_2G[0][ChannelIDX] = pDM_Odm->NHM_cnt_0; ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("odm_AutoChannelSelect(): NHM_cnt_0 = %d \n", pDM_Odm->NHM_cnt_0)); ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("odm_AutoChannelSelect(): Channel_Info[0][%d] = %d, Channel_Info[1][%d] = %d\n", ChannelIDX, pACS->Channel_Info_2G[0][ChannelIDX], ChannelIDX, pACS->Channel_Info_2G[1][ChannelIDX])); for(SearchIDX = 0; SearchIDX < ODM_MAX_CHANNEL_2G; SearchIDX++) { if(pACS->Channel_Info_2G[1][SearchIDX] != 0) { if(pACS->Channel_Info_2G[0][SearchIDX] >= MaxScore) { MaxScore = pACS->Channel_Info_2G[0][SearchIDX]; pACS->CleanChannel_2G = SearchIDX+1; } } } ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("(1)odm_AutoChannelSelect(): 2G: CleanChannel_2G = %d, MaxScore = %d \n", pACS->CleanChannel_2G, MaxScore)); } else if(Channel >= 36) { // Need to do pACS->CleanChannel_5G = Channel; } #endif } #if ( DM_ODM_SUPPORT_TYPE & ODM_AP ) VOID phydm_AutoChannelSelectSettingAP( IN PVOID pDM_VOID, IN u4Byte setting, // 0: STORE_DEFAULT_NHM_SETTING; 1: RESTORE_DEFAULT_NHM_SETTING, 2: ACS_NHM_SETTING IN u4Byte acs_step ) { PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; prtl8192cd_priv priv = pDM_Odm->priv; PACS pACS = &pDM_Odm->DM_ACS; ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("odm_AutoChannelSelectSettingAP()=========> \n")); //3 Store Default Setting if(setting == STORE_DEFAULT_NHM_SETTING) { ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("STORE_DEFAULT_NHM_SETTING\n")); if(pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) // store Reg0x990, Reg0x994, Reg0x998, Reg0x99C, Reg0x9a0 { pACS->Reg0x990 = ODM_Read4Byte(pDM_Odm, ODM_REG_NHM_TIMER_11AC); // Reg0x990 pACS->Reg0x994 = ODM_Read4Byte(pDM_Odm, ODM_REG_NHM_TH9_TH10_11AC); // Reg0x994 pACS->Reg0x998 = ODM_Read4Byte(pDM_Odm, ODM_REG_NHM_TH3_TO_TH0_11AC); // Reg0x998 pACS->Reg0x99C = ODM_Read4Byte(pDM_Odm, ODM_REG_NHM_TH7_TO_TH4_11AC); // Reg0x99c pACS->Reg0x9A0 = ODM_Read1Byte(pDM_Odm, ODM_REG_NHM_TH8_11AC); // Reg0x9a0, u1Byte } else if(pDM_Odm->SupportICType & ODM_IC_11N_SERIES) { pACS->Reg0x890 = ODM_Read4Byte(pDM_Odm, ODM_REG_NHM_TH9_TH10_11N); // Reg0x890 pACS->Reg0x894 = ODM_Read4Byte(pDM_Odm, ODM_REG_NHM_TIMER_11N); // Reg0x894 pACS->Reg0x898 = ODM_Read4Byte(pDM_Odm, ODM_REG_NHM_TH3_TO_TH0_11N); // Reg0x898 pACS->Reg0x89C = ODM_Read4Byte(pDM_Odm, ODM_REG_NHM_TH7_TO_TH4_11N); // Reg0x89c pACS->Reg0xE28 = ODM_Read1Byte(pDM_Odm, ODM_REG_NHM_TH8_11N); // Reg0xe28, u1Byte } } //3 Restore Default Setting else if(setting == RESTORE_DEFAULT_NHM_SETTING) { ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("RESTORE_DEFAULT_NHM_SETTING\n")); if(pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) // store Reg0x990, Reg0x994, Reg0x998, Reg0x99C, Reg0x9a0 { ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TIMER_11AC, pACS->Reg0x990); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH9_TH10_11AC, pACS->Reg0x994); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH3_TO_TH0_11AC, pACS->Reg0x998); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH7_TO_TH4_11AC, pACS->Reg0x99C); ODM_Write1Byte(pDM_Odm, ODM_REG_NHM_TH8_11AC, pACS->Reg0x9A0); } else if(pDM_Odm->SupportICType & ODM_IC_11N_SERIES) { ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH9_TH10_11N, pACS->Reg0x890); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TIMER_11N, pACS->Reg0x894); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH3_TO_TH0_11N, pACS->Reg0x898); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH7_TO_TH4_11N, pACS->Reg0x89C); ODM_Write1Byte(pDM_Odm, ODM_REG_NHM_TH8_11N, pACS->Reg0xE28); } } //3 ACS Setting else if(setting == ACS_NHM_SETTING) { ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("ACS_NHM_SETTING\n")); u2Byte period; period = 0x61a8; pACS->ACS_Step = acs_step; if(pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) { //4 Set NHM period, 0x990[31:16]=0x61a8, Time duration for NHM unit: 4us, 0x61a8=100ms ODM_Write2Byte(pDM_Odm, ODM_REG_NHM_TIMER_11AC+2, period); //4 Set NHM ignore_cca=1, ignore_txon=1, ccx_en=0 ODM_SetBBReg(pDM_Odm, ODM_REG_NHM_TH9_TH10_11AC,BIT8|BIT9|BIT10, 3); if(pACS->ACS_Step == 0) { //4 Set IGI ODM_SetBBReg(pDM_Odm,0xc50,BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6,0x3E); if (get_rf_mimo_mode(priv) != MIMO_1T1R) ODM_SetBBReg(pDM_Odm,0xe50,BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6,0x3E); //4 Set ACS NHM threshold ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH3_TO_TH0_11AC, 0x82786e64); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH7_TO_TH4_11AC, 0xffffff8c); ODM_Write1Byte(pDM_Odm, ODM_REG_NHM_TH8_11AC, 0xff); ODM_Write2Byte(pDM_Odm, ODM_REG_NHM_TH9_TH10_11AC+2, 0xffff); } else if(pACS->ACS_Step == 1) { //4 Set IGI ODM_SetBBReg(pDM_Odm,0xc50,BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6,0x2A); if (get_rf_mimo_mode(priv) != MIMO_1T1R) ODM_SetBBReg(pDM_Odm,0xe50,BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6,0x2A); //4 Set ACS NHM threshold ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH3_TO_TH0_11AC, 0x5a50463c); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH7_TO_TH4_11AC, 0xffffff64); } } else if (pDM_Odm->SupportICType & ODM_IC_11N_SERIES) { //4 Set NHM period, 0x894[31:16]=0x61a8, Time duration for NHM unit: 4us, 0x61a8=100ms ODM_Write2Byte(pDM_Odm, ODM_REG_NHM_TIMER_11N+2, period); //4 Set NHM ignore_cca=1, ignore_txon=1, ccx_en=0 ODM_SetBBReg(pDM_Odm, ODM_REG_NHM_TH9_TH10_11N,BIT8|BIT9|BIT10, 3); if(pACS->ACS_Step == 0) { //4 Set IGI ODM_SetBBReg(pDM_Odm,0xc50,BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6,0x3E); if (get_rf_mimo_mode(priv) != MIMO_1T1R) ODM_SetBBReg(pDM_Odm,0xc58,BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6,0x3E); //4 Set ACS NHM threshold ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH3_TO_TH0_11N, 0x82786e64); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH7_TO_TH4_11N, 0xffffff8c); ODM_Write1Byte(pDM_Odm, ODM_REG_NHM_TH8_11N, 0xff); ODM_Write2Byte(pDM_Odm, ODM_REG_NHM_TH9_TH10_11N+2, 0xffff); } else if(pACS->ACS_Step == 1) { //4 Set IGI ODM_SetBBReg(pDM_Odm,0xc50,BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6,0x2A); if (get_rf_mimo_mode(priv) != MIMO_1T1R) ODM_SetBBReg(pDM_Odm,0xc58,BIT0|BIT1|BIT2|BIT3|BIT4|BIT5|BIT6,0x2A); //4 Set ACS NHM threshold ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH3_TO_TH0_11N, 0x5a50463c); ODM_Write4Byte(pDM_Odm, ODM_REG_NHM_TH7_TO_TH4_11N, 0xffffff64); } } } } VOID phydm_GetNHMStatisticsAP( IN PVOID pDM_VOID, IN u4Byte idx, // @ 2G, Real channel number = idx+1 IN u4Byte acs_step ) { PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; prtl8192cd_priv priv = pDM_Odm->priv; PACS pACS = &pDM_Odm->DM_ACS; u4Byte value32 = 0; u1Byte i; pACS->ACS_Step = acs_step; if(pDM_Odm->SupportICType & ODM_IC_11N_SERIES) { //4 Check if NHM result is ready for (i=0; i<20; i++) { ODM_delay_ms(1); if ( ODM_GetBBReg(pDM_Odm,rFPGA0_PSDReport,BIT17) ) break; } //4 Get NHM Statistics if ( pACS->ACS_Step==1 ) { value32 = ODM_Read4Byte(pDM_Odm,ODM_REG_NHM_CNT7_TO_CNT4_11N); pACS->NHM_Cnt[idx][9] = (value32 & bMaskByte1) >> 8; pACS->NHM_Cnt[idx][8] = (value32 & bMaskByte0); value32 = ODM_Read4Byte(pDM_Odm,ODM_REG_NHM_CNT_11N); // ODM_REG_NHM_CNT3_TO_CNT0_11N pACS->NHM_Cnt[idx][7] = (value32 & bMaskByte3) >> 24; pACS->NHM_Cnt[idx][6] = (value32 & bMaskByte2) >> 16; pACS->NHM_Cnt[idx][5] = (value32 & bMaskByte1) >> 8; } else if (pACS->ACS_Step==2) { value32 = ODM_Read4Byte(pDM_Odm,ODM_REG_NHM_CNT_11N); // ODM_REG_NHM_CNT3_TO_CNT0_11N pACS->NHM_Cnt[idx][4] = ODM_Read1Byte(pDM_Odm, ODM_REG_NHM_CNT7_TO_CNT4_11N); pACS->NHM_Cnt[idx][3] = (value32 & bMaskByte3) >> 24; pACS->NHM_Cnt[idx][2] = (value32 & bMaskByte2) >> 16; pACS->NHM_Cnt[idx][1] = (value32 & bMaskByte1) >> 8; pACS->NHM_Cnt[idx][0] = (value32 & bMaskByte0); } } else if(pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) { //4 Check if NHM result is ready for (i=0; i<20; i++) { ODM_delay_ms(1); if (ODM_GetBBReg(pDM_Odm,ODM_REG_NHM_DUR_READY_11AC,BIT17)) break; } if ( pACS->ACS_Step==1 ) { value32 = ODM_Read4Byte(pDM_Odm,ODM_REG_NHM_CNT7_TO_CNT4_11AC); pACS->NHM_Cnt[idx][9] = (value32 & bMaskByte1) >> 8; pACS->NHM_Cnt[idx][8] = (value32 & bMaskByte0); value32 = ODM_Read4Byte(pDM_Odm,ODM_REG_NHM_CNT_11AC); // ODM_REG_NHM_CNT3_TO_CNT0_11AC pACS->NHM_Cnt[idx][7] = (value32 & bMaskByte3) >> 24; pACS->NHM_Cnt[idx][6] = (value32 & bMaskByte2) >> 16; pACS->NHM_Cnt[idx][5] = (value32 & bMaskByte1) >> 8; } else if (pACS->ACS_Step==2) { value32 = ODM_Read4Byte(pDM_Odm,ODM_REG_NHM_CNT_11AC); // ODM_REG_NHM_CNT3_TO_CNT0_11AC pACS->NHM_Cnt[idx][4] = ODM_Read1Byte(pDM_Odm, ODM_REG_NHM_CNT7_TO_CNT4_11AC); pACS->NHM_Cnt[idx][3] = (value32 & bMaskByte3) >> 24; pACS->NHM_Cnt[idx][2] = (value32 & bMaskByte2) >> 16; pACS->NHM_Cnt[idx][1] = (value32 & bMaskByte1) >> 8; pACS->NHM_Cnt[idx][0] = (value32 & bMaskByte0); } } } //#define ACS_DEBUG_INFO //acs debug default off /* int phydm_AutoChannelSelectAP( IN PVOID pDM_VOID, IN u4Byte ACS_Type, // 0: RXCount_Type, 1:NHM_Type IN u4Byte available_chnl_num // amount of all channels ) { PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; PACS pACS = &pDM_Odm->DM_ACS; prtl8192cd_priv priv = pDM_Odm->priv; static u4Byte score2G[MAX_2G_CHANNEL_NUM], score5G[MAX_5G_CHANNEL_NUM]; u4Byte score[MAX_BSS_NUM], use_nhm = 0; u4Byte minScore=0xffffffff; u4Byte tmpScore, tmpIdx=0; u4Byte traffic_check = 0; u4Byte fa_count_weighting = 1; int i, j, idx=0, idx_2G_end=-1, idx_5G_begin=-1, minChan=0; struct bss_desc *pBss=NULL; #ifdef _DEBUG_RTL8192CD_ char tmpbuf[400]; int len=0; #endif memset(score2G, '\0', sizeof(score2G)); memset(score5G, '\0', sizeof(score5G)); for (i=0; i<priv->available_chnl_num; i++) { if (priv->available_chnl[i] <= 14) idx_2G_end = i; else break; } for (i=0; i<priv->available_chnl_num; i++) { if (priv->available_chnl[i] > 14) { idx_5G_begin = i; break; } } // DELETE #ifndef CONFIG_RTL_NEW_AUTOCH for (i=0; i<priv->site_survey->count; i++) { pBss = &priv->site_survey->bss[i]; for (idx=0; idx<priv->available_chnl_num; idx++) { if (pBss->channel == priv->available_chnl[idx]) { if (pBss->channel <= 14) setChannelScore(idx, score2G, 0, MAX_2G_CHANNEL_NUM-1); else score5G[idx - idx_5G_begin] += 5; break; } } } #endif if (idx_2G_end >= 0) for (i=0; i<=idx_2G_end; i++) score[i] = score2G[i]; if (idx_5G_begin >= 0) for (i=idx_5G_begin; i<priv->available_chnl_num; i++) score[i] = score5G[i - idx_5G_begin]; #ifdef CONFIG_RTL_NEW_AUTOCH { u4Byte y, ch_begin=0, ch_end= priv->available_chnl_num; u4Byte do_ap_check = 1, ap_ratio = 0; if (idx_2G_end >= 0) ch_end = idx_2G_end+1; if (idx_5G_begin >= 0) ch_begin = idx_5G_begin; #ifdef ACS_DEBUG_INFO//for debug printk("\n"); for (y=ch_begin; y<ch_end; y++) printk("1. init: chnl[%d] 20M_rx[%d] 40M_rx[%d] fa_cnt[%d] score[%d]\n", priv->available_chnl[y], priv->chnl_ss_mac_rx_count[y], priv->chnl_ss_mac_rx_count_40M[y], priv->chnl_ss_fa_count[y], score[y]); printk("\n"); #endif #if defined(CONFIG_RTL_88E_SUPPORT) || defined(CONFIG_WLAN_HAL_8192EE) if( pDM_Odm->SupportICType&(ODM_RTL8188E|ODM_RTL8192E)&& priv->pmib->dot11RFEntry.acs_type ) { u4Byte tmp_score[MAX_BSS_NUM]; memcpy(tmp_score, score, sizeof(score)); if (find_clean_channel(priv, ch_begin, ch_end, tmp_score)) { //memcpy(score, tmp_score, sizeof(score)); #ifdef _DEBUG_RTL8192CD_ printk("!! Found clean channel, select minimum FA channel\n"); #endif goto USE_CLN_CH; } #ifdef _DEBUG_RTL8192CD_ printk("!! Not found clean channel, use NHM algorithm\n"); #endif use_nhm = 1; USE_CLN_CH: for (y=ch_begin; y<ch_end; y++) { for (i=0; i<=9; i++) { u4Byte val32 = priv->nhm_cnt[y][i]; for (j=0; j<i; j++) val32 *= 3; score[y] += val32; } #ifdef _DEBUG_RTL8192CD_ printk("nhm_cnt_%d: H<-[ %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d]->L, score: %d\n", y+1, priv->nhm_cnt[y][9], priv->nhm_cnt[y][8], priv->nhm_cnt[y][7], priv->nhm_cnt[y][6], priv->nhm_cnt[y][5], priv->nhm_cnt[y][4], priv->nhm_cnt[y][3], priv->nhm_cnt[y][2], priv->nhm_cnt[y][1], priv->nhm_cnt[y][0], score[y]); #endif } if (!use_nhm) memcpy(score, tmp_score, sizeof(score)); goto choose_ch; } #endif // For each channel, weighting behind channels with MAC RX counter //For each channel, weighting the channel with FA counter for (y=ch_begin; y<ch_end; y++) { score[y] += 8 * priv->chnl_ss_mac_rx_count[y]; if (priv->chnl_ss_mac_rx_count[y] > 30) do_ap_check = 0; if( priv->chnl_ss_mac_rx_count[y] > MAC_RX_COUNT_THRESHOLD ) traffic_check = 1; #ifdef RTK_5G_SUPPORT if (priv->pmib->dot11RFEntry.phyBandSelect == PHY_BAND_2G) #endif { if ((int)(y-4) >= (int)ch_begin) score[y-4] += 2 * priv->chnl_ss_mac_rx_count[y]; if ((int)(y-3) >= (int)ch_begin) score[y-3] += 8 * priv->chnl_ss_mac_rx_count[y]; if ((int)(y-2) >= (int)ch_begin) score[y-2] += 8 * priv->chnl_ss_mac_rx_count[y]; if ((int)(y-1) >= (int)ch_begin) score[y-1] += 10 * priv->chnl_ss_mac_rx_count[y]; if ((int)(y+1) < (int)ch_end) score[y+1] += 10 * priv->chnl_ss_mac_rx_count[y]; if ((int)(y+2) < (int)ch_end) score[y+2] += 8 * priv->chnl_ss_mac_rx_count[y]; if ((int)(y+3) < (int)ch_end) score[y+3] += 8 * priv->chnl_ss_mac_rx_count[y]; if ((int)(y+4) < (int)ch_end) score[y+4] += 2 * priv->chnl_ss_mac_rx_count[y]; } //this is for CH_LOAD caculation if( priv->chnl_ss_cca_count[y] > priv->chnl_ss_fa_count[y]) priv->chnl_ss_cca_count[y]-= priv->chnl_ss_fa_count[y]; else priv->chnl_ss_cca_count[y] = 0; } #ifdef ACS_DEBUG_INFO//for debug printk("\n"); for (y=ch_begin; y<ch_end; y++) printk("2. after 20M check: chnl[%d] score[%d]\n",priv->available_chnl[y], score[y]); printk("\n"); #endif for (y=ch_begin; y<ch_end; y++) { if (priv->chnl_ss_mac_rx_count_40M[y]) { score[y] += 5 * priv->chnl_ss_mac_rx_count_40M[y]; if (priv->chnl_ss_mac_rx_count_40M[y] > 30) do_ap_check = 0; if( priv->chnl_ss_mac_rx_count_40M[y] > MAC_RX_COUNT_THRESHOLD ) traffic_check = 1; #ifdef RTK_5G_SUPPORT if (priv->pmib->dot11RFEntry.phyBandSelect == PHY_BAND_2G) #endif { if ((int)(y-6) >= (int)ch_begin) score[y-6] += 1 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y-5) >= (int)ch_begin) score[y-5] += 4 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y-4) >= (int)ch_begin) score[y-4] += 4 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y-3) >= (int)ch_begin) score[y-3] += 5 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y-2) >= (int)ch_begin) score[y-2] += (5 * priv->chnl_ss_mac_rx_count_40M[y])/2; if ((int)(y-1) >= (int)ch_begin) score[y-1] += 5 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y+1) < (int)ch_end) score[y+1] += 5 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y+2) < (int)ch_end) score[y+2] += (5 * priv->chnl_ss_mac_rx_count_40M[y])/2; if ((int)(y+3) < (int)ch_end) score[y+3] += 5 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y+4) < (int)ch_end) score[y+4] += 4 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y+5) < (int)ch_end) score[y+5] += 4 * priv->chnl_ss_mac_rx_count_40M[y]; if ((int)(y+6) < (int)ch_end) score[y+6] += 1 * priv->chnl_ss_mac_rx_count_40M[y]; } } } #ifdef ACS_DEBUG_INFO//for debug printk("\n"); for (y=ch_begin; y<ch_end; y++) printk("3. after 40M check: chnl[%d] score[%d]\n",priv->available_chnl[y], score[y]); printk("\n"); printk("4. do_ap_check=%d traffic_check=%d\n", do_ap_check, traffic_check); printk("\n"); #endif if( traffic_check == 0) fa_count_weighting = 5; else fa_count_weighting = 1; for (y=ch_begin; y<ch_end; y++) { score[y] += fa_count_weighting * priv->chnl_ss_fa_count[y]; } #ifdef ACS_DEBUG_INFO//for debug printk("\n"); for (y=ch_begin; y<ch_end; y++) printk("5. after fa check: chnl[%d] score[%d]\n",priv->available_chnl[y], score[y]); printk("\n"); #endif if (do_ap_check) { for (i=0; i<priv->site_survey->count; i++) { pBss = &priv->site_survey->bss[i]; for (y=ch_begin; y<ch_end; y++) { if (pBss->channel == priv->available_chnl[y]) { if (pBss->channel <= 14) { #ifdef ACS_DEBUG_INFO//for debug printk("\n"); printk("chnl[%d] has ap rssi=%d bw[0x%02x]\n", pBss->channel, pBss->rssi, pBss->t_stamp[1]); printk("\n"); #endif if (pBss->rssi > 60) ap_ratio = 4; else if (pBss->rssi > 35) ap_ratio = 2; else ap_ratio = 1; if ((pBss->t_stamp[1] & 0x6) == 0) { score[y] += 50 * ap_ratio; if ((int)(y-4) >= (int)ch_begin) score[y-4] += 10 * ap_ratio; if ((int)(y-3) >= (int)ch_begin) score[y-3] += 20 * ap_ratio; if ((int)(y-2) >= (int)ch_begin) score[y-2] += 30 * ap_ratio; if ((int)(y-1) >= (int)ch_begin) score[y-1] += 40 * ap_ratio; if ((int)(y+1) < (int)ch_end) score[y+1] += 40 * ap_ratio; if ((int)(y+2) < (int)ch_end) score[y+2] += 30 * ap_ratio; if ((int)(y+3) < (int)ch_end) score[y+3] += 20 * ap_ratio; if ((int)(y+4) < (int)ch_end) score[y+4] += 10 * ap_ratio; } else if ((pBss->t_stamp[1] & 0x4) == 0) { score[y] += 50 * ap_ratio; if ((int)(y-3) >= (int)ch_begin) score[y-3] += 20 * ap_ratio; if ((int)(y-2) >= (int)ch_begin) score[y-2] += 30 * ap_ratio; if ((int)(y-1) >= (int)ch_begin) score[y-1] += 40 * ap_ratio; if ((int)(y+1) < (int)ch_end) score[y+1] += 50 * ap_ratio; if ((int)(y+2) < (int)ch_end) score[y+2] += 50 * ap_ratio; if ((int)(y+3) < (int)ch_end) score[y+3] += 50 * ap_ratio; if ((int)(y+4) < (int)ch_end) score[y+4] += 50 * ap_ratio; if ((int)(y+5) < (int)ch_end) score[y+5] += 40 * ap_ratio; if ((int)(y+6) < (int)ch_end) score[y+6] += 30 * ap_ratio; if ((int)(y+7) < (int)ch_end) score[y+7] += 20 * ap_ratio; } else { score[y] += 50 * ap_ratio; if ((int)(y-7) >= (int)ch_begin) score[y-7] += 20 * ap_ratio; if ((int)(y-6) >= (int)ch_begin) score[y-6] += 30 * ap_ratio; if ((int)(y-5) >= (int)ch_begin) score[y-5] += 40 * ap_ratio; if ((int)(y-4) >= (int)ch_begin) score[y-4] += 50 * ap_ratio; if ((int)(y-3) >= (int)ch_begin) score[y-3] += 50 * ap_ratio; if ((int)(y-2) >= (int)ch_begin) score[y-2] += 50 * ap_ratio; if ((int)(y-1) >= (int)ch_begin) score[y-1] += 50 * ap_ratio; if ((int)(y+1) < (int)ch_end) score[y+1] += 40 * ap_ratio; if ((int)(y+2) < (int)ch_end) score[y+2] += 30 * ap_ratio; if ((int)(y+3) < (int)ch_end) score[y+3] += 20 * ap_ratio; } } else { if ((pBss->t_stamp[1] & 0x6) == 0) { score[y] += 500; } else if ((pBss->t_stamp[1] & 0x4) == 0) { score[y] += 500; if ((int)(y+1) < (int)ch_end) score[y+1] += 500; } else { score[y] += 500; if ((int)(y-1) >= (int)ch_begin) score[y-1] += 500; } } break; } } } } #ifdef ACS_DEBUG_INFO//for debug printk("\n"); for (y=ch_begin; y<ch_end; y++) printk("6. after ap check: chnl[%d]:%d\n", priv->available_chnl[y],score[y]); printk("\n"); #endif #ifdef SS_CH_LOAD_PROC // caculate noise level -- suggested by wilson for (y=ch_begin; y<ch_end; y++) { int fa_lv=0, cca_lv=0; if (priv->chnl_ss_fa_count[y]>1000) { fa_lv = 100; } else if (priv->chnl_ss_fa_count[y]>500) { fa_lv = 34 * (priv->chnl_ss_fa_count[y]-500) / 500 + 66; } else if (priv->chnl_ss_fa_count[y]>200) { fa_lv = 33 * (priv->chnl_ss_fa_count[y] - 200) / 300 + 33; } else if (priv->chnl_ss_fa_count[y]>100) { fa_lv = 18 * (priv->chnl_ss_fa_count[y] - 100) / 100 + 15; } else { fa_lv = 15 * priv->chnl_ss_fa_count[y] / 100; } if (priv->chnl_ss_cca_count[y]>400) { cca_lv = 100; } else if (priv->chnl_ss_cca_count[y]>200) { cca_lv = 34 * (priv->chnl_ss_cca_count[y] - 200) / 200 + 66; } else if (priv->chnl_ss_cca_count[y]>80) { cca_lv = 33 * (priv->chnl_ss_cca_count[y] - 80) / 120 + 33; } else if (priv->chnl_ss_cca_count[y]>40) { cca_lv = 18 * (priv->chnl_ss_cca_count[y] - 40) / 40 + 15; } else { cca_lv = 15 * priv->chnl_ss_cca_count[y] / 40; } priv->chnl_ss_load[y] = (((fa_lv > cca_lv)? fa_lv : cca_lv)*75+((score[y]>100)?100:score[y])*25)/100; DEBUG_INFO("ch:%d f=%d (%d), c=%d (%d), fl=%d, cl=%d, sc=%d, cu=%d\n", priv->available_chnl[y], priv->chnl_ss_fa_count[y], fa_thd, priv->chnl_ss_cca_count[y], cca_thd, fa_lv, cca_lv, score[y], priv->chnl_ss_load[y]); } #endif } #endif choose_ch: #ifdef DFS // heavy weighted DFS channel if (idx_5G_begin >= 0){ for (i=idx_5G_begin; i<priv->available_chnl_num; i++) { if (!priv->pmib->dot11DFSEntry.disable_DFS && is_DFS_channel(priv->available_chnl[i]) && (score[i]!= 0xffffffff)){ score[i] += 1600; } } } #endif //prevent Auto Channel selecting wrong channel in 40M mode----------------- if ((priv->pmib->dot11BssType.net_work_type & WIRELESS_11N) && priv->pshare->is_40m_bw) { #if 0 if (GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset == 1) { //Upper Primary Channel, cannot select the two lowest channels if (priv->pmib->dot11BssType.net_work_type & WIRELESS_11G) { score[0] = 0xffffffff; score[1] = 0xffffffff; score[2] = 0xffffffff; score[3] = 0xffffffff; score[4] = 0xffffffff; score[13] = 0xffffffff; score[12] = 0xffffffff; score[11] = 0xffffffff; } // if (priv->pmib->dot11BssType.net_work_type & WIRELESS_11A) { // score[idx_5G_begin] = 0xffffffff; // score[idx_5G_begin + 1] = 0xffffffff; // } } else if (GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset == 2) { //Lower Primary Channel, cannot select the two highest channels if (priv->pmib->dot11BssType.net_work_type & WIRELESS_11G) { score[0] = 0xffffffff; score[1] = 0xffffffff; score[2] = 0xffffffff; score[13] = 0xffffffff; score[12] = 0xffffffff; score[11] = 0xffffffff; score[10] = 0xffffffff; score[9] = 0xffffffff; } // if (priv->pmib->dot11BssType.net_work_type & WIRELESS_11A) { // score[priv->available_chnl_num - 2] = 0xffffffff; // score[priv->available_chnl_num - 1] = 0xffffffff; // } } #endif for (i=0; i<=idx_2G_end; ++i) if (priv->available_chnl[i] == 14) score[i] = 0xffffffff; // mask chan14 #ifdef RTK_5G_SUPPORT if (idx_5G_begin >= 0) { for (i=idx_5G_begin; i<priv->available_chnl_num; i++) { int ch = priv->available_chnl[i]; if(priv->available_chnl[i] > 144) --ch; if((ch%4) || ch==140 || ch == 164 ) //mask ch 140, ch 165, ch 184... score[i] = 0xffffffff; } } #endif } if (priv->pmib->dot11RFEntry.disable_ch1213) { for (i=0; i<=idx_2G_end; ++i) { int ch = priv->available_chnl[i]; if ((ch == 12) || (ch == 13)) score[i] = 0xffffffff; } } if (((priv->pmib->dot11StationConfigEntry.dot11RegDomain == DOMAIN_GLOBAL) || (priv->pmib->dot11StationConfigEntry.dot11RegDomain == DOMAIN_WORLD_WIDE)) && (idx_2G_end >= 11) && (idx_2G_end < 14)) { score[13] = 0xffffffff; // mask chan14 score[12] = 0xffffffff; // mask chan13 score[11] = 0xffffffff; // mask chan12 } //------------------------------------------------------------------ #ifdef _DEBUG_RTL8192CD_ for (i=0; i<priv->available_chnl_num; i++) { len += sprintf(tmpbuf+len, "ch%d:%u ", priv->available_chnl[i], score[i]); } strcat(tmpbuf, "\n"); panic_printk("%s", tmpbuf); #endif if ( (priv->pmib->dot11RFEntry.phyBandSelect == PHY_BAND_5G) && (priv->pmib->dot11nConfigEntry.dot11nUse40M == HT_CHANNEL_WIDTH_80)) { for (i=0; i<priv->available_chnl_num; i++) { if (is80MChannel(priv->available_chnl, priv->available_chnl_num, priv->available_chnl[i])) { tmpScore = 0; for (j=0; j<4; j++) { if ((tmpScore != 0xffffffff) && (score[i+j] != 0xffffffff)) tmpScore += score[i+j]; else tmpScore = 0xffffffff; } tmpScore = tmpScore / 4; if (minScore > tmpScore) { minScore = tmpScore; tmpScore = 0xffffffff; for (j=0; j<4; j++) { if (score[i+j] < tmpScore) { tmpScore = score[i+j]; tmpIdx = i+j; } } idx = tmpIdx; } i += 3; } } if (minScore == 0xffffffff) { // there is no 80M channels priv->pshare->is_40m_bw = HT_CHANNEL_WIDTH_20; for (i=0; i<priv->available_chnl_num; i++) { if (score[i] < minScore) { minScore = score[i]; idx = i; } } } } else if( (priv->pmib->dot11RFEntry.phyBandSelect == PHY_BAND_5G) && (priv->pmib->dot11nConfigEntry.dot11nUse40M == HT_CHANNEL_WIDTH_20_40)) { for (i=0; i<priv->available_chnl_num; i++) { if(is40MChannel(priv->available_chnl,priv->available_chnl_num,priv->available_chnl[i])) { tmpScore = 0; for(j=0;j<2;j++) { if ((tmpScore != 0xffffffff) && (score[i+j] != 0xffffffff)) tmpScore += score[i+j]; else tmpScore = 0xffffffff; } tmpScore = tmpScore / 2; if(minScore > tmpScore) { minScore = tmpScore; tmpScore = 0xffffffff; for (j=0; j<2; j++) { if (score[i+j] < tmpScore) { tmpScore = score[i+j]; tmpIdx = i+j; } } idx = tmpIdx; } i += 1; } } if (minScore == 0xffffffff) { // there is no 40M channels priv->pshare->is_40m_bw = HT_CHANNEL_WIDTH_20; for (i=0; i<priv->available_chnl_num; i++) { if (score[i] < minScore) { minScore = score[i]; idx = i; } } } } else if( (priv->pmib->dot11RFEntry.phyBandSelect == PHY_BAND_2G) && (priv->pmib->dot11nConfigEntry.dot11nUse40M == HT_CHANNEL_WIDTH_20_40) && (priv->available_chnl_num >= 8) ) { u4Byte groupScore[14]; memset(groupScore, 0xff , sizeof(groupScore)); for (i=0; i<priv->available_chnl_num-4; i++) { if (score[i] != 0xffffffff && score[i+4] != 0xffffffff) { groupScore[i] = score[i] + score[i+4]; DEBUG_INFO("groupScore, ch %d,%d: %d\n", i+1, i+5, groupScore[i]); if (groupScore[i] < minScore) { #ifdef AUTOCH_SS_SPEEDUP if(priv->pmib->miscEntry.autoch_1611_enable) { if(priv->available_chnl[i]==1 || priv->available_chnl[i]==6 || priv->available_chnl[i]==11) { minScore = groupScore[i]; idx = i; } } else #endif { minScore = groupScore[i]; idx = i; } } } } if (score[idx] < score[idx+4]) { GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset = HT_2NDCH_OFFSET_ABOVE; priv->pshare->offset_2nd_chan = HT_2NDCH_OFFSET_ABOVE; } else { idx = idx + 4; GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset = HT_2NDCH_OFFSET_BELOW; priv->pshare->offset_2nd_chan = HT_2NDCH_OFFSET_BELOW; } } else { for (i=0; i<priv->available_chnl_num; i++) { if (score[i] < minScore) { #ifdef AUTOCH_SS_SPEEDUP if(priv->pmib->miscEntry.autoch_1611_enable) { if(priv->available_chnl[i]==1 || priv->available_chnl[i]==6 || priv->available_chnl[i]==11) { minScore = score[i]; idx = i; } } else #endif { minScore = score[i]; idx = i; } } } } if (IS_A_CUT_8881A(priv) && (priv->pmib->dot11nConfigEntry.dot11nUse40M == HT_CHANNEL_WIDTH_80)) { if ((priv->available_chnl[idx] == 36) || (priv->available_chnl[idx] == 52) || (priv->available_chnl[idx] == 100) || (priv->available_chnl[idx] == 116) || (priv->available_chnl[idx] == 132) || (priv->available_chnl[idx] == 149) || (priv->available_chnl[idx] == 165)) idx++; else if ((priv->available_chnl[idx] == 48) || (priv->available_chnl[idx] == 64) || (priv->available_chnl[idx] == 112) || (priv->available_chnl[idx] == 128) || (priv->available_chnl[idx] == 144) || (priv->available_chnl[idx] == 161) || (priv->available_chnl[idx] == 177)) idx--; } minChan = priv->available_chnl[idx]; // skip channel 14 if don't support ofdm if ((priv->pmib->dot11RFEntry.disable_ch14_ofdm) && (minChan == 14)) { score[idx] = 0xffffffff; minScore = 0xffffffff; for (i=0; i<priv->available_chnl_num; i++) { if (score[i] < minScore) { minScore = score[i]; idx = i; } } minChan = priv->available_chnl[idx]; } #if 0 //Check if selected channel available for 80M/40M BW or NOT ? if(priv->pmib->dot11RFEntry.phyBandSelect == PHY_BAND_5G) { if(priv->pmib->dot11nConfigEntry.dot11nUse40M == HT_CHANNEL_WIDTH_80) { if(!is80MChannel(priv->available_chnl,priv->available_chnl_num,minChan)) { //printk("BW=80M, selected channel = %d is unavaliable! reduce to 40M\n", minChan); //priv->pmib->dot11nConfigEntry.dot11nUse40M = HT_CHANNEL_WIDTH_20_40; priv->pshare->is_40m_bw = HT_CHANNEL_WIDTH_20_40; } } if(priv->pmib->dot11nConfigEntry.dot11nUse40M == HT_CHANNEL_WIDTH_20_40) { if(!is40MChannel(priv->available_chnl,priv->available_chnl_num,minChan)) { //printk("BW=40M, selected channel = %d is unavaliable! reduce to 20M\n", minChan); //priv->pmib->dot11nConfigEntry.dot11nUse40M = HT_CHANNEL_WIDTH_20; priv->pshare->is_40m_bw = HT_CHANNEL_WIDTH_20; } } } #endif #ifdef CONFIG_RTL_NEW_AUTOCH RTL_W32(RXERR_RPT, RXERR_RPT_RST); #endif // auto adjust contro-sideband if ((priv->pmib->dot11BssType.net_work_type & WIRELESS_11N) && (priv->pshare->is_40m_bw ==1 || priv->pshare->is_40m_bw ==2)) { #ifdef RTK_5G_SUPPORT if (priv->pmib->dot11RFEntry.phyBandSelect & PHY_BAND_5G) { if( (minChan>144) ? ((minChan-1)%8) : (minChan%8)) { GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset = HT_2NDCH_OFFSET_ABOVE; priv->pshare->offset_2nd_chan = HT_2NDCH_OFFSET_ABOVE; } else { GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset = HT_2NDCH_OFFSET_BELOW; priv->pshare->offset_2nd_chan = HT_2NDCH_OFFSET_BELOW; } } else #endif { #if 0 #ifdef CONFIG_RTL_NEW_AUTOCH unsigned int ch_max; if (priv->available_chnl[idx_2G_end] >= 13) ch_max = 13; else ch_max = priv->available_chnl[idx_2G_end]; if ((minChan >= 5) && (minChan <= (ch_max-5))) { if (score[minChan+4] > score[minChan-4]) { // what if some channels were cancelled? GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset = HT_2NDCH_OFFSET_BELOW; priv->pshare->offset_2nd_chan = HT_2NDCH_OFFSET_BELOW; } else { GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset = HT_2NDCH_OFFSET_ABOVE; priv->pshare->offset_2nd_chan = HT_2NDCH_OFFSET_ABOVE; } } else #endif { if (minChan < 5) { GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset = HT_2NDCH_OFFSET_ABOVE; priv->pshare->offset_2nd_chan = HT_2NDCH_OFFSET_ABOVE; } else if (minChan > 7) { GET_MIB(priv)->dot11nConfigEntry.dot11n2ndChOffset = HT_2NDCH_OFFSET_BELOW; priv->pshare->offset_2nd_chan = HT_2NDCH_OFFSET_BELOW; } } #endif } } //----------------------- #if defined(__ECOS) && defined(CONFIG_SDIO_HCI) panic_printk("Auto channel choose ch:%d\n", minChan); #else #ifdef _DEBUG_RTL8192CD_ panic_printk("Auto channel choose ch:%d\n", minChan); #endif #endif #ifdef ACS_DEBUG_INFO//for debug printk("7. minChan:%d 2nd_offset:%d\n", minChan, priv->pshare->offset_2nd_chan); #endif return minChan; } */ #endif VOID phydm_CLMInit( IN PVOID pDM_VOID, IN u2Byte sampleNum /*unit : 4us*/ ) { PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; if (pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) { ODM_SetBBReg(pDM_Odm, ODM_REG_CLM_TIME_PERIOD_11AC, bMaskLWord, sampleNum); /*4us sample 1 time*/ ODM_SetBBReg(pDM_Odm, ODM_REG_CLM_11AC, BIT8, 0x1); /*Enable CCX for CLM*/ } else if (pDM_Odm->SupportICType & ODM_IC_11N_SERIES) { ODM_SetBBReg(pDM_Odm, ODM_REG_CLM_TIME_PERIOD_11N, bMaskLWord, sampleNum); /*4us sample 1 time*/ ODM_SetBBReg(pDM_Odm, ODM_REG_CLM_11N, BIT8, 0x1); /*Enable CCX for CLM*/ } ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("[%s] : CLM sampleNum = %d\n", __func__, sampleNum)); } VOID phydm_CLMtrigger( IN PVOID pDM_VOID ) { PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; if (pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) { ODM_SetBBReg(pDM_Odm, ODM_REG_CLM_11AC, BIT0, 0x0); /*Trigger CLM*/ ODM_SetBBReg(pDM_Odm, ODM_REG_CLM_11AC, BIT0, 0x1); } else if (pDM_Odm->SupportICType & ODM_IC_11N_SERIES) { ODM_SetBBReg(pDM_Odm, ODM_REG_CLM_11N, BIT0, 0x0); /*Trigger CLM*/ ODM_SetBBReg(pDM_Odm, ODM_REG_CLM_11N, BIT0, 0x1); } } BOOLEAN phydm_checkCLMready( IN PVOID pDM_VOID ) { PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; u4Byte value32 = 0; BOOLEAN ret = FALSE; if (pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) value32 = ODM_GetBBReg(pDM_Odm, ODM_REG_CLM_RESULT_11AC, bMaskDWord); /*make sure CLM calc is ready*/ else if (pDM_Odm->SupportICType & ODM_IC_11N_SERIES) value32 = ODM_GetBBReg(pDM_Odm, ODM_REG_CLM_READY_11N, bMaskDWord); /*make sure CLM calc is ready*/ if (value32 & BIT16) ret = TRUE; else ret = FALSE; ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("[%s] : CLM ready = %d\n", __func__, ret)); return ret; } u2Byte phydm_getCLMresult( IN PVOID pDM_VOID ) { PDM_ODM_T pDM_Odm = (PDM_ODM_T)pDM_VOID; u4Byte value32 = 0; u2Byte results = 0; if (pDM_Odm->SupportICType & ODM_IC_11AC_SERIES) value32 = ODM_GetBBReg(pDM_Odm, ODM_REG_CLM_RESULT_11AC, bMaskDWord); /*read CLM calc result*/ else if (pDM_Odm->SupportICType & ODM_IC_11N_SERIES) value32 = ODM_GetBBReg(pDM_Odm, ODM_REG_CLM_RESULT_11N, bMaskDWord); /*read CLM calc result*/ results = (u2Byte)(value32 & bMaskLWord); ODM_RT_TRACE(pDM_Odm, ODM_COMP_ACS, ODM_DBG_LOUD, ("[%s] : CLM result = %d\n", __func__, results)); return results; /*results are number of CCA times in sampleNum*/ }
Java
<?php namespace Pantheon\Terminus\UnitTests\Commands\Tag; use Pantheon\Terminus\Collections\OrganizationSiteMemberships; use Pantheon\Terminus\Collections\UserOrganizationMemberships; use Pantheon\Terminus\Models\Organization; use Pantheon\Terminus\Models\OrganizationSiteMembership; use Pantheon\Terminus\Models\User; use Pantheon\Terminus\Models\UserOrganizationMembership; use Pantheon\Terminus\Session\Session; use Pantheon\Terminus\UnitTests\Commands\CommandTestCase; use Pantheon\Terminus\Collections\Tags; /** * Class TagCommandTest * Abstract testing class for Pantheon\Terminus\Commands\Tag\*Command * @package Pantheon\Terminus\UnitTests\Commands\Tag */ abstract class TagCommandTest extends CommandTestCase { /** * @inheritdoc */ protected function setUp() { parent::setUp(); $this->site->id = 'site_id'; $this->session = $this->getMockBuilder(Session::class) ->disableOriginalConstructor() ->getMock(); $user = $this->getMockBuilder(User::class) ->disableOriginalConstructor() ->getMock(); $this->org_site_membership = $this->getMockBuilder(OrganizationSiteMembership::class) ->disableOriginalConstructor() ->getMock(); $this->tags = $this->getMockBuilder(Tags::class) ->disableOriginalConstructor() ->getMock(); $user_org_memberships = $this->getMockBuilder(UserOrganizationMemberships::class) ->disableOriginalConstructor() ->getMock(); $user_org_membership = $this->getMockBuilder(UserOrganizationMembership::class) ->disableOriginalConstructor() ->getMock(); $this->organization = $this->getMockBuilder(Organization::class) ->disableOriginalConstructor() ->getMock(); $this->organization->id = 'org_id'; $this->org_site_memberships = $this->getMockBuilder(OrganizationSiteMemberships::class) ->disableOriginalConstructor() ->getMock(); $this->org_site_membership = $this->getMockBuilder(OrganizationSiteMembership::class) ->disableOriginalConstructor() ->getMock(); $this->tags = $this->getMockBuilder(Tags::class) ->disableOriginalConstructor() ->getMock(); $this->site->tags = $this->tags; $this->org_site_membership->method('getSite')->willReturn($this->site); $this->session->expects($this->once()) ->method('getUser') ->with() ->willReturn($user); $user->expects($this->once()) ->method('getOrgMemberships') ->with() ->willReturn($user_org_memberships); $user_org_memberships->expects($this->once()) ->method('get') ->with($this->organization->id) ->willReturn($user_org_membership); $user_org_membership->expects($this->once()) ->method('getOrganization') ->with() ->willReturn($this->organization); $this->organization->expects($this->once()) ->method('getSiteMemberships') ->with() ->willReturn($this->org_site_memberships); $this->org_site_memberships->expects($this->once()) ->method('get') ->with($this->site->id) ->willReturn($this->org_site_membership); } }
Java
<!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_60) on Thu Jul 17 09:47:20 BST 2014 --> <title>tools</title> <meta name="date" content="2014-07-17"> <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="tools"; } //--> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../ontology/sprites/producer/package-summary.html">Prev Package</a></li> <li>Next Package</li> </ul> <ul class="navList"> <li><a href="../index.html?tools/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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"> <h1 title="Package" class="title">Package&nbsp;tools</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../tools/ElapsedCpuTimer.html" title="class in tools">ElapsedCpuTimer</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../tools/IO.html" title="class in tools">IO</a></td> <td class="colLast"> <div class="block">Created with IntelliJ IDEA.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../tools/JEasyFrame.html" title="class in tools">JEasyFrame</a></td> <td class="colLast"> <div class="block">Frame for the graphics.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../tools/KeyInput.html" title="class in tools">KeyInput</a></td> <td class="colLast"> <div class="block">This class is used to manage the key input.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../tools/Pair.html" title="class in tools">Pair</a></td> <td class="colLast"> <div class="block">Created with IntelliJ IDEA.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../tools/StatSummary.html" title="class in tools">StatSummary</a></td> <td class="colLast"> <div class="block">This class is used to model the statistics of a fix of numbers.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../tools/Utils.html" title="class in tools">Utils</a></td> <td class="colLast"> <div class="block">Created with IntelliJ IDEA.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../tools/Vector2d.html" title="class in tools">Vector2d</a></td> <td class="colLast"> <div class="block">This class represents a vector, or a position, in the map.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../tools/ElapsedCpuTimer.TimerType.html" title="enum in tools">ElapsedCpuTimer.TimerType</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-files/index-1.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../ontology/sprites/producer/package-summary.html">Prev Package</a></li> <li>Next Package</li> </ul> <ul class="navList"> <li><a href="../index.html?tools/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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 ======= --> </body> </html>
Java
; void p_forward_list_clear_fastcall(p_forward_list_t *list) SECTION code_clib SECTION code_adt_p_forward_list PUBLIC _p_forward_list_clear_fastcall EXTERN asm_p_forward_list_clear defc _p_forward_list_clear_fastcall = asm_p_forward_list_clear
Java
/** * Client UI Javascript for the Calendar plugin * * @version @package_version@ * @author Lazlo Westerhof <hello@lazlo.me> * @author Thomas Bruederli <bruederli@kolabsys.com> * * Copyright (C) 2010, Lazlo Westerhof <hello@lazlo.me> * Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Roundcube calendar UI client class function rcube_calendar_ui(settings) { // extend base class rcube_calendar.call(this, settings); /*** member vars ***/ this.is_loading = false; this.selected_event = null; this.selected_calendar = null; this.search_request = null; this.saving_lock; /*** private vars ***/ var DAY_MS = 86400000; var HOUR_MS = 3600000; var me = this; var gmt_offset = (new Date().getTimezoneOffset() / -60) - (settings.timezone || 0) - (settings.dst || 0); var client_timezone = new Date().getTimezoneOffset(); var day_clicked = day_clicked_ts = 0; var ignore_click = false; var event_defaults = { free_busy:'busy', alarms:'' }; var event_attendees = []; var attendees_list; var freebusy_ui = { workinhoursonly:false, needsupdate:false }; var freebusy_data = {}; var current_view = null; var exec_deferred = bw.ie6 ? 5 : 1; var sensitivitylabels = { 'public':rcmail.gettext('public','calendar'), 'private':rcmail.gettext('private','calendar'), 'confidential':rcmail.gettext('confidential','calendar') }; var ui_loading = rcmail.set_busy(true, 'loading'); // general datepicker settings var datepicker_settings = { // translate from fullcalendar format to datepicker format dateFormat: settings['date_format'].replace(/M/g, 'm').replace(/mmmmm/, 'MM').replace(/mmm/, 'M').replace(/dddd/, 'DD').replace(/ddd/, 'D').replace(/yy/g, 'y'), firstDay : settings['first_day'], dayNamesMin: settings['days_short'], monthNames: settings['months'], monthNamesShort: settings['months'], changeMonth: false, showOtherMonths: true, selectOtherMonths: true }; /*** imports ***/ var Q = this.quote_html; var text2html = this.text2html; var event_date_text = this.event_date_text; var parse_datetime = this.parse_datetime; var date2unixtime = this.date2unixtime; var fromunixtime = this.fromunixtime; var parseISO8601 = this.parseISO8601; var init_alarms_edit = this.init_alarms_edit; /*** private methods ***/ // same as str.split(delimiter) but it ignores delimiters within quoted strings var explode_quoted_string = function(str, delimiter) { var result = [], strlen = str.length, q, p, i, char, last; for (q = p = i = 0; i < strlen; i++) { char = str.charAt(i); if (char == '"' && last != '\\') { q = !q; } else if (!q && char == delimiter) { result.push(str.substring(p, i)); p = i + 1; } last = char; } result.push(str.substr(p)); return result; }; // clone the given date object and optionally adjust time var clone_date = function(date, adjust) { var d = new Date(date.getTime()); // set time to 00:00 if (adjust == 1) { d.setHours(0); d.setMinutes(0); } // set time to 23:59 else if (adjust == 2) { d.setHours(23); d.setMinutes(59); } return d; }; // fix date if jumped over a DST change var fix_date = function(date) { if (date.getHours() == 23) date.setTime(date.getTime() + HOUR_MS); else if (date.getHours() > 0) date.setHours(0); }; // turn the given date into an ISO 8601 date string understandable by PHPs strtotime() var date2servertime = function(date) { return date.getFullYear()+'-'+zeropad(date.getMonth()+1)+'-'+zeropad(date.getDate()) + 'T'+zeropad(date.getHours())+':'+zeropad(date.getMinutes())+':'+zeropad(date.getSeconds()); } var date2timestring = function(date, dateonly) { return date2servertime(date).replace(/[^0-9]/g, '').substr(0, (dateonly ? 8 : 14)); } var zeropad = function(num) { return (num < 10 ? '0' : '') + num; } var render_link = function(url) { var islink = false, href = url; if (url.match(/^[fhtpsmailo]+?:\/\//i)) { islink = true; } else if (url.match(/^[a-z0-9.-:]+(\/|$)/i)) { islink = true; href = 'http://' + url; } return islink ? '<a href="' + Q(href) + '" target="_blank">' + Q(url) + '</a>' : Q(url); } // determine whether the given date is on a weekend var is_weekend = function(date) { return date.getDay() == 0 || date.getDay() == 6; }; var is_workinghour = function(date) { if (settings['work_start'] > settings['work_end']) return date.getHours() >= settings['work_start'] || date.getHours() < settings['work_end']; else return date.getHours() >= settings['work_start'] && date.getHours() < settings['work_end']; }; // check if the event has 'real' attendees, excluding the current user var has_attendees = function(event) { return (event.attendees && event.attendees.length && (event.attendees.length > 1 || String(event.attendees[0].email).toLowerCase() != settings.identity.email)); }; // check if the current user is an attendee of this event var is_attendee = function(event, role, email) { var emails = email ? ';'+email.toLowerCase() : settings.identity.emails; for (var i=0; event.attendees && i < event.attendees.length; i++) { if ((!role || event.attendees[i].role == role) && event.attendees[i].email && emails.indexOf(';'+event.attendees[i].email.toLowerCase()) >= 0) return event.attendees[i]; } return false; }; // check if the current user is the organizer var is_organizer = function(event, email) { return is_attendee(event, 'ORGANIZER', email) || !event.id; }; var load_attachment = function(event, att) { var qstring = '_id='+urlencode(att.id)+'&_event='+urlencode(event.recurrence_id||event.id)+'&_cal='+urlencode(event.calendar); // open attachment in frame if it's of a supported mimetype if (id && att.mimetype && $.inArray(att.mimetype, settings.mimetypes)>=0) { if (rcmail.open_window(rcmail.env.comm_path+'&_action=get-attachment&'+qstring+'&_frame=1', true, true)) { return; } } rcmail.goto_url('get-attachment', qstring+'&_download=1', false); }; // build event attachments list var event_show_attachments = function(list, container, event, edit) { var i, id, len, img, content, li, elem, ul = document.createElement('UL'); ul.className = 'attachmentslist'; for (i=0, len=list.length; i<len; i++) { elem = list[i]; li = document.createElement('LI'); li.className = elem.classname; if (edit) { rcmail.env.attachments[elem.id] = elem; // delete icon content = document.createElement('A'); content.href = '#delete'; content.title = rcmail.gettext('delete'); content.className = 'delete'; $(content).click({id: elem.id}, function(e) { remove_attachment(this, e.data.id); return false; }); if (!rcmail.env.deleteicon) content.innerHTML = rcmail.gettext('delete'); else { img = document.createElement('IMG'); img.src = rcmail.env.deleteicon; img.alt = rcmail.gettext('delete'); content.appendChild(img); } li.appendChild(content); } // name/link content = document.createElement('A'); content.innerHTML = elem.name; content.className = 'file'; content.href = '#load'; $(content).click({event: event, att: elem}, function(e) { load_attachment(e.data.event, e.data.att); return false; }); li.appendChild(content); ul.appendChild(li); } if (edit && rcmail.gui_objects.attachmentlist) { ul.id = rcmail.gui_objects.attachmentlist.id; rcmail.gui_objects.attachmentlist = ul; } container.empty().append(ul); }; var remove_attachment = function(elem, id) { $(elem.parentNode).hide(); rcmail.env.deleted_attachments.push(id); delete rcmail.env.attachments[id]; }; // event details dialog (show only) var event_show_dialog = function(event) { var $dialog = $("#eventshow").removeClass().addClass('uidialog'); var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:false }; me.selected_event = event; // allow other plugins to do actions when event form is opened rcmail.triggerEvent('calendar-event-init', {o: event}); $dialog.find('div.event-section, div.event-line').hide(); $('#event-title').html(Q(event.title)).show(); if (event.location) $('#event-location').html('@ ' + text2html(event.location)).show(); if (event.description) $('#event-description').show().children('.event-text').html(text2html(event.description, 300, 6)); if (event.vurl) $('#event-url').show().children('.event-text').html(render_link(event.vurl)); // render from-to in a nice human-readable way // -> now shown in dialog title // $('#event-date').html(Q(me.event_date_text(event))).show(); if (event.recurrence && event.recurrence_text) $('#event-repeat').show().children('.event-text').html(Q(event.recurrence_text)); if (event.alarms && event.alarms_text) $('#event-alarm').show().children('.event-text').html(Q(event.alarms_text)); if (calendar.name) $('#event-calendar').show().children('.event-text').html(Q(calendar.name)).removeClass().addClass('event-text').addClass('cal-'+calendar.id); if (event.categories) $('#event-category').show().children('.event-text').html(Q(event.categories)).removeClass().addClass('event-text cat-'+String(event.categories).replace(rcmail.identifier_expr, '')); if (event.free_busy) $('#event-free-busy').show().children('.event-text').html(Q(rcmail.gettext(event.free_busy, 'calendar'))); if (event.priority > 0) { var priolabels = [ '', rcmail.gettext('highest'), rcmail.gettext('high'), '', '', rcmail.gettext('normal'), '', '', rcmail.gettext('low'), rcmail.gettext('lowest') ]; $('#event-priority').show().children('.event-text').html(Q(event.priority+' '+priolabels[event.priority])); } if (event.sensitivity && event.sensitivity != 'public') { $('#event-sensitivity').show().children('.event-text').html(Q(sensitivitylabels[event.sensitivity])); $dialog.addClass('sensitivity-'+event.sensitivity); } // create attachments list if ($.isArray(event.attachments)) { event_show_attachments(event.attachments, $('#event-attachments').children('.event-text'), event); if (event.attachments.length > 0) { $('#event-attachments').show(); } } else if (calendar.attachments) { // fetch attachments, some drivers doesn't set 'attachments' prop of the event? } // list event attendees if (calendar.attendees && event.attendees) { var data, dispname, organizer = false, rsvp = false, line, morelink, html = '',overflow = ''; for (var j=0; j < event.attendees.length; j++) { data = event.attendees[j]; dispname = Q(data.name || data.email); if (data.email) { dispname = '<a href="mailto:' + data.email + '" title="' + Q(data.email) + '" class="mailtolink">' + dispname + '</a>'; if (data.role == 'ORGANIZER') organizer = true; else if ((data.status == 'NEEDS-ACTION' || data.status == 'TENTATIVE') && settings.identity.emails.indexOf(';'+data.email) >= 0) rsvp = data.status.toLowerCase(); } line = '<span class="attendee ' + String(data.role == 'ORGANIZER' ? 'organizer' : data.status).toLowerCase() + '">' + dispname + '</span> '; if (morelink) overflow += line; else html += line; // stop listing attendees if (j == 7 && event.attendees.length >= 7) { morelink = $('<a href="#more" class="morelink"></a>').html(rcmail.gettext('andnmore', 'calendar').replace('$nr', event.attendees.length - j - 1)); } } if (html && (event.attendees.length > 1 || !organizer)) { $('#event-attendees').show() .children('.event-text') .html(html) .find('a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; }); // display all attendees in a popup when clicking the "more" link if (morelink) { $('#event-attendees .event-text').append(morelink); morelink.click(function(e){ rcmail.show_popup_dialog( '<div id="all-event-attendees" class="event-attendees">' + html + overflow + '</div>', rcmail.gettext('tabattendees','calendar'), null, { width:450, modal:false }); $('#all-event-attendees a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; }); return false; }) } } $('#event-rsvp')[(rsvp&&!organizer?'show':'hide')](); $('#event-rsvp .rsvp-buttons input').prop('disabled', false).filter('input[rel='+rsvp+']').prop('disabled', true); } var buttons = {}; if (calendar.editable && event.editable !== false) { buttons[rcmail.gettext('edit', 'calendar')] = function() { event_edit_dialog('edit', event); }; buttons[rcmail.gettext('remove', 'calendar')] = function() { me.delete_event(event); $dialog.dialog('close'); }; } else { buttons[rcmail.gettext('close', 'calendar')] = function(){ $dialog.dialog('close'); }; } // open jquery UI dialog $dialog.dialog({ modal: false, resizable: !bw.ie6, closeOnEscape: (!bw.ie6 && !bw.ie7), // disable for performance reasons title: Q(me.event_date_text(event)), open: function() { $dialog.parent().find('.ui-button').first().focus(); }, close: function() { $dialog.dialog('destroy').hide(); }, buttons: buttons, minWidth: 320, width: 420 }).show(); // set dialog size according to content me.dialog_resize($dialog.get(0), $dialog.height(), 420); /* // add link for "more options" drop-down $('<a>') .attr('href', '#') .html('More Options') .addClass('dropdown-link') .click(function(){ return false; }) .insertBefore($dialog.parent().find('.ui-dialog-buttonset').children().first()); */ }; // bring up the event dialog (jquery-ui popup) var event_edit_dialog = function(action, event) { // close show dialog first $("#eventshow:ui-dialog").dialog('close'); var $dialog = $('<div>'); var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:action=='new' }; me.selected_event = $.extend($.extend({}, event_defaults), event); // clone event object (with defaults) event = me.selected_event; // change reference to clone freebusy_ui.needsupdate = false; // reset dialog first $('#eventtabs').get(0).reset(); // allow other plugins to do actions when event form is opened rcmail.triggerEvent('calendar-event-init', {o: event}); // event details var title = $('#edit-title').val(event.title || ''); var location = $('#edit-location').val(event.location || ''); var description = $('#edit-description').html(event.description || ''); var vurl = $('#edit-url').val(event.vurl || ''); var categories = $('#edit-categories').val(event.categories); var calendars = $('#edit-calendar').val(event.calendar); var freebusy = $('#edit-free-busy').val(event.free_busy); var priority = $('#edit-priority').val(event.priority); var sensitivity = $('#edit-sensitivity').val(event.sensitivity); var duration = Math.round((event.end.getTime() - event.start.getTime()) / 1000); var startdate = $('#edit-startdate').val($.fullCalendar.formatDate(event.start, settings['date_format'])).data('duration', duration); var starttime = $('#edit-starttime').val($.fullCalendar.formatDate(event.start, settings['time_format'])).show(); var enddate = $('#edit-enddate').val($.fullCalendar.formatDate(event.end, settings['date_format'])); var endtime = $('#edit-endtime').val($.fullCalendar.formatDate(event.end, settings['time_format'])).show(); var allday = $('#edit-allday').get(0); var notify = $('#edit-attendees-donotify').get(0); var invite = $('#edit-attendees-invite').get(0); notify.checked = has_attendees(event), invite.checked = true; if (event.allDay) { starttime.val("12:00").hide(); endtime.val("13:00").hide(); allday.checked = true; } else { allday.checked = false; } // set alarm(s) // TODO: support multiple alarm entries if (event.alarms || action != 'new') { if (typeof event.alarms == 'string') event.alarms = event.alarms.split(';'); var valarms = event.alarms || ['']; for (var alarm, i=0; i < valarms.length; i++) { alarm = String(valarms[i]).split(':'); if (!alarm[1] && alarm[0]) alarm[1] = 'DISPLAY'; $('#eventedit select.edit-alarm-type').val(alarm[1]); if (alarm[0].match(/@(\d+)/)) { var ondate = fromunixtime(parseInt(RegExp.$1)); $('#eventedit select.edit-alarm-offset').val('@'); $('#eventedit input.edit-alarm-date').val($.fullCalendar.formatDate(ondate, settings['date_format'])); $('#eventedit input.edit-alarm-time').val($.fullCalendar.formatDate(ondate, settings['time_format'])); } else if (alarm[0].match(/([-+])(\d+)([MHD])/)) { $('#eventedit input.edit-alarm-value').val(RegExp.$2); $('#eventedit select.edit-alarm-offset').val(''+RegExp.$1+RegExp.$3); } } } // set correct visibility by triggering onchange handlers $('#eventedit select.edit-alarm-type, #eventedit select.edit-alarm-offset').change(); // enable/disable alarm property according to backend support $('#edit-alarms')[(calendar.alarms ? 'show' : 'hide')](); // check categories drop-down: add value if not exists if (event.categories && !categories.find("option[value='"+event.categories+"']").length) { $('<option>').attr('value', event.categories).text(event.categories).appendTo(categories).prop('selected', true); } // set recurrence form var recurrence, interval, rrtimes, rrenddate; var load_recurrence_tab = function() { recurrence = $('#edit-recurrence-frequency').val(event.recurrence ? event.recurrence.FREQ : '').change(); interval = $('#eventedit select.edit-recurrence-interval').val(event.recurrence ? event.recurrence.INTERVAL : 1); rrtimes = $('#edit-recurrence-repeat-times').val(event.recurrence ? event.recurrence.COUNT : 1); rrenddate = $('#edit-recurrence-enddate').val(event.recurrence && event.recurrence.UNTIL ? $.fullCalendar.formatDate(parseISO8601(event.recurrence.UNTIL), settings['date_format']) : ''); $('#eventedit input.edit-recurrence-until:checked').prop('checked', false); var weekdays = ['SU','MO','TU','WE','TH','FR','SA']; var rrepeat_id = '#edit-recurrence-repeat-forever'; if (event.recurrence && event.recurrence.COUNT) rrepeat_id = '#edit-recurrence-repeat-count'; else if (event.recurrence && event.recurrence.UNTIL) rrepeat_id = '#edit-recurrence-repeat-until'; $(rrepeat_id).prop('checked', true); if (event.recurrence && event.recurrence.BYDAY && event.recurrence.FREQ == 'WEEKLY') { var wdays = event.recurrence.BYDAY.split(','); $('input.edit-recurrence-weekly-byday').val(wdays); } if (event.recurrence && event.recurrence.BYMONTHDAY) { $('input.edit-recurrence-monthly-bymonthday').val(String(event.recurrence.BYMONTHDAY).split(',')); $('input.edit-recurrence-monthly-mode').val(['BYMONTHDAY']); } if (event.recurrence && event.recurrence.BYDAY && (event.recurrence.FREQ == 'MONTHLY' || event.recurrence.FREQ == 'YEARLY')) { var byday, section = event.recurrence.FREQ.toLowerCase(); if ((byday = String(event.recurrence.BYDAY).match(/(-?[1-4])([A-Z]+)/))) { $('#edit-recurrence-'+section+'-prefix').val(byday[1]); $('#edit-recurrence-'+section+'-byday').val(byday[2]); } $('input.edit-recurrence-'+section+'-mode').val(['BYDAY']); } else if (event.start) { $('#edit-recurrence-monthly-byday').val(weekdays[event.start.getDay()]); } if (event.recurrence && event.recurrence.BYMONTH) { $('input.edit-recurrence-yearly-bymonth').val(String(event.recurrence.BYMONTH).split(',')); } else if (event.start) { $('input.edit-recurrence-yearly-bymonth').val([String(event.start.getMonth()+1)]); } }; // show warning if editing a recurring event if (event.id && event.recurrence) { var sel = event.thisandfuture ? 'future' : (event.isexception ? 'current' : 'all'); $('#edit-recurring-warning').show(); $('input.edit-recurring-savemode[value="'+sel+'"]').prop('checked', true); } else $('#edit-recurring-warning').hide(); // init attendees tab var organizer = !event.attendees || is_organizer(event), allow_invitations = organizer || (calendar.owner && calendar.owner == 'anonymous') || settings.invite_shared; event_attendees = []; attendees_list = $('#edit-attendees-table > tbody').html(''); $('#edit-attendees-notify')[(notify.checked && allow_invitations ? 'show' : 'hide')](); $('#edit-localchanges-warning')[(has_attendees(event) && !(allow_invitations || (calendar.owner && is_organizer(event, calendar.owner))) ? 'show' : 'hide')](); var load_attendees_tab = function() { if (event.attendees) { for (var j=0; j < event.attendees.length; j++) add_attendee(event.attendees[j], !allow_invitations); } // select the correct organizer identity var identity_id = 0; $.each(settings.identities, function(i,v){ if (organizer && v == organizer.email) { identity_id = i; return false; } }); $('#edit-identities-list').val(identity_id); $('#edit-attendees-form')[(allow_invitations?'show':'hide')](); $('#edit-attendee-schedule')[(calendar.freebusy?'show':'hide')](); }; // attachments var load_attachments_tab = function() { rcmail.enable_command('remove-attachment', !calendar.readonly); rcmail.env.deleted_attachments = []; // we're sharing some code for uploads handling with app.js rcmail.env.attachments = []; rcmail.env.compose_id = event.id; // for rcmail.async_upload_form() if ($.isArray(event.attachments)) { event_show_attachments(event.attachments, $('#edit-attachments'), event, true); } else { $('#edit-attachments > ul').empty(); // fetch attachments, some drivers doesn't set 'attachments' array for event? } }; // init dialog buttons var buttons = {}; // save action buttons[rcmail.gettext('save', 'calendar')] = function() { var start = parse_datetime(allday.checked ? '12:00' : starttime.val(), startdate.val()); var end = parse_datetime(allday.checked ? '13:00' : endtime.val(), enddate.val()); // basic input validatetion if (start.getTime() > end.getTime()) { alert(rcmail.gettext('invalideventdates', 'calendar')); return false; } // post data to server var data = { calendar: event.calendar, start: date2servertime(start), end: date2servertime(end), allday: allday.checked?1:0, title: title.val(), description: description.val(), location: location.val(), categories: categories.val(), vurl: vurl.val(), free_busy: freebusy.val(), priority: priority.val(), sensitivity: sensitivity.val(), recurrence: '', alarms: '', attendees: event_attendees, deleted_attachments: rcmail.env.deleted_attachments, attachments: [] }; // serialize alarm settings // TODO: support multiple alarm entries var alarm = $('#eventedit select.edit-alarm-type').val(); if (alarm) { var val, offset = $('#eventedit select.edit-alarm-offset').val(); if (offset == '@') data.alarms = '@' + date2unixtime(parse_datetime($('#eventedit input.edit-alarm-time').val(), $('#eventedit input.edit-alarm-date').val())) + ':' + alarm; else if ((val = parseInt($('#eventedit input.edit-alarm-value').val())) && !isNaN(val) && val >= 0) data.alarms = offset[0] + val + offset[1] + ':' + alarm; } // uploaded attachments list for (var i in rcmail.env.attachments) if (i.match(/^rcmfile(.+)/)) data.attachments.push(RegExp.$1); // read attendee roles $('select.edit-attendee-role').each(function(i, elem){ if (data.attendees[i]) data.attendees[i].role = $(elem).val(); }); if (organizer) data._identity = $('#edit-identities-list option:selected').val(); // don't submit attendees if only myself is added as organizer if (data.attendees.length == 1 && data.attendees[0].role == 'ORGANIZER' && String(data.attendees[0].email).toLowerCase() == settings.identity.email) data.attendees = []; // tell server to send notifications if ((data.attendees.length || (event.id && event.attendees.length)) && allow_invitations && (notify.checked || invite.checked)) { data._notify = 1; } // gather recurrence settings var freq; if ((freq = recurrence.val()) != '') { data.recurrence = { FREQ: freq, INTERVAL: $('#edit-recurrence-interval-'+freq.toLowerCase()).val() }; var until = $('input.edit-recurrence-until:checked').val(); if (until == 'count') data.recurrence.COUNT = rrtimes.val(); else if (until == 'until') data.recurrence.UNTIL = date2servertime(parse_datetime(endtime.val(), rrenddate.val())); if (freq == 'WEEKLY') { var byday = []; $('input.edit-recurrence-weekly-byday:checked').each(function(){ byday.push(this.value); }); if (byday.length) data.recurrence.BYDAY = byday.join(','); } else if (freq == 'MONTHLY') { var mode = $('input.edit-recurrence-monthly-mode:checked').val(), bymonday = []; if (mode == 'BYMONTHDAY') { $('input.edit-recurrence-monthly-bymonthday:checked').each(function(){ bymonday.push(this.value); }); if (bymonday.length) data.recurrence.BYMONTHDAY = bymonday.join(','); } else data.recurrence.BYDAY = $('#edit-recurrence-monthly-prefix').val() + $('#edit-recurrence-monthly-byday').val(); } else if (freq == 'YEARLY') { var byday, bymonth = []; $('input.edit-recurrence-yearly-bymonth:checked').each(function(){ bymonth.push(this.value); }); if (bymonth.length) data.recurrence.BYMONTH = bymonth.join(','); if ((byday = $('#edit-recurrence-yearly-byday').val())) data.recurrence.BYDAY = $('#edit-recurrence-yearly-prefix').val() + byday; } } data.calendar = calendars.val(); if (event.id) { data.id = event.id; if (event.recurrence) data._savemode = $('input.edit-recurring-savemode:checked').val(); if (data.calendar && data.calendar != event.calendar) data._fromcalendar = event.calendar; } update_event(action, data); $dialog.dialog("close"); }; if (event.id) { buttons[rcmail.gettext('remove', 'calendar')] = function() { me.delete_event(event); $dialog.dialog('close'); }; } buttons[rcmail.gettext('cancel', 'calendar')] = function() { $dialog.dialog("close"); }; // show/hide tabs according to calendar's feature support $('#edit-tab-attendees')[(calendar.attendees?'show':'hide')](); $('#edit-tab-attachments')[(calendar.attachments?'show':'hide')](); // activate the first tab $('#eventtabs').tabs('select', 0); // hack: set task to 'calendar' to make all dialog actions work correctly var comm_path_before = rcmail.env.comm_path; rcmail.env.comm_path = comm_path_before.replace(/_task=[a-z]+/, '_task=calendar'); var editform = $("#eventedit"); // open jquery UI dialog $dialog.dialog({ modal: true, resizable: (!bw.ie6 && !bw.ie7), // disable for performance reasons closeOnEscape: false, title: rcmail.gettext((action == 'edit' ? 'edit_event' : 'new_event'), 'calendar'), close: function() { editform.hide().appendTo(document.body); $dialog.dialog("destroy").remove(); rcmail.ksearch_blur(); rcmail.ksearch_destroy(); freebusy_data = {}; rcmail.env.comm_path = comm_path_before; // restore comm_path }, buttons: buttons, minWidth: 500, width: 580 }).append(editform.show()); // adding form content AFTERWARDS massively speeds up opening on IE6 // set dialog size according to form content me.dialog_resize($dialog.get(0), editform.height() + (bw.ie ? 20 : 0), 530); title.select(); // init other tabs asynchronously window.setTimeout(load_recurrence_tab, exec_deferred); if (calendar.attendees) window.setTimeout(load_attendees_tab, exec_deferred); if (calendar.attachments) window.setTimeout(load_attachments_tab, exec_deferred); }; // open a dialog to display detailed free-busy information and to find free slots var event_freebusy_dialog = function() { var $dialog = $('#eventfreebusy'), event = me.selected_event; if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); if (!event_attendees.length) return false; // set form elements var allday = $('#edit-allday').get(0); var duration = Math.round((event.end.getTime() - event.start.getTime()) / 1000); freebusy_ui.startdate = $('#schedule-startdate').val($.fullCalendar.formatDate(event.start, settings['date_format'])).data('duration', duration); freebusy_ui.starttime = $('#schedule-starttime').val($.fullCalendar.formatDate(event.start, settings['time_format'])).show(); freebusy_ui.enddate = $('#schedule-enddate').val($.fullCalendar.formatDate(event.end, settings['date_format'])); freebusy_ui.endtime = $('#schedule-endtime').val($.fullCalendar.formatDate(event.end, settings['time_format'])).show(); if (allday.checked) { freebusy_ui.starttime.val("12:00").hide(); freebusy_ui.endtime.val("13:00").hide(); event.allDay = true; } // read attendee roles from drop-downs $('select.edit-attendee-role').each(function(i, elem){ if (event_attendees[i]) event_attendees[i].role = $(elem).val(); }); // render time slots var now = new Date(), fb_start = new Date(), fb_end = new Date(); fb_start.setTime(event.start); fb_start.setHours(0); fb_start.setMinutes(0); fb_start.setSeconds(0); fb_start.setMilliseconds(0); fb_end.setTime(fb_start.getTime() + DAY_MS); freebusy_data = { required:{}, all:{} }; freebusy_ui.loading = 1; // prevent render_freebusy_grid() to load data yet freebusy_ui.numdays = Math.max(allday.checked ? 14 : 1, Math.ceil(duration * 2 / 86400)); freebusy_ui.interval = allday.checked ? 1440 : 60; freebusy_ui.start = fb_start; freebusy_ui.end = new Date(freebusy_ui.start.getTime() + DAY_MS * freebusy_ui.numdays); render_freebusy_grid(0); // render list of attendees freebusy_ui.attendees = {}; var domid, dispname, data, role_html, list_html = ''; for (var i=0; i < event_attendees.length; i++) { data = event_attendees[i]; dispname = Q(data.name || data.email); domid = String(data.email).replace(rcmail.identifier_expr, ''); role_html = '<a class="attendee-role-toggle" id="rcmlia' + domid + '" title="' + Q(rcmail.gettext('togglerole', 'calendar')) + '">&nbsp;</a>'; list_html += '<div class="attendee ' + String(data.role).toLowerCase() + '" id="rcmli' + domid + '">' + role_html + dispname + '</div>'; // clone attendees data for local modifications freebusy_ui.attendees[i] = freebusy_ui.attendees[domid] = $.extend({}, data); } // add total row list_html += '<div class="attendee spacer">&nbsp;</div>'; list_html += '<div class="attendee total">' + rcmail.gettext('reqallattendees','calendar') + '</div>'; $('#schedule-attendees-list').html(list_html) .unbind('click.roleicons') .bind('click.roleicons', function(e){ // toggle attendee status upon click on icon if (e.target.id && e.target.id.match(/rcmlia(.+)/)) { var attendee, domid = RegExp.$1, roles = [ 'REQ-PARTICIPANT', 'OPT-PARTICIPANT', 'CHAIR' ]; if ((attendee = freebusy_ui.attendees[domid]) && attendee.role != 'ORGANIZER') { var req = attendee.role != 'OPT-PARTICIPANT'; var j = $.inArray(attendee.role, roles); j = (j+1) % roles.length; attendee.role = roles[j]; $(e.target).parent().removeClass().addClass('attendee '+String(attendee.role).toLowerCase()); // update total display if required-status changed if (req != (roles[j] != 'OPT-PARTICIPANT')) { compute_freebusy_totals(); update_freebusy_display(attendee.email); } } } return false; }); // enable/disable buttons $('#shedule-find-prev').button('option', 'disabled', (fb_start.getTime() < now.getTime())); // dialog buttons var buttons = {}; buttons[rcmail.gettext('select', 'calendar')] = function() { $('#edit-startdate').val(freebusy_ui.startdate.val()); $('#edit-starttime').val(freebusy_ui.starttime.val()); $('#edit-enddate').val(freebusy_ui.enddate.val()); $('#edit-endtime').val(freebusy_ui.endtime.val()); // write role changes back to main dialog $('select.edit-attendee-role').each(function(i, elem){ if (event_attendees[i] && freebusy_ui.attendees[i]) { event_attendees[i].role = freebusy_ui.attendees[i].role; $(elem).val(event_attendees[i].role); } }); if (freebusy_ui.needsupdate) update_freebusy_status(me.selected_event); freebusy_ui.needsupdate = false; $dialog.dialog("close"); }; buttons[rcmail.gettext('cancel', 'calendar')] = function() { $dialog.dialog("close"); }; $dialog.dialog({ modal: true, resizable: true, closeOnEscape: (!bw.ie6 && !bw.ie7), title: rcmail.gettext('scheduletime', 'calendar'), open: function() { $dialog.parent().find('.ui-dialog-buttonset .ui-button').first().focus(); }, close: function() { if (bw.ie6) $("#edit-attendees-table").css('visibility','visible'); $dialog.dialog("destroy").hide(); }, resizeStop: function() { render_freebusy_overlay(); }, buttons: buttons, minWidth: 640, width: 850 }).show(); // hide edit dialog on IE6 because of drop-down elements if (bw.ie6) $("#edit-attendees-table").css('visibility','hidden'); // adjust dialog size to fit grid without scrolling var gridw = $('#schedule-freebusy-times').width(); var overflow = gridw - $('#attendees-freebusy-table td.times').width() + 1; me.dialog_resize($dialog.get(0), $dialog.height() + (bw.ie ? 20 : 0), 800 + Math.max(0, overflow)); // fetch data from server freebusy_ui.loading = 0; load_freebusy_data(freebusy_ui.start, freebusy_ui.interval); }; // render an HTML table showing free-busy status for all the event attendees var render_freebusy_grid = function(delta) { if (delta) { freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta); fix_date(freebusy_ui.start); // skip weekends if in workinhoursonly-mode if (Math.abs(delta) == 1 && freebusy_ui.workinhoursonly) { while (is_weekend(freebusy_ui.start)) freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta); fix_date(freebusy_ui.start); } freebusy_ui.end = new Date(freebusy_ui.start.getTime() + DAY_MS * freebusy_ui.numdays); } var dayslots = Math.floor(1440 / freebusy_ui.interval); var date_format = 'ddd '+ (dayslots <= 2 ? settings.date_short : settings.date_format); var lastdate, datestr, css, curdate = new Date(), allday = (freebusy_ui.interval == 1440), times_css = (allday ? 'allday ' : ''), dates_row = '<tr class="dates">', times_row = '<tr class="times">', slots_row = ''; for (var s = 0, t = freebusy_ui.start.getTime(); t < freebusy_ui.end.getTime(); s++) { curdate.setTime(t); datestr = fc.fullCalendar('formatDate', curdate, date_format); if (datestr != lastdate) { if (lastdate && !allday) break; dates_row += '<th colspan="' + dayslots + '" class="boxtitle date' + $.fullCalendar.formatDate(curdate, 'ddMMyyyy') + '">' + Q(datestr) + '</th>'; lastdate = datestr; } // set css class according to working hours css = is_weekend(curdate) || (freebusy_ui.interval <= 60 && !is_workinghour(curdate)) ? 'offhours' : 'workinghours'; times_row += '<td class="' + times_css + css + '" id="t-' + Math.floor(t/1000) + '">' + Q(allday ? rcmail.gettext('all-day','calendar') : $.fullCalendar.formatDate(curdate, settings['time_format'])) + '</td>'; slots_row += '<td class="' + css + ' unknown">&nbsp;</td>'; t += freebusy_ui.interval * 60000; } dates_row += '</tr>'; times_row += '</tr>'; // render list of attendees var domid, data, list_html = '', times_html = ''; for (var i=0; i < event_attendees.length; i++) { data = event_attendees[i]; domid = String(data.email).replace(rcmail.identifier_expr, ''); times_html += '<tr id="fbrow' + domid + '">' + slots_row + '</tr>'; } // add line for all/required attendees times_html += '<tr class="spacer"><td colspan="' + (dayslots * freebusy_ui.numdays) + '">&nbsp;</td>'; times_html += '<tr id="fbrowall">' + slots_row + '</tr>'; var table = $('#schedule-freebusy-times'); table.children('thead').html(dates_row + times_row); table.children('tbody').html(times_html); // initialize event handlers on grid if (!freebusy_ui.grid_events) { freebusy_ui.grid_events = true; table.children('thead').click(function(e){ // move event to the clicked date/time if (e.target.id && e.target.id.match(/t-(\d+)/)) { var newstart = new Date(RegExp.$1 * 1000); // set time to 00:00 if (me.selected_event.allDay) { newstart.setMinutes(0); newstart.setHours(0); } update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000)); render_freebusy_overlay(); } }) } // if we have loaded free-busy data, show it if (!freebusy_ui.loading) { if (freebusy_ui.start < freebusy_data.start || freebusy_ui.end > freebusy_data.end || freebusy_ui.interval != freebusy_data.interval) { load_freebusy_data(freebusy_ui.start, freebusy_ui.interval); } else { for (var email, i=0; i < event_attendees.length; i++) { if ((email = event_attendees[i].email)) update_freebusy_display(email); } } } // render current event date/time selection over grid table // use timeout to let the dom attributes (width/height/offset) be set first window.setTimeout(function(){ render_freebusy_overlay(); }, 10); }; // render overlay element over the grid to visiualize the current event date/time var render_freebusy_overlay = function() { var overlay = $('#schedule-event-time'); if (me.selected_event.end.getTime() <= freebusy_ui.start.getTime() || me.selected_event.start.getTime() >= freebusy_ui.end.getTime()) { overlay.hide(); if (overlay.data('isdraggable')) overlay.draggable('disable'); } else { var table = $('#schedule-freebusy-times'), width = 0, pos = { top:table.children('thead').height(), left:0 }, eventstart = date2unixtime(clone_date(me.selected_event.start, me.selected_event.allDay?1:0)), eventend = date2unixtime(clone_date(me.selected_event.end, me.selected_event.allDay?2:0)) - 60, slotstart = date2unixtime(freebusy_ui.start), slotsize = freebusy_ui.interval * 60, slotend, fraction, $cell; // iterate through slots to determine position and size of the overlay table.children('thead').find('td').each(function(i, cell){ slotend = slotstart + slotsize - 1; // event starts in this slot: compute left if (eventstart >= slotstart && eventstart <= slotend) { fraction = 1 - (slotend - eventstart) / slotsize; pos.left = Math.round(cell.offsetLeft + cell.offsetWidth * fraction); } // event ends in this slot: compute width if (eventend >= slotstart && eventend <= slotend) { fraction = 1 - (slotend - eventend) / slotsize; width = Math.round(cell.offsetLeft + cell.offsetWidth * fraction) - pos.left; } slotstart = slotstart + slotsize; }); if (!width) width = table.width() - pos.left; // overlay is visible if (width > 0) { overlay.css({ width: (width-5)+'px', height:(table.children('tbody').height() - 4)+'px', left:pos.left+'px', top:pos.top+'px' }).show(); // configure draggable if (!overlay.data('isdraggable')) { overlay.draggable({ axis: 'x', scroll: true, stop: function(e, ui){ // convert pixels to time var px = ui.position.left; var range_p = $('#schedule-freebusy-times').width(); var range_t = freebusy_ui.end.getTime() - freebusy_ui.start.getTime(); var newstart = new Date(freebusy_ui.start.getTime() + px * (range_t / range_p)); newstart.setSeconds(0); newstart.setMilliseconds(0); // snap to day boundaries if (me.selected_event.allDay) { if (newstart.getHours() >= 12) // snap to next day newstart.setTime(newstart.getTime() + DAY_MS); newstart.setMinutes(0); newstart.setHours(0); } else { // round to 5 minutes var round = newstart.getMinutes() % 5; if (round > 2.5) newstart.setTime(newstart.getTime() + (5 - round) * 60000); else if (round > 0) newstart.setTime(newstart.getTime() - round * 60000); } // update event times and display update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000)); if (me.selected_event.allDay) render_freebusy_overlay(); } }).data('isdraggable', true); } else overlay.draggable('enable'); } else overlay.draggable('disable').hide(); } }; // fetch free-busy information for each attendee from server var load_freebusy_data = function(from, interval) { var start = new Date(from.getTime() - DAY_MS * 2); // start 2 days before event fix_date(start); var end = new Date(start.getTime() + DAY_MS * Math.max(14, freebusy_ui.numdays + 7)); // load min. 14 days freebusy_ui.numrequired = 0; freebusy_data.all = []; freebusy_data.required = []; // load free-busy information for every attendee var domid, email; for (var i=0; i < event_attendees.length; i++) { if ((email = event_attendees[i].email)) { domid = String(email).replace(rcmail.identifier_expr, ''); $('#rcmli' + domid).addClass('loading'); freebusy_ui.loading++; $.ajax({ type: 'GET', dataType: 'json', url: rcmail.url('freebusy-times'), data: { email:email, start:date2servertime(clone_date(start, 1)), end:date2servertime(clone_date(end, 2)), interval:interval, _remote:1 }, success: function(data) { freebusy_ui.loading--; // find attendee var attendee = null; for (var i=0; i < event_attendees.length; i++) { if (freebusy_ui.attendees[i].email == data.email) { attendee = freebusy_ui.attendees[i]; break; } } // copy data to member var var ts, req = attendee.role != 'OPT-PARTICIPANT'; freebusy_data.start = parseISO8601(data.start); freebusy_data[data.email] = {}; for (var i=0; i < data.slots.length; i++) { ts = data.times[i] + ''; freebusy_data[data.email][ts] = data.slots[i]; // set totals if (!freebusy_data.required[ts]) freebusy_data.required[ts] = [0,0,0,0]; if (req) freebusy_data.required[ts][data.slots[i]]++; if (!freebusy_data.all[ts]) freebusy_data.all[ts] = [0,0,0,0]; freebusy_data.all[ts][data.slots[i]]++; } freebusy_data.end = parseISO8601(data.end); freebusy_data.interval = data.interval; // hide loading indicator var domid = String(data.email).replace(rcmail.identifier_expr, ''); $('#rcmli' + domid).removeClass('loading'); // update display update_freebusy_display(data.email); } }); // count required attendees if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT') freebusy_ui.numrequired++; } } }; // re-calculate total status after role change var compute_freebusy_totals = function() { freebusy_ui.numrequired = 0; freebusy_data.all = []; freebusy_data.required = []; var email, req, status; for (var i=0; i < event_attendees.length; i++) { if (!(email = event_attendees[i].email)) continue; req = freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT'; if (req) freebusy_ui.numrequired++; for (var ts in freebusy_data[email]) { if (!freebusy_data.required[ts]) freebusy_data.required[ts] = [0,0,0,0]; if (!freebusy_data.all[ts]) freebusy_data.all[ts] = [0,0,0,0]; status = freebusy_data[email][ts]; freebusy_data.all[ts][status]++; if (req) freebusy_data.required[ts][status]++; } } }; // update free-busy grid with status loaded from server var update_freebusy_display = function(email) { var status_classes = ['unknown','free','busy','tentative','out-of-office']; var domid = String(email).replace(rcmail.identifier_expr, ''); var row = $('#fbrow' + domid); var rowall = $('#fbrowall').children(); var dateonly = freebusy_ui.interval > 60, t, ts = date2timestring(freebusy_ui.start, dateonly), curdate = new Date(), fbdata = freebusy_data[email]; if (fbdata && fbdata[ts] !== undefined && row.length) { t = freebusy_ui.start.getTime(); row.children().each(function(i, cell){ curdate.setTime(t); ts = date2timestring(curdate, dateonly); cell.className = cell.className.replace('unknown', fbdata[ts] ? status_classes[fbdata[ts]] : 'unknown'); // also update total row if all data was loaded if (freebusy_ui.loading == 0 && freebusy_data.all[ts] && (cell = rowall.get(i))) { var workinghours = cell.className.indexOf('workinghours') >= 0; var all_status = freebusy_data.all[ts][2] ? 'busy' : 'unknown'; req_status = freebusy_data.required[ts][2] ? 'busy' : 'free'; for (var j=1; j < status_classes.length; j++) { if (freebusy_ui.numrequired && freebusy_data.required[ts][j] >= freebusy_ui.numrequired) req_status = status_classes[j]; if (freebusy_data.all[ts][j] == event_attendees.length) all_status = status_classes[j]; } cell.className = (workinghours ? 'workinghours ' : 'offhours ') + req_status + ' all-' + all_status; } t += freebusy_ui.interval * 60000; }); } }; // write changed event date/times back to form fields var update_freebusy_dates = function(start, end) { // fix all-day evebt times if (me.selected_event.allDay) { var numdays = Math.floor((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / DAY_MS); start.setHours(12); start.setMinutes(0); end.setTime(start.getTime() + numdays * DAY_MS); end.setHours(13); end.setMinutes(0); } me.selected_event.start = start; me.selected_event.end = end; freebusy_ui.startdate.val($.fullCalendar.formatDate(start, settings['date_format'])); freebusy_ui.starttime.val($.fullCalendar.formatDate(start, settings['time_format'])); freebusy_ui.enddate.val($.fullCalendar.formatDate(end, settings['date_format'])); freebusy_ui.endtime.val($.fullCalendar.formatDate(end, settings['time_format'])); freebusy_ui.needsupdate = true; }; // attempt to find a time slot where all attemdees are available var freebusy_find_slot = function(dir) { // exit if free-busy data isn't available yet if (!freebusy_data || !freebusy_data.start) return false; var event = me.selected_event, eventstart = clone_date(event.start, event.allDay ? 1 : 0).getTime(), // calculate with integers eventend = clone_date(event.end, event.allDay ? 2 : 0).getTime(), duration = eventend - eventstart - (event.allDay ? HOUR_MS : 0), // make sure we don't cross day borders on DST change sinterval = freebusy_data.interval * 60000, intvlslots = 1, numslots = Math.ceil(duration / sinterval), checkdate, slotend, email, ts, slot, slotdate = new Date(); // shift event times to next possible slot eventstart += sinterval * intvlslots * dir; eventend += sinterval * intvlslots * dir; // iterate through free-busy slots and find candidates var candidatecount = 0, candidatestart = candidateend = success = false; for (slot = dir > 0 ? freebusy_data.start.getTime() : freebusy_data.end.getTime() - sinterval; (dir > 0 && slot < freebusy_data.end.getTime()) || (dir < 0 && slot >= freebusy_data.start.getTime()); slot += sinterval * dir) { slotdate.setTime(slot); // fix slot if just crossed a DST change if (event.allDay) { fix_date(slotdate); slot = slotdate.getTime(); } slotend = slot + sinterval; if ((dir > 0 && slotend <= eventstart) || (dir < 0 && slot >= eventend)) // skip continue; // respect workingours setting if (freebusy_ui.workinhoursonly) { if (is_weekend(slotdate) || (freebusy_data.interval <= 60 && !is_workinghour(slotdate))) { // skip off-hours candidatestart = candidateend = false; candidatecount = 0; continue; } } if (!candidatestart) candidatestart = slot; // check freebusy data for all attendees ts = date2timestring(slotdate, freebusy_data.interval > 60); for (var i=0; i < event_attendees.length; i++) { if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT' && (email = freebusy_ui.attendees[i].email) && freebusy_data[email] && freebusy_data[email][ts] > 1) { candidatestart = candidateend = false; break; } } // occupied slot if (!candidatestart) { slot += Math.max(0, intvlslots - candidatecount - 1) * sinterval * dir; candidatecount = 0; continue; } // set candidate end to slot end time candidatecount++; if (dir < 0 && !candidateend) candidateend = slotend; // if candidate is big enough, this is it! if (candidatecount == numslots) { if (dir > 0) { event.start.setTime(candidatestart); event.end.setTime(candidatestart + duration); } else { event.end.setTime(candidateend); event.start.setTime(candidateend - duration); } success = true; break; } } // update event date/time display if (success) { update_freebusy_dates(event.start, event.end); // move freebusy grid if necessary var offset = Math.ceil((event.start.getTime() - freebusy_ui.end.getTime()) / DAY_MS); if (event.start.getTime() >= freebusy_ui.end.getTime()) render_freebusy_grid(Math.max(1, offset)); else if (event.end.getTime() <= freebusy_ui.start.getTime()) render_freebusy_grid(Math.min(-1, offset)); else render_freebusy_overlay(); var now = new Date(); $('#shedule-find-prev').button('option', 'disabled', (event.start.getTime() < now.getTime())); } else { alert(rcmail.gettext('noslotfound','calendar')); } }; // update event properties and attendees availability if event times have changed var event_times_changed = function() { if (me.selected_event) { var allday = $('#edit-allday').get(0); me.selected_event.allDay = allday.checked; me.selected_event.start = parse_datetime(allday.checked ? '12:00' : $('#edit-starttime').val(), $('#edit-startdate').val()); me.selected_event.end = parse_datetime(allday.checked ? '13:00' : $('#edit-endtime').val(), $('#edit-enddate').val()); if (event_attendees) freebusy_ui.needsupdate = true; $('#edit-startdate').data('duration', Math.round((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / 1000)); } }; // add the given list of participants var add_attendees = function(names) { names = explode_quoted_string(names.replace(/,\s*$/, ''), ','); // parse name/email pairs var item, email, name, success = false; for (var i=0; i < names.length; i++) { email = name = ''; item = $.trim(names[i]); if (!item.length) { continue; } // address in brackets without name (do nothing) else if (item.match(/^<[^@]+@[^>]+>$/)) { email = item.replace(/[<>]/g, ''); } // address without brackets and without name (add brackets) else if (rcube_check_email(item)) { email = item; } // address with name else if (item.match(/([^\s<@]+@[^>]+)>*$/)) { email = RegExp.$1; name = item.replace(email, '').replace(/^["\s<>]+/, '').replace(/["\s<>]+$/, ''); } if (email) { add_attendee({ email:email, name:name, role:'REQ-PARTICIPANT', status:'NEEDS-ACTION' }); success = true; } else { alert(rcmail.gettext('noemailwarning')); } } return success; }; // add the given attendee to the list var add_attendee = function(data, readonly) { // check for dupes... var exists = false; $.each(event_attendees, function(i, v){ exists |= (v.email == data.email); }); if (exists) return false; var dispname = Q(data.name || data.email); if (data.email) dispname = '<a href="mailto:' + data.email + '" title="' + Q(data.email) + '" class="mailtolink">' + dispname + '</a>'; // role selection var organizer = data.role == 'ORGANIZER'; var opts = {}; if (organizer) opts.ORGANIZER = rcmail.gettext('calendar.roleorganizer'); opts['REQ-PARTICIPANT'] = rcmail.gettext('calendar.rolerequired'); opts['OPT-PARTICIPANT'] = rcmail.gettext('calendar.roleoptional'); opts['CHAIR'] = rcmail.gettext('calendar.rolechair'); if (organizer && !readonly) dispname = rcmail.env['identities-selector']; var select = '<select class="edit-attendee-role"' + (organizer || readonly ? ' disabled="true"' : '') + '>'; for (var r in opts) select += '<option value="'+ r +'" class="' + r.toLowerCase() + '"' + (data.role == r ? ' selected="selected"' : '') +'>' + Q(opts[r]) + '</option>'; select += '</select>'; // availability var avail = data.email ? 'loading' : 'unknown'; // delete icon var icon = rcmail.env.deleteicon ? '<img src="' + rcmail.env.deleteicon + '" alt="" />' : rcmail.gettext('delete'); var dellink = '<a href="#delete" class="iconlink delete deletelink" title="' + Q(rcmail.gettext('delete')) + '">' + icon + '</a>'; var html = '<td class="role">' + select + '</td>' + '<td class="name">' + dispname + '</td>' + '<td class="availability"><img src="./program/resources/blank.gif" class="availabilityicon ' + avail + '" /></td>' + '<td class="confirmstate"><span class="' + String(data.status).toLowerCase() + '">' + Q(data.status) + '</span></td>' + '<td class="options">' + (organizer || readonly ? '' : dellink) + '</td>'; var tr = $('<tr>') .addClass(String(data.role).toLowerCase()) .html(html) .appendTo(attendees_list); tr.find('a.deletelink').click({ id:(data.email || data.name) }, function(e) { remove_attendee(this, e.data.id); return false; }); tr.find('a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; }); // select organizer identity if (data.identity_id) $('#edit-identities-list').val(data.identity_id); // check free-busy status if (avail == 'loading') { check_freebusy_status(tr.find('img.availabilityicon'), data.email, me.selected_event); } event_attendees.push(data); }; // iterate over all attendees and update their free-busy status display var update_freebusy_status = function(event) { var icons = attendees_list.find('img.availabilityicon'); for (var i=0; i < event_attendees.length; i++) { if (icons.get(i) && event_attendees[i].email) check_freebusy_status(icons.get(i), event_attendees[i].email, event); } freebusy_ui.needsupdate = false; }; // load free-busy status from server and update icon accordingly var check_freebusy_status = function(icon, email, event) { var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { freebusy:false }; if (!calendar.freebusy) { $(icon).removeClass().addClass('availabilityicon unknown'); return; } icon = $(icon).removeClass().addClass('availabilityicon loading'); $.ajax({ type: 'GET', dataType: 'html', url: rcmail.url('freebusy-status'), data: { email:email, start:date2servertime(clone_date(event.start, event.allDay?1:0)), end:date2servertime(clone_date(event.end, event.allDay?2:0)), _remote: 1 }, success: function(status){ icon.removeClass('loading').addClass(String(status).toLowerCase()); }, error: function(){ icon.removeClass('loading').addClass('unknown'); } }); }; // remove an attendee from the list var remove_attendee = function(elem, id) { $(elem).closest('tr').remove(); event_attendees = $.grep(event_attendees, function(data){ return (data.name != id && data.email != id) }); }; // when the user accepts or declines an event invitation var event_rsvp = function(response) { if (me.selected_event && me.selected_event.attendees && response) { // update attendee status for (var data, i=0; i < me.selected_event.attendees.length; i++) { data = me.selected_event.attendees[i]; if (settings.identity.emails.indexOf(';'+String(data.email).toLowerCase()) >= 0) data.status = response.toUpperCase(); } event_show_dialog(me.selected_event); // submit status change to server me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('event', { action:'rsvp', e:me.selected_event, status:response }); } } // post the given event data to server var update_event = function(action, data) { me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('calendar/event', { action:action, e:data }); // render event temporarily into the calendar if ((data.start && data.end) || data.id) { var event = data.id ? $.extend(fc.fullCalendar('clientEvents', function(e){ return e.id == data.id; })[0], data) : data; if (data.start) event.start = data.start; if (data.end) event.end = data.end; if (data.allday !== undefined) event.allDay = data.allday; event.editable = false; event.temp = true; event.className = 'fc-event-cal-'+data.calendar+' fc-event-temp'; fc.fullCalendar(data.id ? 'updateEvent' : 'renderEvent', event); } }; // mouse-click handler to check if the show dialog is still open and prevent default action var dialog_check = function(e) { var showd = $("#eventshow"); if (showd.is(':visible') && !$(e.target).closest('.ui-dialog').length) { showd.dialog('close'); e.stopImmediatePropagation(); ignore_click = true; return false; } else if (ignore_click) { window.setTimeout(function(){ ignore_click = false; }, 20); return false; } return true; }; // display confirm dialog when modifying/deleting an event var update_event_confirm = function(action, event, data) { if (!data) data = event; var decline = false, notify = false, html = '', cal = me.calendars[event.calendar]; // event has attendees, ask whether to notify them if (has_attendees(event)) { if (is_organizer(event)) { notify = true; html += '<div class="message">' + '<label><input class="confirm-attendees-donotify" type="checkbox" checked="checked" value="1" name="notify" />&nbsp;' + rcmail.gettext((action == 'remove' ? 'sendcancellation' : 'sendnotifications'), 'calendar') + '</label></div>'; } else if (action == 'remove' && is_attendee(event)) { decline = true; html += '<div class="message">' + '<label><input class="confirm-attendees-decline" type="checkbox" checked="checked" value="1" name="decline" />&nbsp;' + rcmail.gettext('itipdeclineevent', 'calendar') + '</label></div>'; } else { html += '<div class="message">' + rcmail.gettext('localchangeswarning', 'calendar') + '</div>'; } } // recurring event: user needs to select the savemode if (event.recurrence) { html += '<div class="message"><span class="ui-icon ui-icon-alert"></span>' + rcmail.gettext((action == 'remove' ? 'removerecurringeventwarning' : 'changerecurringeventwarning'), 'calendar') + '</div>' + '<div class="savemode">' + '<a href="#current" class="button">' + rcmail.gettext('currentevent', 'calendar') + '</a>' + '<a href="#future" class="button">' + rcmail.gettext('futurevents', 'calendar') + '</a>' + '<a href="#all" class="button">' + rcmail.gettext('allevents', 'calendar') + '</a>' + (action != 'remove' ? '<a href="#new" class="button">' + rcmail.gettext('saveasnew', 'calendar') + '</a>' : '') + '</div>'; } // show dialog if (html) { var $dialog = $('<div>').html(html); $dialog.find('a.button').button().click(function(e){ data._savemode = String(this.href).replace(/.+#/, ''); if ($dialog.find('input.confirm-attendees-donotify').get(0)) data._notify = notify && $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0; if (decline && $dialog.find('input.confirm-attendees-decline:checked')) data.decline = 1; update_event(action, data); $dialog.dialog("destroy").hide(); return false; }); var buttons = [{ text: rcmail.gettext('cancel', 'calendar'), click: function() { $(this).dialog("close"); } }]; if (!event.recurrence) { buttons.push({ text: rcmail.gettext((action == 'remove' ? 'remove' : 'save'), 'calendar'), click: function() { data._notify = notify && $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0; data.decline = decline && $dialog.find('input.confirm-attendees-decline:checked').length ? 1 : 0; update_event(action, data); $(this).dialog("close"); } }); } $dialog.dialog({ modal: true, width: 460, dialogClass: 'warning', title: rcmail.gettext((action == 'remove' ? 'removeeventconfirm' : 'changeeventconfirm'), 'calendar'), buttons: buttons, close: function(){ $dialog.dialog("destroy").hide(); if (!rcmail.busy) fc.fullCalendar('refetchEvents'); } }).addClass('event-update-confirm').show(); return false; } // show regular confirm box when deleting else if (action == 'remove' && !cal.undelete) { if (!confirm(rcmail.gettext('deleteventconfirm', 'calendar'))) return false; } // do update update_event(action, data); return true; }; var update_agenda_toolbar = function() { $('#agenda-listrange').val(fc.fullCalendar('option', 'listRange')); $('#agenda-listsections').val(fc.fullCalendar('option', 'listSections')); } /*** fullcalendar event handlers ***/ var fc_event_render = function(event, element, view) { if (view.name != 'list' && view.name != 'table') { var prefix = event.sensitivity && event.sensitivity != 'public' ? String(sensitivitylabels[event.sensitivity]).toUpperCase()+': ' : ''; element.attr('title', prefix + event.title); } if (view.name != 'month') { if (event.location) { element.find('div.fc-event-title').after('<div class="fc-event-location">@&nbsp;' + Q(event.location) + '</div>'); } if (event.sensitivity && event.sensitivity != 'public') element.find('div.fc-event-time').append('<i class="fc-icon-sensitive"></i>'); if (event.recurrence) element.find('div.fc-event-time').append('<i class="fc-icon-recurring"></i>'); if (event.alarms) element.find('div.fc-event-time').append('<i class="fc-icon-alarms"></i>'); } }; /*** public methods ***/ /** * Remove saving lock and free the UI for new input */ this.unlock_saving = function() { if (me.saving_lock) rcmail.set_busy(false, null, me.saving_lock); }; // opens calendar day-view in a popup this.fisheye_view = function(date) { $('#fish-eye-view:ui-dialog').dialog('close'); // create list of active event sources var src, cals = {}, sources = []; for (var id in this.calendars) { src = $.extend({}, this.calendars[id]); src.editable = false; src.url = null; src.events = []; if (src.active) { cals[id] = src; sources.push(src); } } // copy events already loaded var events = fc.fullCalendar('clientEvents'); for (var event, i=0; i< events.length; i++) { event = events[i]; if (event.source && (src = cals[event.source.id])) { src.events.push(event); } } var h = $(window).height() - 50; var dialog = $('<div>') .attr('id', 'fish-eye-view') .dialog({ modal: true, width: 680, height: h, title: $.fullCalendar.formatDate(date, 'dddd ' + settings['date_long']), close: function(){ dialog.dialog("destroy"); me.fisheye_date = null; } }) .fullCalendar({ header: { left: '', center: '', right: '' }, height: h - 50, defaultView: 'agendaDay', date: date.getDate(), month: date.getMonth(), year: date.getFullYear(), ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone eventSources: sources, monthNames : settings['months'], monthNamesShort : settings['months_short'], dayNames : settings['days'], dayNamesShort : settings['days_short'], firstDay : settings['first_day'], firstHour : settings['first_hour'], slotMinutes : 60/settings['timeslots'], timeFormat: { '': settings['time_format'] }, axisFormat : settings['time_format'], columnFormat: { day: 'dddd ' + settings['date_short'] }, titleFormat: { day: 'dddd ' + settings['date_long'] }, allDayText: rcmail.gettext('all-day', 'calendar'), currentTimeIndicator: settings.time_indicator, eventRender: fc_event_render, eventClick: function(event) { event_show_dialog(event); } }); this.fisheye_date = date; }; //public method to show the print dialog. this.print_calendars = function(view) { if (!view) view = fc.fullCalendar('getView').name; var date = fc.fullCalendar('getDate') || new Date(); var range = fc.fullCalendar('option', 'listRange'); var sections = fc.fullCalendar('option', 'listSections'); rcmail.open_window(rcmail.url('print', { view: view, date: date2unixtime(date), range: range, sections: sections, search: this.search_query }), true, true); }; // public method to bring up the new event dialog this.add_event = function(templ) { if (this.selected_calendar) { var now = new Date(); var date = fc.fullCalendar('getDate'); if (typeof date != 'Date') date = now; date.setHours(now.getHours()+1); date.setMinutes(0); var end = new Date(date.getTime()); end.setHours(date.getHours()+1); event_edit_dialog('new', $.extend({ start:date, end:end, allDay:false, calendar:this.selected_calendar }, templ || {})); } }; // delete the given event after showing a confirmation dialog this.delete_event = function(event) { // show confirm dialog for recurring events, use jquery UI dialog return update_event_confirm('remove', event, { id:event.id, calendar:event.calendar, attendees:event.attendees }); }; // opens a jquery UI dialog with event properties (or empty for creating a new calendar) this.calendar_edit_dialog = function(calendar) { // close show dialog first var $dialog = $("#calendarform"); if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); if (!calendar) calendar = { name:'', color:'cc0000', editable:true, showalarms:true }; var form, name, color, alarms; $dialog.html(rcmail.get_label('loading')); $.ajax({ type: 'GET', dataType: 'html', url: rcmail.url('calendar'), data: { action:(calendar.id ? 'form-edit' : 'form-new'), c:{ id:calendar.id } }, success: function(data) { $dialog.html(data); // resize and reposition dialog window form = $('#calendarpropform'); me.dialog_resize('#calendarform', form.height(), form.width()); name = $('#calendar-name').prop('disabled', !calendar.editable).val(calendar.editname || calendar.name); color = $('#calendar-color').val(calendar.color).miniColors({ value: calendar.color, colorValues:rcmail.env.mscolors }); alarms = $('#calendar-showalarms').prop('checked', calendar.showalarms).get(0); name.select(); } }); // dialog buttons var buttons = {}; buttons[rcmail.gettext('save', 'calendar')] = function() { // form is not loaded if (!form || !form.length) return; // TODO: do some input validation if (!name.val() || name.val().length < 2) { alert(rcmail.gettext('invalidcalendarproperties', 'calendar')); name.select(); return; } // post data to server var data = form.serializeJSON(); if (data.color) data.color = data.color.replace(/^#/, ''); if (calendar.id) data.id = calendar.id; if (alarms) data.showalarms = alarms.checked ? 1 : 0; me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata'); rcmail.http_post('calendar', { action:(calendar.id ? 'edit' : 'new'), c:data }); $dialog.dialog("close"); }; buttons[rcmail.gettext('cancel', 'calendar')] = function() { $dialog.dialog("close"); }; // open jquery UI dialog $dialog.dialog({ modal: true, resizable: true, closeOnEscape: false, title: rcmail.gettext((calendar.id ? 'editcalendar' : 'createcalendar'), 'calendar'), close: function() { $dialog.html('').dialog("destroy").hide(); }, buttons: buttons, minWidth: 400, width: 420 }).show(); }; this.calendar_remove = function(calendar) { if (confirm(rcmail.gettext(calendar.children ? 'deletecalendarconfirmrecursive' : 'deletecalendarconfirm', 'calendar'))) { rcmail.http_post('calendar', { action:'remove', c:{ id:calendar.id } }); return true; } return false; }; this.calendar_destroy_source = function(id) { var delete_ids = []; if (this.calendars[id]) { // find sub-calendars if (this.calendars[id].children) { for (var child_id in this.calendars) { if (String(child_id).indexOf(id) == 0) delete_ids.push(child_id); } } else { delete_ids.push(id); } } // delete all calendars in the list for (var i=0; i < delete_ids.length; i++) { id = delete_ids[i]; fc.fullCalendar('removeEventSource', this.calendars[id]); $(rcmail.get_folder_li(id, 'rcmlical')).remove(); $('#edit-calendar option[value="'+id+'"]').remove(); delete this.calendars[id]; } }; // open a dialog to upload an .ics file with events to be imported this.import_events = function(calendar) { // close show dialog first var $dialog = $("#eventsimport"), form = rcmail.gui_objects.importform; if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); if (calendar) $('#event-import-calendar').val(calendar.id); var buttons = {}; buttons[rcmail.gettext('import', 'calendar')] = function() { if (form && form.elements._data.value) { rcmail.async_upload_form(form, 'import_events', function(e) { rcmail.set_busy(false, null, me.saving_lock); $('.ui-dialog-buttonpane button', $dialog.parent()).button('enable'); // display error message if no sophisticated response from server arrived (e.g. iframe load error) if (me.import_succeeded === null) rcmail.display_message(rcmail.get_label('importerror', 'calendar'), 'error'); }); // display upload indicator (with extended timeout) var timeout = rcmail.env.request_timeout; rcmail.env.request_timeout = 600; me.import_succeeded = null; me.saving_lock = rcmail.set_busy(true, 'uploading'); $('.ui-dialog-buttonpane button', $dialog.parent()).button('disable'); // restore settings rcmail.env.request_timeout = timeout; } }; buttons[rcmail.gettext('cancel', 'calendar')] = function() { $dialog.dialog("close"); }; // open jquery UI dialog $dialog.dialog({ modal: true, resizable: false, closeOnEscape: false, title: rcmail.gettext('importevents', 'calendar'), close: function() { $('.ui-dialog-buttonpane button', $dialog.parent()).button('enable'); $dialog.dialog("destroy").hide(); }, buttons: buttons, width: 520 }).show(); }; // callback from server if import succeeded this.import_success = function(p) { this.import_succeeded = true; $("#eventsimport:ui-dialog").dialog('close'); rcmail.set_busy(false, null, me.saving_lock); rcmail.gui_objects.importform.reset(); if (p.refetch) this.refresh(p); }; // callback from server to report errors on import this.import_error = function(p) { this.import_succeeded = false; rcmail.display_message(p.message || rcmail.get_label('importerror', 'calendar'), 'error'); } // show URL of the given calendar in a dialog box this.showurl = function(calendar) { var $dialog = $('#calendarurlbox'); if ($dialog.is(':ui-dialog')) $dialog.dialog('close'); if (calendar.feedurl) { if (calendar.caldavurl) { $('#caldavurl').val(calendar.caldavurl); $('#calendarcaldavurl').show(); } else { $('#calendarcaldavurl').hide(); } $dialog.dialog({ resizable: true, closeOnEscape: true, title: rcmail.gettext('showurl', 'calendar'), close: function() { $dialog.dialog("destroy").hide(); }, width: 520 }).show(); $('#calfeedurl').val(calendar.feedurl).select(); } }; // refresh the calendar view after saving event data this.refresh = function(p) { var source = me.calendars[p.source]; if (source && (p.refetch || (p.update && !source.active))) { // activate event source if new event was added to an invisible calendar if (!source.active) { source.active = true; fc.fullCalendar('addEventSource', source); $('#' + rcmail.get_folder_li(source.id, 'rcmlical').id + ' input').prop('checked', true); } else fc.fullCalendar('refetchEvents', source); } // add/update single event object else if (source && p.update) { var event = p.update; event.temp = false; event.editable = source.editable; var existing = fc.fullCalendar('clientEvents', event._id); if (existing.length) { $.extend(existing[0], event); fc.fullCalendar('updateEvent', existing[0]); } else { event.source = source; // link with source fc.fullCalendar('renderEvent', event); } // refresh fish-eye view if (me.fisheye_date) me.fisheye_view(me.fisheye_date); } // remove temp events fc.fullCalendar('removeEvents', function(e){ return e.temp; }); }; // modify query parameters for refresh requests this.before_refresh = function(query) { var view = fc.fullCalendar('getView'); query.start = date2unixtime(view.visStart); query.end = date2unixtime(view.visEnd); if (this.search_query) query.q = this.search_query; return query; }; /*** event searching ***/ // execute search this.quicksearch = function() { if (rcmail.gui_objects.qsearchbox) { var q = rcmail.gui_objects.qsearchbox.value; if (q != '') { var id = 'search-'+q; var sources = []; if (this._search_message) rcmail.hide_message(this._search_message); for (var sid in this.calendars) { if (this.calendars[sid]) { this.calendars[sid].url = this.calendars[sid].url.replace(/&q=.+/, '') + '&q='+escape(q); sources.push(sid); } } id += '@'+sources.join(','); // ignore if query didn't change if (this.search_request == id) { return; } // remember current view else if (!this.search_request) { this.default_view = fc.fullCalendar('getView').name; } this.search_request = id; this.search_query = q; // change to list view fc.fullCalendar('option', 'listSections', 'month') .fullCalendar('option', 'listRange', Math.max(60, settings['agenda_range'])) .fullCalendar('changeView', 'table'); update_agenda_toolbar(); // refetch events with new url (if not already triggered by changeView) if (!this.is_loading) fc.fullCalendar('refetchEvents'); } else // empty search input equals reset this.reset_quicksearch(); } }; // reset search and get back to normal event listing this.reset_quicksearch = function() { $(rcmail.gui_objects.qsearchbox).val(''); if (this._search_message) rcmail.hide_message(this._search_message); if (this.search_request) { // hide bottom links of agenda view fc.find('.fc-list-content > .fc-listappend').hide(); // restore original event sources and view mode from fullcalendar fc.fullCalendar('option', 'listSections', settings['agenda_sections']) .fullCalendar('option', 'listRange', settings['agenda_range']); update_agenda_toolbar(); for (var sid in this.calendars) { if (this.calendars[sid]) this.calendars[sid].url = this.calendars[sid].url.replace(/&q=.+/, ''); } if (this.default_view) fc.fullCalendar('changeView', this.default_view); if (!this.is_loading) fc.fullCalendar('refetchEvents'); this.search_request = this.search_query = null; } }; // callback if all sources have been fetched from server this.events_loaded = function(count) { var addlinks, append = ''; // enhance list view when searching if (this.search_request) { if (!count) { this._search_message = rcmail.display_message(rcmail.gettext('searchnoresults', 'calendar'), 'notice'); append = '<div class="message">' + rcmail.gettext('searchnoresults', 'calendar') + '</div>'; } append += '<div class="fc-bottomlinks formlinks"></div>'; addlinks = true; } if (fc.fullCalendar('getView').name == 'table') { var container = fc.find('.fc-list-content > .fc-listappend'); if (append) { if (!container.length) container = $('<div class="fc-listappend"></div>').appendTo(fc.find('.fc-list-content')); container.html(append).show(); } else if (container.length) container.hide(); // add links to adjust search date range if (addlinks) { var lc = container.find('.fc-bottomlinks'); $('<a>').attr('href', '#').html(rcmail.gettext('searchearlierdates', 'calendar')).appendTo(lc).click(function(){ fc.fullCalendar('incrementDate', 0, -1, 0); }); lc.append(" "); $('<a>').attr('href', '#').html(rcmail.gettext('searchlaterdates', 'calendar')).appendTo(lc).click(function(){ var range = fc.fullCalendar('option', 'listRange'); if (range < 90) { fc.fullCalendar('option', 'listRange', fc.fullCalendar('option', 'listRange') + 30).fullCalendar('render'); update_agenda_toolbar(); } else fc.fullCalendar('incrementDate', 0, 1, 0); }); } } if (this.fisheye_date) this.fisheye_view(this.fisheye_date); }; // resize and reposition (center) the dialog window this.dialog_resize = function(id, height, width) { var win = $(window), w = win.width(), h = win.height(); $(id).dialog('option', { height: Math.min(h-20, height+130), width: Math.min(w-20, width+50) }) .dialog('option', 'position', ['center', 'center']); // only works in a separate call (!?) }; // adjust calendar view size this.view_resize = function() { var footer = fc.fullCalendar('getView').name == 'table' ? $('#agendaoptions').outerHeight() : 0; fc.fullCalendar('option', 'height', $('#calendar').height() - footer); }; /*** startup code ***/ // create list of event sources AKA calendars this.calendars = {}; var li, cal, active, event_sources = []; for (var id in rcmail.env.calendars) { cal = rcmail.env.calendars[id]; this.calendars[id] = $.extend({ url: "./?_task=calendar&_action=load_events&source="+escape(id), editable: !cal.readonly, className: 'fc-event-cal-'+id, id: id }, cal); this.calendars[id].color = settings.event_coloring % 2 ? '' : '#' + cal.color; if ((active = cal.active || false)) { event_sources.push(this.calendars[id]); } // init event handler on calendar list checkbox if ((li = rcmail.get_folder_li(id, 'rcmlical'))) { $('#'+li.id+' input').click(function(e){ var id = $(this).data('id'); if (me.calendars[id]) { // add or remove event source on click var action; if (this.checked) { action = 'addEventSource'; me.calendars[id].active = true; } else { action = 'removeEventSource'; me.calendars[id].active = false; } // add/remove event source fc.fullCalendar(action, me.calendars[id]); rcmail.http_post('calendar', { action:'subscribe', c:{ id:id, active:me.calendars[id].active?1:0 } }); } }).data('id', id).get(0).checked = active; $(li).click(function(e){ var id = $(this).data('id'); rcmail.select_folder(id, 'rcmlical'); rcmail.enable_command('calendar-edit', true); rcmail.enable_command('calendar-remove', 'calendar-showurl', true); me.selected_calendar = id; }) .dblclick(function(){ me.calendar_edit_dialog(me.calendars[me.selected_calendar]); }) .data('id', id); } if (!cal.readonly && !this.selected_calendar) { this.selected_calendar = id; rcmail.enable_command('addevent', true); } } // select default calendar if (settings.default_calendar && this.calendars[settings.default_calendar] && !this.calendars[settings.default_calendar].readonly) this.selected_calendar = settings.default_calendar; var viewdate = new Date(); if (rcmail.env.date) viewdate.setTime(fromunixtime(rcmail.env.date)); // initalize the fullCalendar plugin var fc = $('#calendar').fullCalendar({ header: { right: 'prev,next today', center: 'title', left: 'agendaDay,agendaWeek,month,table' }, aspectRatio: 1, date: viewdate.getDate(), month: viewdate.getMonth(), year: viewdate.getFullYear(), ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone height: $('#calendar').height(), eventSources: event_sources, monthNames : settings['months'], monthNamesShort : settings['months_short'], dayNames : settings['days'], dayNamesShort : settings['days_short'], firstDay : settings['first_day'], firstHour : settings['first_hour'], slotMinutes : 60/settings['timeslots'], timeFormat: { '': settings['time_format'], agenda: settings['time_format'] + '{ - ' + settings['time_format'] + '}', list: settings['time_format'] + '{ - ' + settings['time_format'] + '}', table: settings['time_format'] + '{ - ' + settings['time_format'] + '}' }, axisFormat : settings['time_format'], columnFormat: { month: 'ddd', // Mon week: 'ddd ' + settings['date_short'], // Mon 9/7 day: 'dddd ' + settings['date_short'], // Monday 9/7 table: settings['date_agenda'] }, titleFormat: { month: 'MMMM yyyy', week: settings['dates_long'], day: 'dddd ' + settings['date_long'], table: settings['dates_long'] }, listPage: 1, // advance one day in agenda view listRange: settings['agenda_range'], listSections: settings['agenda_sections'], tableCols: ['handle', 'date', 'time', 'title', 'location'], defaultView: rcmail.env.view || settings['default_view'], allDayText: rcmail.gettext('all-day', 'calendar'), buttonText: { prev: (bw.ie6 ? '&nbsp;&lt;&lt;&nbsp;' : '&nbsp;&#9668;&nbsp;'), next: (bw.ie6 ? '&nbsp;&gt;&gt;&nbsp;' : '&nbsp;&#9658;&nbsp;'), today: settings['today'], day: rcmail.gettext('day', 'calendar'), week: rcmail.gettext('week', 'calendar'), month: rcmail.gettext('month', 'calendar'), table: rcmail.gettext('agenda', 'calendar') }, listTexts: { until: rcmail.gettext('until', 'calendar'), past: rcmail.gettext('pastevents', 'calendar'), today: rcmail.gettext('today', 'calendar'), tomorrow: rcmail.gettext('tomorrow', 'calendar'), thisWeek: rcmail.gettext('thisweek', 'calendar'), nextWeek: rcmail.gettext('nextweek', 'calendar'), thisMonth: rcmail.gettext('thismonth', 'calendar'), nextMonth: rcmail.gettext('nextmonth', 'calendar'), future: rcmail.gettext('futureevents', 'calendar'), week: rcmail.gettext('weekofyear', 'calendar') }, selectable: true, selectHelper: false, currentTimeIndicator: settings.time_indicator, loading: function(isLoading) { me.is_loading = isLoading; this._rc_loading = rcmail.set_busy(isLoading, 'loading', this._rc_loading); // trigger callback if (!isLoading) me.events_loaded($(this).fullCalendar('clientEvents').length); }, // event rendering eventRender: fc_event_render, // render element indicating more (invisible) events overflowRender: function(data, element) { element.html(rcmail.gettext('andnmore', 'calendar').replace('$nr', data.count)) .click(function(e){ me.fisheye_view(data.date); }); }, // callback for date range selection select: function(start, end, allDay, e, view) { var range_select = (!allDay || start.getDate() != end.getDate()) if (dialog_check(e) && range_select) event_edit_dialog('new', { start:start, end:end, allDay:allDay, calendar:me.selected_calendar }); if (range_select || ignore_click) view.calendar.unselect(); }, // callback for clicks in all-day box dayClick: function(date, allDay, e, view) { var now = new Date().getTime(); if (now - day_clicked_ts < 400 && day_clicked == date.getTime()) { // emulate double-click on day var enddate = new Date(); enddate.setTime(date.getTime() + DAY_MS - 60000); return event_edit_dialog('new', { start:date, end:enddate, allDay:allDay, calendar:me.selected_calendar }); } if (!ignore_click) { view.calendar.gotoDate(date); if (day_clicked && new Date(day_clicked).getMonth() != date.getMonth()) view.calendar.select(date, date, allDay); } day_clicked = date.getTime(); day_clicked_ts = now; }, // callback when a specific event is clicked eventClick: function(event) { if (!event.temp) event_show_dialog(event); }, // callback when an event was dragged and finally dropped eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc) { if (event.end == null || event.end.getTime() < event.start.getTime()) { event.end = new Date(event.start.getTime() + (allDay ? DAY_MS : HOUR_MS)); } // moved to all-day section: set times to 12:00 - 13:00 if (allDay && !event.allDay) { event.start.setHours(12); event.start.setMinutes(0); event.start.setSeconds(0); event.end.setHours(13); event.end.setMinutes(0); event.end.setSeconds(0); } // moved from all-day section: set times to working hours else if (event.allDay && !allDay) { var newstart = event.start.getTime(); revertFunc(); // revert to get original duration var numdays = Math.max(1, Math.round((event.end.getTime() - event.start.getTime()) / DAY_MS)) - 1; event.start = new Date(newstart); event.end = new Date(newstart + numdays * DAY_MS); event.end.setHours(settings['work_end'] || 18); event.end.setMinutes(0); if (event.end.getTime() < event.start.getTime()) event.end = new Date(newstart + HOUR_MS); } // send move request to server var data = { id: event.id, calendar: event.calendar, start: date2servertime(event.start), end: date2servertime(event.end), allday: allDay?1:0 }; update_event_confirm('move', event, data); }, // callback for event resizing eventResize: function(event, delta) { // sanitize event dates if (event.allDay) event.start.setHours(12); if (!event.end || event.end.getTime() < event.start.getTime()) event.end = new Date(event.start.getTime() + HOUR_MS); // send resize request to server var data = { id: event.id, calendar: event.calendar, start: date2servertime(event.start), end: date2servertime(event.end) }; update_event_confirm('resize', event, data); }, viewDisplay: function(view) { $('#agendaoptions')[view.name == 'table' ? 'show' : 'hide'](); if (minical) { window.setTimeout(function(){ minical.datepicker('setDate', fc.fullCalendar('getDate')); }, exec_deferred); if (view.name != current_view) me.view_resize(); current_view = view.name; } }, viewRender: function(view) { if (fc && view.name == 'month') fc.fullCalendar('option', 'maxHeight', Math.floor((view.element.parent().height()-18) / 6) - 35); } }); // format time string var formattime = function(hour, minutes, start) { var time, diff, unit, duration = '', d = new Date(); d.setHours(hour); d.setMinutes(minutes); time = $.fullCalendar.formatDate(d, settings['time_format']); if (start) { diff = Math.floor((d.getTime() - start.getTime()) / 60000); if (diff > 0) { unit = 'm'; if (diff >= 60) { unit = 'h'; diff = Math.round(diff / 3) / 20; } duration = ' (' + diff + unit + ')'; } } return [time, duration]; }; var autocomplete_times = function(p, callback) { /* Time completions */ var result = []; var now = new Date(); var st, start = (String(this.element.attr('id')).indexOf('endtime') > 0 && (st = $('#edit-starttime').val()) && $('#edit-startdate').val() == $('#edit-enddate').val()) ? parse_datetime(st, '') : null; var full = p.term - 1 > 0 || p.term.length > 1; var hours = start ? start.getHours() : (full ? parse_datetime(p.term, '') : now).getHours(); var step = 15; var minutes = hours * 60 + (full ? 0 : now.getMinutes()); var min = Math.ceil(minutes / step) * step % 60; var hour = Math.floor(Math.ceil(minutes / step) * step / 60); // list hours from 0:00 till now for (var h = start ? start.getHours() : 0; h < hours; h++) result.push(formattime(h, 0, start)); // list 15min steps for the next two hours for (; h < hour + 2 && h < 24; h++) { while (min < 60) { result.push(formattime(h, min, start)); min += step; } min = 0; } // list the remaining hours till 23:00 while (h < 24) result.push(formattime((h++), 0, start)); return callback(result); }; var autocomplete_open = function(event, ui) { // scroll to current time var $this = $(this); var widget = $this.autocomplete('widget'); var menu = $this.data('autocomplete').menu; var amregex = /^(.+)(a[.m]*)/i; var pmregex = /^(.+)(a[.m]*)/i; var val = $(this).val().replace(amregex, '0:$1').replace(pmregex, '1:$1'); var li, html; widget.css('width', '10em'); widget.children().each(function(){ li = $(this); html = li.children().first().html().replace(/\s+\(.+\)$/, '').replace(amregex, '0:$1').replace(pmregex, '1:$1'); if (html.indexOf(val) == 0) menu._scrollIntoView(li); }); }; // if start date is changed, shift end date according to initial duration var shift_enddate = function(dateText) { var newstart = parse_datetime('0', dateText); var newend = new Date(newstart.getTime() + $('#edit-startdate').data('duration') * 1000); $('#edit-enddate').val($.fullCalendar.formatDate(newend, me.settings['date_format'])); event_times_changed(); }; // Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. // Uses the default $.datepicker.iso8601Week() function but takes firstDay setting into account. // This is a temporary fix until http://bugs.jqueryui.com/ticket/8420 is resolved. var iso8601Week = datepicker_settings.calculateWeek = function(date) { var mondayOffset = Math.abs(1 - datepicker_settings.firstDay); return $.datepicker.iso8601Week(new Date(date.getTime() + mondayOffset * 86400000)); }; var minical; var init_calendar_ui = function() { // initialize small calendar widget using jQuery UI datepicker minical = $('#datepicker').datepicker($.extend(datepicker_settings, { inline: true, showWeek: true, changeMonth: false, // maybe enable? changeYear: false, // maybe enable? onSelect: function(dateText, inst) { ignore_click = true; var d = minical.datepicker('getDate'); //parse_datetime('0:0', dateText); fc.fullCalendar('gotoDate', d).fullCalendar('select', d, d, true); }, onChangeMonthYear: function(year, month, inst) { minical.data('year', year).data('month', month); }, beforeShowDay: function(date) { var view = fc.fullCalendar('getView'); var active = view.visStart && date.getTime() >= view.visStart.getTime() && date.getTime() < view.visEnd.getTime(); return [ true, (active ? 'ui-datepicker-activerange ui-datepicker-active-' + view.name : ''), '']; } })) // set event handler for clicks on calendar week cell of the datepicker widget .click(function(e) { var cell = $(e.target); if (e.target.tagName == 'TD' && cell.hasClass('ui-datepicker-week-col')) { var base_date = minical.datepicker('getDate'); if (minical.data('month')) base_date.setMonth(minical.data('month')-1); if (minical.data('year')) base_date.setYear(minical.data('year')); base_date.setHours(12); base_date.setDate(base_date.getDate() - ((base_date.getDay() + 6) % 7) + datepicker_settings.firstDay); var day_off = base_date.getDay() - datepicker_settings.firstDay; var base_kw = iso8601Week(base_date); var target_kw = parseInt(cell.html()); var diff = (target_kw - base_kw) * 7 * DAY_MS; // select monday of the chosen calendar week var date = new Date(base_date.getTime() - day_off * DAY_MS + diff); fc.fullCalendar('gotoDate', date).fullCalendar('setDate', date).fullCalendar('changeView', 'agendaWeek'); minical.datepicker('setDate', date); } }); // init event dialog $('#eventtabs').tabs({ show: function(event, ui) { if (ui.panel.id == 'event-tab-3') { $('#edit-attendee-name').select(); // update free-busy status if needed if (freebusy_ui.needsupdate && me.selected_event) update_freebusy_status(me.selected_event); // add current user as organizer if non added yet if (!event_attendees.length) { add_attendee($.extend({ role:'ORGANIZER' }, settings.identity)); $('#edit-attendees-form .attendees-invitebox').show(); } } } }); $('#edit-enddate').datepicker(datepicker_settings); $('#edit-startdate').datepicker(datepicker_settings).datepicker('option', 'onSelect', shift_enddate).change(function(){ shift_enddate(this.value); }); $('#edit-enddate').datepicker('option', 'onSelect', event_times_changed).change(event_times_changed); $('#edit-allday').click(function(){ $('#edit-starttime, #edit-endtime')[(this.checked?'hide':'show')](); event_times_changed(); }); // configure drop-down menu on time input fields based on jquery UI autocomplete $('#edit-starttime, #edit-endtime, #eventedit input.edit-alarm-time') .attr('autocomplete', "off") .autocomplete({ delay: 100, minLength: 1, source: autocomplete_times, open: autocomplete_open, change: event_times_changed, select: function(event, ui) { $(this).val(ui.item[0]); return false; } }) .click(function() { // show drop-down upon clicks $(this).autocomplete('search', $(this).val() ? $(this).val().replace(/\D.*/, "") : " "); }).each(function(){ $(this).data('autocomplete')._renderItem = function(ul, item) { return $('<li>') .data('item.autocomplete', item) .append('<a>' + item[0] + item[1] + '</a>') .appendTo(ul); }; }); // register events on alarm fields init_alarms_edit('#eventedit'); // toggle recurrence frequency forms $('#edit-recurrence-frequency').change(function(e){ var freq = $(this).val().toLowerCase(); $('.recurrence-form').hide(); if (freq) $('#recurrence-form-'+freq+', #recurrence-form-until').show(); }); $('#edit-recurrence-enddate').datepicker(datepicker_settings).click(function(){ $("#edit-recurrence-repeat-until").prop('checked', true) }); $('#edit-recurrence-repeat-times').change(function(e){ $('#edit-recurrence-repeat-count').prop('checked', true); }); // init attendees autocompletion var ac_props; // parallel autocompletion if (rcmail.env.autocomplete_threads > 0) { ac_props = { threads: rcmail.env.autocomplete_threads, sources: rcmail.env.autocomplete_sources }; } rcmail.init_address_input_events($('#edit-attendee-name'), ac_props); rcmail.addEventListener('autocomplete_insert', function(e){ $('#edit-attendee-add').click(); }); $('#edit-attendee-add').click(function(){ var input = $('#edit-attendee-name'); rcmail.ksearch_blur(); if (add_attendees(input.val())) { input.val(''); } }); // keep these two checkboxes in sync $('#edit-attendees-donotify, #edit-attendees-invite').click(function(){ $('#edit-attendees-donotify, #edit-attendees-invite').prop('checked', this.checked); }); $('#edit-attendee-schedule').click(function(){ event_freebusy_dialog(); }); $('#shedule-freebusy-prev').html(bw.ie6 ? '&lt;&lt;' : '&#9668;').button().click(function(){ render_freebusy_grid(-1); }); $('#shedule-freebusy-next').html(bw.ie6 ? '&gt;&gt;' : '&#9658;').button().click(function(){ render_freebusy_grid(1); }).parent().buttonset(); $('#shedule-find-prev').button().click(function(){ freebusy_find_slot(-1); }); $('#shedule-find-next').button().click(function(){ freebusy_find_slot(1); }); $('#schedule-freebusy-workinghours').click(function(){ freebusy_ui.workinhoursonly = this.checked; $('#workinghourscss').remove(); if (this.checked) $('<style type="text/css" id="workinghourscss"> td.offhours { opacity:0.3; filter:alpha(opacity=30) } </style>').appendTo('head'); }); $('#event-rsvp input.button').click(function(){ event_rsvp($(this).attr('rel')) }); $('#agenda-listrange').change(function(e){ settings['agenda_range'] = parseInt($(this).val()); fc.fullCalendar('option', 'listRange', settings['agenda_range']).fullCalendar('render'); // TODO: save new settings in prefs }).val(settings['agenda_range']); $('#agenda-listsections').change(function(e){ settings['agenda_sections'] = $(this).val(); fc.fullCalendar('option', 'listSections', settings['agenda_sections']).fullCalendar('render'); // TODO: save new settings in prefs }).val(fc.fullCalendar('option', 'listSections')); // hide event dialog when clicking somewhere into document $(document).bind('mousedown', dialog_check); rcmail.set_busy(false, 'loading', ui_loading); } // initialize more UI elements (deferred) window.setTimeout(init_calendar_ui, exec_deferred); // add proprietary css styles if not IE if (!bw.ie) $('div.fc-content').addClass('rcube-fc-content'); // IE supresses 2nd click event when double-clicking if (bw.ie && bw.vendver < 9) { $('div.fc-content').bind('dblclick', function(e){ if (!$(this).hasClass('fc-widget-header') && fc.fullCalendar('getView').name != 'table') { var date = fc.fullCalendar('getDate'); var enddate = new Date(); enddate.setTime(date.getTime() + DAY_MS - 60000); event_edit_dialog('new', { start:date, end:enddate, allDay:true, calendar:me.selected_calendar }); } }); } } // end rcube_calendar class /* calendar plugin initialization */ window.rcmail && rcmail.addEventListener('init', function(evt) { // configure toolbar buttons rcmail.register_command('addevent', function(){ cal.add_event(); }, true); rcmail.register_command('print', function(){ cal.print_calendars(); }, true); // configure list operations rcmail.register_command('calendar-create', function(){ cal.calendar_edit_dialog(null); }, true); rcmail.register_command('calendar-edit', function(){ cal.calendar_edit_dialog(cal.calendars[cal.selected_calendar]); }, false); rcmail.register_command('calendar-remove', function(){ cal.calendar_remove(cal.calendars[cal.selected_calendar]); }, false); rcmail.register_command('events-import', function(){ cal.import_events(cal.calendars[cal.selected_calendar]); }, true); rcmail.register_command('calendar-showurl', function(){ cal.showurl(cal.calendars[cal.selected_calendar]); }, false); // search and export events rcmail.register_command('export', function(){ rcmail.goto_url('export_events', { source:cal.selected_calendar }); }, true); rcmail.register_command('search', function(){ cal.quicksearch(); }, true); rcmail.register_command('reset-search', function(){ cal.reset_quicksearch(); }, true); // register callback commands rcmail.addEventListener('plugin.destroy_source', function(p){ cal.calendar_destroy_source(p.id); }); rcmail.addEventListener('plugin.unlock_saving', function(p){ cal.unlock_saving(); }); rcmail.addEventListener('plugin.refresh_calendar', function(p){ cal.refresh(p); }); rcmail.addEventListener('plugin.import_success', function(p){ cal.import_success(p); }); rcmail.addEventListener('plugin.import_error', function(p){ cal.import_error(p); }); rcmail.addEventListener('requestrefresh', function(q){ return cal.before_refresh(q); }); // let's go var cal = new rcube_calendar_ui($.extend(rcmail.env.calendar_settings, rcmail.env.libcal_settings)); $(window).resize(function(e) { // check target due to bugs in jquery // http://bugs.jqueryui.com/ticket/7514 // http://bugs.jquery.com/ticket/9841 if (e.target == window) { cal.view_resize(); } }).resize(); // show calendars list when ready $('#calendars').css('visibility', 'inherit'); // show toolbar $('#toolbar').show(); });
Java
<?php /** * @package sauto * @subpackage Views * @author Dacian Strain {@link http://shop.elbase.eu} * @author Created on 17-Nov-2013 * @license GNU/GPL */ //-- No direct access defined('_JEXEC') || die('=;)'); $time = time(); $app =& JFactory::getApplication(); $db = JFactory::getDbo(); $request_v =& JRequest::getVar( 'request', '', 'post', 'string' ); $app->setUserState('request', $request_v); $titlu_anunt =& JRequest::getVar( 'titlu_anunt', '', 'post', 'string' ); $app->setUserState('titlu_anunt', $titlu_anunt); $marca =& JRequest::getVar( 'marca', '', 'post', 'string' ); $model_auto =& JRequest::getVar( 'model_auto', '', 'post', 'string' ); $app->setUserState('model_auto', $model_auto); $an_fabricatie =& JRequest::getVar( 'an_fabricatie', '', 'post', 'string' ); $app->setUserState('an_fabricatie', $an_fabricatie); $cilindree =& JRequest::getVar( 'cilindree', '', 'post', 'string' ); $app->setUserState('cilindree', $cilindree); $carburant =& JRequest::getVar( 'carburant', '', 'post', 'string' ); $app->setUserState('carburant', $carburant); $caroserie =& JRequest::getVar( 'caroserie', '', 'post', 'string' ); $app->setUserState('caroserie', $caroserie); $serie_caroserie =& JRequest::getVar( 'serie_caroserie', '', 'post', 'string' ); $app->setUserState('serie_caroserie', $serie_caroserie); $anunt =& JRequest::getVar( 'anunt8', '', 'post', 'string', JREQUEST_ALLOWHTML ); $app->setUserState('anunt', $anunt); $judet =& JRequest::getVar( 'judet', '', 'post', 'string' ); $city =& JRequest::getVar( 'localitate', '', 'post', 'string' ); $query = "SELECT `id` FROM #__sa_judete WHERE `judet` = '".$judet."'"; $db->setQuery($query); $id_judet = $db->loadResult(); $transmisie =& JRequest::getVar( 'transmisie', '', 'post', 'string' ); $app->setUserState('transmisie', $transmisie); $user =& JFactory::getUser(); $uid = $user->id; $register_anunt = 0; //echo '>>>>> marca '.$marca.' >>>> '.$new_marca.' >>>>> '.$model_auto.' >>>>> '.$new_model.'<br />'; $link_redirect = JRoute::_('index.php?option=com_sauto&view=add_request'); if ($marca == '') { //nu am selectat marca $app->redirect($link_redirect, JText::_('SAUTO_NO_MARCA_ADDED')); } else { //marca existenta, obtinem id-ul $query = "SELECT `id` FROM #__sa_marca_auto WHERE `marca_auto` = '".$marca."'"; $db->setQuery($query); $mid = $db->loadResult(); $marca_auto_id = $mid; $app->setUserState('marca', $mid); //echo '<br />>>>>>'.$marca_auto_id.'<br />'; $model_auto_id = $model_auto; $app->setUserState('model_auto', $model_auto); } //echo '<br />>>>>>'.$model_auto_id.'<br />'; //verificam campurile introduse if ($titlu_anunt == '') { //nu avem introdus titlul //SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id); $app->redirect($link_redirect, JText::_('SAUTO_NO_TITLE_ADDED')); } else { if ($an_fabricatie == '') { //nu avem introdus anul fabricatiei //SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id); $app->redirect($link_redirect, JText::_('SAUTO_NO_PRODUCTION_YEAR_ADDED')); } else { if ($cilindree == '') { //cilindreea nu este introdusa //SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id); $app->redirect($link_redirect, JText::_('SAUTO_NO_CAPACITY_ADDED')); } else { if ($carburant == '') { //carburantul nu este ales //SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id); $app->redirect($link_redirect, JText::_('SAUTO_NO_CARBURANT_ADDED')); } else { if ($caroserie == '') { //nu este aleasa caroseria //SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id); $app->redirect($link_redirect, JText::_('SAUTO_NO_CARSERIE_ADDED')); } else { if ($serie_caroserie == '') { //seria caroseriei nu este introdusa //SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id); $app->redirect($link_redirect, JText::_('SAUTO_NO_SERIE_CARSERIE_ADDED')); } else { if ($anunt == '') { //nu este adaugat anuntul //SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id); $app->redirect($link_redirect, JText::_('SAUTO_NO_ANUNT_ADDED')); } else { //e ok $register_anunt = 1; } } } } } } } //sfarsit verificare if ($register_anunt == 1) { //obtin data curenta $curentDate = date('Y-m-d H:i:s', $time); $expiryDate = date('Y-m-d H:i:s', ($time+2592000)); //echo '<br />caroserie>>>>'.$caroserie.'<br />'; //adaug in baza de date $query = "INSERT INTO #__sa_anunturi (`titlu_anunt`, `anunt`, `tip_anunt`, `marca_auto`, `model_auto`, `an_fabricatie`, `cilindree`, `carburant`, `caroserie`, `serie_caroserie`, `proprietar`, `data_adaugarii`, `status_anunt`, `raportat`, `data_expirarii`, `judet`, `city`, `transmisie`) VALUES ('".$titlu_anunt."', '".$anunt."', '8', '".$marca_auto_id."', '".$model_auto_id."', '".$an_fabricatie."', '".$cilindree."', '".$carburant."','".$caroserie."', '".$serie_caroserie."', '".$uid."', '".$curentDate."', '1', '0', '".$expiryDate."', '".$id_judet."', '".$city."', '".$transmisie."')"; $db->setQuery($query); $db->query(); $anunt_id = $db->insertid(); ###########################prelucrare imagine############# SautoViewAdding::uploadImg($time, $uid, $anunt_id); SautoViewAdding::sendMail($anunt_id); ###########################end prelucrare imagine################## $app->setUserState('titlu_anunt', ''); //parcam masina daca este cazul.... $parcheaza =& JRequest::getVar( 'parcheaza', '', 'post', 'string' ); if ($parcheaza == 1) { $query = "INSERT INTO #__sa_garaj (`owner`, `marca`, `model`, `an_fabricatie`, `cilindree`, `carburant`, `caroserie`, `serie_caroserie`, `transmisie`) VALUES ('".$uid."', '".$marca_auto_id."', '".$model_auto_id."', '".$an_fabricatie."', '".$cilindree."', '".$carburant."', '".$caroserie."', '".$serie_caroserie."', '".$transmisie."')"; $db->setQuery($query); $db->query(); } //end parcare masina $app->setUserState('an_fabricatie', ''); $app->setUserState('cilindree', ''); $app->setUserState('carburant', ''); $app->setUserState('marca', ''); $app->setUserState('caroserie', ''); $app->setUserState('serie_caroserie', ''); $app->setUserState('model_auto', ''); $app->setUserState('request', '');$app->setUserState('transmisie', ''); $app->setUserState('titlu_anunt', ''); $app->setUserState('transmisie', ''); $app->setUserState('anunt', ''); $link_redirect_fr = JRoute::_('index.php?option=com_sauto'); $app->redirect($link_redirect_fr, JText::_('SAUTO_SUCCESS_ADDED')); } ?>
Java
#!/usr/bin/env python3 # This file is part of ipxact2systemverilog # Copyright (C) 2013 Andreas Lindh # # 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. # # andreas.lindh (a) hiced.com import math import os import sys import xml.etree.ElementTree as ETree import tabulate from mdutils.mdutils import MdUtils DEFAULT_INI = {'global': {'unusedholes': 'yes', 'onebitenum': 'no'}} def sortRegisterAndFillHoles(regName, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList, unusedHoles=True): # sort the lists, highest offset first fieldNameList = fieldNameList bitOffsetList = [int(x) for x in bitOffsetList] bitWidthList = [int(x) for x in bitWidthList] fieldDescList = fieldDescList enumTypeList = enumTypeList matrix = list(zip(bitOffsetList, fieldNameList, bitWidthList, fieldDescList, enumTypeList)) matrix.sort(key=lambda x: x[0]) # , reverse=True) bitOffsetList, fieldNameList, bitWidthList, fieldDescList, enumTypeList = list(zip(*matrix)) # zip return tuples not lists fieldNameList = list(fieldNameList) bitOffsetList = list([int(x) for x in bitOffsetList]) bitWidthList = list([int(x) for x in bitWidthList]) fieldDescList = list(fieldDescList) enumTypeList = list(enumTypeList) if unusedHoles: unUsedCnt = 0 nextFieldStartingPos = 0 # fill up the holes index = 0 register_width = bitOffsetList[-1] + bitWidthList[-1] while register_width > nextFieldStartingPos: if nextFieldStartingPos != bitOffsetList[index]: newBitWidth = bitOffsetList[index] - nextFieldStartingPos bitOffsetList.insert(index, nextFieldStartingPos) fieldNameList.insert(index, 'unused' + str(unUsedCnt)) bitWidthList.insert(index, newBitWidth) fieldDescList.insert(index, 'unused') enumTypeList.insert(index, '') unUsedCnt += 1 nextFieldStartingPos = int(bitOffsetList[index]) + int(bitWidthList[index]) index += 1 return regName, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList class documentClass(): def __init__(self, name): self.name = name self.memoryMapList = [] def addMemoryMap(self, memoryMap): self.memoryMapList.append(memoryMap) class memoryMapClass(): def __init__(self, name): self.name = name self.addressBlockList = [] def addAddressBlock(self, addressBlock): self.addressBlockList.append(addressBlock) class addressBlockClass(): def __init__(self, name, addrWidth, dataWidth): self.name = name self.addrWidth = addrWidth self.dataWidth = dataWidth self.registerList = [] self.suffix = "" def addRegister(self, reg): assert isinstance(reg, registerClass) self.registerList.append(reg) def setRegisterList(self, registerList): self.registerList = registerList def returnAsString(self): raise NotImplementedError("method returnAsString() is virutal and must be overridden.") class registerClass(): def __init__(self, name, address, resetValue, size, access, desc, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList): assert isinstance(enumTypeList, list), 'enumTypeList is not a list' self.name = name self.address = address self.resetValue = resetValue self.size = size self.access = access self.desc = desc self.fieldNameList = fieldNameList self.bitOffsetList = bitOffsetList self.bitWidthList = bitWidthList self.fieldDescList = fieldDescList self.enumTypeList = enumTypeList class enumTypeClassRegistry(): """ should perhaps be a singleton instead """ def __init__(self): self.listOfEnums = [] def enumAllReadyExist(self, enum): for e in self.listOfEnums: if e.compare(enum): enum.allReadyExist = True enum.enumName = e.name break self.listOfEnums.append(enum) return enum class enumTypeClass(): def __init__(self, name, bitWidth, keyList, valueList, descrList): self.name = name self.bitWidth = bitWidth matrix = list(zip(valueList, keyList, descrList)) matrix.sort(key=lambda x: x[0]) valueList, keyList, descrList = list(zip(*matrix)) self.keyList = list(keyList) self.valueList = list(valueList) self.allReadyExist = False self.enumName = None self.descrList = descrList def compare(self, other): result = True result = self.bitWidth == other.bitWidth and result result = self.compareLists(self.keyList, other.keyList) and result return result def compareLists(self, list1, list2): for val in list1: if val in list2: return True return False class rstAddressBlock(addressBlockClass): """Generates a ReStructuredText file from a IP-XACT register description""" def __init__(self, name, addrWidth, dataWidth): self.name = name self.addrWidth = addrWidth self.dataWidth = dataWidth self.registerList = [] self.suffix = ".rst" def returnEnumValueString(self, enumTypeObj): if isinstance(enumTypeObj, enumTypeClass): l = [] for i in range(len(enumTypeObj.keyList)): l.append(enumTypeObj.keyList[i] + '=' + enumTypeObj.valueList[i]) s = ", ".join(l) else: s = '' return s def returnAsString(self): r = "" regNameList = [reg.name for reg in self.registerList] regAddressList = [reg.address for reg in self.registerList] regDescrList = [reg.desc for reg in self.registerList] r += self.returnRstTitle() r += self.returnRstSubTitle() summary_table = [] for i in range(len(regNameList)): summary_table.append(["%#04x" % regAddressList[i], str(regNameList[i]) + "_", str(regDescrList[i])]) r += tabulate.tabulate(summary_table, headers=['Address', 'Register Name', 'Description'], tablefmt="grid") r += "\n" r += "\n" for reg in self.registerList: r += self.returnRstRegDesc(reg.name, reg.address, reg.size, reg.resetValue, reg.desc, reg.access) reg_table = [] for fieldIndex in reversed(list(range(len(reg.fieldNameList)))): bits = "[" + str(reg.bitOffsetList[fieldIndex] + reg.bitWidthList[fieldIndex] - 1) + \ ":" + str(reg.bitOffsetList[fieldIndex]) + "]" _line = [bits, reg.fieldNameList[fieldIndex]] if reg.resetValue: temp = (int(reg.resetValue, 0) >> reg.bitOffsetList[fieldIndex]) mask = (2 ** reg.bitWidthList[fieldIndex]) - 1 temp &= mask temp = "{value:#0{width}x}".format(value=temp, width=math.ceil(reg.bitWidthList[fieldIndex] / 4) + 2) _line.append(temp) _line.append(reg.fieldDescList[fieldIndex]) reg_table.append(_line) _headers = ['Bits', 'Field name'] if reg.resetValue: _headers.append('Reset') _headers.append('Description') r += tabulate.tabulate(reg_table, headers=_headers, tablefmt="grid") r += "\n" r += "\n" # enumerations for enum in reg.enumTypeList: if enum: # header r += enum.name + "\n" r += ',' * len(enum.name) + "\n" r += "\n" # table enum_table = [] for i in range(len(enum.keyList)): _value = "{value:#0{width}x}".format(value=int(enum.valueList[i], 0), width=math.ceil(int(enum.bitWidth, 0) / 4) + 2) _line = [enum.keyList[i], _value, enum.descrList[i]] enum_table.append(_line) r += tabulate.tabulate(enum_table, headers=['Name', 'Value', 'Description'], tablefmt="grid") r += "\n\n" return r def returnRstTitle(self): r = '' r += "====================\n" r += "Register description\n" r += "====================\n\n" return r def returnRstSubTitle(self): r = '' r += "Registers\n" r += "---------\n\n" return r def returnRstRegDesc(self, name, address, size, resetValue, desc, access): r = "" r += name + "\n" r += len(name) * '-' + "\n" r += "\n" r += ":Name: " + str(name) + "\n" r += ":Address: " + hex(address) + "\n" if resetValue: # display the resetvalue in hex notation in the full length of the register r += ":Reset Value: {value:#0{size:d}x}\n".format(value=int(resetValue, 0), size=size // 4 + 2) r += ":Access: " + access + "\n" r += ":Description: " + desc + "\n" r += "\n" return r class mdAddressBlock(addressBlockClass): """Generates a Markdown file from a IP-XACT register description""" def __init__(self, name, addrWidth, dataWidth): self.name = name self.addrWidth = addrWidth self.dataWidth = dataWidth self.registerList = [] self.suffix = ".md" self.mdFile = MdUtils(file_name="none", title="") def returnEnumValueString(self, enumTypeObj): if isinstance(enumTypeObj, enumTypeClass): l = [] for i in range(len(enumTypeObj.keyList)): l.append(enumTypeObj.keyList[i] + '=' + enumTypeObj.valueList[i]) s = ", ".join(l) else: s = '' return s def returnAsString(self): regNameList = [reg.name for reg in self.registerList] regAddressList = [reg.address for reg in self.registerList] regDescrList = [reg.desc for reg in self.registerList] self.mdFile.new_header(level=1, title="Register description") self.mdFile.new_header(level=2, title="Registers") # summary header = ['Address', 'Register Name', 'Description'] rows = [] for i in range(len(regNameList)): rows.extend(["{:#04x}".format(regAddressList[i]), f"[{regNameList[i]}](#{regNameList[i]})", str(regDescrList[i])]) self.mdFile.new_table(columns=len(header), rows=len(regNameList) + 1, # header + data text=header + rows, text_align='left') # all registers for reg in self.registerList: headers = ['Bits', 'Field name'] if reg.resetValue: headers.append('Reset') headers.append('Description') self.returnMdRegDesc(reg.name, reg.address, reg.size, reg.resetValue, reg.desc, reg.access) reg_table = [] for fieldIndex in reversed(list(range(len(reg.fieldNameList)))): bits = "[" + str(reg.bitOffsetList[fieldIndex] + reg.bitWidthList[fieldIndex] - 1) + \ ":" + str(reg.bitOffsetList[fieldIndex]) + "]" reg_table.append(bits) reg_table.append(reg.fieldNameList[fieldIndex]) if reg.resetValue: temp = (int(reg.resetValue, 0) >> reg.bitOffsetList[fieldIndex]) mask = (2 ** reg.bitWidthList[fieldIndex]) - 1 temp &= mask temp = "{value:#0{width}x}".format(value=temp, width=math.ceil(reg.bitWidthList[fieldIndex] / 4) + 2) reg_table.append(temp) reg_table.append(reg.fieldDescList[fieldIndex]) self.mdFile.new_table(columns=len(headers), rows=len(reg.fieldNameList) + 1, text=headers + reg_table, text_align='left') # enumerations for enum in reg.enumTypeList: if enum: self.mdFile.new_header(level=4, title=enum.name) enum_table = [] for i in range(len(enum.keyList)): _value = "{value:#0{width}x}".format(value=int(enum.valueList[i], 0), width=math.ceil(int(enum.bitWidth, 0) / 4) + 2) enum_table.append(enum.keyList[i]) enum_table.append(_value) enum_table.append(enum.descrList[i]) headers = ['Name', 'Value', 'Description'] self.mdFile.new_table(columns=len(headers), rows=len(enum.keyList) + 1, text=headers + enum_table, text_align='left') return self.mdFile.file_data_text def returnMdRegDesc(self, name, address, size, resetValue, desc, access): self.mdFile.new_header(level=3, title=name) self.mdFile.new_line("**Name** " + str(name)) self.mdFile.new_line("**Address** " + hex(address)) if resetValue: # display the resetvalue in hex notation in the full length of the register self.mdFile.new_line( "**Reset Value** {value:#0{size:d}x}".format(value=int(resetValue, 0), size=size // 4 + 2)) self.mdFile.new_line("**Access** " + access) self.mdFile.new_line("**Description** " + desc) class vhdlAddressBlock(addressBlockClass): """Generates a vhdl file from a IP-XACT register description""" def __init__(self, name, addrWidth, dataWidth): self.name = name self.addrWidth = addrWidth self.dataWidth = dataWidth self.registerList = [] self.suffix = "_vhd_pkg.vhd" def returnAsString(self): r = '' r += self.returnPkgHeaderString() r += "\n\n" r += self.returnPkgBodyString() return r def returnPkgHeaderString(self): r = '' r += "--\n" r += "-- Automatically generated\n" r += "-- with the command '%s'\n" % (' '.join(sys.argv)) r += "--\n" r += "-- Do not manually edit!\n" r += "--\n" r += "-- VHDL 93\n" r += "--\n" r += "\n" r += "library ieee;\n" r += "use ieee.std_logic_1164.all;\n" r += "use ieee.numeric_std.all;\n" r += "\n" r += "package " + self.name + "_vhd_pkg is\n" r += "\n" r += " constant addr_width : natural := " + str(self.addrWidth) + ";\n" r += " constant data_width : natural := " + str(self.dataWidth) + ";\n" r += "\n\n" r += self.returnRegFieldEnumTypeStrings(True) for reg in self.registerList: r += " constant {name}_addr : natural := {address} ; -- {address:#0{width}x}\n".format(name=reg.name, address=reg.address, width=math.ceil( self.addrWidth / 4) + 2) # +2 for the '0x' r += "\n" for reg in self.registerList: if reg.resetValue: r += " constant {name}_reset_value : std_ulogic_vector(data_width-1 downto 0) := std_ulogic_vector(to_unsigned({value:d}, data_width)); -- {value:#0{width}x}\n".format( name=reg.name, value=int(reg.resetValue, 0), width=math.ceil((self.dataWidth / 4)) + 2) r += "\n\n" for reg in self.registerList: r += self.returnRegRecordTypeString(reg) r += self.returnRegistersInRecordTypeString() r += self.returnRegistersOutRecordTypeString() r += self.returnRegistersReadFunction() r += self.returnRegistersWriteFunction() r += self.returnRegistersResetFunction() r += "end;\n" return r def returnRegFieldEnumTypeStrings(self, prototype): r = '' for reg in self.registerList: for enum in reg.enumTypeList: if isinstance(enum, enumTypeClass) and not enum.allReadyExist: r += " -- {}\n".format(enum.name) # group the enums in the package if prototype: t = " type " + enum.name + "_enum is (" indent = t.find('(') + 1 r += t for ki in range(len(enum.keyList)): if ki != 0: # no indentation for the first element r += " " * indent r += enum.keyList[ki] if ki != len(enum.keyList) - 1: # no ',' for the last element r += "," else: # last element r += ");" if enum.descrList[ki]: r += " -- " + enum.descrList[ki] if ki != len(enum.keyList) - 1: # no new line for the last element r += "\n" r += "\n" r += " function " + enum.name + \ "_enum_to_sulv(v: " + enum.name + "_enum ) return std_ulogic_vector" if prototype: r += ";\n" else: r += " is\n" r += " variable r : std_ulogic_vector(" + str(enum.bitWidth) + "-1 downto 0);\n" r += " begin\n" r += " case v is\n" for i in range(len(enum.keyList)): r += ' when {key} => r:="{value_int:0{bitwidth}b}"; -- {value}\n'.format( key=enum.keyList[i], value=enum.valueList[i], value_int=int(enum.valueList[i]), bitwidth=int(enum.bitWidth)) r += " end case;\n" r += " return r;\n" r += " end function;\n\n" r += " function sulv_to_" + enum.name + \ "_enum(v: std_ulogic_vector(" + str(enum.bitWidth) + "-1 downto 0)) return " + \ enum.name + "_enum" if prototype: r += ";\n" else: r += " is\n" r += " variable r : " + enum.name + "_enum;\n" r += " begin\n" r += " case v is\n" for i in range(len(enum.keyList)): r += ' when "{value_int:0{bitwidth}b}" => r:={key};\n'.format(key=enum.keyList[i], value_int=int( enum.valueList[ i]), bitwidth=int( enum.bitWidth)) r += ' when others => r:=' + enum.keyList[0] + '; -- error\n' r += " end case;\n" r += " return r;\n" r += " end function;\n\n" if prototype: r += "\n" if prototype: r += "\n" return r def returnRegRecordTypeString(self, reg): r = '' r += " type " + reg.name + "_record_type is record\n" for i in reversed(list(range(len(reg.fieldNameList)))): bits = "[" + str(reg.bitOffsetList[i] + reg.bitWidthList[i] - 1) + ":" + str(reg.bitOffsetList[i]) + "]" bit = "[" + str(reg.bitOffsetList[i]) + "]" if isinstance(reg.enumTypeList[i], enumTypeClass): if not reg.enumTypeList[i].allReadyExist: r += " " + reg.fieldNameList[i] + " : " + \ reg.enumTypeList[i].name + "_enum; -- " + bits + "\n" else: r += " " + reg.fieldNameList[i] + " : " + \ reg.enumTypeList[i].enumName + "_enum; -- " + bits + "\n" else: if reg.bitWidthList[i] == 1: # single bit r += " " + reg.fieldNameList[i] + " : std_ulogic; -- " + bit + "\n" else: # vector r += " " + reg.fieldNameList[i] + " : std_ulogic_vector(" + str(reg.bitWidthList[i] - 1) + \ " downto 0); -- " + bits + "\n" r += " end record;\n\n" return r def returnRegistersInRecordTypeString(self): r = "" r += " type " + self.name + "_in_record_type is record\n" for reg in self.registerList: if reg.access == "read-only": r += " {name} : {name}_record_type; -- addr {addr:#0{width}x}\n".format(name=reg.name, addr=reg.address, width=math.ceil( self.addrWidth / 4) + 2) # +2 for the '0x' r += " end record;\n\n" return r def returnRegistersOutRecordTypeString(self): r = "" r += " type " + self.name + "_out_record_type is record\n" for reg in self.registerList: if reg.access != "read-only": r += " {name} : {name}_record_type; -- addr {addr:#0{width}x}\n".format(name=reg.name, addr=reg.address, width=math.ceil( self.addrWidth / 4) + 2) # +2 for the '0x' r += " end record;\n\n" return r def returnRegistersReadFunction(self): r = " function read_" + self.name + "(registers_i : " + self.name + "_in_record_type;\n" indent = r.find('(') + 1 r += " " * indent + "registers_o : " + self.name + "_out_record_type;\n" r += " " * indent + "address : std_ulogic_vector(addr_width-1 downto 0)\n" r += " " * indent + ") return std_ulogic_vector;\n\n" return r def returnRegistersWriteFunction(self): r = " function write_" + self.name + "(value : std_ulogic_vector(data_width-1 downto 0);\n" indent = r.find('(') + 1 r += " " * indent + "address : std_ulogic_vector(addr_width-1 downto 0);\n" r += " " * indent + "registers_o : " + self.name + "_out_record_type\n" r += " " * indent + ") return " + self.name + "_out_record_type;\n\n" return r def returnRegistersResetFunction(self): r = " function reset_" + self.name + " return " + self.name + "_out_record_type;\n" r += " function reset_" + self.name + "(address: std_ulogic_vector(addr_width-1 downto 0);\n" indent = r.splitlines()[-1].find('(') + 1 r += " " * indent + "registers_o : " + self.name + "_out_record_type\n" r += " " * indent + ") return " + self.name + "_out_record_type;\n\n" return r def returnRecToSulvFunctionString(self, reg): r = "" r += " function " + reg.name + \ "_record_type_to_sulv(v : " + reg.name + "_record_type) return std_ulogic_vector is\n" r += " variable r : std_ulogic_vector(data_width-1 downto 0);\n" r += " begin\n" r += " r := (others => '0');\n" for i in reversed(list(range(len(reg.fieldNameList)))): bits = str(reg.bitOffsetList[i] + reg.bitWidthList[i] - 1) + " downto " + str(reg.bitOffsetList[i]) bit = str(reg.bitOffsetList[i]) if isinstance(reg.enumTypeList[i], enumTypeClass): if not reg.enumTypeList[i].allReadyExist: r += " r(" + bits + ") := " + \ reg.enumTypeList[i].name + "_enum_to_sulv(v." + reg.fieldNameList[i] + ");\n" else: r += " r(" + bits + ") := " + \ reg.enumTypeList[i].enumName + "_enum_to_sulv(v." + reg.fieldNameList[i] + ");\n" else: if reg.bitWidthList[i] == 1: # single bit r += " r(" + bit + ") := v." + reg.fieldNameList[i] + ";\n" else: # vector r += " r(" + bits + ") := v." + reg.fieldNameList[i] + ";\n" r += " return r;\n" r += " end function;\n\n" return r def returnSulvToRecFunctionString(self, reg): r = "" r += " function sulv_to_" + reg.name + \ "_record_type(v : std_ulogic_vector) return " + reg.name + "_record_type is\n" r += " variable r : " + reg.name + "_record_type;\n" r += " begin\n" for i in reversed(list(range(len(reg.fieldNameList)))): bits = str(reg.bitOffsetList[i] + reg.bitWidthList[i] - 1) + " downto " + str(reg.bitOffsetList[i]) bit = str(reg.bitOffsetList[i]) if isinstance(reg.enumTypeList[i], enumTypeClass): if not reg.enumTypeList[i].allReadyExist: r += " r." + reg.fieldNameList[i] + " := sulv_to_" + \ reg.enumTypeList[i].name + "_enum(v(" + bits + "));\n" else: r += " r." + reg.fieldNameList[i] + " := sulv_to_" + \ reg.enumTypeList[i].enumName + "_enum(v(" + bits + "));\n" else: if reg.bitWidthList[i] == 1: # single bit r += " r." + reg.fieldNameList[i] + " := v(" + bit + ");\n" else: r += " r." + reg.fieldNameList[i] + " := v(" + bits + ");\n" r += " return r;\n" r += " end function;\n\n" return r def returnReadFunctionString(self): r = "" t = " function read_" + self.name + "(registers_i : " + self.name + "_in_record_type;\n" indent = t.find('(') + 1 r += t r += " " * indent + "registers_o : " + self.name + "_out_record_type;\n" r += " " * indent + "address : std_ulogic_vector(addr_width-1 downto 0)\n" r += " " * indent + ") return std_ulogic_vector is\n" r += " variable r : std_ulogic_vector(data_width-1 downto 0);\n" r += " begin\n" r += " case to_integer(unsigned(address)) is\n" for reg in self.registerList: if reg.access == "read-only": r += " when " + reg.name + "_addr => r:= " + reg.name + \ "_record_type_to_sulv(registers_i." + reg.name + ");\n" else: r += " when " + reg.name + "_addr => r:= " + reg.name + \ "_record_type_to_sulv(registers_o." + reg.name + ");\n" r += " when others => r := (others => '0');\n" r += " end case;\n" r += " return r;\n" r += " end function;\n\n" return r def returnWriteFunctionString(self): r = "" t = " function write_" + self.name + "(value : std_ulogic_vector(data_width-1 downto 0);\n" r += t indent = t.find('(') + 1 r += " " * indent + "address : std_ulogic_vector(addr_width-1 downto 0);\n" r += " " * indent + "registers_o : " + self.name + "_out_record_type\n" r += " " * indent + ") return " + self.name + "_out_record_type is\n" r += " variable r : " + self.name + "_out_record_type;\n" r += " begin\n" r += " r := registers_o;\n" r += " case to_integer(unsigned(address)) is\n" for reg in self.registerList: if reg.access != "read-only": r += " when " + reg.name + "_addr => r." + reg.name + \ " := sulv_to_" + reg.name + "_record_type(value);\n" r += " when others => null;\n" r += " end case;\n" r += " return r;\n" r += " end function;\n\n" return r def returnResetFunctionString(self): r = "" r += " function reset_" + self.name + " return " + self.name + "_out_record_type is\n" r += " variable r : " + self.name + "_out_record_type;\n" r += " begin\n" for reg in self.registerList: if reg.resetValue: if reg.access != "read-only": r += " r." + reg.name + " := sulv_to_" + \ reg.name + "_record_type(" + reg.name + "_reset_value);\n" r += " return r;\n" r += " end function;\n" r += "\n" r += " function reset_" + self.name + "(address: std_ulogic_vector(addr_width-1 downto 0);\n" indent = r.splitlines()[-1].find('(') + 1 r += " " * indent + "registers_o : " + self.name + "_out_record_type\n" r += " " * indent + ") return " + self.name + "_out_record_type is\n" r += " variable r : " + self.name + "_out_record_type;\n" r += " begin\n" r += " r := registers_o;\n" r += " case to_integer(unsigned(address)) is\n" for reg in self.registerList: if reg.resetValue: if reg.access != "read-only": r += " when " + reg.name + "_addr => r." + reg.name + \ " := sulv_to_" + reg.name + "_record_type(" + reg.name + "_reset_value);\n" r += " when others => null;\n" r += " end case;\n" r += " return r;\n" r += " end function;\n\n" return r def returnPkgBodyString(self): r = "" r += "package body " + self.name + "_vhd_pkg is\n\n" r += self.returnRegFieldEnumTypeStrings(False) for reg in self.registerList: r += self.returnRecToSulvFunctionString(reg) r += self.returnSulvToRecFunctionString(reg) r += self.returnReadFunctionString() r += self.returnWriteFunctionString() r += self.returnResetFunctionString() r += "end package body;\n" return r class systemVerilogAddressBlock(addressBlockClass): def __init__(self, name, addrWidth, dataWidth): self.name = name self.addrWidth = addrWidth self.dataWidth = dataWidth self.registerList = [] self.suffix = "_sv_pkg.sv" def returnIncludeString(self): r = "\n" r += "`define " + self.name + "_addr_width " + str(self.addrWidth) + "\n" r += "`define " + self.name + "_data_width " + str(self.dataWidth) + "\n" return r def returnSizeString(self): r = "\n" r += "const int addr_width = " + str(self.addrWidth) + ";\n" r += "const int data_width = " + str(self.dataWidth) + ";\n" return r def returnAddressesString(self): r = "\n" for reg in self.registerList: r += "const int " + reg.name + "_addr = " + str(reg.address) + ";\n" r += "\n" return r def returnAddressListString(self): r = "\n" r = "//synopsys translate_off\n" r += "const int " + self.name + "_regAddresses [" + str(len(self.registerList)) + "] = '{" l = [] for reg in self.registerList: l.append("\n " + reg.name + "_addr") r += ",".join(l) r += "};\n" r += "\n" r += "const string " + self.name + "_regNames [" + str(len(self.registerList)) + "] = '{" l = [] for reg in self.registerList: l.append('\n "' + reg.name + '"') r += ",".join(l) r += "};\n" r += "const reg " + self.name + "_regUnResetedAddresses [" + str(len(self.registerList)) + "] = '{" l = [] for reg in self.registerList: if reg.resetValue: l.append("\n 1'b0") else: l.append("\n 1'b1") r += ",".join(l) r += "};\n" r += "\n" r += "//synopsys translate_on\n\n" return r def enumeratedType(self, prepend, fieldName, valueNames, values): r = "\n" members = [] # dont want to create to simple names in the global names space. # should preppend with name from ipxact file for index in range(len(valueNames)): name = valueNames[index] value = values[index] members.append(name + "=" + value) r += "typedef enum { " + ",".join(members) + "} enum_" + fieldName + ";\n" return r def returnResetValuesString(self): r = "" for reg in self.registerList: if reg.resetValue: r += "const " + reg.name + "_struct_type " + reg.name + \ "_reset_value = " + str(int(reg.resetValue, 0)) + ";\n" r += "\n" return r def returnStructString(self): r = "\n" for reg in self.registerList: r += "\ntypedef struct packed {\n" for i in reversed(list(range(len(reg.fieldNameList)))): bits = "bits [" + str(reg.bitOffsetList[i] + reg.bitWidthList[i] - 1) + \ ":" + str(reg.bitOffsetList[i]) + "]" r += " bit [" + str(reg.bitWidthList[i] - 1) + ":0] " + \ str(reg.fieldNameList[i]) + ";//" + bits + "\n" r += "} " + reg.name + "_struct_type;\n\n" return r def returnRegistersStructString(self): r = "typedef struct packed {\n" for reg in self.registerList: r += " " + reg.name + "_struct_type " + reg.name + ";\n" r += "} " + self.name + "_struct_type;\n\n" return r def returnReadFunctionString(self): r = "function bit [31:0] read_" + self.name + "(" + self.name + "_struct_type registers,int address);\n" r += " bit [31:0] r;\n" r += " case(address)\n" for reg in self.registerList: r += " " + reg.name + "_addr: r[$bits(registers." + reg.name + ")-1:0] = registers." + reg.name + ";\n" r += " default: r =0;\n" r += " endcase\n" r += " return r;\n" r += "endfunction\n\n" return r def returnWriteFunctionString(self): t = "function " + self.name + "_struct_type write_" + self.name + "(bit [31:0] data, int address,\n" r = t indent = r.find('(') + 1 r += " " * indent + self.name + "_struct_type registers);\n" r += " " + self.name + "_struct_type r;\n" r += " r = registers;\n" r += " case(address)\n" for reg in self.registerList: r += " " + reg.name + "_addr: r." + reg.name + " = data[$bits(registers." + reg.name + ")-1:0];\n" r += " endcase // case address\n" r += " return r;\n" r += "endfunction\n\n" return r def returnResetFunctionString(self): r = "function " + self.name + "_struct_type reset_" + self.name + "();\n" r += " " + self.name + "_struct_type r;\n" for reg in self.registerList: if reg.resetValue: r += " r." + reg.name + "=" + reg.name + "_reset_value;\n" r += " return r;\n" r += "endfunction\n" r += "\n" return r def returnAsString(self): r = '' r += "// Automatically generated\n" r += "// with the command '%s'\n" % (' '.join(sys.argv)) r += "//\n" r += "// Do not manually edit!\n" r += "//\n" r += "package " + self.name + "_sv_pkg;\n\n" r += self.returnSizeString() r += self.returnAddressesString() r += self.returnAddressListString() r += self.returnStructString() r += self.returnResetValuesString() r += self.returnRegistersStructString() r += self.returnReadFunctionString() r += self.returnWriteFunctionString() r += self.returnResetFunctionString() r += "endpackage //" + self.name + "_sv_pkg\n" return r class ipxactParser(): def __init__(self, srcFile, config): self.srcFile = srcFile self.config = config self.enumTypeClassRegistry = enumTypeClassRegistry() def returnDocument(self): spirit_ns = 'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.5' tree = ETree.parse(self.srcFile) ETree.register_namespace('spirit', spirit_ns) namespace = tree.getroot().tag[1:].split("}")[0] spiritString = '{' + spirit_ns + '}' docName = tree.find(spiritString + "name").text d = documentClass(docName) memoryMaps = tree.find(spiritString + "memoryMaps") memoryMapList = memoryMaps.findall(spiritString + "memoryMap") if memoryMaps is not None else [] for memoryMap in memoryMapList: memoryMapName = memoryMap.find(spiritString + "name").text addressBlockList = memoryMap.findall(spiritString + "addressBlock") m = memoryMapClass(memoryMapName) for addressBlock in addressBlockList: addressBlockName = addressBlock.find(spiritString + "name").text registerList = addressBlock.findall(spiritString + "register") baseAddress = int(addressBlock.find(spiritString + "baseAddress").text, 0) nbrOfAddresses = int(addressBlock.find(spiritString + "range").text, 0) # TODO, this is wrong addrWidth = int(math.ceil((math.log(baseAddress + nbrOfAddresses, 2)))) dataWidth = int(addressBlock.find(spiritString + "width").text, 0) a = addressBlockClass(addressBlockName, addrWidth, dataWidth) for registerElem in registerList: regName = registerElem.find(spiritString + "name").text reset = registerElem.find(spiritString + "reset") if reset is not None: resetValue = reset.find(spiritString + "value").text else: resetValue = None size = int(registerElem.find(spiritString + "size").text, 0) access = registerElem.find(spiritString + "access").text if registerElem.find(spiritString + "description") != None: desc = registerElem.find(spiritString + "description").text else: desc = "" regAddress = baseAddress + int(registerElem.find(spiritString + "addressOffset").text, 0) r = self.returnRegister(spiritString, registerElem, regAddress, resetValue, size, access, desc, dataWidth) a.addRegister(r) m.addAddressBlock(a) d.addMemoryMap(m) return d def returnRegister(self, spiritString, registerElem, regAddress, resetValue, size, access, regDesc, dataWidth): regName = registerElem.find(spiritString + "name").text fieldList = registerElem.findall(spiritString + "field") fieldNameList = [item.find(spiritString + "name").text for item in fieldList] bitOffsetList = [item.find(spiritString + "bitOffset").text for item in fieldList] bitWidthList = [item.find(spiritString + "bitWidth").text for item in fieldList] fieldDescList = [item.find(spiritString + "description").text for item in fieldList] enumTypeList = [] for index in range(len(fieldList)): fieldElem = fieldList[index] bitWidth = bitWidthList[index] fieldName = fieldNameList[index] enumeratedValuesElem = fieldElem.find(spiritString + "enumeratedValues") if enumeratedValuesElem is not None: enumeratedValueList = enumeratedValuesElem.findall(spiritString + "enumeratedValue") valuesNameList = [item.find(spiritString + "name").text for item in enumeratedValueList] descrList = [item.find(spiritString + "description").text if item.find( spiritString + "description") is not None else "" for item in enumeratedValueList] valuesList = [item.find(spiritString + "value").text for item in enumeratedValueList] if len(valuesNameList) > 0: if int(bitWidth) > 1: # if the field of a enum is longer than 1 bit, always use enums enum = enumTypeClass(fieldName, bitWidth, valuesNameList, valuesList, descrList) enum = self.enumTypeClassRegistry.enumAllReadyExist(enum) enumTypeList.append(enum) else: # bit field of 1 bit if self.config['global'].getboolean('onebitenum'): # do create one bit enums enum = enumTypeClass(fieldName, bitWidth, valuesNameList, valuesList, descrList) enum = self.enumTypeClassRegistry.enumAllReadyExist(enum) enumTypeList.append(enum) else: # dont create enums of booleans because this only decreases readability enumTypeList.append(None) else: enumTypeList.append(None) else: enumTypeList.append(None) if len(fieldNameList) == 0: fieldNameList.append(regName) bitOffsetList.append(0) bitWidthList.append(dataWidth) fieldDescList.append('') enumTypeList.append(None) (regName, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList) = sortRegisterAndFillHoles( regName, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList, self.config['global'].getboolean('unusedholes')) reg = registerClass(regName, regAddress, resetValue, size, access, regDesc, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList) return reg class ipxact2otherGenerator(): def __init__(self, destDir, namingScheme="addressBlockName"): self.destDir = destDir self.namingScheme = namingScheme def write(self, fileName, string): _dest = os.path.join(self.destDir, fileName) print("writing file " + _dest) if not os.path.exists(os.path.dirname(_dest)): os.makedirs(os.path.dirname(_dest)) with open(_dest, "w") as f: f.write(string) def generate(self, generatorClass, document): self.document = document docName = document.name for memoryMap in document.memoryMapList: mapName = memoryMap.name for addressBlock in memoryMap.addressBlockList: blockName = addressBlock.name block = generatorClass(addressBlock.name, addressBlock.addrWidth, addressBlock.dataWidth) block.setRegisterList(addressBlock.registerList) s = block.returnAsString() if self.namingScheme == "addressBlockName": fileName = blockName + block.suffix else: fileName = docName + '_' + mapName + '_' + blockName + block.suffix self.write(fileName, s) if generatorClass == systemVerilogAddressBlock: includeFileName = fileName + "h" includeString = block.returnIncludeString() self.write(includeFileName, includeString)
Java
<?php /* +---------------------------------------------------------------------------+ | OpenX v2.8 | | ========== | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by | | the Free Software Foundation; either version 2 of the License, or | | (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License | | along with this program; if not, write to the Free Software | | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | +---------------------------------------------------------------------------+ $Id: PasswordRecovery.php 82775 2013-08-06 23:40:26Z chris.nutting $ */ /** * Password recovery DAL for Openads * * @package OpenXDal */ require_once MAX_PATH.'/lib/OA/Dal.php'; require_once MAX_PATH.'/lib/max/Plugin.php'; class OA_Dal_PasswordRecovery extends OA_Dal { /** * Search users with a matching email address * * @param string e-mail * @return array matching users */ function searchMatchingUsers($email) { $doUsers = OA_Dal::factoryDO('users'); $doUsers->email_address = $email; $doUsers->find(); $users = array(); while ($doUsers->fetch()) { $users[] = $doUsers->toArray(); } return $users; } /** * Generate and save a recovery ID for a user * * @param int user ID * @return array generated recovery ID */ function generateRecoveryId($userId) { $doPwdRecovery = OA_Dal::factoryDO('password_recovery'); // Make sure that recoveryId is unique in password_recovery table do { $recoveryId = strtoupper(md5(uniqid('', true))); $recoveryId = substr(chunk_split($recoveryId, 8, '-'), -23, 22); $doPwdRecovery->recovery_id = $recoveryId; } while ($doPwdRecovery->find()>0); $doPwdRecovery = OA_Dal::factoryDO('password_recovery'); $doPwdRecovery->whereAdd('user_id = '.DBC::makeLiteral($userId)); $doPwdRecovery->delete(true); $doPwdRecovery = OA_Dal::factoryDO('password_recovery'); $doPwdRecovery->user_type = 'user'; $doPwdRecovery->user_id = $userId; $doPwdRecovery->recovery_id = $recoveryId; $doPwdRecovery->updated = OA::getNowUTC(); $doPwdRecovery->insert(); return $recoveryId; } /** * Check if recovery ID is valid * * @param string recovery ID * @return bool true if recovery ID is valid */ function checkRecoveryId($recoveryId) { $doPwdRecovery = OA_Dal::factoryDO('password_recovery'); $doPwdRecovery->recovery_id = $recoveryId; return (bool)$doPwdRecovery->count(); } /** * Save the new password in the user properties * * @param string recovery ID * @param string new password * @return bool Ttrue the new password was correctly saved */ function saveNewPasswordAndLogin($recoveryId, $password) { $doPwdRecovery = OA_Dal::factoryDO('password_recovery'); $doPwdRecovery->recovery_id = $recoveryId; $doPwdRecoveryClone = clone($doPwdRecovery); $doPwdRecovery->find(); if ($doPwdRecovery->fetch()) { $userId = $doPwdRecovery->user_id; $doPlugin = &OA_Auth::staticGetAuthPlugin(); $doPlugin->setNewPassword($userId, $password); $doPwdRecoveryClone->delete(); phpAds_SessionStart(); $doUser = OA_Dal::staticGetDO('users', $userId); phpAds_SessionDataRegister(OA_Auth::getSessionData($doUser)); phpAds_SessionDataStore(); return true; } return false; } } ?>
Java
/* * Copyright (C) 2008 Peter Grasch <peter.grasch@bedahr.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * or (at your option) any later version, as published by the Free * Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SIMON_SIMONDNETWORKCONFIGURATION_H_932B7362E7CC428398A5F279795080B6 #define SIMON_SIMONDNETWORKCONFIGURATION_H_932B7362E7CC428398A5F279795080B6 #include <KCModule> #include <QVariantList> #include "ui_simondnetworkconfiguration.h" class SimondNetworkConfiguration : public KCModule { Q_OBJECT private: Ui::NetworkConfiguration ui; private slots: void slotChanged(); public: explicit SimondNetworkConfiguration(QWidget* parent, const QVariantList& args=QVariantList()); void save(); void load(); ~SimondNetworkConfiguration(); }; #endif
Java
/* * $Id$ * * Copyright 2006 University of Dundee. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package ome.server.itests.hibernate; import java.util.Arrays; import java.util.Set; import ome.model.IAnnotated; import ome.model.ILink; import ome.model.IObject; import ome.model.annotations.Annotation; import ome.model.annotations.BasicAnnotation; import ome.model.annotations.LongAnnotation; import ome.model.containers.Dataset; import ome.model.containers.DatasetImageLink; import ome.model.containers.Project; import ome.model.containers.ProjectDatasetLink; import ome.model.core.Image; import ome.model.core.Pixels; import ome.model.display.RenderingDef; import ome.model.meta.Experimenter; import ome.server.itests.AbstractManagedContextTest; import ome.testing.ObjectFactory; import ome.tools.hibernate.ExtendedMetadata; import org.hibernate.SessionFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ExtendedMetadataTest extends AbstractManagedContextTest { ExtendedMetadata.Impl metadata; @BeforeClass public void init() throws Exception { setUp(); metadata = new ExtendedMetadata.Impl(); metadata.setSessionFactory((SessionFactory)applicationContext.getBean("sessionFactory")); tearDown(); } @Test public void testAnnotatedAreFound() throws Exception { Set<Class<IAnnotated>> anns = metadata.getAnnotatableTypes(); assertTrue(anns.contains(Image.class)); assertTrue(anns.contains(Project.class)); // And several others } @Test public void testAnnotationsAreFound() throws Exception { Set<Class<Annotation>> anns = metadata.getAnnotationTypes(); assertTrue(anns.toString(), anns.contains(Annotation.class)); assertTrue(anns.toString(), anns.contains(BasicAnnotation.class)); assertTrue(anns.toString(), anns.contains(LongAnnotation.class)); // And several others } /** * Where a superclass has a relationship to a class (Annotation to some link type), * it is also necessary to be able to find the same relationship from a subclass * (e.g. FileAnnotation). */ @Test public void testLinkFromSubclassToSuperClassRel() { assertNotNull( metadata.getRelationship("ImageAnnotationLink", "FileAnnotation")); } /** * For simplicity, the relationship map currently holds only the short * class names. Here we are adding a test which checks for the full ones * under "broken" to remember to re-evaluate. */ @Test(groups = {"broken","fixme"}) public void testAnnotatedAreFoundByFQN() throws Exception { Set<Class<IAnnotated>> anns = metadata.getAnnotatableTypes(); assertTrue(anns.contains(Image.class)); assertTrue(anns.contains(Project.class)); // And several others } // ~ Locking // ========================================================================= @Test public void testProjectLocksDataset() throws Exception { Project p = new Project(); Dataset d = new Dataset(); p.linkDataset(d); ILink l = (ILink) p.collectDatasetLinks(null).iterator().next(); assertDoesntContain(metadata.getLockCandidates(p), d); assertContains(metadata.getLockCandidates(l), d); } @Test // Because Pixels does not have a reference to RenderingDef public void testRenderingDefLocksPixels() throws Exception { Pixels p = ObjectFactory.createPixelGraph(null); RenderingDef r = ObjectFactory.createRenderingDef(); r.setPixels(p); assertContains(metadata.getLockCandidates(r), p); } @Test(groups = "ticket:357") // quirky because of defaultTag // see https://trac.openmicroscopy.org/ome/ticket/357 public void testPixelsLocksImage() throws Exception { Pixels p = ObjectFactory.createPixelGraph(null); Image i = new Image(); i.setName("locking"); i.addPixels(p); assertContains(metadata.getLockCandidates(p), i); } @Test // omit locks for system types (TODO they shouldn't have permissions anyway) public void testExperimenterDoesntGetLocked() throws Exception { Experimenter e = new Experimenter(); Project p = new Project(); p.getDetails().setOwner(e); assertDoesntContain(metadata.getLockCandidates(p), e); } @Test public void testNoNulls() throws Exception { Project p = new Project(); ProjectDatasetLink pdl = new ProjectDatasetLink(); pdl.link(p, null); assertDoesntContain(metadata.getLockCandidates(pdl), null); } // ~ Unlocking // ========================================================================= @Test public void testProjectCanBeUnlockedFromDataset() throws Exception { assertContains(metadata.getLockChecks(Project.class), ProjectDatasetLink.class.getName(), "parent"); } @Test // Because Pixels does not have a reference to RenderingDef public void testPixelsCanBeUnlockedFromRenderingDef() throws Exception { assertContains(metadata.getLockChecks(Pixels.class), RenderingDef.class .getName(), "pixels"); } @Test(groups = "ticket:357") // quirky because of defaultTag // see https://trac.openmicroscopy.org/ome/ticket/357 public void testImageCanBeUnlockedFromPixels() throws Exception { assertContains(metadata.getLockChecks(Image.class), Pixels.class .getName(), "image"); } // ~ Updating // ========================================================================= @Test(groups = { "ticket:346", "broken" }) public void testCreateEventImmutable() throws Exception { assertContains(metadata.getImmutableFields(Image.class), "details.creationEvent"); } // ~ Counting // ========================================================================= @Test(groups = { "ticket:657" }) public void testCountQueriesAreCorrect() throws Exception { assertEquals(metadata.getCountQuery(DatasetImageLink.CHILD), metadata .getCountQuery(DatasetImageLink.CHILD), "select target.child.id, count(target) " + "from ome.model.containers.DatasetImageLink target " + "group by target.child.id"); assertEquals(metadata.getCountQuery(Pixels.IMAGE), metadata .getCountQuery(Pixels.IMAGE), "select target.image.id, count(target) " + "from ome.model.core.Pixels target " + "group by target.image.id"); } @Test(groups = { "ticket:657" }) public void testTargetTypes() throws Exception { assertEquals(metadata.getTargetType(Pixels.IMAGE), Image.class); assertEquals(metadata.getTargetType(DatasetImageLink.CHILD), Image.class); } // ~ Relationships // ========================================================================= @Test(groups = "ticket:2665") public void testRelationships() { String rel; rel = metadata.getRelationship(Pixels.class.getSimpleName(), Image.class.getSimpleName()); assertEquals("image", rel); rel = metadata.getRelationship(Image.class.getSimpleName(), Pixels.class.getSimpleName()); assertEquals("pixels", rel); } // ~ Helpers // ========================================================================= private void assertContains(Object[] array, Object i) { if (!contained(array, i)) { fail(i + " not contained in " + Arrays.toString(array)); } } private void assertDoesntContain(IObject[] array, IObject i) { if (contained(array, i)) { fail(i + " contained in " + Arrays.toString(array)); } } private void assertContains(String[][] array, String t1, String t2) { boolean contained = false; for (int i = 0; i < array.length; i++) { String[] test = array[i]; if (test[0].equals(t1) && test[1].equals(t2)) { contained |= true; } } assertTrue(contained); } private boolean contained(Object[] array, Object i) { boolean contained = false; for (Object object : array) { if (i == null) { if (object == null) { contained = true; } } else { if (i.equals(object)) { contained = true; } } } return contained; } }
Java
class CreateTeachers < ActiveRecord::Migration def change create_table :teachers do |t| t.string :name, null: false t.integer :grade t.integer :college_id t.integer :user_id t.string :address t.string :phone t.string :email t.timestamps null: false end end end
Java
<html> <head> <title>RunUO Documentation - Class Overview - OnItemConsumed</title> </head> <body bgcolor="white" style="font-family: Courier New" text="#000000" link="#000000" vlink="#000000" alink="#808080"> <h4><a href="../namespaces/Server.Items.html">Back to Server.Items</a></h4> <h2>OnItemConsumed : MulticastDelegate, <!-- DBG-2.1 --><font color="blue">ICloneable</font>, <!-- DBG-2.1 --><font color="blue">ISerializable</font></h2> (<font color="blue">ctor</font>) OnItemConsumed( <font color="blue">object</font> object, IntPtr method )<br> <font color="blue">virtual</font> IAsyncResult BeginInvoke( <!-- DBG-0 --><a href="Item.html">Item</a> item, <font color="blue">int</font> amount, AsyncCallback callback, <font color="blue">object</font> object )<br> <font color="blue">virtual</font> <font color="blue">void</font> EndInvoke( IAsyncResult result )<br> <font color="blue">virtual</font> <font color="blue">void</font> Invoke( <!-- DBG-0 --><a href="Item.html">Item</a> item, <font color="blue">int</font> amount )<br> </body> </html>
Java
describe('PastDateValidatorWidgetFactory', function() { var Mock = {}; var factory; var whoAmI; beforeEach(function() { angular.mock.module('studio'); mockElement(); inject(function(_$injector_) { mockWidgetScope(_$injector_); factory = _$injector_.get('PastDateValidatorWidgetFactory'); }); widget = factory.create(Mock.scope, Mock.element); }); describe('Start a PastDate Factory Object', function() { it('should return a PastDate Validator Object', function() { pending(); }); it('should start the data field as date', function() { expect(widget.data).toBeDefined(); expect(widget.data).toEqual(false); }); }); describe('updates on data', function() { xit('should model data value be equal to self value', function() { // expect(Mock.question.fillingRules.options['pastDate'].data.reference).toEqual(widget.data); }); it('should call updateFillingRules from parente widget', function() { spyOn(Mock.parentWidget, 'updateFillingRules'); widget.updateData(); expect(Mock.parentWidget.updateFillingRules).toHaveBeenCalled(); }); }); function mockElement() { Mock.element = {}; } function mockWidgetScope($injector) { Mock.scope = { class: '', $parent: { widget: mockParentWidget($injector) } }; return Mock.scope; } function mockParentWidget($injector) { mockQuestion($injector); Mock.parentWidget = { getItem: function() { return Mock.question; }, updateFillingRules: function() {} }; return Mock.parentWidget; } function mockQuestion($injector) { Mock.question = $injector.get('SurveyItemFactory').create('IntegerQuestion', 'Q1'); Mock.question.fillingRules.options.pastDate = $injector.get('RulesFactory').create('pastDate'); return Mock.question; } function mockAdd($injector) { Mock.add = $injector.get('FillingRulesEditorWidgetFactory').create(); } });
Java
/* * linux/drivers/video/omapfb/boot_progressbar.c * * Copyright (c) 2010 Samsung Electronics Co., Ltd. * http://www.samsung.com * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/platform_device.h> #include <plat/vrfb.h> #include "omapfb.h" #define TRUE 1 #define FALSE 0 static int progress_flag = FALSE; static int progress_pos; static struct timer_list progress_timer; #define PROGRESS_BAR_LEFT_POS 54 #define PROGRESS_BAR_RIGHT_POS 425 #define PROGRESS_BAR_START_Y 576 #define PROGRESS_BAR_WIDTH 4 #define PROGRESS_BAR_HEIGHT 8 static unsigned char anycall_progress_bar_left[] = { 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00 }; static unsigned char anycall_progress_bar_right[] = { 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00 }; static unsigned char anycall_progress_bar_center[] = { 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0xf3, 0xc5, 0x00, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00 }; static unsigned char anycall_progress_bar[] = { 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00, 0x33, 0x33, 0x33, 0x00 }; static void progress_timer_handler(unsigned long data); static int show_progress = 1; module_param_named(progress, show_progress, bool, 0); static void omapfb_update_framebuffer( \ struct fb_info *fb, int x, int y, void *buffer, \ int src_width, int src_height) { struct omapfb_info *ofbi = FB2OFB(fb); struct omapfb2_device *fbdev = ofbi->fbdev; struct fb_fix_screeninfo *fix = &fb->fix; struct fb_var_screeninfo *var = &fb->var; int row; int bytes_per_pixel = (var->bits_per_pixel / 8); unsigned char *pSrc = buffer; unsigned char *pDst = fb->screen_base; if (x+src_width > var->xres || y+src_height > var->yres) { dev_err(fbdev->dev, "invalid destination coordinate or" \ " source size (%d, %d) (%d %d)\n", \ x, y, src_width, src_height); return; } pDst += y * fix->line_length + x * bytes_per_pixel; for (row = 0; row < src_height ; row++) { memcpy(pDst, pSrc, src_width * bytes_per_pixel); pSrc += src_width * bytes_per_pixel; pDst += fix->line_length; } } void omapfb_start_progress(struct fb_info *fb) { int x_pos; if (!show_progress) return; init_timer(&progress_timer); progress_timer.expires = (get_jiffies_64() + (HZ/20)); progress_timer.data = (long)fb; progress_timer.function = progress_timer_handler; progress_pos = PROGRESS_BAR_LEFT_POS; /* draw progress background. */ for (x_pos = PROGRESS_BAR_LEFT_POS; x_pos <= PROGRESS_BAR_RIGHT_POS; \ x_pos += PROGRESS_BAR_WIDTH){ omapfb_update_framebuffer(fb, x_pos, PROGRESS_BAR_START_Y, (void *)anycall_progress_bar, PROGRESS_BAR_WIDTH, PROGRESS_BAR_HEIGHT); } omapfb_update_framebuffer(fb, PROGRESS_BAR_LEFT_POS, PROGRESS_BAR_START_Y, (void *)anycall_progress_bar_left, PROGRESS_BAR_WIDTH, PROGRESS_BAR_HEIGHT); progress_pos += PROGRESS_BAR_WIDTH; omapfb_update_framebuffer(fb, progress_pos, PROGRESS_BAR_START_Y, (void *)anycall_progress_bar_right, PROGRESS_BAR_WIDTH, PROGRESS_BAR_HEIGHT); add_timer(&progress_timer); progress_flag = TRUE; } static void omapfb_stop_progress(void) { if (progress_flag == FALSE) return; del_timer(&progress_timer); progress_flag = 0; } static void progress_timer_handler(unsigned long data) { int i; for (i = 0; i < PROGRESS_BAR_WIDTH; i++) { omapfb_update_framebuffer((struct fb_info *)data, progress_pos++, PROGRESS_BAR_START_Y, (void *)anycall_progress_bar_center, 1, PROGRESS_BAR_HEIGHT); } omapfb_update_framebuffer((struct fb_info *)data, progress_pos, PROGRESS_BAR_START_Y, (void *)anycall_progress_bar_right, PROGRESS_BAR_WIDTH, PROGRESS_BAR_HEIGHT); if (progress_pos + PROGRESS_BAR_WIDTH >= PROGRESS_BAR_RIGHT_POS ) { omapfb_stop_progress(); } else { progress_timer.expires = (get_jiffies_64() + (HZ/20)); progress_timer.function = progress_timer_handler; add_timer(&progress_timer); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bc; import be.ReporteFumigacion; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author argos */ @Stateless public class ReporteFumigacionFacade extends AbstractFacade<ReporteFumigacion> implements ReporteFumigacionFacadeLocal { @PersistenceContext(unitName = "sistema-ejbPU") private EntityManager em; protected EntityManager getEntityManager() { return em; } public ReporteFumigacionFacade() { super(ReporteFumigacion.class); } }
Java
/* Copyright (C) 2010 Paul Davis This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "pbd/memento_command.h" #include "evoral/Parameter.hpp" #include "ardour/session.h" namespace ARDOUR { class MidiSource; class AutomationList; /** A class for late-binding a MidiSource and a Parameter to an AutomationList */ class MidiAutomationListBinder : public MementoCommandBinder<ARDOUR::AutomationList> { public: MidiAutomationListBinder (boost::shared_ptr<ARDOUR::MidiSource>, Evoral::Parameter); MidiAutomationListBinder (XMLNode *, ARDOUR::Session::SourceMap const &); ARDOUR::AutomationList* get () const; void add_state (XMLNode *); private: boost::shared_ptr<ARDOUR::MidiSource> _source; Evoral::Parameter _parameter; }; }
Java
/* * empathy-streamed-media-factory.c - Source for EmpathyStreamedMediaFactory * Copyright (C) 2008-2011 Collabora Ltd. * @author Sjoerd Simons <sjoerd.simons@collabora.co.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <telepathy-glib/account-channel-request.h> #include <telepathy-glib/simple-handler.h> #include <telepathy-glib/interfaces.h> #include <telepathy-glib/util.h> #include <libempathy/empathy-request-util.h> #include <libempathy/empathy-utils.h> #include "empathy-streamed-media-factory.h" #include "empathy-streamed-media-handler.h" #define DEBUG_FLAG EMPATHY_DEBUG_VOIP #include <libempathy/empathy-debug.h> G_DEFINE_TYPE(EmpathyStreamedMediaFactory, empathy_streamed_media_factory, G_TYPE_OBJECT) static void handle_channels_cb (TpSimpleHandler *handler, TpAccount *account, TpConnection *connection, GList *channels, GList *requests_satisfied, gint64 user_action_time, TpHandleChannelsContext *context, gpointer user_data); /* signal enum */ enum { NEW_STREAMED_MEDIA_HANDLER, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = {0}; /* private structure */ typedef struct { TpBaseClient *handler; gboolean dispose_has_run; } EmpathyStreamedMediaFactoryPriv; #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyStreamedMediaFactory) static GObject *call_factory = NULL; static void empathy_streamed_media_factory_init (EmpathyStreamedMediaFactory *obj) { EmpathyStreamedMediaFactoryPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (obj, EMPATHY_TYPE_STREAMED_MEDIA_FACTORY, EmpathyStreamedMediaFactoryPriv); TpAccountManager *am; obj->priv = priv; am = tp_account_manager_dup (); priv->handler = tp_simple_handler_new_with_am (am, FALSE, FALSE, EMPATHY_AV_BUS_NAME_SUFFIX, FALSE, handle_channels_cb, obj, NULL); tp_base_client_take_handler_filter (priv->handler, tp_asv_new ( TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA, TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT, NULL)); tp_base_client_take_handler_filter (priv->handler, tp_asv_new ( TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA, TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT, TP_PROP_CHANNEL_TYPE_STREAMED_MEDIA_INITIAL_AUDIO, G_TYPE_BOOLEAN, TRUE, NULL)); tp_base_client_take_handler_filter (priv->handler, tp_asv_new ( TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA, TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT, TP_PROP_CHANNEL_TYPE_STREAMED_MEDIA_INITIAL_VIDEO, G_TYPE_BOOLEAN, TRUE, NULL)); tp_base_client_add_handler_capabilities_varargs (priv->handler, "org.freedesktop.Telepathy.Channel.Interface.MediaSignalling/ice-udp", "org.freedesktop.Telepathy.Channel.Interface.MediaSignalling/gtalk-p2p", "org.freedesktop.Telepathy.Channel.Interface.MediaSignalling/video/h264", NULL); g_object_unref (am); } static GObject * empathy_streamed_media_factory_constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) { g_return_val_if_fail (call_factory == NULL, NULL); call_factory = G_OBJECT_CLASS (empathy_streamed_media_factory_parent_class)->constructor (type, n_construct_params, construct_params); g_object_add_weak_pointer (call_factory, (gpointer)&call_factory); return call_factory; } static void empathy_streamed_media_factory_finalize (GObject *object) { /* free any data held directly by the object here */ if (G_OBJECT_CLASS (empathy_streamed_media_factory_parent_class)->finalize) G_OBJECT_CLASS (empathy_streamed_media_factory_parent_class)->finalize (object); } static void empathy_streamed_media_factory_dispose (GObject *object) { EmpathyStreamedMediaFactoryPriv *priv = GET_PRIV (object); if (priv->dispose_has_run) return; priv->dispose_has_run = TRUE; tp_clear_object (&priv->handler); if (G_OBJECT_CLASS (empathy_streamed_media_factory_parent_class)->dispose) G_OBJECT_CLASS (empathy_streamed_media_factory_parent_class)->dispose (object); } static void empathy_streamed_media_factory_class_init ( EmpathyStreamedMediaFactoryClass *empathy_streamed_media_factory_class) { GObjectClass *object_class = G_OBJECT_CLASS (empathy_streamed_media_factory_class); g_type_class_add_private (empathy_streamed_media_factory_class, sizeof (EmpathyStreamedMediaFactoryPriv)); object_class->constructor = empathy_streamed_media_factory_constructor; object_class->dispose = empathy_streamed_media_factory_dispose; object_class->finalize = empathy_streamed_media_factory_finalize; signals[NEW_STREAMED_MEDIA_HANDLER] = g_signal_new ("new-streamed-media-handler", G_TYPE_FROM_CLASS (empathy_streamed_media_factory_class), G_SIGNAL_RUN_LAST, 0, NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2, EMPATHY_TYPE_STREAMED_MEDIA_HANDLER, G_TYPE_BOOLEAN); } EmpathyStreamedMediaFactory * empathy_streamed_media_factory_initialise (void) { g_return_val_if_fail (call_factory == NULL, NULL); return EMPATHY_STREAMED_MEDIA_FACTORY (g_object_new (EMPATHY_TYPE_STREAMED_MEDIA_FACTORY, NULL)); } EmpathyStreamedMediaFactory * empathy_streamed_media_factory_get (void) { g_return_val_if_fail (call_factory != NULL, NULL); return EMPATHY_STREAMED_MEDIA_FACTORY (call_factory); } static void create_streamed_media_handler (EmpathyStreamedMediaFactory *factory, EmpathyTpStreamedMedia *call) { EmpathyStreamedMediaHandler *handler; g_return_if_fail (factory != NULL); handler = empathy_streamed_media_handler_new_for_channel (call); g_signal_emit (factory, signals[NEW_STREAMED_MEDIA_HANDLER], 0, handler, FALSE); g_object_unref (handler); } static void call_status_changed_cb (EmpathyTpStreamedMedia *call, GParamSpec *spec, EmpathyStreamedMediaFactory *self) { if (empathy_tp_streamed_media_get_status (call) <= EMPATHY_TP_STREAMED_MEDIA_STATUS_READYING) return; create_streamed_media_handler (self, call); g_signal_handlers_disconnect_by_func (call, call_status_changed_cb, self); g_object_unref (call); } static void handle_channels_cb (TpSimpleHandler *handler, TpAccount *account, TpConnection *connection, GList *channels, GList *requests_satisfied, gint64 user_action_time, TpHandleChannelsContext *context, gpointer user_data) { EmpathyStreamedMediaFactory *self = user_data; GList *l; for (l = channels; l != NULL; l = g_list_next (l)) { TpChannel *channel = l->data; EmpathyTpStreamedMedia *call; if (tp_proxy_get_invalidated (channel) != NULL) continue; if (tp_channel_get_channel_type_id (channel) != TP_IFACE_QUARK_CHANNEL_TYPE_STREAMED_MEDIA) continue; call = empathy_tp_streamed_media_new (account, channel); if (empathy_tp_streamed_media_get_status (call) <= EMPATHY_TP_STREAMED_MEDIA_STATUS_READYING) { /* We have to wait that the TpStreamedMedia is ready as the * call-handler rely on it. */ tp_g_signal_connect_object (call, "notify::status", G_CALLBACK (call_status_changed_cb), self, 0); continue; } create_streamed_media_handler (self, call); g_object_unref (call); } tp_handle_channels_context_accept (context); } gboolean empathy_streamed_media_factory_register (EmpathyStreamedMediaFactory *self, GError **error) { EmpathyStreamedMediaFactoryPriv *priv = GET_PRIV (self); return tp_base_client_register (priv->handler, error); }
Java
require File.dirname(__FILE__) + '/../spec_helper' describe PagesController do describe 'handling GET for a single post' do before(:each) do @page = mock_model(Page) Page.stub(:find_by_slug).and_return(@page) end def do_get get :show, :id => 'a-page' end it "should be successful" do do_get response.should be_success end it "should render show template" do do_get response.should render_template('show') end it 'should find the page requested' do Page.should_receive(:find_by_slug).with('a-page').and_return(@page) do_get end it 'should assign the page found for the view' do do_get assigns[:page].should equal(@page) end end describe 'handling GET with invalid page' do it 'raises a RecordNotFound error' do Page.stub(:find_by_slug).and_return(nil) lambda { get :show, :id => 'a-page' }.should raise_error(ActiveRecord::RecordNotFound) end end end
Java
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2013 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 XCSOAR_CYLINDER_ZONE_EDIT_WIDGET_HPP #define XCSOAR_CYLINDER_ZONE_EDIT_WIDGET_HPP #include "ObservationZoneEditWidget.hpp" #include <assert.h> class CylinderZone; class CylinderZoneEditWidget : public ObservationZoneEditWidget { const bool radius_editable; public: CylinderZoneEditWidget(CylinderZone &oz, bool _length_editable); protected: const CylinderZone &GetObject() const { return (const CylinderZone &)ObservationZoneEditWidget::GetObject(); } CylinderZone &GetObject() { return (CylinderZone &)ObservationZoneEditWidget::GetObject(); } public: /* virtual methods from class Widget */ virtual void Prepare(ContainerWindow &parent, const PixelRect &rc) override; virtual bool Save(bool &changed) override; }; #endif
Java
<?php defined('_JEXEC') or die('Restricted access'); // SEF problem $isThereQMR = false; $isThereQMR = preg_match("/\?/i", $this->tmpl['action']); if ($isThereQMR) { $amp = '&amp;'; } else { $amp = '?'; } if ((int)$this->tmpl['displayratingimg'] == 1) { // Leave message for already voted images $vote = JRequest::getVar('vote', 0, '', 'int'); if ($vote == 1) { $voteMsg = JText::_('PHOCA GALLERY IMAGE RATED'); } else { $voteMsg = JText::_('You have already rated this image'); } ?><table style="text-align:left" border="0"><tr><td><?php echo '<strong>' . JText::_('Rating'). '</strong>: ' . $this->tmpl['votesaverageimg'] .' / '.$this->tmpl['votescountimg'] . ' ' . JText::_($this->tmpl['votestextimg']). '&nbsp;&nbsp;'; if ($this->tmpl['alreadyratedimg']) { echo '<td style="text-align:left"><ul class="star-rating">' .'<li class="current-rating" style="width:'.$this->tmpl['voteswidthimg'].'px"></li>' .'<li><span class="star1"></span></li>'; for ($i = 2;$i < 6;$i++) { echo '<li><span class="stars'.$i.'"></span></li>'; } echo '</ul></td>' .'<td style="text-align:left" colspan="4">&nbsp;&nbsp;'.$voteMsg.'</td></tr>'; } else if ($this->tmpl['notregisteredimg']) { echo '<td style="text-align:left"><ul class="star-rating">' .'<li class="current-rating" style="width:'.$this->tmpl['voteswidthimg'].'px"></li>' .'<li><span class="star1"></span></li>'; for ($i = 2;$i < 6;$i++) { echo '<li><span class="stars'.$i.'"></span></li>'; } echo '</ul></td>' .'<td style="text-align:left" colspan="4">&nbsp;&nbsp;'.JText::_('Only registered and logged in user can rate this image').'</td>'; } else { echo '<td style="text-align:left"><ul class="star-rating">' .'<li class="current-rating" style="width:'.$this->tmpl['voteswidthimg'].'px"></li>' .'<li><a href="'.$this->tmpl['action'].$amp.'controller=detail&task=rate&rating=1" title="1 '. JText::_('star out of').' 5" class="star1">1</a></li>'; for ($i = 2;$i < 6;$i++) { echo '<li><a href="'.$this->tmpl['action'].$amp.'controller=detail&task=rate&rating='.$i.'" title="'.$i.' '. JText::_('star out of').' 5" class="stars'.$i.'">'.$i.'</a></li>'; } echo '</td>'; } ?></tr></table><?php } ?>
Java
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s
Java
<?php /* * Child theme creation results page */ ?> <div id="child_created" class="main-panel"> <h3><?php _e( 'Your child theme was successfully created!', 'divi-children' ); ?></h3> <div id="created_theme"> <div class="theme_screenshot"> <img src="<?php echo $divichild['new_theme_dir'] . '/screenshot.jpg'; ?>" alt="screenshot"> </div> <div class="theme_info"> <h3><?php echo $divichild['new_theme_name']; ?></h3> <h4><?php _e( 'By', 'divi-children' ); ?><?php echo ' ' . $divichild['new_theme_authorname']; ?></h4> <p><em><?php _e( 'Version', 'divi-children' ); ?></em><b><?php echo ': ' . $divichild['new_theme_version']; ?></b></p> <p><b><?php echo $divichild['new_theme_description']; ?></b></p> <p><em><?php _e( 'Parent Theme', 'divi-children' ); ?></em><b><?php echo ': ' . $divichild['new_theme_parent']; ?></b></p> <p><em><?php _e( 'Theme URI', 'divi-children' ); ?></em><b><?php echo ': ' . $divichild['new_theme_uri']; ?></b></p> <p><em><?php _e( 'Author URI', 'divi-children' ); ?></em><b><?php echo ': ' . $divichild['new_theme_authoruri']; ?></b></p> <a href="<?php echo admin_url( 'themes.php' ); ?>" class="button-primary"><?php _e( 'You can activate it now in the Themes Manager', 'divi-children' ); ?></a> </div> </div> </div> <div id="footer_display"> <h3><?php _e( 'Your footer credits will look like this:', 'divi-children' ); ?></h3> <div class="footer-display"> <?php $firstyear = get_option( 'footer_credits_firstyear' ); $owner = get_option( 'footer_credits_owner' ); $ownerlink = get_option( 'footer_credits_ownerlink' ); $developed_text = get_option( 'footer_credits_developed' ); $developer = get_option( 'footer_credits_developer' ); $developerlink = get_option( 'footer_credits_developerlink' ); $powered_text = get_option( 'footer_credits_powered' ); $powered_code = get_option( 'footer_credits_poweredcode' ); $powered_codelink = get_option( 'footer_credits_poweredcodelink' ); $footer_credits = 'Copyright &copy; '; $current_year = date( 'Y' ); if ( $firstyear AND ($firstyear != 0 )) { if( $firstyear != $current_year ) { $footer_credits .= $firstyear . ' - ' . $current_year; } } else { $footer_credits .= $current_year; } $footer_credits .= ' <a href="' . esc_url( $ownerlink ) . '">' . $owner . '</a>'; if ( $developed_text ) { $footer_credits .= ' | ' . $developed_text . ' ' . '<a href="' . esc_url( $developerlink ) . '">' . $developer . '</a>'; } if ( $powered_text ) { $footer_credits .= ' | ' . $powered_text . ' ' . '<a href="' . esc_url( $powered_codelink ) . '">' . $powered_code . '</a>'; } echo $footer_credits; ?> </div> </div>
Java
using System.IO; using System.Text; namespace CodeMask.WPF.Controls.Gif.Decoding { internal class GifCommentExtension : GifExtension { internal const int ExtensionLabel = 0xFE; private GifCommentExtension() { } public string Text { get; private set; } internal override GifBlockKind Kind { get { return GifBlockKind.SpecialPurpose; } } internal static GifCommentExtension ReadComment(Stream stream) { var comment = new GifCommentExtension(); comment.Read(stream); return comment; } private void Read(Stream stream) { // Note: at this point, the label (0xFE) has already been read var bytes = GifHelpers.ReadDataBlocks(stream, false); if (bytes != null) Text = Encoding.ASCII.GetString(bytes); } } }
Java
/** * @file SleepTimer.cpp * @author Pere Tuset-Peiro (peretuset@openmote.com) * @version v0.1 * @date May, 2015 * @brief * * @copyright Copyright 2015, OpenMote Technologies, S.L. * This file is licensed under the GNU General Public License v2. */ /*================================ include ==================================*/ #include "SleepTimer.h" #include "InterruptHandler.h" #include "cc2538_include.h" /*================================ define ===================================*/ /*================================ typedef ==================================*/ /*=============================== variables =================================*/ /*=============================== prototypes ================================*/ /*================================= public ==================================*/ SleepTimer::SleepTimer(uint32_t interrupt): interrupt_(interrupt) { } void SleepTimer::start(uint32_t counts) { uint32_t current; // Get current counter current = SleepModeTimerCountGet(); // Set future timeout SleepModeTimerCompareSet(current + counts); } void SleepTimer::stop(void) { // Nothing to do here, SleepTimer cannot be stopped } uint32_t SleepTimer::sleep(void) { return 0; } void SleepTimer::wakeup(uint32_t ticks) { } uint32_t SleepTimer::getCounter(void) { // Get current counter return SleepModeTimerCountGet(); } bool SleepTimer::isExpired(uint32_t future) { uint32_t current; int32_t delta; // Get current counter current = SleepModeTimerCountGet(); // Calculate delta delta = (int32_t) (current - future); // Return true if expired return (delta < 0); } void SleepTimer::setCallback(Callback* callback) { callback_ = callback; } void SleepTimer::clearCallback(void) { callback_ = nullptr; } void SleepTimer::enableInterrupts(void) { InterruptHandler::getInstance().setInterruptHandler(this); IntEnable(interrupt_); } void SleepTimer::disableInterrupts(void) { IntDisable(interrupt_); InterruptHandler::getInstance().clearInterruptHandler(this); } /*=============================== protected =================================*/ /*================================ private ==================================*/ void SleepTimer::interruptHandler(void) { if (callback_ != nullptr) { callback_->execute(); } }
Java
<?php /* * * Copyright 2001-2004 Thomas Belliard, Laurent Delineau, Edouard Hue, Eric Lebrun * * This file is part of GEPI. * * GEPI 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. * * GEPI 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 GEPI; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Initialisations files require_once("../lib/initialisations.inc.php"); // Resume session $resultat_session = $session_gepi->security_check(); if ($resultat_session == '0') { header("Location: ../logout.php?auto=1"); die(); }; //**************** EN-TETE ***************** require_once("../lib/header.inc.php"); //**************** FIN EN-TETE ************* ?> <h1 class='gepi'>GEPI - Informations générales</h1> <?php echo "Vous êtes actuellement connecté sur l'application <b>GEPI (".getSettingValue("gepiSchoolName").")</b>. <br />Par sécurité, si vous n'envoyez aucune information au serveur (activation d'un lien ou soumission d'un formulaire) pendant plus de <b>".getSettingValue("sessionMaxLength")." minutes</b>, vous serez automatiquement déconnecté de l'application."; echo "<h2>Administration de l'application GEPI</h2>\n"; echo "<table cellpadding='5' summary='Infos'>\n"; echo "<tr><td>Nom et prénom de l'administrateur : </td><td><b>".getSettingValue("gepiAdminNom")." ".getSettingValue("gepiAdminPrenom")."</b></td></tr>\n"; echo "<tr><td>Fonction de l'administrateur : </td><td><b>".getSettingValue("gepiAdminFonction")."</b></td></tr>\n"; echo "<tr><td>Email de l'administrateur : </td><td><b><a href=\"mailto:" . getSettingValue("gepiAdminAdress") . "\">".getSettingValue("gepiAdminAdress")."</a></b></td></tr>\n"; echo "<tr><td>Nom de l'établissement : </td><td><b>".getSettingValue("gepiSchoolName")."</b></td></tr>\n"; echo "<tr><td Valign='top'>Adresse : </td><td><b>".getSettingValue("gepiSchoolAdress1")."<br />".getSettingValue("gepiSchoolAdress2")."<br />".getSettingValue("gepiSchoolZipCode")." ".getSettingValue("gepiSchoolCity")."</b></td></tr>\n"; echo "</table>\n"; echo "<h2>Objectifs de l'application GEPI</h2>\n"; echo "L'objectif de GEPI est la <b>gestion pédagogique des élèves et de leur scolarité</b>. Dans ce but, des données sont collectées et stockées dans une base unique de type MySql."; echo "<h2>Obligations de l'utilisateur</h2>\n"; echo "Les membres de l'équipe pédagogique sont tenus de remplir les rubriques qui leur ont été affectées par l'administrateur lors du paramétrage de l'application."; echo "<br />Il est possible de modifier le contenu d'une rubrique tant que la période concernée n'a pas été close par l'administrateur."; echo "<h2>Destinataires des données relatives au bulletin scolaire</h2>\n"; echo "Concernant le bulletin scolaire, les données suivantes sont récoltées auprès des membres de l'équipe pédagogique : <ul><li>absences (pour chaque période : nombre de demi-journées d'absence, nombre d'absences non justifiées, nombre de retards, observations)</li> <li>moyennes et appréciations par matière,</li> <li>moyennes et appréciations par projet inter-disciplinaire,</li> <li>avis du conseil de classe.</li> </ul> Toutes ces informations sont intégralement reproduites sur un bulletin à la fin de chaque période (voir ci-dessous). <br /><br /> Ces données servent à : <ul> <li>l'élaboration d'un bulletin à la fin de chaque période, édité par le service scolarité et communiqué à l'élève et à ses responsables légaux : notes obtenues, absences, moyennes, appréciations des enseignants, avis du conseil de classe.</li> <li>l'élaboration d'un document de travail reprenant les informations du bulletin officiel et disponible pour les membres de l'équipe pédagogique de la classe concernée</li> </ul>\n"; //On vérifie si le module cahiers de texte est activé if (getSettingValue("active_cahiers_texte")=='y') { echo "<h2>Destinataires des données relatives au cahier de texte</h2>\n"; echo "Conformément aux directives de l'Education Nationale, chaque professeur dispose dans GEPI d'un cahier de texte pour chacune de ses classes qu'il peut tenir à jour en étant connecté. <br /> Le cahier de texte relate le travail réalisé en classe : <ul> <li>projet de l'équipe pédagogique,</li> <li>contenu pédagogique de chaque séance, chronologie, objectif visé, travail à faire ...</li> <li>documents divers,</li> <li>évaluations, ...</li> </ul> Il constitue un outil de communication pour l'élève, les équipes disciplinaires et pluridisciplinaires, l'administration, le chef d'établissement, les corps d'inspection et les familles. <br /> Les cahiers de texte sont accessibles en ligne."; if ((getSettingValue("cahiers_texte_login_pub") != '') and (getSettingValue("cahiers_texte_passwd_pub") != '')) { echo " <b>En raison du caractére personnel du contenu, l'accès à l'interface de consultation publique est restreint</b>. Pour accéder aux cahiers de texte, il est nécessaire de demander auprès de l'administrateur, le nom d'utilisateur et le mot de passe valides."; } else { echo " <b>L'accès à l'interface de consultation publique est entièrement libre et n'est soumise à aucune restriction.</b>\n"; } } //On vérifie si le module carnet de notes est activé if (getSettingValue("active_carnets_notes")=='y') { echo "<h2>Destinataires des données relatives au carnet de notes</h2>\n"; echo "Chaque professeur dispose dans GEPI d'un carnet de notes pour chacune de ses classes, qu'il peut tenir à jour en étant connecté. <br /> Le carnet de note permet la saisie des notes et/ou des commentaires de tout type d'évaluation (formatives, sommatives, oral, TP, TD, ...). <br /><b>Le professeur s'engage à ne faire figurer dans le carnet de notes que des notes et commentaires portés à la connaissance de l'élève (note et commentaire portés sur la copie, ...).</b> Ces données stockées dans GEPI n'ont pas d'autre destinataire que le professeur lui-même et le ou les professeurs principaux de la classe. <br />Les notes peuvent servir à l'élaboration d'une moyenne qui figurera dans le bulletin officiel à la fin de chaque période."; } //On vérifie si le plugin suivi_eleves est activé $test_plugin = sql_query1("select ouvert from plugins where nom='suivi_eleves'"); if ($test_plugin=='y') { echo "<h2>Destinataires des données relatives au module de suivi des élèves</h2>\n"; echo "Chaque professeur dispose dans GEPI d'un outil de suivi des élèves (\"observatoire\") pour chacune de ses classes, qu'il peut tenir à jour en étant connecté. <br /> Dans l'observatoire, le professeur a la possibilité d'attribuer à chacun de ses élèves un code pour chaque période. Ces codes et leur signification sont paramétrables par les administrateurs de l'observatoire désignés par l'administrateur général de GEPI. <br />. Le professeur dispose également de la possibilité de saisir un commentaire pour chacun de ses élèves dans le respect de la loi et dans le cadre strict de l'Education Nationale. <br /><br />L'observatoire et les données qui y figurent sont accessibles à l'ensemble de l'équipe pédagogique de l'établissement. <br /><br />Dans le respect de la loi informatique et liberté 78-17 du 6 janvier 1978, chaque élève a également accès dans son espace GEPI aux données qui le concernent"; } require("../lib/footer.inc.php"); ?>
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.commons.math3.stat.clustering; import java.io.Serializable; import java.util.Collection; import java.util.Arrays; import org.apache.commons.math3.util.MathArrays; /** * A simple implementation of {@link Clusterable} for points with double coordinates. * @version $Id$ * @since 3.1 */ public class EuclideanDoublePoint implements Clusterable<EuclideanDoublePoint>, Serializable { /** Serializable version identifier. */ private static final long serialVersionUID = 8026472786091227632L; /** Point coordinates. */ private final double[] point; /** * Build an instance wrapping an integer array. * <p> * The wrapped array is referenced, it is <em>not</em> copied. * * @param point the n-dimensional point in integer space */ public EuclideanDoublePoint(final double[] point) { this.point = point; } /** {@inheritDoc} */ public EuclideanDoublePoint centroidOf(final Collection<EuclideanDoublePoint> points) { final double[] centroid = new double[getPoint().length]; for (final EuclideanDoublePoint p : points) { for (int i = 0; i < centroid.length; i++) { centroid[i] += p.getPoint()[i]; } } for (int i = 0; i < centroid.length; i++) { centroid[i] /= points.size(); } return new EuclideanDoublePoint(centroid); } /** {@inheritDoc} */ public double distanceFrom(final EuclideanDoublePoint p) { return MathArrays.distance(point, p.getPoint()); } /** {@inheritDoc} */ @Override public boolean equals(final Object other) { if (!(other instanceof EuclideanDoublePoint)) { return false; } return Arrays.equals(point, ((EuclideanDoublePoint) other).point); } /** * Get the n-dimensional point in integer space. * * @return a reference (not a copy!) to the wrapped array */ public double[] getPoint() { return point; } /** {@inheritDoc} */ @Override public int hashCode() { return Arrays.hashCode(point); } /** {@inheritDoc} */ @Override public String toString() { return Arrays.toString(point); } }
Java
/* IGraph library. Copyright (C) 2021 The igraph development team <igraph@igraph.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <igraph.h> #include "test_utilities.inc" int main() { igraph_t g_empty, g_lm; igraph_vector_t result; igraph_vs_t vids; igraph_rng_seed(igraph_rng_default(), 42); igraph_vector_init(&result, 0); igraph_vs_all(&vids); igraph_small(&g_empty, 0, 0, -1); igraph_small(&g_lm, 6, 1, 0,1, 0,2, 1,1, 1,3, 2,0, 2,3, 3,4, 3,4, -1); printf("No vertices:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_empty, &result, vids, /*order*/ 1, /*mode*/ IGRAPH_ALL, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 0:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 0, /*mode*/ IGRAPH_ALL, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 1, ignoring direction:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 1, /*mode*/ IGRAPH_ALL, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 1, only checking IGRAPH_IN:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 1, /*mode*/ IGRAPH_IN, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 10, ignoring direction:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 10, /*mode*/ IGRAPH_ALL, /*mindist*/ 0) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 2, mindist 2, IGRAPH_OUT:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 2, /*mode*/ IGRAPH_OUT, /*mindist*/ 2) == IGRAPH_SUCCESS); print_vector(&result); printf("Directed graph with loops and multi-edges, order 4, mindist 4, IGRAPH_ALL:\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 4, /*mode*/ IGRAPH_ALL, /*mindist*/ 4) == IGRAPH_SUCCESS); print_vector(&result); VERIFY_FINALLY_STACK(); igraph_set_error_handler(igraph_error_handler_ignore); printf("Negative order.\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ -4, /*mode*/ IGRAPH_ALL, /*mindist*/ 4) == IGRAPH_EINVAL); printf("Negative mindist.\n"); IGRAPH_ASSERT(igraph_neighborhood_size(&g_lm, &result, vids, /*order*/ 4, /*mode*/ IGRAPH_ALL, /*mindist*/ -4) == IGRAPH_EINVAL); igraph_vector_destroy(&result); igraph_destroy(&g_empty); igraph_destroy(&g_lm); VERIFY_FINALLY_STACK(); return 0; }
Java
/* * linux/mm/vmscan.c * * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds * * Swap reorganised 29.12.95, Stephen Tweedie. * kswapd added: 7.1.96 sct * Removed kswapd_ctl limits, and swap out as many pages as needed * to bring the system back to freepages.high: 2.4.97, Rik van Riel. * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com). * Multiqueue VM started 5.8.00, Rik van Riel. */ #include <linux/mm.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/kernel_stat.h> #include <linux/swap.h> #include <linux/pagemap.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/vmstat.h> #include <linux/file.h> #include <linux/writeback.h> #include <linux/blkdev.h> #include <linux/buffer_head.h> /* for try_to_release_page(), buffer_heads_over_limit */ #include <linux/mm_inline.h> #include <linux/pagevec.h> #include <linux/backing-dev.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/notifier.h> #include <linux/rwsem.h> #include <linux/delay.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <asm/tlbflush.h> #include <asm/div64.h> #include <linux/swapops.h> #include "internal.h" struct scan_control { /* Incremented by the number of inactive pages that were scanned */ unsigned long nr_scanned; /* This context's GFP mask */ gfp_t gfp_mask; int may_writepage; /* Can pages be swapped as part of reclaim? */ int may_swap; /* This context's SWAP_CLUSTER_MAX. If freeing memory for * suspend, we effectively ignore SWAP_CLUSTER_MAX. * In this context, it doesn't matter that we scan the * whole list at once. */ int swap_cluster_max; int swappiness; int all_unreclaimable; }; /* * The list of shrinker callbacks used by to apply pressure to * ageable caches. */ struct shrinker { shrinker_t shrinker; struct list_head list; int seeks; /* seeks to recreate an obj */ long nr; /* objs pending delete */ }; #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru)) #ifdef ARCH_HAS_PREFETCH #define prefetch_prev_lru_page(_page, _base, _field) \ do { \ if ((_page)->lru.prev != _base) { \ struct page *prev; \ \ prev = lru_to_page(&(_page->lru)); \ prefetch(&prev->_field); \ } \ } while (0) #else #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0) #endif #ifdef ARCH_HAS_PREFETCHW #define prefetchw_prev_lru_page(_page, _base, _field) \ do { \ if ((_page)->lru.prev != _base) { \ struct page *prev; \ \ prev = lru_to_page(&(_page->lru)); \ prefetchw(&prev->_field); \ } \ } while (0) #else #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0) #endif /* * From 0 .. 100. Higher means more swappy. */ int vm_swappiness = 60; long vm_total_pages; /* The total number of pages which the VM controls */ static LIST_HEAD(shrinker_list); static DECLARE_RWSEM(shrinker_rwsem); /* * Add a shrinker callback to be called from the vm */ struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker) { struct shrinker *shrinker; shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL); if (shrinker) { shrinker->shrinker = theshrinker; shrinker->seeks = seeks; shrinker->nr = 0; down_write(&shrinker_rwsem); list_add_tail(&shrinker->list, &shrinker_list); up_write(&shrinker_rwsem); } return shrinker; } EXPORT_SYMBOL(set_shrinker); /* * Remove one */ void remove_shrinker(struct shrinker *shrinker) { down_write(&shrinker_rwsem); list_del(&shrinker->list); up_write(&shrinker_rwsem); kfree(shrinker); } EXPORT_SYMBOL(remove_shrinker); #define SHRINK_BATCH 128 /* * Call the shrink functions to age shrinkable caches * * Here we assume it costs one seek to replace a lru page and that it also * takes a seek to recreate a cache object. With this in mind we age equal * percentages of the lru and ageable caches. This should balance the seeks * generated by these structures. * * If the vm encounted mapped pages on the LRU it increase the pressure on * slab to avoid swapping. * * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits. * * `lru_pages' represents the number of on-LRU pages in all the zones which * are eligible for the caller's allocation attempt. It is used for balancing * slab reclaim versus page reclaim. * * Returns the number of slab objects which we shrunk. */ unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask, unsigned long lru_pages) { struct shrinker *shrinker; unsigned long ret = 0; if (scanned == 0) scanned = SWAP_CLUSTER_MAX; if (!down_read_trylock(&shrinker_rwsem)) return 1; /* Assume we'll be able to shrink next time */ list_for_each_entry(shrinker, &shrinker_list, list) { unsigned long long delta; unsigned long total_scan; unsigned long max_pass = (*shrinker->shrinker)(0, gfp_mask); delta = (4 * scanned) / shrinker->seeks; delta *= max_pass; do_div(delta, lru_pages + 1); shrinker->nr += delta; if (shrinker->nr < 0) { printk(KERN_ERR "%s: nr=%ld\n", __FUNCTION__, shrinker->nr); shrinker->nr = max_pass; } /* * Avoid risking looping forever due to too large nr value: * never try to free more than twice the estimate number of * freeable entries. */ if (shrinker->nr > max_pass * 2) shrinker->nr = max_pass * 2; total_scan = shrinker->nr; shrinker->nr = 0; while (total_scan >= SHRINK_BATCH) { long this_scan = SHRINK_BATCH; int shrink_ret; int nr_before; nr_before = (*shrinker->shrinker)(0, gfp_mask); shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask); if (shrink_ret == -1) break; if (shrink_ret < nr_before) ret += nr_before - shrink_ret; count_vm_events(SLABS_SCANNED, this_scan); total_scan -= this_scan; cond_resched(); } shrinker->nr += total_scan; } up_read(&shrinker_rwsem); return ret; } /* Called without lock on whether page is mapped, so answer is unstable */ static inline int page_mapping_inuse(struct page *page) { struct address_space *mapping; /* Page is in somebody's page tables. */ if (page_mapped(page)) return 1; /* Be more reluctant to reclaim swapcache than pagecache */ if (PageSwapCache(page)) return 1; mapping = page_mapping(page); if (!mapping) return 0; /* File is mmap'd by somebody? */ return mapping_mapped(mapping); } static inline int is_page_cache_freeable(struct page *page) { return page_count(page) - !!PagePrivate(page) == 2; } static int may_write_to_queue(struct backing_dev_info *bdi) { if (current->flags & PF_SWAPWRITE) return 1; if (!bdi_write_congested(bdi)) return 1; if (bdi == current->backing_dev_info) return 1; return 0; } /* * We detected a synchronous write error writing a page out. Probably * -ENOSPC. We need to propagate that into the address_space for a subsequent * fsync(), msync() or close(). * * The tricky part is that after writepage we cannot touch the mapping: nothing * prevents it from being freed up. But we have a ref on the page and once * that page is locked, the mapping is pinned. * * We're allowed to run sleeping lock_page() here because we know the caller has * __GFP_FS. */ static void handle_write_error(struct address_space *mapping, struct page *page, int error) { lock_page(page); if (page_mapping(page) == mapping) { if (error == -ENOSPC) set_bit(AS_ENOSPC, &mapping->flags); else set_bit(AS_EIO, &mapping->flags); } unlock_page(page); } /* possible outcome of pageout() */ typedef enum { /* failed to write page out, page is locked */ PAGE_KEEP, /* move page to the active list, page is locked */ PAGE_ACTIVATE, /* page has been sent to the disk successfully, page is unlocked */ PAGE_SUCCESS, /* page is clean and locked */ PAGE_CLEAN, } pageout_t; /* * pageout is called by shrink_page_list() for each dirty page. * Calls ->writepage(). */ static pageout_t pageout(struct page *page, struct address_space *mapping) { /* * If the page is dirty, only perform writeback if that write * will be non-blocking. To prevent this allocation from being * stalled by pagecache activity. But note that there may be * stalls if we need to run get_block(). We could test * PagePrivate for that. * * If this process is currently in generic_file_write() against * this page's queue, we can perform writeback even if that * will block. * * If the page is swapcache, write it back even if that would * block, for some throttling. This happens by accident, because * swap_backing_dev_info is bust: it doesn't reflect the * congestion state of the swapdevs. Easy to fix, if needed. * See swapfile.c:page_queue_congested(). */ if (!is_page_cache_freeable(page)) return PAGE_KEEP; if (!mapping) { /* * Some data journaling orphaned pages can have * page->mapping == NULL while being dirty with clean buffers. */ if (PagePrivate(page)) { if (try_to_free_buffers(page)) { ClearPageDirty(page); printk("%s: orphaned page\n", __FUNCTION__); return PAGE_CLEAN; } } return PAGE_KEEP; } if (mapping->a_ops->writepage == NULL) return PAGE_ACTIVATE; if (!may_write_to_queue(mapping->backing_dev_info)) return PAGE_KEEP; if (clear_page_dirty_for_io(page)) { int res; struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = SWAP_CLUSTER_MAX, .range_start = 0, .range_end = LLONG_MAX, .nonblocking = 1, .for_reclaim = 1, }; SetPageReclaim(page); res = mapping->a_ops->writepage(page, &wbc); if (res < 0) handle_write_error(mapping, page, res); if (res == AOP_WRITEPAGE_ACTIVATE) { ClearPageReclaim(page); return PAGE_ACTIVATE; } if (!PageWriteback(page)) { /* synchronous write or broken a_ops? */ ClearPageReclaim(page); } inc_zone_page_state(page, NR_VMSCAN_WRITE); return PAGE_SUCCESS; } return PAGE_CLEAN; } /* * Attempt to detach a locked page from its ->mapping. If it is dirty or if * someone else has a ref on the page, abort and return 0. If it was * successfully detached, return 1. Assumes the caller has a single ref on * this page. */ int remove_mapping(struct address_space *mapping, struct page *page) { BUG_ON(!PageLocked(page)); BUG_ON(mapping != page_mapping(page)); write_lock_irq(&mapping->tree_lock); /* * The non racy check for a busy page. * * Must be careful with the order of the tests. When someone has * a ref to the page, it may be possible that they dirty it then * drop the reference. So if PageDirty is tested before page_count * here, then the following race may occur: * * get_user_pages(&page); * [user mapping goes away] * write_to(page); * !PageDirty(page) [good] * SetPageDirty(page); * put_page(page); * !page_count(page) [good, discard it] * * [oops, our write_to data is lost] * * Reversing the order of the tests ensures such a situation cannot * escape unnoticed. The smp_rmb is needed to ensure the page->flags * load is not satisfied before that of page->_count. * * Note that if SetPageDirty is always performed via set_page_dirty, * and thus under tree_lock, then this ordering is not required. */ if (unlikely(page_count(page) != 2)) goto cannot_free; smp_rmb(); if (unlikely(PageDirty(page))) goto cannot_free; if (PageSwapCache(page)) { swp_entry_t swap = { .val = page_private(page) }; __delete_from_swap_cache(page); write_unlock_irq(&mapping->tree_lock); swap_free(swap); __put_page(page); /* The pagecache ref */ return 1; } __remove_from_page_cache(page); write_unlock_irq(&mapping->tree_lock); __put_page(page); return 1; cannot_free: write_unlock_irq(&mapping->tree_lock); return 0; } /* * shrink_page_list() returns the number of reclaimed pages */ static unsigned long shrink_page_list(struct list_head *page_list, struct scan_control *sc) { LIST_HEAD(ret_pages); struct pagevec freed_pvec; int pgactivate = 0; unsigned long nr_reclaimed = 0; cond_resched(); pagevec_init(&freed_pvec, 1); while (!list_empty(page_list)) { struct address_space *mapping; struct page *page; int may_enter_fs; int referenced; cond_resched(); page = lru_to_page(page_list); list_del(&page->lru); if (TestSetPageLocked(page)) goto keep; VM_BUG_ON(PageActive(page)); sc->nr_scanned++; if (!sc->may_swap && page_mapped(page)) goto keep_locked; /* Double the slab pressure for mapped and swapcache pages */ if (page_mapped(page) || PageSwapCache(page)) sc->nr_scanned++; if (PageWriteback(page)) goto keep_locked; referenced = page_referenced(page, 1); /* In active use or really unfreeable? Activate it. */ if (referenced && page_mapping_inuse(page)) goto activate_locked; #ifdef CONFIG_SWAP /* * Anonymous process memory has backing store? * Try to allocate it some swap space here. */ if (PageAnon(page) && !PageSwapCache(page)) if (!add_to_swap(page, GFP_ATOMIC)) goto activate_locked; #endif /* CONFIG_SWAP */ mapping = page_mapping(page); may_enter_fs = (sc->gfp_mask & __GFP_FS) || (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO)); /* * The page is mapped into the page tables of one or more * processes. Try to unmap it here. */ if (page_mapped(page) && mapping) { switch (try_to_unmap(page, 0)) { case SWAP_FAIL: goto activate_locked; case SWAP_AGAIN: goto keep_locked; case SWAP_SUCCESS: ; /* try to free the page below */ } } if (PageDirty(page)) { if (referenced) goto keep_locked; if (!may_enter_fs) goto keep_locked; if (!sc->may_writepage) goto keep_locked; /* Page is dirty, try to write it out here */ switch(pageout(page, mapping)) { case PAGE_KEEP: goto keep_locked; case PAGE_ACTIVATE: goto activate_locked; case PAGE_SUCCESS: if (PageWriteback(page) || PageDirty(page)) goto keep; /* * A synchronous write - probably a ramdisk. Go * ahead and try to reclaim the page. */ if (TestSetPageLocked(page)) goto keep; if (PageDirty(page) || PageWriteback(page)) goto keep_locked; mapping = page_mapping(page); case PAGE_CLEAN: ; /* try to free the page below */ } } /* * If the page has buffers, try to free the buffer mappings * associated with this page. If we succeed we try to free * the page as well. * * We do this even if the page is PageDirty(). * try_to_release_page() does not perform I/O, but it is * possible for a page to have PageDirty set, but it is actually * clean (all its buffers are clean). This happens if the * buffers were written out directly, with submit_bh(). ext3 * will do this, as well as the blockdev mapping. * try_to_release_page() will discover that cleanness and will * drop the buffers and mark the page clean - it can be freed. * * Rarely, pages can have buffers and no ->mapping. These are * the pages which were not successfully invalidated in * truncate_complete_page(). We try to drop those buffers here * and if that worked, and the page is no longer mapped into * process address space (page_count == 1) it can be freed. * Otherwise, leave the page on the LRU so it is swappable. */ if (PagePrivate(page)) { if (!try_to_release_page(page, sc->gfp_mask)) goto activate_locked; if (!mapping && page_count(page) == 1) goto free_it; } if (!mapping || !remove_mapping(mapping, page)) goto keep_locked; free_it: unlock_page(page); nr_reclaimed++; if (!pagevec_add(&freed_pvec, page)) __pagevec_release_nonlru(&freed_pvec); continue; activate_locked: SetPageActive(page); pgactivate++; keep_locked: unlock_page(page); keep: list_add(&page->lru, &ret_pages); VM_BUG_ON(PageLRU(page)); } list_splice(&ret_pages, page_list); if (pagevec_count(&freed_pvec)) __pagevec_release_nonlru(&freed_pvec); count_vm_events(PGACTIVATE, pgactivate); return nr_reclaimed; } /* * zone->lru_lock is heavily contended. Some of the functions that * shrink the lists perform better by taking out a batch of pages * and working on them outside the LRU lock. * * For pagecache intensive workloads, this function is the hottest * spot in the kernel (apart from copy_*_user functions). * * Appropriate locks must be held before calling this function. * * @nr_to_scan: The number of pages to look through on the list. * @src: The LRU list to pull pages off. * @dst: The temp list to put pages on to. * @scanned: The number of pages that were scanned. * * returns how many pages were moved onto *@dst. */ static unsigned long isolate_lru_pages(unsigned long nr_to_scan, struct list_head *src, struct list_head *dst, unsigned long *scanned) { unsigned long nr_taken = 0; struct page *page; unsigned long scan; for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) { struct list_head *target; page = lru_to_page(src); prefetchw_prev_lru_page(page, src, flags); VM_BUG_ON(!PageLRU(page)); list_del(&page->lru); target = src; if (likely(get_page_unless_zero(page))) { /* * Be careful not to clear PageLRU until after we're * sure the page is not being freed elsewhere -- the * page release code relies on it. */ ClearPageLRU(page); target = dst; nr_taken++; } /* else it is being freed elsewhere */ list_add(&page->lru, target); } *scanned = scan; return nr_taken; } /* * shrink_inactive_list() is a helper for shrink_zone(). It returns the number * of reclaimed pages */ static unsigned long shrink_inactive_list(unsigned long max_scan, struct zone *zone, struct scan_control *sc) { LIST_HEAD(page_list); struct pagevec pvec; unsigned long nr_scanned = 0; unsigned long nr_reclaimed = 0; pagevec_init(&pvec, 1); lru_add_drain(); spin_lock_irq(&zone->lru_lock); do { struct page *page; unsigned long nr_taken; unsigned long nr_scan; unsigned long nr_freed; nr_taken = isolate_lru_pages(sc->swap_cluster_max, &zone->inactive_list, &page_list, &nr_scan); __mod_zone_page_state(zone, NR_INACTIVE, -nr_taken); zone->pages_scanned += nr_scan; spin_unlock_irq(&zone->lru_lock); nr_scanned += nr_scan; nr_freed = shrink_page_list(&page_list, sc); nr_reclaimed += nr_freed; local_irq_disable(); if (current_is_kswapd()) { __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scan); __count_vm_events(KSWAPD_STEAL, nr_freed); } else __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scan); __count_zone_vm_events(PGSTEAL, zone, nr_freed); if (nr_taken == 0) goto done; spin_lock(&zone->lru_lock); /* * Put back any unfreeable pages. */ while (!list_empty(&page_list)) { page = lru_to_page(&page_list); VM_BUG_ON(PageLRU(page)); SetPageLRU(page); list_del(&page->lru); if (PageActive(page)) add_page_to_active_list(zone, page); else add_page_to_inactive_list(zone, page); if (!pagevec_add(&pvec, page)) { spin_unlock_irq(&zone->lru_lock); __pagevec_release(&pvec); spin_lock_irq(&zone->lru_lock); } } } while (nr_scanned < max_scan); spin_unlock(&zone->lru_lock); done: local_irq_enable(); pagevec_release(&pvec); return nr_reclaimed; } /* * We are about to scan this zone at a certain priority level. If that priority * level is smaller (ie: more urgent) than the previous priority, then note * that priority level within the zone. This is done so that when the next * process comes in to scan this zone, it will immediately start out at this * priority level rather than having to build up its own scanning priority. * Here, this priority affects only the reclaim-mapped threshold. */ static inline void note_zone_scanning_priority(struct zone *zone, int priority) { if (priority < zone->prev_priority) zone->prev_priority = priority; } static inline int zone_is_near_oom(struct zone *zone) { return zone->pages_scanned >= (zone_page_state(zone, NR_ACTIVE) + zone_page_state(zone, NR_INACTIVE))*3; } /* * This moves pages from the active list to the inactive list. * * We move them the other way if the page is referenced by one or more * processes, from rmap. * * If the pages are mostly unmapped, the processing is fast and it is * appropriate to hold zone->lru_lock across the whole operation. But if * the pages are mapped, the processing is slow (page_referenced()) so we * should drop zone->lru_lock around each page. It's impossible to balance * this, so instead we remove the pages from the LRU while processing them. * It is safe to rely on PG_active against the non-LRU pages in here because * nobody will play with that bit on a non-LRU page. * * The downside is that we have to touch page->_count against each page. * But we had to alter page->flags anyway. */ static void shrink_active_list(unsigned long nr_pages, struct zone *zone, struct scan_control *sc, int priority) { unsigned long pgmoved; int pgdeactivate = 0; unsigned long pgscanned; LIST_HEAD(l_hold); /* The pages which were snipped off */ LIST_HEAD(l_inactive); /* Pages to go onto the inactive_list */ LIST_HEAD(l_active); /* Pages to go onto the active_list */ struct page *page; struct pagevec pvec; int reclaim_mapped = 0; if (sc->may_swap) { long mapped_ratio; long distress; long swap_tendency; if (zone_is_near_oom(zone)) goto force_reclaim_mapped; /* * `distress' is a measure of how much trouble we're having * reclaiming pages. 0 -> no problems. 100 -> great trouble. */ distress = 100 >> min(zone->prev_priority, priority); /* * The point of this algorithm is to decide when to start * reclaiming mapped memory instead of just pagecache. Work out * how much memory * is mapped. */ mapped_ratio = ((global_page_state(NR_FILE_MAPPED) + global_page_state(NR_ANON_PAGES)) * 100) / vm_total_pages; /* * Now decide how much we really want to unmap some pages. The * mapped ratio is downgraded - just because there's a lot of * mapped memory doesn't necessarily mean that page reclaim * isn't succeeding. * * The distress ratio is important - we don't want to start * going oom. * * A 100% value of vm_swappiness overrides this algorithm * altogether. */ swap_tendency = mapped_ratio / 2 + distress + sc->swappiness; /* * Now use this metric to decide whether to start moving mapped * memory onto the inactive list. */ if (swap_tendency >= 100) force_reclaim_mapped: reclaim_mapped = 1; } lru_add_drain(); spin_lock_irq(&zone->lru_lock); pgmoved = isolate_lru_pages(nr_pages, &zone->active_list, &l_hold, &pgscanned); zone->pages_scanned += pgscanned; __mod_zone_page_state(zone, NR_ACTIVE, -pgmoved); spin_unlock_irq(&zone->lru_lock); while (!list_empty(&l_hold)) { cond_resched(); page = lru_to_page(&l_hold); list_del(&page->lru); if (page_mapped(page)) { if (!reclaim_mapped || (total_swap_pages == 0 && PageAnon(page)) || page_referenced(page, 0)) { list_add(&page->lru, &l_active); continue; } } list_add(&page->lru, &l_inactive); } pagevec_init(&pvec, 1); pgmoved = 0; spin_lock_irq(&zone->lru_lock); while (!list_empty(&l_inactive)) { page = lru_to_page(&l_inactive); prefetchw_prev_lru_page(page, &l_inactive, flags); VM_BUG_ON(PageLRU(page)); SetPageLRU(page); VM_BUG_ON(!PageActive(page)); ClearPageActive(page); list_move(&page->lru, &zone->inactive_list); pgmoved++; if (!pagevec_add(&pvec, page)) { __mod_zone_page_state(zone, NR_INACTIVE, pgmoved); spin_unlock_irq(&zone->lru_lock); pgdeactivate += pgmoved; pgmoved = 0; if (buffer_heads_over_limit) pagevec_strip(&pvec); __pagevec_release(&pvec); spin_lock_irq(&zone->lru_lock); } } __mod_zone_page_state(zone, NR_INACTIVE, pgmoved); pgdeactivate += pgmoved; if (buffer_heads_over_limit) { spin_unlock_irq(&zone->lru_lock); pagevec_strip(&pvec); spin_lock_irq(&zone->lru_lock); } pgmoved = 0; while (!list_empty(&l_active)) { page = lru_to_page(&l_active); prefetchw_prev_lru_page(page, &l_active, flags); VM_BUG_ON(PageLRU(page)); SetPageLRU(page); VM_BUG_ON(!PageActive(page)); list_move(&page->lru, &zone->active_list); pgmoved++; if (!pagevec_add(&pvec, page)) { __mod_zone_page_state(zone, NR_ACTIVE, pgmoved); pgmoved = 0; spin_unlock_irq(&zone->lru_lock); __pagevec_release(&pvec); spin_lock_irq(&zone->lru_lock); } } __mod_zone_page_state(zone, NR_ACTIVE, pgmoved); __count_zone_vm_events(PGREFILL, zone, pgscanned); __count_vm_events(PGDEACTIVATE, pgdeactivate); spin_unlock_irq(&zone->lru_lock); pagevec_release(&pvec); } /* * This is a basic per-zone page freer. Used by both kswapd and direct reclaim. */ static unsigned long shrink_zone(int priority, struct zone *zone, struct scan_control *sc) { unsigned long nr_active; unsigned long nr_inactive; unsigned long nr_to_scan; unsigned long nr_reclaimed = 0; atomic_inc(&zone->reclaim_in_progress); /* * Add one to `nr_to_scan' just to make sure that the kernel will * slowly sift through the active list. */ zone->nr_scan_active += (zone_page_state(zone, NR_ACTIVE) >> priority) + 1; nr_active = zone->nr_scan_active; if (nr_active >= sc->swap_cluster_max) zone->nr_scan_active = 0; else nr_active = 0; zone->nr_scan_inactive += (zone_page_state(zone, NR_INACTIVE) >> priority) + 1; nr_inactive = zone->nr_scan_inactive; if (nr_inactive >= sc->swap_cluster_max) zone->nr_scan_inactive = 0; else nr_inactive = 0; while (nr_active || nr_inactive) { if (nr_active) { nr_to_scan = min(nr_active, (unsigned long)sc->swap_cluster_max); nr_active -= nr_to_scan; shrink_active_list(nr_to_scan, zone, sc, priority); } if (nr_inactive) { nr_to_scan = min(nr_inactive, (unsigned long)sc->swap_cluster_max); nr_inactive -= nr_to_scan; nr_reclaimed += shrink_inactive_list(nr_to_scan, zone, sc); } } throttle_vm_writeout(sc->gfp_mask); atomic_dec(&zone->reclaim_in_progress); return nr_reclaimed; } /* * This is the direct reclaim path, for page-allocating processes. We only * try to reclaim pages from zones which will satisfy the caller's allocation * request. * * We reclaim from a zone even if that zone is over pages_high. Because: * a) The caller may be trying to free *extra* pages to satisfy a higher-order * allocation or * b) The zones may be over pages_high but they must go *over* pages_high to * satisfy the `incremental min' zone defense algorithm. * * Returns the number of reclaimed pages. * * If a zone is deemed to be full of pinned pages then just give it a light * scan then give up on it. */ static unsigned long shrink_zones(int priority, struct zone **zones, struct scan_control *sc) { unsigned long nr_reclaimed = 0; int i; sc->all_unreclaimable = 1; for (i = 0; zones[i] != NULL; i++) { struct zone *zone = zones[i]; if (!populated_zone(zone)) continue; if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) continue; note_zone_scanning_priority(zone, priority); if (zone->all_unreclaimable && priority != DEF_PRIORITY) continue; /* Let kswapd poll it */ sc->all_unreclaimable = 0; nr_reclaimed += shrink_zone(priority, zone, sc); } return nr_reclaimed; } /* * This is the main entry point to direct page reclaim. * * If a full scan of the inactive list fails to free enough memory then we * are "out of memory" and something needs to be killed. * * If the caller is !__GFP_FS then the probability of a failure is reasonably * high - the zone may be full of dirty or under-writeback pages, which this * caller can't do much about. We kick pdflush and take explicit naps in the * hope that some of these pages can be written. But if the allocating task * holds filesystem locks which prevent writeout this might not work, and the * allocation attempt will fail. */ unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask) { int priority; int ret = 0; unsigned long total_scanned = 0; unsigned long nr_reclaimed = 0; struct reclaim_state *reclaim_state = current->reclaim_state; unsigned long lru_pages = 0; int i; struct scan_control sc = { .gfp_mask = gfp_mask, .may_writepage = !laptop_mode, .swap_cluster_max = SWAP_CLUSTER_MAX, .may_swap = 1, .swappiness = vm_swappiness, }; count_vm_event(ALLOCSTALL); for (i = 0; zones[i] != NULL; i++) { struct zone *zone = zones[i]; if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) continue; lru_pages += zone_page_state(zone, NR_ACTIVE) + zone_page_state(zone, NR_INACTIVE); } for (priority = DEF_PRIORITY; priority >= 0; priority--) { sc.nr_scanned = 0; if (!priority) disable_swap_token(); nr_reclaimed += shrink_zones(priority, zones, &sc); shrink_slab(sc.nr_scanned, gfp_mask, lru_pages); if (reclaim_state) { nr_reclaimed += reclaim_state->reclaimed_slab; reclaim_state->reclaimed_slab = 0; } total_scanned += sc.nr_scanned; if (nr_reclaimed >= sc.swap_cluster_max) { ret = 1; goto out; } /* * Try to write back as many pages as we just scanned. This * tends to cause slow streaming writers to write data to the * disk smoothly, at the dirtying rate, which is nice. But * that's undesirable in laptop mode, where we *want* lumpy * writeout. So in laptop mode, write out the whole world. */ if (total_scanned > sc.swap_cluster_max + sc.swap_cluster_max / 2) { wakeup_pdflush(laptop_mode ? 0 : total_scanned); sc.may_writepage = 1; } /* Take a nap, wait for some writeback to complete */ if (sc.nr_scanned && priority < DEF_PRIORITY - 2) congestion_wait(WRITE, HZ/10); } /* top priority shrink_caches still had more to do? don't OOM, then */ if (!sc.all_unreclaimable) ret = 1; out: /* * Now that we've scanned all the zones at this priority level, note * that level within the zone so that the next thread which performs * scanning of this zone will immediately start out at this priority * level. This affects only the decision whether or not to bring * mapped pages onto the inactive list. */ if (priority < 0) priority = 0; for (i = 0; zones[i] != 0; i++) { struct zone *zone = zones[i]; if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) continue; zone->prev_priority = priority; } return ret; } /* * For kswapd, balance_pgdat() will work across all this node's zones until * they are all at pages_high. * * Returns the number of pages which were actually freed. * * There is special handling here for zones which are full of pinned pages. * This can happen if the pages are all mlocked, or if they are all used by * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb. * What we do is to detect the case where all pages in the zone have been * scanned twice and there has been zero successful reclaim. Mark the zone as * dead and from now on, only perform a short scan. Basically we're polling * the zone for when the problem goes away. * * kswapd scans the zones in the highmem->normal->dma direction. It skips * zones which have free_pages > pages_high, but once a zone is found to have * free_pages <= pages_high, we scan that zone and the lower zones regardless * of the number of free pages in the lower zones. This interoperates with * the page allocator fallback scheme to ensure that aging of pages is balanced * across the zones. */ static unsigned long balance_pgdat(pg_data_t *pgdat, int order) { int all_zones_ok; int priority; int i; unsigned long total_scanned; unsigned long nr_reclaimed; struct reclaim_state *reclaim_state = current->reclaim_state; struct scan_control sc = { .gfp_mask = GFP_KERNEL, .may_swap = 1, .swap_cluster_max = SWAP_CLUSTER_MAX, .swappiness = vm_swappiness, }; /* * temp_priority is used to remember the scanning priority at which * this zone was successfully refilled to free_pages == pages_high. */ int temp_priority[MAX_NR_ZONES]; loop_again: total_scanned = 0; nr_reclaimed = 0; sc.may_writepage = !laptop_mode; count_vm_event(PAGEOUTRUN); for (i = 0; i < pgdat->nr_zones; i++) temp_priority[i] = DEF_PRIORITY; for (priority = DEF_PRIORITY; priority >= 0; priority--) { int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */ unsigned long lru_pages = 0; /* The swap token gets in the way of swapout... */ if (!priority) disable_swap_token(); all_zones_ok = 1; /* * Scan in the highmem->dma direction for the highest * zone which needs scanning */ for (i = pgdat->nr_zones - 1; i >= 0; i--) { struct zone *zone = pgdat->node_zones + i; if (!populated_zone(zone)) continue; if (zone->all_unreclaimable && priority != DEF_PRIORITY) continue; if (!zone_watermark_ok(zone, order, zone->pages_high, 0, 0)) { end_zone = i; break; } } if (i < 0) goto out; for (i = 0; i <= end_zone; i++) { struct zone *zone = pgdat->node_zones + i; lru_pages += zone_page_state(zone, NR_ACTIVE) + zone_page_state(zone, NR_INACTIVE); } /* * Now scan the zone in the dma->highmem direction, stopping * at the last zone which needs scanning. * * We do this because the page allocator works in the opposite * direction. This prevents the page allocator from allocating * pages behind kswapd's direction of progress, which would * cause too much scanning of the lower zones. */ for (i = 0; i <= end_zone; i++) { struct zone *zone = pgdat->node_zones + i; int nr_slab; if (!populated_zone(zone)) continue; if (zone->all_unreclaimable && priority != DEF_PRIORITY) continue; if (!zone_watermark_ok(zone, order, zone->pages_high, end_zone, 0)) all_zones_ok = 0; temp_priority[i] = priority; sc.nr_scanned = 0; note_zone_scanning_priority(zone, priority); nr_reclaimed += shrink_zone(priority, zone, &sc); reclaim_state->reclaimed_slab = 0; nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages); nr_reclaimed += reclaim_state->reclaimed_slab; total_scanned += sc.nr_scanned; if (zone->all_unreclaimable) continue; if (nr_slab == 0 && zone->pages_scanned >= (zone_page_state(zone, NR_ACTIVE) + zone_page_state(zone, NR_INACTIVE)) * 6) zone->all_unreclaimable = 1; /* * If we've done a decent amount of scanning and * the reclaim ratio is low, start doing writepage * even in laptop mode */ if (total_scanned > SWAP_CLUSTER_MAX * 2 && total_scanned > nr_reclaimed + nr_reclaimed / 2) sc.may_writepage = 1; } if (all_zones_ok) break; /* kswapd: all done */ /* * OK, kswapd is getting into trouble. Take a nap, then take * another pass across the zones. */ if (total_scanned && priority < DEF_PRIORITY - 2) congestion_wait(WRITE, HZ/10); /* * We do this so kswapd doesn't build up large priorities for * example when it is freeing in parallel with allocators. It * matches the direct reclaim path behaviour in terms of impact * on zone->*_priority. */ if (nr_reclaimed >= SWAP_CLUSTER_MAX) break; } out: /* * Note within each zone the priority level at which this zone was * brought into a happy state. So that the next thread which scans this * zone will start out at that priority level. */ for (i = 0; i < pgdat->nr_zones; i++) { struct zone *zone = pgdat->node_zones + i; zone->prev_priority = temp_priority[i]; } if (!all_zones_ok) { cond_resched(); try_to_freeze(); goto loop_again; } return nr_reclaimed; } /* * The background pageout daemon, started as a kernel thread * from the init process. * * This basically trickles out pages so that we have _some_ * free memory available even if there is no other activity * that frees anything up. This is needed for things like routing * etc, where we otherwise might have all activity going on in * asynchronous contexts that cannot page things out. * * If there are applications that are active memory-allocators * (most normal use), this basically shouldn't matter. */ static int kswapd(void *p) { unsigned long order; pg_data_t *pgdat = (pg_data_t*)p; struct task_struct *tsk = current; DEFINE_WAIT(wait); struct reclaim_state reclaim_state = { .reclaimed_slab = 0, }; cpumask_t cpumask; cpumask = node_to_cpumask(pgdat->node_id); if (!cpus_empty(cpumask)) set_cpus_allowed(tsk, cpumask); current->reclaim_state = &reclaim_state; /* * Tell the memory management that we're a "memory allocator", * and that if we need more memory we should get access to it * regardless (see "__alloc_pages()"). "kswapd" should * never get caught in the normal page freeing logic. * * (Kswapd normally doesn't need memory anyway, but sometimes * you need a small amount of memory in order to be able to * page out something else, and this flag essentially protects * us from recursively trying to free more memory as we're * trying to free the first piece of memory in the first place). */ tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD; order = 0; for ( ; ; ) { unsigned long new_order; try_to_freeze(); prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); new_order = pgdat->kswapd_max_order; pgdat->kswapd_max_order = 0; if (order < new_order) { /* * Don't sleep if someone wants a larger 'order' * allocation */ order = new_order; } else { schedule(); order = pgdat->kswapd_max_order; } finish_wait(&pgdat->kswapd_wait, &wait); balance_pgdat(pgdat, order); } return 0; } /* * A zone is low on free memory, so wake its kswapd task to service it. */ void wakeup_kswapd(struct zone *zone, int order) { pg_data_t *pgdat; if (!populated_zone(zone)) return; pgdat = zone->zone_pgdat; if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0)) return; if (pgdat->kswapd_max_order < order) pgdat->kswapd_max_order = order; if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL)) return; if (!waitqueue_active(&pgdat->kswapd_wait)) return; wake_up_interruptible(&pgdat->kswapd_wait); } #ifdef CONFIG_PM /* * Helper function for shrink_all_memory(). Tries to reclaim 'nr_pages' pages * from LRU lists system-wide, for given pass and priority, and returns the * number of reclaimed pages * * For pass > 3 we also try to shrink the LRU lists that contain a few pages */ static unsigned long shrink_all_zones(unsigned long nr_pages, int prio, int pass, struct scan_control *sc) { struct zone *zone; unsigned long nr_to_scan, ret = 0; for_each_zone(zone) { if (!populated_zone(zone)) continue; if (zone->all_unreclaimable && prio != DEF_PRIORITY) continue; /* For pass = 0 we don't shrink the active list */ if (pass > 0) { zone->nr_scan_active += (zone_page_state(zone, NR_ACTIVE) >> prio) + 1; if (zone->nr_scan_active >= nr_pages || pass > 3) { zone->nr_scan_active = 0; nr_to_scan = min(nr_pages, zone_page_state(zone, NR_ACTIVE)); shrink_active_list(nr_to_scan, zone, sc, prio); } } zone->nr_scan_inactive += (zone_page_state(zone, NR_INACTIVE) >> prio) + 1; if (zone->nr_scan_inactive >= nr_pages || pass > 3) { zone->nr_scan_inactive = 0; nr_to_scan = min(nr_pages, zone_page_state(zone, NR_INACTIVE)); ret += shrink_inactive_list(nr_to_scan, zone, sc); if (ret >= nr_pages) return ret; } } return ret; } static unsigned long count_lru_pages(void) { return global_page_state(NR_ACTIVE) + global_page_state(NR_INACTIVE); } /* * Try to free `nr_pages' of memory, system-wide, and return the number of * freed pages. * * Rather than trying to age LRUs the aim is to preserve the overall * LRU order by reclaiming preferentially * inactive > active > active referenced > active mapped */ unsigned long shrink_all_memory(unsigned long nr_pages) { unsigned long lru_pages, nr_slab; unsigned long ret = 0; int pass; struct reclaim_state reclaim_state; struct scan_control sc = { .gfp_mask = GFP_KERNEL, .may_swap = 0, .swap_cluster_max = nr_pages, .may_writepage = 1, .swappiness = vm_swappiness, }; current->reclaim_state = &reclaim_state; lru_pages = count_lru_pages(); nr_slab = global_page_state(NR_SLAB_RECLAIMABLE); /* If slab caches are huge, it's better to hit them first */ while (nr_slab >= lru_pages) { reclaim_state.reclaimed_slab = 0; shrink_slab(nr_pages, sc.gfp_mask, lru_pages); if (!reclaim_state.reclaimed_slab) break; ret += reclaim_state.reclaimed_slab; if (ret >= nr_pages) goto out; nr_slab -= reclaim_state.reclaimed_slab; } /* * We try to shrink LRUs in 5 passes: * 0 = Reclaim from inactive_list only * 1 = Reclaim from active list but don't reclaim mapped * 2 = 2nd pass of type 1 * 3 = Reclaim mapped (normal reclaim) * 4 = 2nd pass of type 3 */ for (pass = 0; pass < 5; pass++) { int prio; /* Force reclaiming mapped pages in the passes #3 and #4 */ if (pass > 2) { sc.may_swap = 1; sc.swappiness = 100; } for (prio = DEF_PRIORITY; prio >= 0; prio--) { unsigned long nr_to_scan = nr_pages - ret; sc.nr_scanned = 0; ret += shrink_all_zones(nr_to_scan, prio, pass, &sc); if (ret >= nr_pages) goto out; reclaim_state.reclaimed_slab = 0; shrink_slab(sc.nr_scanned, sc.gfp_mask, count_lru_pages()); ret += reclaim_state.reclaimed_slab; if (ret >= nr_pages) goto out; if (sc.nr_scanned && prio < DEF_PRIORITY - 2) congestion_wait(WRITE, HZ / 10); } } /* * If ret = 0, we could not shrink LRUs, but there may be something * in slab caches */ if (!ret) { do { reclaim_state.reclaimed_slab = 0; shrink_slab(nr_pages, sc.gfp_mask, count_lru_pages()); ret += reclaim_state.reclaimed_slab; } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0); } out: current->reclaim_state = NULL; return ret; } #endif /* It's optimal to keep kswapds on the same CPUs as their memory, but not required for correctness. So if the last cpu in a node goes away, we get changed to run anywhere: as the first one comes back, restore their cpu bindings. */ static int __devinit cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { pg_data_t *pgdat; cpumask_t mask; if (action == CPU_ONLINE) { for_each_online_pgdat(pgdat) { mask = node_to_cpumask(pgdat->node_id); if (any_online_cpu(mask) != NR_CPUS) /* One of our CPUs online: restore mask */ set_cpus_allowed(pgdat->kswapd, mask); } } return NOTIFY_OK; } /* * This kswapd start function will be called by init and node-hot-add. * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added. */ int kswapd_run(int nid) { pg_data_t *pgdat = NODE_DATA(nid); int ret = 0; if (pgdat->kswapd) return 0; pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid); if (IS_ERR(pgdat->kswapd)) { /* failure at boot is fatal */ BUG_ON(system_state == SYSTEM_BOOTING); printk("Failed to start kswapd on node %d\n",nid); ret = -1; } return ret; } static int __init kswapd_init(void) { int nid; swap_setup(); for_each_online_node(nid) kswapd_run(nid); hotcpu_notifier(cpu_callback, 0); return 0; } module_init(kswapd_init) #ifdef CONFIG_NUMA /* * Zone reclaim mode * * If non-zero call zone_reclaim when the number of free pages falls below * the watermarks. */ int zone_reclaim_mode __read_mostly; #define RECLAIM_OFF 0 #define RECLAIM_ZONE (1<<0) /* Run shrink_cache on the zone */ #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */ #define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */ /* * Priority for ZONE_RECLAIM. This determines the fraction of pages * of a node considered for each zone_reclaim. 4 scans 1/16th of * a zone. */ #define ZONE_RECLAIM_PRIORITY 4 /* * Percentage of pages in a zone that must be unmapped for zone_reclaim to * occur. */ int sysctl_min_unmapped_ratio = 1; /* * If the number of slab pages in a zone grows beyond this percentage then * slab reclaim needs to occur. */ int sysctl_min_slab_ratio = 5; /* * Try to free up some pages from this zone through reclaim. */ static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order) { /* Minimum pages needed in order to stay on node */ const unsigned long nr_pages = 1 << order; struct task_struct *p = current; struct reclaim_state reclaim_state; int priority; unsigned long nr_reclaimed = 0; struct scan_control sc = { .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE), .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP), .swap_cluster_max = max_t(unsigned long, nr_pages, SWAP_CLUSTER_MAX), .gfp_mask = gfp_mask, .swappiness = vm_swappiness, }; unsigned long slab_reclaimable; disable_swap_token(); cond_resched(); /* * We need to be able to allocate from the reserves for RECLAIM_SWAP * and we also need to be able to write out pages for RECLAIM_WRITE * and RECLAIM_SWAP. */ p->flags |= PF_MEMALLOC | PF_SWAPWRITE; reclaim_state.reclaimed_slab = 0; p->reclaim_state = &reclaim_state; if (zone_page_state(zone, NR_FILE_PAGES) - zone_page_state(zone, NR_FILE_MAPPED) > zone->min_unmapped_pages) { /* * Free memory by calling shrink zone with increasing * priorities until we have enough memory freed. */ priority = ZONE_RECLAIM_PRIORITY; do { note_zone_scanning_priority(zone, priority); nr_reclaimed += shrink_zone(priority, zone, &sc); priority--; } while (priority >= 0 && nr_reclaimed < nr_pages); } slab_reclaimable = zone_page_state(zone, NR_SLAB_RECLAIMABLE); if (slab_reclaimable > zone->min_slab_pages) { /* * shrink_slab() does not currently allow us to determine how * many pages were freed in this zone. So we take the current * number of slab pages and shake the slab until it is reduced * by the same nr_pages that we used for reclaiming unmapped * pages. * * Note that shrink_slab will free memory on all zones and may * take a long time. */ while (shrink_slab(sc.nr_scanned, gfp_mask, order) && zone_page_state(zone, NR_SLAB_RECLAIMABLE) > slab_reclaimable - nr_pages) ; /* * Update nr_reclaimed by the number of slab pages we * reclaimed from this zone. */ nr_reclaimed += slab_reclaimable - zone_page_state(zone, NR_SLAB_RECLAIMABLE); } p->reclaim_state = NULL; current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE); return nr_reclaimed >= nr_pages; } int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order) { cpumask_t mask; int node_id; /* * Zone reclaim reclaims unmapped file backed pages and * slab pages if we are over the defined limits. * * A small portion of unmapped file backed pages is needed for * file I/O otherwise pages read by file I/O will be immediately * thrown out if the zone is overallocated. So we do not reclaim * if less than a specified percentage of the zone is used by * unmapped file backed pages. */ if (zone_page_state(zone, NR_FILE_PAGES) - zone_page_state(zone, NR_FILE_MAPPED) <= zone->min_unmapped_pages && zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages) return 0; /* * Avoid concurrent zone reclaims, do not reclaim in a zone that does * not have reclaimable pages and if we should not delay the allocation * then do not scan. */ if (!(gfp_mask & __GFP_WAIT) || zone->all_unreclaimable || atomic_read(&zone->reclaim_in_progress) > 0 || (current->flags & PF_MEMALLOC)) return 0; /* * Only run zone reclaim on the local zone or on zones that do not * have associated processors. This will favor the local processor * over remote processors and spread off node memory allocations * as wide as possible. */ node_id = zone_to_nid(zone); mask = node_to_cpumask(node_id); if (!cpus_empty(mask) && node_id != numa_node_id()) return 0; return __zone_reclaim(zone, gfp_mask, order); } #endif
Java
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { MemoryInputStream::MemoryInputStream (const void* sourceData, size_t sourceDataSize, bool keepCopy) : data (sourceData), dataSize (sourceDataSize) { if (keepCopy) { internalCopy = MemoryBlock (sourceData, sourceDataSize); data = internalCopy.getData(); } } MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData, bool keepCopy) : data (sourceData.getData()), dataSize (sourceData.getSize()) { if (keepCopy) { internalCopy = sourceData; data = internalCopy.getData(); } } MemoryInputStream::MemoryInputStream (MemoryBlock&& source) : internalCopy (std::move (source)) { data = internalCopy.getData(); } MemoryInputStream::~MemoryInputStream() { } int64 MemoryInputStream::getTotalLength() { return (int64) dataSize; } int MemoryInputStream::read (void* buffer, int howMany) { jassert (buffer != nullptr && howMany >= 0); if (howMany <= 0 || position >= dataSize) return 0; auto num = jmin ((size_t) howMany, dataSize - position); if (num > 0) { memcpy (buffer, addBytesToPointer (data, position), num); position += num; } return (int) num; } bool MemoryInputStream::isExhausted() { return position >= dataSize; } bool MemoryInputStream::setPosition (const int64 pos) { position = (size_t) jlimit ((int64) 0, (int64) dataSize, pos); return true; } int64 MemoryInputStream::getPosition() { return (int64) position; } void MemoryInputStream::skipNextBytes (int64 numBytesToSkip) { if (numBytesToSkip > 0) setPosition (getPosition() + numBytesToSkip); } //============================================================================== //============================================================================== #if JUCE_UNIT_TESTS class MemoryStreamTests : public UnitTest { public: MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream", UnitTestCategories::streams) {} void runTest() override { beginTest ("Basics"); Random r = getRandom(); int randomInt = r.nextInt(); int64 randomInt64 = r.nextInt64(); double randomDouble = r.nextDouble(); String randomString (createRandomWideCharString (r)); MemoryOutputStream mo; mo.writeInt (randomInt); mo.writeIntBigEndian (randomInt); mo.writeCompressedInt (randomInt); mo.writeString (randomString); mo.writeInt64 (randomInt64); mo.writeInt64BigEndian (randomInt64); mo.writeDouble (randomDouble); mo.writeDoubleBigEndian (randomDouble); MemoryInputStream mi (mo.getData(), mo.getDataSize(), false); expect (mi.readInt() == randomInt); expect (mi.readIntBigEndian() == randomInt); expect (mi.readCompressedInt() == randomInt); expectEquals (mi.readString(), randomString); expect (mi.readInt64() == randomInt64); expect (mi.readInt64BigEndian() == randomInt64); expect (mi.readDouble() == randomDouble); expect (mi.readDoubleBigEndian() == randomDouble); const MemoryBlock data ("abcdefghijklmnopqrstuvwxyz", 26); MemoryInputStream stream (data, true); beginTest ("Read"); expectEquals (stream.getPosition(), (int64) 0); expectEquals (stream.getTotalLength(), (int64) data.getSize()); expectEquals (stream.getNumBytesRemaining(), stream.getTotalLength()); expect (! stream.isExhausted()); size_t numBytesRead = 0; MemoryBlock readBuffer (data.getSize()); while (numBytesRead < data.getSize()) { numBytesRead += (size_t) stream.read (&readBuffer[numBytesRead], 3); expectEquals (stream.getPosition(), (int64) numBytesRead); expectEquals (stream.getNumBytesRemaining(), (int64) (data.getSize() - numBytesRead)); expect (stream.isExhausted() == (numBytesRead == data.getSize())); } expectEquals (stream.getPosition(), (int64) data.getSize()); expectEquals (stream.getNumBytesRemaining(), (int64) 0); expect (stream.isExhausted()); expect (readBuffer == data); beginTest ("Skip"); stream.setPosition (0); expectEquals (stream.getPosition(), (int64) 0); expectEquals (stream.getTotalLength(), (int64) data.getSize()); expectEquals (stream.getNumBytesRemaining(), stream.getTotalLength()); expect (! stream.isExhausted()); numBytesRead = 0; const int numBytesToSkip = 5; while (numBytesRead < data.getSize()) { stream.skipNextBytes (numBytesToSkip); numBytesRead += numBytesToSkip; numBytesRead = std::min (numBytesRead, data.getSize()); expectEquals (stream.getPosition(), (int64) numBytesRead); expectEquals (stream.getNumBytesRemaining(), (int64) (data.getSize() - numBytesRead)); expect (stream.isExhausted() == (numBytesRead == data.getSize())); } expectEquals (stream.getPosition(), (int64) data.getSize()); expectEquals (stream.getNumBytesRemaining(), (int64) 0); expect (stream.isExhausted()); } static String createRandomWideCharString (Random& r) { juce_wchar buffer [50] = { 0 }; for (int i = 0; i < numElementsInArray (buffer) - 1; ++i) { if (r.nextBool()) { do { buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1)); } while (! CharPointer_UTF16::canRepresent (buffer[i])); } else buffer[i] = (juce_wchar) (1 + r.nextInt (0xff)); } return CharPointer_UTF32 (buffer); } }; static MemoryStreamTests memoryInputStreamUnitTests; #endif } // namespace juce
Java
/* Install given floating-point environment and raise exceptions. Copyright (C) 2000 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by David Huggins-Daines <dhd@debian.org>, 2000 The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <fenv.h> #include <string.h> int feupdateenv (const fenv_t *envp) { union { unsigned long long l; unsigned int sw[2]; } s; fenv_t temp; /* Get the current exception status */ __asm__ ("fstd %%fr0,0(%1) \n\t" "fldd 0(%1),%%fr0 \n\t" : "=m" (s.l) : "r" (&s.l)); memcpy(&temp, envp, sizeof(fenv_t)); /* Currently raised exceptions not cleared */ temp.__status_word |= s.sw[0] & (FE_ALL_EXCEPT << 27); /* Install new environment. */ fesetenv (&temp); /* Success. */ return 0; }
Java
# (c) 2017 - Copyright Red Hat Inc # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # version 2 as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # Authors: # Pierre-Yves Chibon <pingou@pingoured.fr> """This test module contains tests for the migration system.""" import os import subprocess import unittest REPO_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) class TestAlembic(unittest.TestCase): """This test class contains tests pertaining to alembic.""" def test_alembic_history(self): """Enforce a linear alembic history. This test runs the `alembic history | grep ' (head), '` command, and ensure it returns only one line. """ proc1 = subprocess.Popen( ["alembic", "history"], cwd=REPO_PATH, stdout=subprocess.PIPE ) proc2 = subprocess.Popen( ["grep", " (head), "], stdin=proc1.stdout, stdout=subprocess.PIPE ) stdout = proc2.communicate()[0] stdout = stdout.strip().split(b"\n") self.assertEqual(len(stdout), 1) proc1.communicate()
Java
import pybedtools import os testdir = os.path.dirname(__file__) test_tempdir = os.path.join(os.path.abspath(testdir), 'tmp') unwriteable = os.path.join(os.path.abspath(testdir), 'unwriteable') def setup(): if not os.path.exists(test_tempdir): os.system('mkdir -p %s' % test_tempdir) pybedtools.set_tempdir(test_tempdir) def teardown(): if os.path.exists(test_tempdir): os.system('rm -r %s' % test_tempdir) pybedtools.cleanup()
Java
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2006 Donald N. Allingham # # 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$ __all__ = ["LinkBox"] #------------------------------------------------------------------------- # # Standard python modules # #------------------------------------------------------------------------- import logging _LOG = logging.getLogger(".widgets.linkbox") #------------------------------------------------------------------------- # # GTK/Gnome modules # #------------------------------------------------------------------------- from gi.repository import GObject from gi.repository import Gtk #------------------------------------------------------------------------- # # LinkBox class # #------------------------------------------------------------------------- class LinkBox(Gtk.HBox): def __init__(self, link, button): GObject.GObject.__init__(self) self.set_spacing(6) self.pack_start(link, False, True, 0) if button: self.pack_start(button, False, True, 0) self.show()
Java
/* Copyright_License { Top Hat Soaring Glide Computer - http://www.tophatsoaring.org/ Copyright (C) 2000-2016 The Top Hat Soaring Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 "ConditionMonitors.hpp" #include "ConditionMonitorAATTime.hpp" #include "ConditionMonitorFinalGlide.hpp" #include "ConditionMonitorGlideTerrain.hpp" #include "ConditionMonitorLandableReachable.hpp" #include "ConditionMonitorSunset.hpp" #include "ConditionMonitorWind.hpp" static ConditionMonitorWind cm_wind; static ConditionMonitorFinalGlide cm_finalglide; static ConditionMonitorSunset cm_sunset; static ConditionMonitorAATTime cm_aattime; static ConditionMonitorGlideTerrain cm_glideterrain; static ConditionMonitorLandableReachable cm_landablereachable; void ConditionMonitorsUpdate(const NMEAInfo &basic, const DerivedInfo &calculated, const ComputerSettings &settings) { cm_wind.Update(basic, calculated, settings); cm_finalglide.Update(basic, calculated, settings); cm_sunset.Update(basic, calculated, settings); cm_aattime.Update(basic, calculated, settings); cm_glideterrain.Update(basic, calculated, settings); cm_landablereachable.Update(basic, calculated, settings); }
Java
/* * Automatically generated C config: don't edit * Linux/arm 3.0.36 Kernel Configuration */ #define CONFIG_RING_BUFFER 1 #define CONFIG_NF_CONNTRACK_H323 1 #define CONFIG_SCSI_DMA 1 #define CONFIG_SND_RK29_SOC_I2S 1 #define CONFIG_RTC_DRV_WM831X 1 #define CONFIG_INPUT_KEYBOARD 1 #define CONFIG_RFS_ACCEL 1 #define CONFIG_IP_NF_TARGET_REDIRECT 1 #define CONFIG_CRC32 1 #define CONFIG_I2C_BOARDINFO 1 #define CONFIG_NF_NAT_PROTO_SCTP 1 #define CONFIG_HAVE_AOUT 1 #define CONFIG_MFD_WM831X_I2C 1 #define CONFIG_VFP 1 #define CONFIG_IR_JVC_DECODER 1 #define CONFIG_AEABI 1 #define CONFIG_APANIC 1 #define CONFIG_CPU_FREQ_GOV_CONSERVATIVE 1 #define CONFIG_HIGH_RES_TIMERS 1 #define CONFIG_BLK_DEV_DM 1 #define CONFIG_IP_MULTIPLE_TABLES 1 #define CONFIG_FLATMEM_MANUAL 1 #define CONFIG_BT_RFCOMM 1 #define CONFIG_EXT3_DEFAULTS_TO_ORDERED 1 #define CONFIG_HID_ROCCAT_PYRA 1 #define CONFIG_INOTIFY_USER 1 #define CONFIG_NF_CONNTRACK_NETBIOS_NS 1 #define CONFIG_MODULE_FORCE_UNLOAD 1 #define CONFIG_CPU_FREQ_GOV_ONDEMAND 1 #define CONFIG_DEINTERLACE 1 #define CONFIG_EXPERIMENTAL 1 #define CONFIG_PPP_SYNC_TTY 1 #define CONFIG_ARCH_SUSPEND_POSSIBLE 1 #define CONFIG_RC_CORE 1 #define CONFIG_ARM_UNWIND 1 #define CONFIG_HID_ROCCAT_KOVAPLUS 1 #define CONFIG_I2C3_CONTROLLER_RK30 1 #define CONFIG_NETFILTER_XT_MATCH_HELPER 1 #define CONFIG_SSB_POSSIBLE 1 #define CONFIG_NF_NAT_SIP 1 #define CONFIG_MTD_RKNAND 1 #define CONFIG_NETFILTER_XT_MATCH_STATISTIC 1 #define CONFIG_UART3_RK29 1 #define CONFIG_MTD_CMDLINE_PARTS 1 #define CONFIG_NET_SCH_FIFO 1 #define CONFIG_FSNOTIFY 1 #define CONFIG_STP 1 #define CONFIG_MFD_TPS65910 1 #define CONFIG_INET6_TUNNEL 1 #define CONFIG_NF_CONNTRACK_SIP 1 #define CONFIG_CRYPTO_MANAGER_DISABLE_TESTS 1 #define CONFIG_SND_RK29_SOC_RT3261 1 #define CONFIG_HAVE_KERNEL_LZMA 1 #define CONFIG_DEFAULT_SECURITY_DAC 1 #define CONFIG_FIB_RULES 1 #define CONFIG_HID_ACRUX_FF 1 #define CONFIG_VIDEO_RK29_DIGITALZOOM_IPP_ON 1 #define CONFIG_RT_GROUP_SCHED 1 #define CONFIG_HID_EMS_FF 1 #define CONFIG_KTIME_SCALAR 1 #define CONFIG_IP6_NF_MANGLE 1 #define CONFIG_LCDC1_RK30 1 #define CONFIG_IPV6 1 #define CONFIG_USB_SERIAL_QUALCOMM 1 #define CONFIG_CRYPTO_AEAD 1 #define CONFIG_DEFAULT_TCP_CONG "cubic" #define CONFIG_UEVENT_HELPER_PATH "" #define CONFIG_USB_DEVICEFS 1 #define CONFIG_SND_RK29_CODEC_SOC_SLAVE 1 #define CONFIG_DEVTMPFS 1 #define CONFIG_TOUCHSCREEN_GT82X_IIC 1 #define CONFIG_NF_NAT_PROTO_GRE 1 #define CONFIG_ANDROID_BINDER_IPC 1 #define CONFIG_IP6_NF_TARGET_REJECT 1 #define CONFIG_IR_NEC_DECODER 1 #define CONFIG_HOTPLUG_CPU 1 #define CONFIG_WLAN 1 #define CONFIG_DEFAULT_MESSAGE_LOGLEVEL 4 #define CONFIG_HAVE_ARM_SCU 1 #define CONFIG_BLK_DEV_BSG 1 #define CONFIG_I2C0_CONTROLLER_RK30 1 #define CONFIG_NETFILTER_XT_MATCH_QUOTA2_LOG 1 #define CONFIG_I2C2_CONTROLLER_RK30 1 #define CONFIG_SOC_CAMERA_HI704 1 #define CONFIG_XFRM_IPCOMP 1 #define CONFIG_CRYPTO_RNG2 1 #define CONFIG_NETFILTER_NETLINK_QUEUE 1 #define CONFIG_TUN 1 #define CONFIG_BATTERY_RK30_AC_CHARGE 1 #define CONFIG_FIQ_DEBUGGER_CONSOLE 1 #define CONFIG_TREE_PREEMPT_RCU 1 #define CONFIG_DM_CRYPT 1 #define CONFIG_HAVE_PROC_CPU 1 #define CONFIG_HID_BELKIN 1 #define CONFIG_VIDEO_IR_I2C 1 #define CONFIG_SND_RK_SOC_I2S2_2CH 1 #define CONFIG_WIRELESS_EXT_SYSFS 1 #define CONFIG_USB_SERIAL_OPTION 1 #define CONFIG_HID_ACRUX 1 #define CONFIG_BT_AUTOSLEEP 1 #define CONFIG_USB 1 #define CONFIG_SWITCH_GPIO 1 #define CONFIG_CRYPTO_HMAC 1 #define CONFIG_HID_ROCCAT_KONEPLUS 1 #define CONFIG_BP_AUTO_MT6229 1 #define CONFIG_BRANCH_PROFILE_NONE 1 #define CONFIG_IP6_NF_TARGET_LOG 1 #define CONFIG_IP_NF_ARPTABLES 1 #define CONFIG_USB_SERIAL_GENERIC 1 #define CONFIG_HID_CHERRY 1 #define CONFIG_I2C0_RK30 1 #define CONFIG_HID_SUNPLUS 1 #define CONFIG_HID_PICOLCD 1 #define CONFIG_BCMA_POSSIBLE 1 #define CONFIG_FORCE_MAX_ZONEORDER 11 #define CONFIG_SND_SOC 1 #define CONFIG_CAN_PM_TRACE 1 #define CONFIG_MEDIA_TUNER_XC5000_MODULE 1 #define CONFIG_I2C3_RK30 1 #define CONFIG_PRINTK 1 #define CONFIG_FIQ_GLUE 1 #define CONFIG_NF_CONNTRACK_PROC_COMPAT 1 #define CONFIG_WIFI_CONTROL_FUNC 1 #define CONFIG_TIMERFD 1 #define CONFIG_HID_THRUSTMASTER 1 #define CONFIG_RK_PL330_DMA 1 #define CONFIG_TRACEPOINTS 1 #define CONFIG_MTD_CFI_I2 1 #define CONFIG_CRYPTO_AUTHENC 1 #define CONFIG_NET_EMATCH_STACK 32 #define CONFIG_BOUNCE 1 #define CONFIG_SHMEM 1 #define CONFIG_MIGRATION 1 #define CONFIG_MTD 1 #define CONFIG_MMC_BLOCK_MINORS 8 #define CONFIG_DWC_CONN_EN 1 #define CONFIG_DEVTMPFS_MOUNT 1 #define CONFIG_CRYPTO_DES 1 #define CONFIG_ENABLE_MUST_CHECK 1 #define CONFIG_NLS_CODEPAGE_437 1 #define CONFIG_MTD_NAND_IDS 1 #define CONFIG_NET_CLS_U32 1 #define CONFIG_FIQ_DEBUGGER 1 #define CONFIG_SOC_CAMERA_GT2005 1 #define CONFIG_ARM_GIC 1 #define CONFIG_SERIO 1 #define CONFIG_SCHEDSTATS 1 #define CONFIG_RTC_INTF_SYSFS 1 #define CONFIG_NET_EMATCH_U32 1 #define CONFIG_BLK_DEV_INITRD 1 #define CONFIG_COMPASS_AK8975 1 #define CONFIG_REGULATOR_WM831X 1 #define CONFIG_NF_CONNTRACK_SANE 1 #define CONFIG_NF_CT_PROTO_DCCP 1 #define CONFIG_ZLIB_INFLATE 1 #define CONFIG_MEDIA_TUNER_QT1010_MODULE 1 #define CONFIG_GPIO_WM831X 1 #define CONFIG_USB_G_ANDROID 1 #define CONFIG_ARM_ERRATA_764369 1 #define CONFIG_CRYPTO_TWOFISH_COMMON 1 #define CONFIG_LOGO_LINUX_CLUT224 1 #define CONFIG_RTC_INTF_PROC 1 #define CONFIG_CPU_IDLE_GOV_MENU 1 #define CONFIG_STACKTRACE_SUPPORT 1 #define CONFIG_USB_DEVICE_CLASS 1 #define CONFIG_ANDROID_TIMED_GPIO 1 #define CONFIG_ARM 1 #define CONFIG_ARM_L1_CACHE_SHIFT 5 #define CONFIG_BT_RFCOMM_TTY 1 #define CONFIG_DISPLAY_SUPPORT 1 #define CONFIG_VIDEO_RK29_WORK_IPP 1 #define CONFIG_NETFILTER_XT_MATCH_STRING 1 #define CONFIG_INPUT_TABLET 1 #define CONFIG_IP_NF_TARGET_LOG 1 #define CONFIG_MEDIA_TUNER_MAX2165_MODULE 1 #define CONFIG_HAS_WAKELOCK 1 #define CONFIG_LOGO 1 #define CONFIG_USB_STORAGE 1 #define CONFIG_STANDALONE 1 #define CONFIG_CPU_FREQ_GOV_PERFORMANCE 1 #define CONFIG_IR_LIRC_CODEC 1 #define CONFIG_THREE_FB_BUFFER 1 #define CONFIG_MMC_EMBEDDED_SDIO 1 #define CONFIG_ARCH_HAS_CPUFREQ 1 #define CONFIG_I2C1_CONTROLLER_RK30 1 #define CONFIG_I2C2_RK30 1 #define CONFIG_ASHMEM 1 #define CONFIG_BLOCK 1 #define CONFIG_HAVE_IDE 1 #define CONFIG_HID_APPLE 1 #define CONFIG_MEDIA_TUNER_TDA827X_MODULE 1 #define CONFIG_INIT_ENV_ARG_LIMIT 32 #define CONFIG_IP_NF_ARP_MANGLE 1 #define CONFIG_GENERIC_GPIO 1 #define CONFIG_NF_CONNTRACK_PPTP 1 #define CONFIG_BUG 1 #define CONFIG_CONTEXT_SWITCH_TRACER 1 #define CONFIG_SND_I2S_DMA_EVENT_STATIC 1 #define CONFIG_PANTHERLORD_FF 1 #define CONFIG_PM 1 #define CONFIG_NF_CONNTRACK_IRC 1 #define CONFIG_SWITCH 1 #define CONFIG_DEVKMEM 1 #define CONFIG_PPP_DEFLATE 1 #define CONFIG_TEXTSEARCH_KMP 1 #define CONFIG_RK_SN 1 #define CONFIG_VT 1 #define CONFIG_USB_NET_NET1080 1 #define CONFIG_NETFILTER_XT_TARGET_CLASSIFY 1 #define CONFIG_SPLIT_PTLOCK_CPUS 4 #define CONFIG_BT_SCO 1 #define CONFIG_POWER_SUPPLY 1 #define CONFIG_CPU_CACHE_VIPT 1 #define CONFIG_NETFILTER_XT_TARGET_NFQUEUE 1 #define CONFIG_V4L_USB_DRIVERS 1 #define CONFIG_WEXT_CORE 1 #define CONFIG_NLS 1 #define CONFIG_USB_GADGET_DWC_OTG 1 #define CONFIG_HID_MAGICMOUSE 1 #define CONFIG_MFD_SUPPORT 1 #define CONFIG_IP_ADVANCED_ROUTER 1 #define CONFIG_ENABLE_WARN_DEPRECATED 1 #define CONFIG_MEDIA_TUNER_TDA18271_MODULE 1 #define CONFIG_IP6_NF_IPTABLES 1 #define CONFIG_CPU_FREQ_GOV_USERSPACE 1 #define CONFIG_EVENT_TRACING 1 #define CONFIG_HID_KEYTOUCH 1 #define CONFIG_HID_CYPRESS 1 #define CONFIG_NLS_ISO8859_1 1 #define CONFIG_CRYPTO_WORKQUEUE 1 #define CONFIG_HID_KENSINGTON 1 #define CONFIG_CPU_FREQ_TABLE 1 #define CONFIG_TEXTSEARCH_BM 1 #define CONFIG_BT_HCIUART_LL 1 #define CONFIG_HID_ZYDACRON 1 #define CONFIG_PPP_MPPE 1 #define CONFIG_INPUT_KEYRESET 1 #define CONFIG_USB_NET_SR9700 1 #define CONFIG_RFKILL 1 #define CONFIG_NETDEVICES 1 #define CONFIG_NET_KEY 1 #define CONFIG_IOSCHED_DEADLINE 1 #define CONFIG_USB_SERIAL_USI 1 #define CONFIG_CGROUP_FREEZER 1 #define CONFIG_CPU_TLB_V7 1 #define CONFIG_EVENTFD 1 #define CONFIG_IPV6_SIT 1 #define CONFIG_XFRM 1 #define CONFIG_DEFCONFIG_LIST "/lib/modules/$UNAME_RELEASE/.config" #define CONFIG_IPV6_MULTIPLE_TABLES 1 #define CONFIG_USB_ANNOUNCE_NEW_DEVICES 1 #define CONFIG_IP_NF_TARGET_MASQUERADE 1 #define CONFIG_NF_CONNTRACK_BROADCAST 1 #define CONFIG_IR_RC5_SZ_DECODER 1 #define CONFIG_PROC_PAGE_MONITOR 1 #define CONFIG_NF_NAT_PROTO_DCCP 1 #define CONFIG_USB_VIDEO_CLASS_INPUT_EVDEV 1 #define CONFIG_SDMMC0_RK29_SDCARD_DET_FROM_GPIO 1 #define CONFIG_ANDROID_LOW_MEMORY_KILLER 1 #define CONFIG_ARCH_HAS_CPU_IDLE_WAIT 1 #define CONFIG_GREENASIA_FF 1 #define CONFIG_SND_RK29_SOC_I2S_8CH 1 #define CONFIG_SOC_CAMERA_HI253 1 #define CONFIG_PHONET 1 #define CONFIG_SCSI_WAIT_SCAN_MODULE 1 #define CONFIG_BACKLIGHT_CLASS_DEVICE 1 #define CONFIG_NF_DEFRAG_IPV4 1 #define CONFIG_SELECT_MEMORY_MODEL 1 #define CONFIG_HID_LCPOWER 1 #define CONFIG_MMC_UNSAFE_RESUME 1 #define CONFIG_HAVE_ARCH_PFN_VALID 1 #define CONFIG_CPU_COPY_V6 1 #define CONFIG_PM_DEBUG 1 #define CONFIG_NETFILTER_ADVANCED 1 #define CONFIG_CRYPTO_DEFLATE 1 #define CONFIG_IPV6_ROUTER_PREF 1 #define CONFIG_SPI_FPGA_GPIO_NUM 0 #define CONFIG_NETFILTER_NETLINK_LOG 1 #define CONFIG_HAVE_DYNAMIC_FTRACE 1 #define CONFIG_MAGIC_SYSRQ 1 #define CONFIG_VIDEO_RKCIF_WORK_ONEFRAME 1 #define CONFIG_NETFILTER_XT_MATCH_MARK 1 #define CONFIG_HAVE_ARM_TWD 1 #define CONFIG_IP_NF_MANGLE 1 #define CONFIG_DEFAULT_CFQ 1 #define CONFIG_DUAL_LCDC_DUAL_DISP_IN_KERNEL 1 #define CONFIG_INET6_XFRM_MODE_TUNNEL 1 #define CONFIG_MEDIA_SUPPORT 1 #define CONFIG_DEBUG_BUGVERBOSE 1 #define CONFIG_IP_NF_FILTER 1 #define CONFIG_HID_ZEROPLUS 1 #define CONFIG_EXT3_FS 1 #define CONFIG_NETFILTER_XT_MATCH_LENGTH 1 #define CONFIG_FAT_FS 1 #define CONFIG_TEXTSEARCH_FSM 1 #define CONFIG_HIGHMEM 1 #define CONFIG_IP6_NF_RAW 1 #define CONFIG_INET_TUNNEL 1 #define CONFIG_WM8326_VBAT_LOW_DETECTION 1 #define CONFIG_MMC_BLOCK_BOUNCE 1 #define CONFIG_GENERIC_CLOCKEVENTS 1 #define CONFIG_IOSCHED_CFQ 1 #define CONFIG_MFD_CORE 1 #define CONFIG_CPU_CP15_MMU 1 #define CONFIG_STOP_MACHINE 1 #define CONFIG_CPU_FREQ 1 #define CONFIG_USB_GSPCA_MODULE 1 #define CONFIG_DUMMY_CONSOLE 1 #define CONFIG_NLS_ASCII 1 #define CONFIG_SDMMC0_RK29 1 #define CONFIG_TRACE_IRQFLAGS_SUPPORT 1 #define CONFIG_USB_NET_CDC_SUBSET 1 #define CONFIG_NETFILTER_XT_MATCH_CONNMARK 1 #define CONFIG_SND_USB 1 #define CONFIG_LOGIG940_FF 1 #define CONFIG_RD_GZIP 1 #define CONFIG_HAVE_REGS_AND_STACK_ACCESS_API 1 #define CONFIG_THRUSTMASTER_FF 1 #define CONFIG_LBDAF 1 #define CONFIG_BP_AUTO 1 #define CONFIG_HID_ROCCAT 1 #define CONFIG_INET_XFRM_MODE_TRANSPORT 1 #define CONFIG_CRYPTO_MD5 1 #define CONFIG_MEDIA_TUNER_TEA5767_MODULE 1 #define CONFIG_HAVE_GENERIC_HARDIRQS 1 #define CONFIG_BINFMT_ELF 1 #define CONFIG_SCSI_PROC_FS 1 #define CONFIG_HOTPLUG 1 #define CONFIG_INET6_AH 1 #define CONFIG_CPU_CP15 1 #define CONFIG_USB_SERIAL 1 #define CONFIG_I2C_RK30 1 #define CONFIG_NETFILTER_XT_MARK 1 #define CONFIG_NETFILTER_XTABLES 1 #define CONFIG_RESOURCE_COUNTERS 1 #define CONFIG_SOC_CAMERA_GC0308 1 #define CONFIG_PM_SLEEP_SMP 1 #define CONFIG_CRYPTO_HW 1 #define CONFIG_ION 1 #define CONFIG_HID_GREENASIA 1 #define CONFIG_EXPANDED_GPIO_IRQ_NUM 0 #define CONFIG_HARDIRQS_SW_RESEND 1 #define CONFIG_BACKLIGHT_RK29_BL 1 #define CONFIG_HID_ROCCAT_COMMON 1 #define CONFIG_NET_ACT_GACT 1 #define CONFIG_HID_GYRATION 1 #define CONFIG_MACH_RK3066_SDK 1 #define CONFIG_VIDEO_RKCIF_WORK_SIMUL_OFF 1 #define CONFIG_NETFILTER_XT_TARGET_TPROXY 1 #define CONFIG_EARLYSUSPEND 1 #define CONFIG_USB_ACM 1 #define CONFIG_CRC16 1 #define CONFIG_USB_NET_AX8817X 1 #define CONFIG_GENERIC_CALIBRATE_DELAY 1 #define CONFIG_NET_CLS 1 #define CONFIG_CPU_HAS_PMU 1 #define CONFIG_ARCH_REQUIRE_GPIOLIB 1 #define CONFIG_TMPFS 1 #define CONFIG_LS_ISL29023 1 #define CONFIG_ANON_INODES 1 #define CONFIG_SUSPEND_SYNC_WORKQUEUE 1 #define CONFIG_FUTEX 1 #define CONFIG_JOYSTICK_XPAD_FF 1 #define CONFIG_VMSPLIT_3G 1 #define CONFIG_RTC_HCTOSYS 1 #define CONFIG_LCDC_RK30 1 #define CONFIG_USB_HID 1 #define CONFIG_RTL8192CU 1 #define CONFIG_ANDROID 1 #define CONFIG_NET_SCH_INGRESS 1 #define CONFIG_RK29_VPU_MODULE 1 #define CONFIG_NF_CONNTRACK_EVENTS 1 #define CONFIG_IPV6_NDISC_NODETYPE 1 #define CONFIG_CGROUP_SCHED 1 #define CONFIG_CRYPTO_PCOMP2 1 #define CONFIG_NF_CONNTRACK_FTP 1 #define CONFIG_MODULES 1 #define CONFIG_IP_NF_MATCH_ECN 1 #define CONFIG_CPU_HAS_ASID 1 #define CONFIG_USB_GADGET 1 #define CONFIG_MEDIA_TUNER_MXL5005S_MODULE 1 #define CONFIG_SOUND 1 #define CONFIG_MEDIA_TUNER_TDA9887_MODULE 1 #define CONFIG_UNIX 1 #define CONFIG_HAVE_CLK 1 #define CONFIG_CRYPTO_HASH2 1 #define CONFIG_DEFAULT_HOSTNAME "(none)" #define CONFIG_CPU_FREQ_GOV_POWERSAVE 1 #define CONFIG_XPS 1 #define CONFIG_INET_ESP 1 #define CONFIG_HID_QUANTA 1 #define CONFIG_NF_CONNTRACK_IPV6 1 #define CONFIG_MD 1 #define CONFIG_CRYPTO_ALGAPI 1 #define CONFIG_RK_HDMI_CTL_CODEC 1 #define CONFIG_BRIDGE 1 #define CONFIG_MEDIA_TUNER 1 #define CONFIG_TABLET_USB_GTCO 1 #define CONFIG_MISC_DEVICES 1 #define CONFIG_INPUT_UINPUT 1 #define CONFIG_MEDIA_TUNER_SIMPLE_MODULE 1 #define CONFIG_UART0_DMA_RK29 0 #define CONFIG_MTD_CFI_I1 1 #define CONFIG_NF_NAT 1 #define CONFIG_CPU_IDLE 1 #define CONFIG_DWC_OTG_BOTH_HOST_SLAVE 1 #define CONFIG_REGULATOR 1 #define CONFIG_FAIR_GROUP_SCHED 1 #define CONFIG_RK_HEADSET_IRQ_HOOK_ADC_DET 1 #define CONFIG_SND_RK29_SOC 1 #define CONFIG_CRYPTO_HASH 1 #define CONFIG_EFI_PARTITION 1 #define CONFIG_GS_MMA7660 1 #define CONFIG_LOG_BUF_SHIFT 19 #define CONFIG_SOC_CAMERA_GC2035 1 #define CONFIG_EXTRA_FIRMWARE "" #define CONFIG_CACHE_L2X0 1 #define CONFIG_CPU_FREQ_GOV_INTERACTIVE 1 #define CONFIG_VIRT_TO_BUS 1 #define CONFIG_VFAT_FS 1 #define CONFIG_UART1_CTS_RTS_RK29 1 #define CONFIG_CPU_RMAP 1 #define CONFIG_BLK_DEV_LOOP 1 #define CONFIG_WAKELOCK 1 #define CONFIG_NF_NAT_IRC 1 #define CONFIG_MEDIA_TUNER_CUSTOMISE 1 #define CONFIG_MEDIA_TUNER_XC2028_MODULE 1 #define CONFIG_INPUT_MISC 1 #define CONFIG_CPU_PABRT_V7 1 #define CONFIG_SOC_CAMERA 1 #define CONFIG_SUSPEND 1 #define CONFIG_CRYPTO_CBC 1 #define CONFIG_DDR_TYPE_DDR3_DEFAULT 1 #define CONFIG_UART1_RK29 1 #define CONFIG_RTC_CLASS 1 #define CONFIG_USB20_HOST 1 #define CONFIG_CPU_PM 1 #define CONFIG_HDMI_RK30 1 #define CONFIG_ARCH_RK30 1 #define CONFIG_HAVE_FUNCTION_TRACER 1 #define CONFIG_NF_NAT_TFTP 1 #define CONFIG_OUTER_CACHE 1 #define CONFIG_EXPANDED_GPIO_NUM 0 #define CONFIG_CPU_CACHE_V7 1 #define CONFIG_ZEROPLUS_FF 1 #define CONFIG_CRYPTO_MANAGER2 1 #define CONFIG_USB_GADGET_VBUS_DRAW 2 #define CONFIG_DRAGONRISE_FF 1 #define CONFIG_SLUB 1 #define CONFIG_PM_SLEEP 1 #define CONFIG_I2C 1 #define CONFIG_PPP_MULTILINK 1 #define CONFIG_ES603_PROTOCOL_DRIVER 1 #define CONFIG_UART1_DMA_RK29 0 #define CONFIG_BT_HIDP 1 #define CONFIG_RK_EARLY_PRINTK 1 #define CONFIG_CPU_ABRT_EV7 1 #define CONFIG_WLAN_80211 1 #define CONFIG_VM_EVENT_COUNTERS 1 #define CONFIG_CRYPTO_ECB 1 #define CONFIG_NF_CONNTRACK_AMANDA 1 #define CONFIG_DEBUG_FS 1 #define CONFIG_UART3_CTS_RTS_RK29 1 #define CONFIG_BASE_FULL 1 #define CONFIG_FB_CFB_IMAGEBLIT 1 #define CONFIG_ZLIB_DEFLATE 1 #define CONFIG_GPIO_SYSFS 1 #define CONFIG_FW_LOADER 1 #define CONFIG_KALLSYMS 1 #define CONFIG_RTC_HCTOSYS_DEVICE "rtc0" #define CONFIG_NETFILTER_XT_MATCH_PKTTYPE 1 #define CONFIG_MII 1 #define CONFIG_SIGNALFD 1 #define CONFIG_IP_NF_TARGET_REJECT_SKERR 1 #define CONFIG_SOC_CAMERA_SP0838 1 #define CONFIG_EXT4_FS 1 #define CONFIG_CRYPTO_SHA1 1 #define CONFIG_ARM_DMA_MEM_BUFFERABLE 1 #define CONFIG_SUSPEND_TIME 1 #define CONFIG_IPV6_PRIVACY 1 #define CONFIG_USB_BELKIN 1 #define CONFIG_USB_GADGET_DUALSPEED 1 #define CONFIG_HAS_IOMEM 1 #define CONFIG_PPPOPNS 1 #define CONFIG_KERNEL_LZO 1 #define CONFIG_GENERIC_IRQ_PROBE 1 #define CONFIG_IP_NF_MATCH_TTL 1 #define CONFIG_NETFILTER_XT_TARGET_TRACE 1 #define CONFIG_MTD_MAP_BANK_WIDTH_1 1 #define CONFIG_EPOLL 1 #define CONFIG_SND_PCM 1 #define CONFIG_PM_RUNTIME 1 #define CONFIG_PARTITION_ADVANCED 1 #define CONFIG_RK30_I2C_INSRAM 1 #define CONFIG_IR_SONY_DECODER 1 #define CONFIG_NETFILTER_XT_MATCH_COMMENT 1 #define CONFIG_NET 1 #define CONFIG_INPUT_EVDEV 1 #define CONFIG_SND_JACK 1 #define CONFIG_HAVE_SPARSE_IRQ 1 #define CONFIG_TABLET_USB_WACOM 1 #define CONFIG_HID_DRAGONRISE 1 #define CONFIG_NETFILTER_XT_MATCH_CONNTRACK 1 #define CONFIG_MMC_PARANOID_SD_INIT 1 #define CONFIG_VFPv3 1 #define CONFIG_RFKILL_RK 1 #define CONFIG_USB_NET_CDCETHER 1 #define CONFIG_PACKET 1 #define CONFIG_NETFILTER_XT_MATCH_IPRANGE 1 #define CONFIG_RK30_PWM_REGULATOR 1 #define CONFIG_NF_CONNTRACK_TFTP 1 #define CONFIG_NOP_TRACER 1 #define CONFIG_BACKLIGHT_LCD_SUPPORT 1 #define CONFIG_INET 1 #define CONFIG_PREVENT_FIRMWARE_BUILD 1 #define CONFIG_CRYPTO_TWOFISH 1 #define CONFIG_FREEZER 1 #define CONFIG_BT 1 #define CONFIG_RFKILL_PM 1 #define CONFIG_NET_CLS_ACT 1 #define CONFIG_I2C4_RK30 1 #define CONFIG_HID_WACOM 1 #define CONFIG_RTC_LIB 1 #define CONFIG_NETFILTER_XT_MATCH_POLICY 1 #define CONFIG_HAVE_KPROBES 1 #define CONFIG_CRYPTO_AES 1 #define CONFIG_BATTERY_RK30_ADC_FAC 1 #define CONFIG_GPIOLIB 1 #define CONFIG_EXT4_USE_FOR_EXT23 1 #define CONFIG_BT_HCIUART_H4 1 #define CONFIG_HID_WALTOP 1 #define CONFIG_IP6_NF_TARGET_REJECT_SKERR 1 #define CONFIG_NF_CONNTRACK_MARK 1 #define CONFIG_NETFILTER 1 #define CONFIG_NETFILTER_XT_MATCH_HASHLIMIT 1 #define CONFIG_SENSOR_DEVICE 1 #define CONFIG_USE_GENERIC_SMP_HELPERS 1 #define CONFIG_DVFS 1 #define CONFIG_DWC_OTG 1 #define CONFIG_SERIO_SERPORT 1 #define CONFIG_LIRC 1 #define CONFIG_BT_BNEP 1 #define CONFIG_FB_ROCKCHIP 1 #define CONFIG_INET_XFRM_MODE_TUNNEL 1 #define CONFIG_FIQ_DEBUGGER_CONSOLE_DEFAULT_ENABLE 1 #define CONFIG_PREEMPT_RCU 1 #define CONFIG_NF_NAT_NEEDED 1 #define CONFIG_SERIAL_RK29 1 #define CONFIG_GS_MMA8452 1 #define CONFIG_MEDIA_TUNER_MT2266_MODULE 1 #define CONFIG_LOCKDEP_SUPPORT 1 #define CONFIG_NO_HZ 1 #define CONFIG_RTC_INTF_ALARM 1 #define CONFIG_RK_BOARD_ID 1 #define CONFIG_CPU_FREQ_STAT 1 #define CONFIG_SND_SOC_RT3261 1 #define CONFIG_MTD_BLKDEVS 1 #define CONFIG_VIDEO_CAPTURE_DRIVERS 1 #define CONFIG_INET6_ESP 1 #define CONFIG_BT_HCIBCM4325 1 #define CONFIG_IP6_NF_FILTER 1 #define CONFIG_NEED_DMA_MAP_STATE 1 #define CONFIG_NETFILTER_XT_MATCH_CONNBYTES 1 #define CONFIG_ANDROID_PARANOID_NETWORK 1 #define CONFIG_PAGE_OFFSET 0xC0000000 #define CONFIG_CPU_V7 1 #define CONFIG_GS_LIS3DH 1 #define CONFIG_HID_TWINHAN 1 #define CONFIG_PANIC_TIMEOUT 1 #define CONFIG_ZBOOT_ROM_BSS 0x0 #define CONFIG_INPUT_JOYSTICK 1 #define CONFIG_USB20_HOST_EN 1 #define CONFIG_SMP 1 #define CONFIG_NETFILTER_XT_MATCH_TIME 1 #define CONFIG_HAVE_KERNEL_GZIP 1 #define CONFIG_DM_UEVENT 1 #define CONFIG_NETFILTER_XT_MATCH_MAC 1 #define CONFIG_NETFILTER_XT_TARGET_NFLOG 1 #define CONFIG_GENERIC_ALLOCATOR 1 #define CONFIG_ANDROID_TIMED_OUTPUT 1 #define CONFIG_LIBCRC32C 1 #define CONFIG_CRYPTO_SHA256 1 #define CONFIG_HAVE_FTRACE_MCOUNT_RECORD 1 #define CONFIG_INET_TCP_DIAG 1 #define CONFIG_HID_SONY 1 #define CONFIG_HW_CONSOLE 1 #define CONFIG_DEVMEM 1 #define CONFIG_HID_MONTEREY 1 #define CONFIG_HID_EZKEY 1 #define CONFIG_IOSCHED_NOOP 1 #define CONFIG_LCD_MR13 1 #define CONFIG_JOYSTICK_XPAD_LEDS 1 #define CONFIG_NEON 1 #define CONFIG_DEBUG_KERNEL 1 #define CONFIG_ARCH_RK30XX 1 #define CONFIG_COMPAT_BRK 1 #define CONFIG_LOCALVERSION "+" #define CONFIG_RADIO_ADAPTERS 1 #define CONFIG_MACH_NO_WESTBRIDGE 1 #define CONFIG_DDR_TEST 1 #define CONFIG_CRYPTO 1 #define CONFIG_I2C4_CONTROLLER_RK30 1 #define CONFIG_MTD_RKNAND_BUFFER 1 #define CONFIG_LEDS_GPIO_PLATFORM 1 #define CONFIG_DEFAULT_MMAP_MIN_ADDR 32768 #define CONFIG_MEDIA_TUNER_TDA18218_MODULE 1 #define CONFIG_IP_NF_IPTABLES 1 #define CONFIG_CMDLINE "console=ttyFIQ0 androidboot.console=ttyFIQ0 init=/init" #define CONFIG_HAVE_DMA_API_DEBUG 1 #define CONFIG_REGULATOR_TPS65910 1 #define CONFIG_HID_SAMSUNG 1 #define CONFIG_USB_ARCH_HAS_HCD 1 #define CONFIG_GENERIC_IRQ_SHOW 1 #define CONFIG_IPV6_OPTIMISTIC_DAD 1 #define CONFIG_ALIGNMENT_TRAP 1 #define CONFIG_SCSI_MOD 1 #define CONFIG_CRYPTO_CRC32C 1 #define CONFIG_SERIAL_CORE 1 #define CONFIG_FUSE_FS 1 #define CONFIG_UID16 1 #define CONFIG_EMBEDDED 1 #define CONFIG_HID_MICROSOFT 1 #define CONFIG_HAVE_KRETPROBES 1 #define CONFIG_NF_DEFRAG_IPV6 1 #define CONFIG_VIDEO_DEV 1 #define CONFIG_MFD_WM831X 1 #define CONFIG_PPP_FILTER 1 #define CONFIG_HAS_DMA 1 #define CONFIG_NF_CT_PROTO_SCTP 1 #define CONFIG_BT_L2CAP 1 #define CONFIG_SCSI 1 #define CONFIG_FB_CFB_FILLRECT 1 #define CONFIG_NF_NAT_PPTP 1 #define CONFIG_HID_CHICONY 1 #define CONFIG_HID 1 #define CONFIG_LOGIWII_FF 1 #define CONFIG_USB_ARMLINUX 1 #define CONFIG_CLKDEV_LOOKUP 1 #define CONFIG_KEYS_RK29 1 #define CONFIG_MEDIA_TUNER_TDA8290_MODULE 1 #define CONFIG_MEDIA_TUNER_TDA18212_MODULE 1 #define CONFIG_JBD2 1 #define CONFIG_LCDC0_RK30 1 #define CONFIG_INET6_IPCOMP 1 #define CONFIG_PHYLIB 1 #define CONFIG_IPV6_TUNNEL 1 #define CONFIG_MEDIA_TUNER_MT20XX_MODULE 1 #define CONFIG_FTRACE 1 #define CONFIG_NETFILTER_XT_MATCH_CONNLIMIT 1 #define CONFIG_IP_NF_RAW 1 #define CONFIG_IP_NF_ARPFILTER 1 #define CONFIG_MIGHT_HAVE_CACHE_L2X0 1 #define CONFIG_NETFILTER_XT_MATCH_SOCKET 1 #define CONFIG_HID_TOPSEED 1 #define CONFIG_CLK_SWITCH_TO_32K 1 #define CONFIG_NF_NAT_H323 1 #define CONFIG_HID_A4TECH 1 #define CONFIG_MEDIA_TUNER_MC44S803_MODULE 1 #define CONFIG_BP_AUTO_MU509 1 #define CONFIG_IP_NF_TARGET_NETMAP 1 #define CONFIG_RCU_CPU_STALL_TIMEOUT 60 #define CONFIG_SPI_FPGA_GPIO_IRQ_NUM 0 #define CONFIG_INPUT_FF_MEMLESS 1 #define CONFIG_SOC_RK3066 1 #define CONFIG_UART0_CTS_RTS_RK29 1 #define CONFIG_NF_NAT_AMANDA 1 #define CONFIG_CACHE_PL310 1 #define CONFIG_INET6_XFRM_MODE_TRANSPORT 1 #define CONFIG_CRYPTO_ARC4 1 #define CONFIG_SLHC 1 #define CONFIG_HAVE_SMP 1 #define CONFIG_RGA_RK30 1 #define CONFIG_CRYPTO_MANAGER 1 #define CONFIG_NET_SCH_HTB 1 #define CONFIG_PPP_BSDCOMP 1 #define CONFIG_RT_MUTEXES 1 #define CONFIG_VECTORS_BASE 0xffff0000 #define CONFIG_HID_ORTEK 1 #define CONFIG_NETFILTER_XT_TARGET_MARK 1 #define CONFIG_MEDIA_TUNER_MXL5007T_MODULE 1 #define CONFIG_MMC_BLOCK 1 #define CONFIG_EXPERT 1 #define CONFIG_WIRELESS 1 #define CONFIG_WEXT_PROC 1 #define CONFIG_PERF_USE_VMALLOC 1 #define CONFIG_FAT_DEFAULT_IOCHARSET "iso8859-1" #define CONFIG_FRAME_WARN 1024 #define CONFIG_USB_NET_CDC_NCM 1 #define CONFIG_RCU_CPU_STALL_VERBOSE 1 #define CONFIG_GENERIC_HWEIGHT 1 #define CONFIG_INITRAMFS_SOURCE "" #define CONFIG_GYRO_L3G4200D 1 #define CONFIG_CGROUPS 1 #define CONFIG_MMC 1 #define CONFIG_SDMMC1_RK29 1 #define CONFIG_HID_LOGITECH 1 #define CONFIG_RK_CLOCK_PROC 1 #define CONFIG_STACKTRACE 1 #define CONFIG_PPPOLAC 1 #define CONFIG_APANIC_PLABEL "kpanic" #define CONFIG_VIDEO_RK29 1 #define CONFIG_NETFILTER_XT_TARGET_IDLETIMER 1 #define CONFIG_UART0_RK29 1 #define CONFIG_HAS_IOPORT 1 #define CONFIG_VIDEOBUF_DMA_CONTIG 1 #define CONFIG_CGROUP_CPUACCT 1 #define CONFIG_FB_EARLYSUSPEND 1 #define CONFIG_HZ 100 #define CONFIG_USB20_OTG_EN 1 #define CONFIG_I2C_HELPER_AUTO 1 #define CONFIG_NETFILTER_XT_MATCH_U32 1 #define CONFIG_COMPASS_DEVICE 1 #define CONFIG_GENERIC_LOCKBREAK 1 #define CONFIG_DEFAULT_IOSCHED "cfq" #define CONFIG_TABLET_USB_KBTAB 1 #define CONFIG_IPV6_MIP6 1 #define CONFIG_RK29_IPP_MODULE 1 #define CONFIG_NLATTR 1 #define CONFIG_TCP_CONG_CUBIC 1 #define CONFIG_PM_RUNTIME_CLK 1 #define CONFIG_NR_CPUS 2 #define CONFIG_SUSPEND_FREEZER 1 #define CONFIG_NETFILTER_XT_CONNMARK 1 #define CONFIG_LOGITECH_FF 1 #define CONFIG_HID_KYE 1 #define CONFIG_SYSFS 1 #define CONFIG_INPUT_TOUCHSCREEN 1 #define CONFIG_OUTER_CACHE_SYNC 1 #define CONFIG_ARM_THUMB 1 #define CONFIG_IP_NF_MATCH_AH 1 #define CONFIG_NETFILTER_XT_MATCH_LIMIT 1 #define CONFIG_DWC_OTG_DEFAULT_ID 1 #define CONFIG_ARM_ERRATA_754322 1 #define CONFIG_FB 1 #define CONFIG_TRACING 1 #define CONFIG_CPU_32v7 1 #define CONFIG_ADC 1 #define CONFIG_MSDOS_PARTITION 1 #define CONFIG_RK_DEBUG_UART 2 #define CONFIG_BT_HCIUART 1 #define CONFIG_SND_RK29_SOC_RT5623 1 #define CONFIG_HAVE_OPROFILE 1 #define CONFIG_HAVE_GENERIC_DMA_COHERENT 1 #define CONFIG_CPU_IDLE_GOV_LADDER 1 #define CONFIG_HID_PETALYNX 1 #define CONFIG_NET_ACT_MIRRED 1 #define CONFIG_HAVE_ARCH_KGDB 1 #define CONFIG_NF_CONNTRACK_IPV4 1 #define CONFIG_ZONE_DMA_FLAG 0 #define CONFIG_FIQ_DEBUGGER_NO_SLEEP 1 #define CONFIG_RPS 1 #define CONFIG_USB_NET_ZAURUS 1 #define CONFIG_INET6_XFRM_TUNNEL 1 #define CONFIG_MTD_MAP_BANK_WIDTH_2 1 #define CONFIG_MTD_NAND_RK29XX 1 #define CONFIG_TABLET_USB_ACECAD 1 #define CONFIG_VIDEO_MEDIA 1 #define CONFIG_IP_MULTICAST 1 #define CONFIG_WAKELOCK_STAT 1 #define CONFIG_INPUT_KEYCHORD 1 #define CONFIG_HAS_EARLYSUSPEND 1 #define CONFIG_CPU_32v6K 1 #define CONFIG_DEFAULT_SECURITY "" #define CONFIG_TICK_ONESHOT 1 #define CONFIG_NF_NAT_PROTO_UDPLITE 1 #define CONFIG_CGROUP_DEBUG 1 #define CONFIG_WIRELESS_EXT 1 #define CONFIG_MEDIA_TUNER_MT2060_MODULE 1 #define CONFIG_GPIO_TPS65910 1 #define CONFIG_ANDROID_LOGGER 1 #define CONFIG_MUTEX_SPIN_ON_OWNER 1 #define CONFIG_RWSEM_GENERIC_SPINLOCK 1 #define CONFIG_HAVE_FUNCTION_GRAPH_TRACER 1 #define CONFIG_VIDEOBUF2_CORE 1 #define CONFIG_BASE_SMALL 0 #define CONFIG_CRYPTO_BLKCIPHER2 1 #define CONFIG_COMPACTION 1 #define CONFIG_PROC_FS 1 #define CONFIG_MTD_BLOCK 1 #define CONFIG_RC_MAP 1 #define CONFIG_WEXT_PRIV 1 #define CONFIG_SCSI_LOWLEVEL 1 #define CONFIG_HID_PANTHERLORD 1 #define CONFIG_SND 1 #define CONFIG_FLATMEM 1 #define CONFIG_IR_RC6_DECODER 1 #define CONFIG_UART3_DMA_RK29 0 #define CONFIG_PAGEFLAGS_EXTENDED 1 #define CONFIG_TABLET_USB_HANWANG 1 #define CONFIG_SYSCTL 1 #define CONFIG_PLAT_RK 1 #define CONFIG_LOCAL_TIMERS 1 #define CONFIG_WM831X_BACKUP 1 #define CONFIG_HAVE_C_RECORDMCOUNT 1 #define CONFIG_MEDIA_TUNER_MT2131_MODULE 1 #define CONFIG_XFRM_USER 1 #define CONFIG_HAVE_PERF_EVENTS 1 #define CONFIG_PPP_ASYNC 1 #define CONFIG_UID_STAT 1 #define CONFIG_GS_KXTIK 1 #define CONFIG_SYS_SUPPORTS_APM_EMULATION 1 #define CONFIG_RTC_INTF_ALARM_DEV 1 #define CONFIG_HID_MULTITOUCH 1 #define CONFIG_NETFILTER_XT_MATCH_QUOTA2 1 #define CONFIG_GSENSOR_DEVICE 1 #define CONFIG_POWER_ON_CHARGER_DISPLAY 1 #define CONFIG_IDBLOCK 1 #define CONFIG_HID_ELECOM 1 #define CONFIG_SND_TIMER 1 #define CONFIG_FAT_DEFAULT_CODEPAGE 437 #define CONFIG_BLK_DEV 1 #define CONFIG_VIDEO_RK29_CAMMEM_ION 1 #define CONFIG_TRACING_SUPPORT 1 #define CONFIG_UNIX98_PTYS 1 #define CONFIG_NETFILTER_XT_TARGET_CONNMARK 1 #define CONFIG_HAVE_SCHED_CLOCK 1 #define CONFIG_NET_SCHED 1 #define CONFIG_JBD 1 #define CONFIG_PRINTK_TIME 1 #define CONFIG_PPP 1 #define CONFIG_NETFILTER_XT_MATCH_QUOTA 1 #define CONFIG_SOC_CAMERA_SP2518 1 #define CONFIG_HAVE_KERNEL_LZO 1 #define CONFIG_INET_DIAG 1 #define CONFIG_I2C1_RK30 1 #define CONFIG_NF_NAT_FTP 1 #define CONFIG_HID_ROCCAT_KONE 1 #define CONFIG_NF_CT_PROTO_UDPLITE 1 #define CONFIG_TEXTSEARCH 1 #define CONFIG_ADC_RK30 1 #define CONFIG_USB_SUPPORT 1 #define CONFIG_NETFILTER_XT_MATCH_QTAGUID 1 #define CONFIG_RK_HDMI 1 #define CONFIG_PL330 1 #define CONFIG_LIGHT_DEVICE 1 #define CONFIG_STAGING 1 #define CONFIG_MTD_CHAR 1 #define CONFIG_FLAT_NODE_MEM_MAP 1 #define CONFIG_VT_CONSOLE 1 #define CONFIG_HID_UCLOGIC 1 #define CONFIG_LEDS_GPIO 1 #define CONFIG_SMARTJOYPLUS_FF 1 #define CONFIG_NETFILTER_XT_MATCH_STATE 1 #define CONFIG_LOGIRUMBLEPAD2_FF 1 #define CONFIG_USB20_OTG 1 #define CONFIG_IR_RC5_DECODER 1 #define CONFIG_INET6_XFRM_MODE_BEET 1 #define CONFIG_GYROSCOPE_DEVICE 1 #define CONFIG_PREEMPT 1 #define CONFIG_FB_CFB_COPYAREA 1 #define CONFIG_BINARY_PRINTF 1 #define CONFIG_RK_SRAM_DMA 1 #define CONFIG_GENERIC_CLOCKEVENTS_BUILD 1 #define CONFIG_VIDEOBUF_GEN 1 #define CONFIG_VIDEO_V4L2 1 #define CONFIG_HID_NTRIG 1 #define CONFIG_DDR_SDRAM_FREQ 336 #define CONFIG_DECOMPRESS_GZIP 1 #define CONFIG_SDMMC_RK29 1 #define CONFIG_LLC 1 #define CONFIG_CROSS_COMPILE "" #define CONFIG_MEDIA_TUNER_TEA5761_MODULE 1 #define CONFIG_BATTERY_RK30_VOL3V8 1 #define CONFIG_USB_GADGET_SELECTED 1 #define CONFIG_GENERIC_CLOCKEVENTS_BROADCAST 1 #define CONFIG_JOYSTICK_XPAD 1 #define CONFIG_NETFILTER_TPROXY 1 #define CONFIG_RK29_LAST_LOG 1 #define CONFIG_USB_USBNET 1 #define CONFIG_SCSI_MULTI_LUN 1 #define CONFIG_NET_ACT_POLICE 1 #define CONFIG_SND_SOC_RT5623 1 #define CONFIG_HID_SMARTJOYPLUS 1 #define CONFIG_TPS65910_RTC 1 #define CONFIG_NEW_LEDS 1 #define CONFIG_SWAP 1 #define CONFIG_CRC_CCITT 1 #define CONFIG_BLK_DEV_SD 1 #define CONFIG_CMDLINE_FROM_BOOTLOADER 1 #define CONFIG_NETFILTER_NETLINK 1 #define CONFIG_MODULE_UNLOAD 1 #define CONFIG_CPU_FREQ_DEFAULT_GOV_INTERACTIVE 1 #define CONFIG_USB_DWC_OTG 1 #define CONFIG_RK_CONSOLE_THREAD 1 #define CONFIG_RCU_FANOUT 32 #define CONFIG_BITREVERSE 1 #define CONFIG_USB_SERIAL_WWAN 1 #define CONFIG_VIDEO_V4L2_COMMON 1 #define CONFIG_FB_MODE_HELPERS 1 #define CONFIG_CRYPTO_BLKCIPHER 1 #define CONFIG_NF_CONNTRACK 1 #define CONFIG_FILE_LOCKING 1 #define CONFIG_SND_SOC_I2C_AND_SPI 1 #define CONFIG_FIQ 1 #define CONFIG_HID_ROCCAT_ARVO 1 #define CONFIG_NET_EMATCH 1 #define CONFIG_IP_NF_TARGET_REJECT 1 #define CONFIG_LEDS_CLASS 1 #define CONFIG_GENERIC_HARDIRQS 1 #define CONFIG_RTC_INTF_DEV 1 #define CONFIG_MTD_MAP_BANK_WIDTH_4 1 #define CONFIG_HID_SUPPORT 1 #define CONFIG_NET_ACTIVITY_STATS 1 #define CONFIG_NLS_DEFAULT "iso8859-1" #define CONFIG_NF_CT_PROTO_GRE 1 #define CONFIG_ION_ROCKCHIP 1 #define CONFIG_NF_CT_NETLINK 1 #define CONFIG_CRYPTO_AEAD2 1 #define CONFIG_NETFILTER_XT_MATCH_HL 1 #define CONFIG_CRYPTO_ALGAPI2 1 #define CONFIG_USB_NET_DM9620 1 #define CONFIG_ZBOOT_ROM_TEXT 0x0 #define CONFIG_HAVE_MEMBLOCK 1 #define CONFIG_INPUT 1 #define CONFIG_PROC_SYSCTL 1 #define CONFIG_MMU 1 #define CONFIG_HAVE_IRQ_WORK 1 #define CONFIG_USER_WAKELOCK 1 #define CONFIG_ENABLE_DEFAULT_TRACERS 1 #define CONFIG_TABLET_USB_AIPTEK 1
Java
/* * AAC decoder data * Copyright (c) 2005-2006 Oded Shimon ( ods15 ods15 dyndns org ) * Copyright (c) 2006-2007 Maxim Gavrilov ( maxim.gavrilov gmail com ) * * This file is part of Libav. * * Libav is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Libav is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * AAC decoder data * @author Oded Shimon ( ods15 ods15 dyndns org ) * @author Maxim Gavrilov ( maxim.gavrilov gmail com ) */ #ifndef AVCODEC_AACDECTAB_H #define AVCODEC_AACDECTAB_H #include "libavutil/audioconvert.h" #include "aac.h" #include <stdint.h> /* @name ltp_coef * Table of the LTP coefficients */ static const float ltp_coef[8] = { 0.570829, 0.696616, 0.813004, 0.911304, 0.984900, 1.067894, 1.194601, 1.369533, }; /* @name tns_tmp2_map * Tables of the tmp2[] arrays of LPC coefficients used for TNS. * The suffix _M_N[] indicate the values of coef_compress and coef_res * respectively. * @{ */ static const float tns_tmp2_map_1_3[4] = { 0.00000000, -0.43388373, 0.64278758, 0.34202015, }; static const float tns_tmp2_map_0_3[8] = { 0.00000000, -0.43388373, -0.78183150, -0.97492790, 0.98480773, 0.86602539, 0.64278758, 0.34202015, }; static const float tns_tmp2_map_1_4[8] = { 0.00000000, -0.20791170, -0.40673664, -0.58778524, 0.67369562, 0.52643216, 0.36124167, 0.18374951, }; static const float tns_tmp2_map_0_4[16] = { 0.00000000, -0.20791170, -0.40673664, -0.58778524, -0.74314481, -0.86602539, -0.95105654, -0.99452192, 0.99573416, 0.96182561, 0.89516330, 0.79801720, 0.67369562, 0.52643216, 0.36124167, 0.18374951, }; static const float * const tns_tmp2_map[4] = { tns_tmp2_map_0_3, tns_tmp2_map_0_4, tns_tmp2_map_1_3, tns_tmp2_map_1_4 }; // @} static const int8_t tags_per_config[16] = { 0, 1, 1, 2, 3, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0 }; static const uint8_t aac_channel_layout_map[7][5][2] = { { { TYPE_SCE, 0 }, }, { { TYPE_CPE, 0 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, { TYPE_SCE, 1 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, { TYPE_CPE, 1 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, { TYPE_LFE, 0 }, { TYPE_CPE, 1 }, }, { { TYPE_CPE, 0 }, { TYPE_SCE, 0 }, { TYPE_LFE, 0 }, { TYPE_CPE, 2 }, { TYPE_CPE, 1 }, }, }; static const int64_t aac_channel_layout[8] = { AV_CH_LAYOUT_MONO, AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_SURROUND, AV_CH_LAYOUT_4POINT0, AV_CH_LAYOUT_5POINT0_BACK, AV_CH_LAYOUT_5POINT1_BACK, AV_CH_LAYOUT_7POINT1_WIDE, 0, }; #endif /* AVCODEC_AACDECTAB_H */
Java
template <typename Item> void mergesort(Item a[], int l, int r) { if (r <= 1) return ; int m = (r+1)/2; mergesort(a, l, m); mergesort(a, m+1, r); merge(a, l, m, r); }
Java
/* This file is part of the KDE project Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.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, version 2. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <dcopclient.h> #include <kapplication.h> #include <kprocess.h> #include <kstaticdeleter.h> #include "watcher_stub.h" #include "mrml_utils.h" // after 100 of no use, terminate the mrmld #define TIMEOUT 100 // how often to restart the mrmld in case of failure #define NUM_RESTARTS 5 using namespace KMrml; KStaticDeleter<Util> utils_sd; Util *Util::s_self = 0L; Util::Util() { // we need our own dcopclient, when used in kio_mrml if ( !DCOPClient::mainClient() ) { DCOPClient::setMainClient( new DCOPClient() ); if ( !DCOPClient::mainClient()->attach() ) qWarning( "kio_mrml: Can't attach to DCOP Server."); } } Util::~Util() { if ( this == s_self ) s_self = 0L; } Util *Util::self() { if ( !s_self ) s_self = utils_sd.setObject( new Util() ); return s_self; } bool Util::requiresLocalServerFor( const KURL& url ) { return url.host().isEmpty() || url.host() == "localhost"; } bool Util::startLocalServer( const Config& config ) { if ( config.serverStartedIndividually() ) return true; DCOPClient *client = DCOPClient::mainClient(); // ### check if it's already running (add dcop method to Watcher) Watcher_stub watcher( client, "kded", "daemonwatcher"); return ( watcher.requireDaemon( client->appId(), "mrmld", config.mrmldCommandline(), TIMEOUT, NUM_RESTARTS ) && watcher.ok() ); } void Util::unrequireLocalServer() { DCOPClient *client = DCOPClient::mainClient(); Watcher_stub watcher( client, "kded", "daemonwatcher"); watcher.unrequireDaemon( client->appId(), "mrmld" ); }
Java
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Unit tests for the ranking engine.""" __revision__ = "$Id$" from invenio.importutils import lazy_import from invenio.testutils import make_test_suite, run_test_suite, InvenioTestCase bibrank_tag_based_indexer = lazy_import('invenio.bibrank_tag_based_indexer') split_ranges = lazy_import('invenio.bibrank:split_ranges') class TestListSetOperations(InvenioTestCase): """Test list set operations.""" def test_union_dicts(self): """bibrank tag based indexer - union dicts""" self.assertEqual({1: 5, 2: 6, 3: 9, 4: 10, 10: 1}, bibrank_tag_based_indexer.union_dicts({1: 5, 2: 6, 3: 9}, {3:9, 4:10, 10: 1})) def test_split_ranges(self): """bibrank tag based indexer - split ranges""" self.assertEqual([[0, 500], [600, 1000]], split_ranges("0-500,600-1000")) TEST_SUITE = make_test_suite(TestListSetOperations,) if __name__ == "__main__": run_test_suite(TEST_SUITE)
Java
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.7 | +--------------------------------------------------------------------+ | 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_Event_Import_Controller extends CRM_Core_Controller { /** * Class constructor. * * @param null $title * @param bool|int $action * @param bool $modal */ public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) { parent::__construct($title, $modal); // lets get around the time limit issue if possible, CRM-2113 if (!ini_get('safe_mode')) { set_time_limit(0); } $this->_stateMachine = new CRM_Import_StateMachine($this, $action); // create and instantiate the pages $this->addPages($this->_stateMachine, $action); // add all the actions $config = CRM_Core_Config::singleton(); $this->addActions($config->uploadDir, array('uploadFile')); } }
Java
--- layout: post title: For Rusty - 1988 - 2004 author: Chris Metcalf date: 2004/04/21 slug: for-rusty-1988-2004 category: tags: [ dogs, family, me ] --- Today we had to say goodbye to a loyal friend. <img src="/images/posts/rusty.jpg" alt="an old friend" /> Today we had to put one of our family's favorite pets to sleep. As he approached the ripe old age of 16, age had simply taken too much of a toll on him. He had a long, full life of deer and bunny chasing, and we're all sure he's much happier now. I decided I'd blog the occasion to make sure I always remembered him. The most loyal of friends deserve that.
Java
/* protocol_subnet.c -- handle the meta-protocol, subnets Copyright (C) 1999-2005 Ivo Timmermans, 2000-2012 Guus Sliepen <guus@tinc-vpn.org> 2009 Michael Tokarev <mjt@tls.msk.ru> 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 "system.h" #include "conf.h" #include "connection.h" #include "logger.h" #include "net.h" #include "netutl.h" #include "node.h" #include "protocol.h" #include "subnet.h" #include "utils.h" #include "xalloc.h" bool send_add_subnet(connection_t *c, const subnet_t *subnet) { char netstr[MAXNETSTR]; if(!net2str(netstr, sizeof netstr, subnet)) return false; return send_request(c, "%d %x %s %s", ADD_SUBNET, rand(), subnet->owner->name, netstr); } bool add_subnet_h(connection_t *c, const char *request) { char subnetstr[MAX_STRING_SIZE]; char name[MAX_STRING_SIZE]; node_t *owner; subnet_t s, *new, *old; memset(&s, 0x0, sizeof(subnet_t)); if(sscanf(request, "%*d %*x " MAX_STRING " " MAX_STRING, name, subnetstr) != 2) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ADD_SUBNET", c->name, c->hostname); return false; } /* Check if owner name is valid */ if(!check_id(name)) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ADD_SUBNET", c->name, c->hostname, "invalid name"); return false; } /* Check if subnet string is valid */ if(!str2net(&s, subnetstr)) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ADD_SUBNET", c->name, c->hostname, "invalid subnet string"); return false; } if(seen_request(request)) return true; /* Check if the owner of the new subnet is in the connection list */ owner = lookup_node(name); if(tunnelserver && owner != myself && owner != c->node) { /* in case of tunnelserver, ignore indirect subnet registrations */ logger(DEBUG_PROTOCOL, LOG_WARNING, "Ignoring indirect %s from %s (%s) for %s", "ADD_SUBNET", c->name, c->hostname, subnetstr); return true; } if(!owner) { owner = new_node(); owner->name = xstrdup(name); node_add(owner); } /* Check if we already know this subnet */ if(lookup_subnet(owner, &s)) return true; /* If we don't know this subnet, but we are the owner, retaliate with a DEL_SUBNET */ if(owner == myself) { logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) for ourself", "ADD_SUBNET", c->name, c->hostname); s.owner = myself; send_del_subnet(c, &s); return true; } /* In tunnel server mode, we should already know all allowed subnets */ if(tunnelserver) { logger(DEBUG_ALWAYS, LOG_WARNING, "Ignoring unauthorized %s from %s (%s): %s", "ADD_SUBNET", c->name, c->hostname, subnetstr); return true; } /* Ignore if strictsubnets is true, but forward it to others */ if(strictsubnets) { logger(DEBUG_ALWAYS, LOG_WARNING, "Ignoring unauthorized %s from %s (%s): %s", "ADD_SUBNET", c->name, c->hostname, subnetstr); if ((!owner->status.reachable) && ((now.tv_sec - owner->last_state_change) >= keylifetime*2)) { logger(DEBUG_CONNECTIONS, LOG_INFO, "Not forwarding informations about %s to ALL (%lf / %d)", owner->name, difftime(now.tv_sec, owner->last_state_change), keylifetime); } else { forward_request(c, request); } return true; } /* If everything is correct, add the subnet to the list of the owner */ *(new = new_subnet()) = s; subnet_add(owner, new); if(owner->status.reachable) subnet_update(owner, new, true); /* Tell the rest */ if(!tunnelserver) forward_request(c, request); /* Fast handoff of roaming MAC addresses */ if(s.type == SUBNET_MAC && owner != myself && (old = lookup_subnet(myself, &s)) && old->expires) old->expires = 1; return true; } bool send_del_subnet(connection_t *c, const subnet_t *s) { char netstr[MAXNETSTR]; if(!net2str(netstr, sizeof netstr, s)) return false; return send_request(c, "%d %x %s %s", DEL_SUBNET, rand(), s->owner->name, netstr); } bool del_subnet_h(connection_t *c, const char *request) { char subnetstr[MAX_STRING_SIZE]; char name[MAX_STRING_SIZE]; node_t *owner; subnet_t s, *find; memset(&s, 0x0, sizeof(subnet_t)); if(sscanf(request, "%*d %*x " MAX_STRING " " MAX_STRING, name, subnetstr) != 2) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "DEL_SUBNET", c->name, c->hostname); return false; } /* Check if owner name is valid */ if(!check_id(name)) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "DEL_SUBNET", c->name, c->hostname, "invalid name"); return false; } /* Check if subnet string is valid */ if(!str2net(&s, subnetstr)) { logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "DEL_SUBNET", c->name, c->hostname, "invalid subnet string"); return false; } if(seen_request(request)) return true; /* Check if the owner of the subnet being deleted is in the connection list */ owner = lookup_node(name); if(tunnelserver && owner != myself && owner != c->node) { /* in case of tunnelserver, ignore indirect subnet deletion */ logger(DEBUG_PROTOCOL, LOG_WARNING, "Ignoring indirect %s from %s (%s) for %s", "DEL_SUBNET", c->name, c->hostname, subnetstr); return true; } if(!owner) { logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) for %s which is not in our node tree", "DEL_SUBNET", c->name, c->hostname, name); return true; } /* If everything is correct, delete the subnet from the list of the owner */ s.owner = owner; find = lookup_subnet(owner, &s); if(!find) { logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) for %s which does not appear in his subnet tree", "DEL_SUBNET", c->name, c->hostname, name); if(strictsubnets) forward_request(c, request); return true; } /* If we are the owner of this subnet, retaliate with an ADD_SUBNET */ if(owner == myself) { logger(DEBUG_PROTOCOL, LOG_WARNING, "Got %s from %s (%s) for ourself", "DEL_SUBNET", c->name, c->hostname); send_add_subnet(c, find); return true; } if(tunnelserver) return true; /* Tell the rest */ if(!tunnelserver) forward_request(c, request); if(strictsubnets) return true; /* Finally, delete it. */ if(owner->status.reachable) subnet_update(owner, find, false); subnet_del(owner, find); return true; }
Java
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> // System.Reflection.Emit.ModuleBuilder struct ModuleBuilder_t973; // System.Object struct Object_t; // System.Type[] struct TypeU5BU5D_t194; // System.Reflection.MemberInfo struct MemberInfo_t; // System.Reflection.Emit.TokenGenerator struct TokenGenerator_t970; #include "codegen/il2cpp-codegen.h" // System.Void System.Reflection.Emit.ModuleBuilder::.cctor() extern "C" void ModuleBuilder__cctor_m5685 (Object_t * __this /* static, unused */, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Int32 System.Reflection.Emit.ModuleBuilder::get_next_table_index(System.Object,System.Int32,System.Boolean) extern "C" int32_t ModuleBuilder_get_next_table_index_m5686 (ModuleBuilder_t973 * __this, Object_t * ___obj, int32_t ___table, bool ___inc, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Type[] System.Reflection.Emit.ModuleBuilder::GetTypes() extern "C" TypeU5BU5D_t194* ModuleBuilder_GetTypes_m5687 (ModuleBuilder_t973 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Int32 System.Reflection.Emit.ModuleBuilder::getToken(System.Reflection.Emit.ModuleBuilder,System.Object) extern "C" int32_t ModuleBuilder_getToken_m5688 (Object_t * __this /* static, unused */, ModuleBuilder_t973 * ___mb, Object_t * ___obj, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Int32 System.Reflection.Emit.ModuleBuilder::GetToken(System.Reflection.MemberInfo) extern "C" int32_t ModuleBuilder_GetToken_m5689 (ModuleBuilder_t973 * __this, MemberInfo_t * ___member, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void System.Reflection.Emit.ModuleBuilder::RegisterToken(System.Object,System.Int32) extern "C" void ModuleBuilder_RegisterToken_m5690 (ModuleBuilder_t973 * __this, Object_t * ___obj, int32_t ___token, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Reflection.Emit.TokenGenerator System.Reflection.Emit.ModuleBuilder::GetTokenGenerator() extern "C" Object_t * ModuleBuilder_GetTokenGenerator_m5691 (ModuleBuilder_t973 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
Java
<?php /** * LICENSE: Anahita is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * * @category Anahita * @package Com_Base * @subpackage Template_Filter * @author Arash Sanieyan <ash@anahitapolis.com> * @author Rastin Mehr <rastin@anahitapolis.com> * @copyright 2008 - 2010 rmdStudio Inc./Peerglobe Technology Inc * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl-3.0.html> * @version SVN: $Id: view.php 13650 2012-04-11 08:56:41Z asanieyan $ * @link http://www.anahitapolis.com */ /** * Module Filter * * @category Anahita * @package Com_Base * @subpackage Template_Filter * @author Arash Sanieyan <ash@anahitapolis.com> * @author Rastin Mehr <rastin@anahitapolis.com> * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl-3.0.html> * @link http://www.anahitapolis.com */ class ComBaseTemplateFilterModule extends KTemplateFilterAbstract implements KTemplateFilterWrite { /** * Initializes the options for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param object An optional KConfig object with configuration options * @return void */ protected function _initialize(KConfig $config) { $config->append(array( 'priority' => KCommand::PRIORITY_LOW, )); parent::_initialize($config); } /** * Find any <module></module> elements and inject them into the JDocument object * * @param string Block of text to parse * * @return void */ public function write(&$text) { $matches = array(); if(preg_match_all('#<module([^>]*)>(.*)</module>#siU', $text, $matches)) { $modules = array(); foreach($matches[0] as $key => $match) { $text = str_replace($match, '', $text); $attributes = array( 'style' => 'default', 'params' => '', 'title' => '', 'class' => '', 'prepend' => true ); $attributes = array_merge($attributes, $this->_parseAttributes($matches[1][$key])); if ( !empty($attributes['class']) ) { $attributes['params'] .= ' moduleclass_sfx= '.$attributes['class']; } $module = new KObject(); $module->id = uniqid(); $module->content = $matches[2][$key]; $module->position = $attributes['position']; $module->params = $attributes['params']; $module->showtitle = !empty($attributes['title']); $module->title = $attributes['title']; $module->name = $attributes['position']; $module->attribs = $attributes; $module->user = 0; $module->module = 'mod_dynamic'; $modules[] = $module; } $mods =& JModuleHelper::_load(); $mods = array_merge($modules, $mods); } return $this; } }
Java
<?php /** * @version $Id: legacy.php 10066 2008-02-26 04:20:57Z ian $ * @package Joomla * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); jimport( 'joomla.plugin.plugin' ); /** * Joomla! Debug plugin * * @author Johan Janssens <johan.janssens@joomla.org> * @package Joomla * @subpackage System */ class plgSystemLegacy extends JPlugin { /** * Constructor * * For php4 compatability we must not use the __constructor as a constructor for plugins * because func_get_args ( void ) returns a copy of all passed arguments NOT references. * This causes problems with cross-referencing necessary for the observer design pattern. * * @param object $subject The object to observe * @param array $config An array that holds the plugin configuration * @since 1.0 */ function plgSystemLegacy(& $subject, $config) { parent::__construct($subject, $config); global $mainframe; // Define the 1.0 legacy mode constant define('_JLEGACY', '1.0'); // Set global configuration var for legacy mode $config = &JFactory::getConfig(); $config->setValue('config.legacy', 1); // Import library dependencies require_once(dirname(__FILE__).DS.'legacy'.DS.'classes.php'); require_once(dirname(__FILE__).DS.'legacy'.DS.'functions.php'); // Register legacy classes for autoloading JLoader::register('mosAdminMenus' , dirname(__FILE__).DS.'legacy'.DS.'adminmenus.php'); JLoader::register('mosCache' , dirname(__FILE__).DS.'legacy'.DS.'cache.php'); JLoader::register('mosCategory' , dirname(__FILE__).DS.'legacy'.DS.'category.php'); JLoader::register('mosCommonHTML' , dirname(__FILE__).DS.'legacy'.DS.'commonhtml.php'); JLoader::register('mosComponent' , dirname(__FILE__).DS.'legacy'.DS.'component.php'); JLoader::register('mosContent' , dirname(__FILE__).DS.'legacy'.DS.'content.php'); JLoader::register('mosDBTable' , dirname(__FILE__).DS.'legacy'.DS.'dbtable.php'); JLoader::register('mosHTML' , dirname(__FILE__).DS.'legacy'.DS.'html.php'); JLoader::register('mosInstaller' , dirname(__FILE__).DS.'legacy'.DS.'installer.php'); JLoader::register('mosMainFrame' , dirname(__FILE__).DS.'legacy'.DS.'mainframe.php'); JLoader::register('mosMambot' , dirname(__FILE__).DS.'legacy'.DS.'mambot.php'); JLoader::register('mosMambotHandler', dirname(__FILE__).DS.'legacy'.DS.'mambothandler.php'); JLoader::register('mosMenu' , dirname(__FILE__).DS.'legacy'.DS.'menu.php'); JLoader::register('mosMenuBar' , dirname(__FILE__).DS.'legacy'.DS.'menubar.php'); JLoader::register('mosModule' , dirname(__FILE__).DS.'legacy'.DS.'module.php'); //JLoader::register('mosPageNav' , dirname(__FILE__).DS.'legacy'.DS.'pagination.php'); JLoader::register('mosParameters' , dirname(__FILE__).DS.'legacy'.DS.'parameters.php'); JLoader::register('patFactory' , dirname(__FILE__).DS.'legacy'.DS.'patfactory.php'); JLoader::register('mosProfiler' , dirname(__FILE__).DS.'legacy'.DS.'profiler.php'); JLoader::register('mosSection' , dirname(__FILE__).DS.'legacy'.DS.'section.php'); JLoader::register('mosSession' , dirname(__FILE__).DS.'legacy'.DS.'session.php'); JLoader::register('mosToolbar' , dirname(__FILE__).DS.'legacy'.DS.'toolbar.php'); JLoader::register('mosUser' , dirname(__FILE__).DS.'legacy'.DS.'user.php'); // Register class for the database, depends on which db type has been selected for use $dbtype = $config->getValue('config.dbtype', 'mysql'); JLoader::register('database' , dirname(__FILE__).DS.'legacy'.DS.$dbtype.'.php'); /** * Legacy define, _ISO define not used anymore. All output is forced as utf-8. * @deprecated As of version 1.5 */ define('_ISO','charset=utf-8'); /** * Legacy constant, use _JEXEC instead * @deprecated As of version 1.5 */ define( '_VALID_MOS', 1 ); /** * Legacy constant, use _JEXEC instead * @deprecated As of version 1.5 */ define( '_MOS_MAMBO_INCLUDED', 1 ); /** * Legacy constant, use DATE_FORMAT_LC instead * @deprecated As of version 1.5 */ DEFINE('_DATE_FORMAT_LC', JText::_('DATE_FORMAT_LC1') ); //Uses PHP's strftime Command Format /** * Legacy constant, use DATE_FORMAT_LC2 instead * @deprecated As of version 1.5 */ DEFINE('_DATE_FORMAT_LC2', JText::_('DATE_FORMAT_LC2')); /** * Legacy constant, use JFilterInput instead * @deprecated As of version 1.5 */ DEFINE( "_MOS_NOTRIM", 0x0001 ); /** * Legacy constant, use JFilterInput instead * @deprecated As of version 1.5 */ DEFINE( "_MOS_ALLOWHTML", 0x0002 ); /** * Legacy constant, use JFilterInput instead * @deprecated As of version 1.5 */ DEFINE( "_MOS_ALLOWRAW", 0x0004 ); /** * Legacy global, use JVersion->getLongVersion() instead * @name $_VERSION * @deprecated As of version 1.5 */ $GLOBALS['_VERSION'] = new JVersion(); $version = $GLOBALS['_VERSION']->getLongVersion(); /** * Legacy global, use JFactory::getDBO() instead * @name $database * @deprecated As of version 1.5 */ $conf =& JFactory::getConfig(); $GLOBALS['database'] = new database($conf->getValue('config.host'), $conf->getValue('config.user'), $conf->getValue('config.password'), $conf->getValue('config.db'), $conf->getValue('config.dbprefix')); $GLOBALS['database']->debug($conf->getValue('config.debug')); /** * Legacy global, use JFactory::getUser() [JUser object] instead * @name $my * @deprecated As of version 1.5 */ $user =& JFactory::getUser(); $GLOBALS['my'] = (object)$user->getProperties(); $GLOBALS['my']->gid = $user->get('aid', 0); /** * Insert configuration values into global scope (for backwards compatibility) * @deprecated As of version 1.5 */ $temp = new JConfig; foreach (get_object_vars($temp) as $k => $v) { $name = 'mosConfig_'.$k; $GLOBALS[$name] = $v; } $GLOBALS['mosConfig_live_site'] = substr_replace(JURI::root(), '', -1, 1); $GLOBALS['mosConfig_absolute_path'] = JPATH_SITE; $GLOBALS['mosConfig_cachepath'] = JPATH_BASE.DS.'cache'; $GLOBALS['mosConfig_offset_user'] = 0; $lang =& JFactory::getLanguage(); $GLOBALS['mosConfig_lang'] = $lang->getBackwardLang(); $config->setValue('config.live_site', $GLOBALS['mosConfig_live_site']); $config->setValue('config.absolute_path', $GLOBALS['mosConfig_absolute_path']); $config->setValue('config.lang', $GLOBALS['mosConfig_lang']); /** * Legacy global, use JFactory::getUser() instead * @name $acl * @deprecated As of version 1.5 */ $acl =& JFactory::getACL(); // Legacy ACL's for backward compat $acl->addACL( 'administration', 'edit', 'users', 'super administrator', 'components', 'all' ); $acl->addACL( 'administration', 'edit', 'users', 'administrator', 'components', 'all' ); $acl->addACL( 'administration', 'edit', 'users', 'super administrator', 'user properties', 'block_user' ); $acl->addACL( 'administration', 'manage', 'users', 'super administrator', 'components', 'com_users' ); $acl->addACL( 'administration', 'manage', 'users', 'administrator', 'components', 'com_users' ); $acl->addACL( 'administration', 'config', 'users', 'super administrator' ); //$acl->addACL( 'administration', 'config', 'users', 'administrator' ); $acl->addACL( 'action', 'add', 'users', 'author', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'editor', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'publisher', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'author', 'content', 'own' ); $acl->addACL( 'action', 'edit', 'users', 'editor', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'publisher', 'content', 'all' ); $acl->addACL( 'action', 'publish', 'users', 'publisher', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'manager', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'manager', 'content', 'all' ); $acl->addACL( 'action', 'publish', 'users', 'manager', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'administrator', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'administrator', 'content', 'all' ); $acl->addACL( 'action', 'publish', 'users', 'administrator', 'content', 'all' ); $acl->addACL( 'action', 'add', 'users', 'super administrator', 'content', 'all' ); $acl->addACL( 'action', 'edit', 'users', 'super administrator', 'content', 'all' ); $acl->addACL( 'action', 'publish', 'users', 'super administrator', 'content', 'all' ); $acl->addACL( 'com_syndicate', 'manage', 'users', 'super administrator' ); $acl->addACL( 'com_syndicate', 'manage', 'users', 'administrator' ); $acl->addACL( 'com_syndicate', 'manage', 'users', 'manager' ); $GLOBALS['acl'] =& $acl; /** * Legacy global * @name $task * @deprecated As of version 1.5 */ $GLOBALS['task'] = JRequest::getString('task'); /** * Load the site language file (the old way - to be deprecated) * @deprecated As of version 1.5 */ global $mosConfig_lang; $mosConfig_lang = JFilterInput::clean($mosConfig_lang, 'cmd'); $file = JPATH_SITE.DS.'language'.DS.$mosConfig_lang.'.php'; if (file_exists( $file )) { require_once( $file); } else { $file = JPATH_SITE.DS.'language'.DS.'english.php'; if (file_exists( $file )) { require_once( $file ); } } /** * Legacy global * use JApplicaiton->registerEvent and JApplication->triggerEvent for event handling * use JPlugingHelper::importPlugin to load bot code * @deprecated As of version 1.5 */ $GLOBALS['_MAMBOTS'] = new mosMambotHandler(); } function onAfterRoute() { global $mainframe; if ($mainframe->isAdmin()) { return; } switch(JRequest::getCmd('option')) { case 'com_content' : $this->routeContent(); break; case 'com_newsfeeds' : $this->routeNewsfeeds(); break; case 'com_weblinks' : $this->routeWeblinks(); break; case 'com_frontpage' : JRequest::setVar('option', 'com_content'); JRequest::setVar('view', 'frontpage'); break; case 'com_login' : JRequest::setVar('option', 'com_user'); JRequest::setVar('view', 'login'); break; case 'com_registration' : JRequest::setVar('option', 'com_user'); JRequest::setVar('view', 'register'); break; } /** * Legacy global, use JApplication::getTemplate() instead * @name $cur_template * @deprecated As of version 1.5 */ $GLOBALS['cur_template'] = $mainframe->getTemplate(); } function routeContent() { $viewName = JRequest::getCmd( 'view', 'article' ); $layout = JRequest::getCmd( 'layout', 'default' ); // interceptors to support legacy urls switch( JRequest::getCmd('task')) { //index.php?option=com_content&task=x&id=x&Itemid=x case 'blogsection': $viewName = 'section'; $layout = 'blog'; break; case 'section': $viewName = 'section'; break; case 'category': $viewName = 'category'; break; case 'blogcategory': $viewName = 'category'; $layout = 'blog'; break; case 'archivesection': case 'archivecategory': $viewName = 'archive'; break; case 'frontpage' : $viewName = 'frontpage'; break; case 'view': $viewName = 'article'; break; } JRequest::setVar('layout', $layout); JRequest::setVar('view', $viewName); } function routeNewsfeeds() { $viewName = JRequest::getCmd( 'view', 'categories' ); // interceptors to support legacy urls switch( JRequest::getCmd('task')) { //index.php?option=com_newsfeeds&task=x&catid=xid=x&Itemid=x case 'view': $viewName = 'newsfeed'; break; default: { if(JRequest::getInt('catid') && !JRequest::getCmd('view')) { $viewName = 'category'; } } } JRequest::setVar('view', $viewName); } function routeWeblinks() { $viewName = JRequest::getCmd( 'view', 'categories' ); // interceptors to support legacy urls switch( JRequest::getCmd('task')) { //index.php?option=com_weblinks&task=x&catid=xid=x case 'view': $viewName = 'weblink'; break; default: { if(($catid = JRequest::getInt('catid')) && !JRequest::getCmd('view')) { $viewName = 'category'; JRequest::setVar('id', $catid); } } } JRequest::setVar('view', $viewName); } }
Java
def spaceship_building(cans): total_cans = 0 for week in range(1,53): total_cans = total_cans + cans print('Week %s = %s cans' % (week, total_cans)) spaceship_building(2) spaceship_building(13)
Java
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-24 15:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('emailer', '0007_auto_20150509_1922'), ] operations = [ migrations.AlterField( model_name='email', name='recipient', field=models.EmailField(db_index=True, max_length=254), ), ]
Java
<html> <head> <title>Stożek</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="../books.css" /> </head> <body align="left"> <h1>Stożek</h1> <center><img src="../images/cone.png" /></center> <br /> <div align="left"> <a href="file:#V=(1/3)*pi*r%5e2*h">V = (1/3) * pi * r^2 * h</a><br /> <br /> <a href="file:#A=(pi*r%5e2)+(pi*r*s)">A = (pi * r^2) + (pi * r * s)</a><br /> <a href="file:#A=(pi*r%5e2)+(pi*r*sqrt(r%5e2+h%5e2))">A = (pi * r^2) + (pi * r * sqrt(r^2 + h^2))</a><br /> </div> </body> </html>
Java
/* * rev-parse.c * * Copyright (C) Linus Torvalds, 2005 */ #include "cache.h" #include "commit.h" #include "refs.h" #include "quote.h" #include "builtin.h" #include "parse-options.h" #include "diff.h" #include "revision.h" #include "split-index.h" #define DO_REVS 1 #define DO_NOREV 2 #define DO_FLAGS 4 #define DO_NONFLAGS 8 static int filter = ~0; static const char *def; #define NORMAL 0 #define REVERSED 1 static int show_type = NORMAL; #define SHOW_SYMBOLIC_ASIS 1 #define SHOW_SYMBOLIC_FULL 2 static int symbolic; static int abbrev; static int abbrev_ref; static int abbrev_ref_strict; static int output_sq; static int stuck_long; static struct string_list *ref_excludes; /* * Some arguments are relevant "revision" arguments, * others are about output format or other details. * This sorts it all out. */ static int is_rev_argument(const char *arg) { static const char *rev_args[] = { "--all", "--bisect", "--dense", "--branches=", "--branches", "--header", "--ignore-missing", "--max-age=", "--max-count=", "--min-age=", "--no-merges", "--min-parents=", "--no-min-parents", "--max-parents=", "--no-max-parents", "--objects", "--objects-edge", "--parents", "--pretty", "--remotes=", "--remotes", "--glob=", "--sparse", "--tags=", "--tags", "--topo-order", "--date-order", "--unpacked", NULL }; const char **p = rev_args; /* accept -<digit>, like traditional "head" */ if ((*arg == '-') && isdigit(arg[1])) return 1; for (;;) { const char *str = *p++; int len; if (!str) return 0; len = strlen(str); if (!strcmp(arg, str) || (str[len-1] == '=' && !strncmp(arg, str, len))) return 1; } } /* Output argument as a string, either SQ or normal */ static void show(const char *arg) { if (output_sq) { int sq = '\'', ch; putchar(sq); while ((ch = *arg++)) { if (ch == sq) fputs("'\\'", stdout); putchar(ch); } putchar(sq); putchar(' '); } else puts(arg); } /* Like show(), but with a negation prefix according to type */ static void show_with_type(int type, const char *arg) { if (type != show_type) putchar('^'); show(arg); } /* Output a revision, only if filter allows it */ static void show_rev(int type, const unsigned char *sha1, const char *name) { if (!(filter & DO_REVS)) return; def = NULL; if ((symbolic || abbrev_ref) && name) { if (symbolic == SHOW_SYMBOLIC_FULL || abbrev_ref) { unsigned char discard[20]; char *full; switch (dwim_ref(name, strlen(name), discard, &full)) { case 0: /* * Not found -- not a ref. We could * emit "name" here, but symbolic-full * users are interested in finding the * refs spelled in full, and they would * need to filter non-refs if we did so. */ break; case 1: /* happy */ if (abbrev_ref) full = shorten_unambiguous_ref(full, abbrev_ref_strict); show_with_type(type, full); break; default: /* ambiguous */ error("refname '%s' is ambiguous", name); break; } free(full); } else { show_with_type(type, name); } } else if (abbrev) show_with_type(type, find_unique_abbrev(sha1, abbrev)); else show_with_type(type, sha1_to_hex(sha1)); } /* Output a flag, only if filter allows it. */ static int show_flag(const char *arg) { if (!(filter & DO_FLAGS)) return 0; if (filter & (is_rev_argument(arg) ? DO_REVS : DO_NOREV)) { show(arg); return 1; } return 0; } static int show_default(void) { const char *s = def; if (s) { unsigned char sha1[20]; def = NULL; if (!get_sha1(s, sha1)) { show_rev(NORMAL, sha1, s); return 1; } } return 0; } static int show_reference(const char *refname, const struct object_id *oid, int flag, void *cb_data) { if (ref_excluded(ref_excludes, refname)) return 0; show_rev(NORMAL, oid->hash, refname); return 0; } static int anti_reference(const char *refname, const struct object_id *oid, int flag, void *cb_data) { show_rev(REVERSED, oid->hash, refname); return 0; } static int show_abbrev(const unsigned char *sha1, void *cb_data) { show_rev(NORMAL, sha1, NULL); return 0; } static void show_datestring(const char *flag, const char *datestr) { static char buffer[100]; /* date handling requires both flags and revs */ if ((filter & (DO_FLAGS | DO_REVS)) != (DO_FLAGS | DO_REVS)) return; snprintf(buffer, sizeof(buffer), "%s%lu", flag, approxidate(datestr)); show(buffer); } static int show_file(const char *arg, int output_prefix) { show_default(); if ((filter & (DO_NONFLAGS|DO_NOREV)) == (DO_NONFLAGS|DO_NOREV)) { if (output_prefix) { const char *prefix = startup_info->prefix; show(prefix_filename(prefix, prefix ? strlen(prefix) : 0, arg)); } else show(arg); return 1; } return 0; } static int try_difference(const char *arg) { char *dotdot; unsigned char sha1[20]; unsigned char end[20]; const char *next; const char *this; int symmetric; static const char head_by_default[] = "HEAD"; if (!(dotdot = strstr(arg, ".."))) return 0; next = dotdot + 2; this = arg; symmetric = (*next == '.'); *dotdot = 0; next += symmetric; if (!*next) next = head_by_default; if (dotdot == arg) this = head_by_default; if (this == head_by_default && next == head_by_default && !symmetric) { /* * Just ".."? That is not a range but the * pathspec for the parent directory. */ *dotdot = '.'; return 0; } if (!get_sha1_committish(this, sha1) && !get_sha1_committish(next, end)) { show_rev(NORMAL, end, next); show_rev(symmetric ? NORMAL : REVERSED, sha1, this); if (symmetric) { struct commit_list *exclude; struct commit *a, *b; a = lookup_commit_reference(sha1); b = lookup_commit_reference(end); exclude = get_merge_bases(a, b); while (exclude) { struct commit *commit = pop_commit(&exclude); show_rev(REVERSED, commit->object.oid.hash, NULL); } } *dotdot = '.'; return 1; } *dotdot = '.'; return 0; } static int try_parent_shorthands(const char *arg) { char *dotdot; unsigned char sha1[20]; struct commit *commit; struct commit_list *parents; int parents_only; if ((dotdot = strstr(arg, "^!"))) parents_only = 0; else if ((dotdot = strstr(arg, "^@"))) parents_only = 1; if (!dotdot || dotdot[2]) return 0; *dotdot = 0; if (get_sha1_committish(arg, sha1)) { *dotdot = '^'; return 0; } if (!parents_only) show_rev(NORMAL, sha1, arg); commit = lookup_commit_reference(sha1); for (parents = commit->parents; parents; parents = parents->next) show_rev(parents_only ? NORMAL : REVERSED, parents->item->object.oid.hash, arg); *dotdot = '^'; return 1; } static int parseopt_dump(const struct option *o, const char *arg, int unset) { struct strbuf *parsed = o->value; if (unset) strbuf_addf(parsed, " --no-%s", o->long_name); else if (o->short_name && (o->long_name == NULL || !stuck_long)) strbuf_addf(parsed, " -%c", o->short_name); else strbuf_addf(parsed, " --%s", o->long_name); if (arg) { if (!stuck_long) strbuf_addch(parsed, ' '); else if (o->long_name) strbuf_addch(parsed, '='); sq_quote_buf(parsed, arg); } return 0; } static const char *skipspaces(const char *s) { while (isspace(*s)) s++; return s; } static int cmd_parseopt(int argc, const char **argv, const char *prefix) { static int keep_dashdash = 0, stop_at_non_option = 0; static char const * const parseopt_usage[] = { N_("git rev-parse --parseopt [<options>] -- [<args>...]"), NULL }; static struct option parseopt_opts[] = { OPT_BOOL(0, "keep-dashdash", &keep_dashdash, N_("keep the `--` passed as an arg")), OPT_BOOL(0, "stop-at-non-option", &stop_at_non_option, N_("stop parsing after the " "first non-option argument")), OPT_BOOL(0, "stuck-long", &stuck_long, N_("output in stuck long form")), OPT_END(), }; static const char * const flag_chars = "*=?!"; struct strbuf sb = STRBUF_INIT, parsed = STRBUF_INIT; const char **usage = NULL; struct option *opts = NULL; int onb = 0, osz = 0, unb = 0, usz = 0; strbuf_addstr(&parsed, "set --"); argc = parse_options(argc, argv, prefix, parseopt_opts, parseopt_usage, PARSE_OPT_KEEP_DASHDASH); if (argc < 1 || strcmp(argv[0], "--")) usage_with_options(parseopt_usage, parseopt_opts); /* get the usage up to the first line with a -- on it */ for (;;) { if (strbuf_getline(&sb, stdin) == EOF) die("premature end of input"); ALLOC_GROW(usage, unb + 1, usz); if (!strcmp("--", sb.buf)) { if (unb < 1) die("no usage string given before the `--' separator"); usage[unb] = NULL; break; } usage[unb++] = strbuf_detach(&sb, NULL); } /* parse: (<short>|<short>,<long>|<long>)[*=?!]*<arghint>? SP+ <help> */ while (strbuf_getline(&sb, stdin) != EOF) { const char *s; const char *help; struct option *o; if (!sb.len) continue; ALLOC_GROW(opts, onb + 1, osz); memset(opts + onb, 0, sizeof(opts[onb])); o = &opts[onb++]; help = strchr(sb.buf, ' '); if (!help || *sb.buf == ' ') { o->type = OPTION_GROUP; o->help = xstrdup(skipspaces(sb.buf)); continue; } o->type = OPTION_CALLBACK; o->help = xstrdup(skipspaces(help)); o->value = &parsed; o->flags = PARSE_OPT_NOARG; o->callback = &parseopt_dump; /* name(s) */ s = strpbrk(sb.buf, flag_chars); if (s == NULL) s = help; if (s - sb.buf == 1) /* short option only */ o->short_name = *sb.buf; else if (sb.buf[1] != ',') /* long option only */ o->long_name = xmemdupz(sb.buf, s - sb.buf); else { o->short_name = *sb.buf; o->long_name = xmemdupz(sb.buf + 2, s - sb.buf - 2); } /* flags */ while (s < help) { switch (*s++) { case '=': o->flags &= ~PARSE_OPT_NOARG; continue; case '?': o->flags &= ~PARSE_OPT_NOARG; o->flags |= PARSE_OPT_OPTARG; continue; case '!': o->flags |= PARSE_OPT_NONEG; continue; case '*': o->flags |= PARSE_OPT_HIDDEN; continue; } s--; break; } if (s < help) o->argh = xmemdupz(s, help - s); } strbuf_release(&sb); /* put an OPT_END() */ ALLOC_GROW(opts, onb + 1, osz); memset(opts + onb, 0, sizeof(opts[onb])); argc = parse_options(argc, argv, prefix, opts, usage, (keep_dashdash ? PARSE_OPT_KEEP_DASHDASH : 0) | (stop_at_non_option ? PARSE_OPT_STOP_AT_NON_OPTION : 0) | PARSE_OPT_SHELL_EVAL); strbuf_addstr(&parsed, " --"); sq_quote_argv(&parsed, argv, 0); puts(parsed.buf); return 0; } static int cmd_sq_quote(int argc, const char **argv) { struct strbuf buf = STRBUF_INIT; if (argc) sq_quote_argv(&buf, argv, 0); printf("%s\n", buf.buf); strbuf_release(&buf); return 0; } static void die_no_single_rev(int quiet) { if (quiet) exit(1); else die("Needed a single revision"); } static const char builtin_rev_parse_usage[] = N_("git rev-parse --parseopt [<options>] -- [<args>...]\n" " or: git rev-parse --sq-quote [<arg>...]\n" " or: git rev-parse [<options>] [<arg>...]\n" "\n" "Run \"git rev-parse --parseopt -h\" for more information on the first usage."); int cmd_rev_parse(int argc, const char **argv, const char *prefix) { int i, as_is = 0, verify = 0, quiet = 0, revs_count = 0, type = 0; int did_repo_setup = 0; int has_dashdash = 0; int output_prefix = 0; unsigned char sha1[20]; unsigned int flags = 0; const char *name = NULL; struct object_context unused; if (argc > 1 && !strcmp("--parseopt", argv[1])) return cmd_parseopt(argc - 1, argv + 1, prefix); if (argc > 1 && !strcmp("--sq-quote", argv[1])) return cmd_sq_quote(argc - 2, argv + 2); if (argc > 1 && !strcmp("-h", argv[1])) usage(builtin_rev_parse_usage); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "--")) { has_dashdash = 1; break; } } /* No options; just report on whether we're in a git repo or not. */ if (argc == 1) { setup_git_directory(); git_config(git_default_config, NULL); return 0; } for (i = 1; i < argc; i++) { const char *arg = argv[i]; if (!strcmp(arg, "--local-env-vars")) { int i; for (i = 0; local_repo_env[i]; i++) printf("%s\n", local_repo_env[i]); continue; } if (!strcmp(arg, "--resolve-git-dir")) { const char *gitdir = argv[++i]; if (!gitdir) die("--resolve-git-dir requires an argument"); gitdir = resolve_gitdir(gitdir); if (!gitdir) die("not a gitdir '%s'", argv[i]); puts(gitdir); continue; } /* The rest of the options require a git repository. */ if (!did_repo_setup) { prefix = setup_git_directory(); git_config(git_default_config, NULL); did_repo_setup = 1; } if (!strcmp(arg, "--git-path")) { if (!argv[i + 1]) die("--git-path requires an argument"); puts(git_path("%s", argv[i + 1])); i++; continue; } if (as_is) { if (show_file(arg, output_prefix) && as_is < 2) verify_filename(prefix, arg, 0); continue; } if (!strcmp(arg,"-n")) { if (++i >= argc) die("-n requires an argument"); if ((filter & DO_FLAGS) && (filter & DO_REVS)) { show(arg); show(argv[i]); } continue; } if (starts_with(arg, "-n")) { if ((filter & DO_FLAGS) && (filter & DO_REVS)) show(arg); continue; } if (*arg == '-') { if (!strcmp(arg, "--")) { as_is = 2; /* Pass on the "--" if we show anything but files.. */ if (filter & (DO_FLAGS | DO_REVS)) show_file(arg, 0); continue; } if (!strcmp(arg, "--default")) { def = argv[++i]; if (!def) die("--default requires an argument"); continue; } if (!strcmp(arg, "--prefix")) { prefix = argv[++i]; if (!prefix) die("--prefix requires an argument"); startup_info->prefix = prefix; output_prefix = 1; continue; } if (!strcmp(arg, "--revs-only")) { filter &= ~DO_NOREV; continue; } if (!strcmp(arg, "--no-revs")) { filter &= ~DO_REVS; continue; } if (!strcmp(arg, "--flags")) { filter &= ~DO_NONFLAGS; continue; } if (!strcmp(arg, "--no-flags")) { filter &= ~DO_FLAGS; continue; } if (!strcmp(arg, "--verify")) { filter &= ~(DO_FLAGS|DO_NOREV); verify = 1; continue; } if (!strcmp(arg, "--quiet") || !strcmp(arg, "-q")) { quiet = 1; flags |= GET_SHA1_QUIETLY; continue; } if (!strcmp(arg, "--short") || starts_with(arg, "--short=")) { filter &= ~(DO_FLAGS|DO_NOREV); verify = 1; abbrev = DEFAULT_ABBREV; if (arg[7] == '=') abbrev = strtoul(arg + 8, NULL, 10); if (abbrev < MINIMUM_ABBREV) abbrev = MINIMUM_ABBREV; else if (40 <= abbrev) abbrev = 40; continue; } if (!strcmp(arg, "--sq")) { output_sq = 1; continue; } if (!strcmp(arg, "--not")) { show_type ^= REVERSED; continue; } if (!strcmp(arg, "--symbolic")) { symbolic = SHOW_SYMBOLIC_ASIS; continue; } if (!strcmp(arg, "--symbolic-full-name")) { symbolic = SHOW_SYMBOLIC_FULL; continue; } if (starts_with(arg, "--abbrev-ref") && (!arg[12] || arg[12] == '=')) { abbrev_ref = 1; abbrev_ref_strict = warn_ambiguous_refs; if (arg[12] == '=') { if (!strcmp(arg + 13, "strict")) abbrev_ref_strict = 1; else if (!strcmp(arg + 13, "loose")) abbrev_ref_strict = 0; else die("unknown mode for %s", arg); } continue; } if (!strcmp(arg, "--all")) { for_each_ref(show_reference, NULL); continue; } if (starts_with(arg, "--disambiguate=")) { for_each_abbrev(arg + 15, show_abbrev, NULL); continue; } if (!strcmp(arg, "--bisect")) { for_each_ref_in("refs/bisect/bad", show_reference, NULL); for_each_ref_in("refs/bisect/good", anti_reference, NULL); continue; } if (starts_with(arg, "--branches=")) { for_each_glob_ref_in(show_reference, arg + 11, "refs/heads/", NULL); clear_ref_exclusion(&ref_excludes); continue; } if (!strcmp(arg, "--branches")) { for_each_branch_ref(show_reference, NULL); clear_ref_exclusion(&ref_excludes); continue; } if (starts_with(arg, "--tags=")) { for_each_glob_ref_in(show_reference, arg + 7, "refs/tags/", NULL); clear_ref_exclusion(&ref_excludes); continue; } if (!strcmp(arg, "--tags")) { for_each_tag_ref(show_reference, NULL); clear_ref_exclusion(&ref_excludes); continue; } if (starts_with(arg, "--glob=")) { for_each_glob_ref(show_reference, arg + 7, NULL); clear_ref_exclusion(&ref_excludes); continue; } if (starts_with(arg, "--remotes=")) { for_each_glob_ref_in(show_reference, arg + 10, "refs/remotes/", NULL); clear_ref_exclusion(&ref_excludes); continue; } if (!strcmp(arg, "--remotes")) { for_each_remote_ref(show_reference, NULL); clear_ref_exclusion(&ref_excludes); continue; } if (starts_with(arg, "--exclude=")) { add_ref_exclusion(&ref_excludes, arg + 10); continue; } if (!strcmp(arg, "--show-toplevel")) { const char *work_tree = get_git_work_tree(); if (work_tree) puts(work_tree); continue; } if (!strcmp(arg, "--show-prefix")) { if (prefix) puts(prefix); else putchar('\n'); continue; } if (!strcmp(arg, "--show-cdup")) { const char *pfx = prefix; if (!is_inside_work_tree()) { const char *work_tree = get_git_work_tree(); if (work_tree) printf("%s\n", work_tree); continue; } while (pfx) { pfx = strchr(pfx, '/'); if (pfx) { pfx++; printf("../"); } } putchar('\n'); continue; } if (!strcmp(arg, "--git-dir")) { const char *gitdir = getenv(GIT_DIR_ENVIRONMENT); char *cwd; int len; if (gitdir) { puts(gitdir); continue; } if (!prefix) { puts(".git"); continue; } cwd = xgetcwd(); len = strlen(cwd); printf("%s%s.git\n", cwd, len && cwd[len-1] != '/' ? "/" : ""); free(cwd); continue; } if (!strcmp(arg, "--git-common-dir")) { const char *pfx = prefix ? prefix : ""; puts(prefix_filename(pfx, strlen(pfx), get_git_common_dir())); continue; } if (!strcmp(arg, "--is-inside-git-dir")) { printf("%s\n", is_inside_git_dir() ? "true" : "false"); continue; } if (!strcmp(arg, "--is-inside-work-tree")) { printf("%s\n", is_inside_work_tree() ? "true" : "false"); continue; } if (!strcmp(arg, "--is-bare-repository")) { printf("%s\n", is_bare_repository() ? "true" : "false"); continue; } if (!strcmp(arg, "--shared-index-path")) { if (read_cache() < 0) die(_("Could not read the index")); if (the_index.split_index) { const unsigned char *sha1 = the_index.split_index->base_sha1; puts(git_path("sharedindex.%s", sha1_to_hex(sha1))); } continue; } if (starts_with(arg, "--since=")) { show_datestring("--max-age=", arg+8); continue; } if (starts_with(arg, "--after=")) { show_datestring("--max-age=", arg+8); continue; } if (starts_with(arg, "--before=")) { show_datestring("--min-age=", arg+9); continue; } if (starts_with(arg, "--until=")) { show_datestring("--min-age=", arg+8); continue; } if (show_flag(arg) && verify) die_no_single_rev(quiet); continue; } /* Not a flag argument */ if (try_difference(arg)) continue; if (try_parent_shorthands(arg)) continue; name = arg; type = NORMAL; if (*arg == '^') { name++; type = REVERSED; } if (!get_sha1_with_context(name, flags, sha1, &unused)) { if (verify) revs_count++; else show_rev(type, sha1, name); continue; } if (verify) die_no_single_rev(quiet); if (has_dashdash) die("bad revision '%s'", arg); as_is = 1; if (!show_file(arg, output_prefix)) continue; verify_filename(prefix, arg, 1); } if (verify) { if (revs_count == 1) { show_rev(type, sha1, name); return 0; } else if (revs_count == 0 && show_default()) return 0; die_no_single_rev(quiet); } else show_default(); return 0; }
Java
/* * Copyright (C) 2011 Peter Grasch <peter.grasch@bedahr.org> * Copyright (C) 2012 Vladislav Sitalo <root@stvad.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * or (at your option) any later version, as published by the Free * Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef JULIUSRECOGNIZER_H #define JULIUSRECOGNIZER_H #include "recognizer.h" #include <QMutex> #include <QString> #include "simonrecognizer_export.h" class KProcess; class SIMONRECOGNIZER_EXPORT JuliusRecognizer : public Recognizer { private: KProcess *m_juliusProcess; bool isBeingKilled; QMutex recognitionLock; QMutex initializationLock; private: bool blockTillPrompt(QByteArray *data=0); QByteArray readData(); bool startProcess(); public: JuliusRecognizer(); bool init(RecognitionConfiguration* config); QList<RecognitionResult> recognize(const QString& file); bool uninitialize(); virtual ~JuliusRecognizer(); }; #endif // JULIUSRECOGNIZER_H
Java
#pragma once #include <OpenEXR/ImathVec.h> #include <string> struct RenderSettings { // maximum path length allowed in the path tracer (1 = direct // illumination only). int m_pathtracerMaxNumBounces; // Max number of accumulated samples before the render finishes int m_pathtracerMaxSamples; // rendered image resolution in pixels Imath::V2i m_imageResolution; // Viewport within which to render the image. This may not match the // resolution of the rendered image, in which case stretching or squashing // will occur. int m_viewport[4]; float m_wireframeOpacity; float m_wireframeThickness; std::string m_backgroundImage; Imath::V3f m_backgroundColor[2]; // gradient (top/bottom) int m_backgroundRotationDegrees; };
Java
/* $Id: VBoxGuest-win.cpp $ */ /** @file * VBoxGuest - Windows specifics. */ /* * Copyright (C) 2010-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. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP LOG_GROUP_SUP_DRV #include "VBoxGuest-win.h" #include "VBoxGuestInternal.h" #include <iprt/asm.h> #include <iprt/asm-amd64-x86.h> #include <VBox/log.h> #include <VBox/VBoxGuestLib.h> #include <iprt/string.h> /* * XP DDK #defines ExFreePool to ExFreePoolWithTag. The latter does not exist * on NT4, so... The same for ExAllocatePool. */ #ifdef TARGET_NT4 # undef ExAllocatePool # undef ExFreePool #endif /******************************************************************************* * Internal Functions * *******************************************************************************/ RT_C_DECLS_BEGIN static NTSTATUS vbgdNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj); static void vbgdNtUnload(PDRIVER_OBJECT pDrvObj); static NTSTATUS vbgdNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtInternalIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue); static NTSTATUS vbgdNtSystemControl(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtShutdown(PDEVICE_OBJECT pDevObj, PIRP pIrp); static NTSTATUS vbgdNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp); #ifdef DEBUG static void vbgdNtDoTests(void); #endif RT_C_DECLS_END /******************************************************************************* * Exported Functions * *******************************************************************************/ RT_C_DECLS_BEGIN ULONG DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath); RT_C_DECLS_END #ifdef ALLOC_PRAGMA # pragma alloc_text(INIT, DriverEntry) # pragma alloc_text(PAGE, vbgdNtAddDevice) # pragma alloc_text(PAGE, vbgdNtUnload) # pragma alloc_text(PAGE, vbgdNtCreate) # pragma alloc_text(PAGE, vbgdNtClose) # pragma alloc_text(PAGE, vbgdNtShutdown) # pragma alloc_text(PAGE, vbgdNtNotSupportedStub) # pragma alloc_text(PAGE, vbgdNtScanPCIResourceList) #endif /******************************************************************************* * Global Variables * *******************************************************************************/ /** The detected NT (windows) version. */ VBGDNTVER g_enmVbgdNtVer = VBGDNTVER_INVALID; /** * Driver entry point. * * @returns appropriate status code. * @param pDrvObj Pointer to driver object. * @param pRegPath Registry base path. */ ULONG DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath) { NTSTATUS rc = STATUS_SUCCESS; LogFunc(("Driver built: %s %s\n", __DATE__, __TIME__)); /* * Check if the the NT version is supported and initializing * g_enmVbgdNtVer in the process. */ ULONG ulMajorVer; ULONG ulMinorVer; ULONG ulBuildNo; BOOLEAN fCheckedBuild = PsGetVersion(&ulMajorVer, &ulMinorVer, &ulBuildNo, NULL); /* Use RTLogBackdoorPrintf to make sure that this goes to VBox.log */ RTLogBackdoorPrintf("VBoxGuest: Windows version %u.%u, build %u\n", ulMajorVer, ulMinorVer, ulBuildNo); if (fCheckedBuild) RTLogBackdoorPrintf("VBoxGuest: Windows checked build\n"); #ifdef DEBUG vbgdNtDoTests(); #endif switch (ulMajorVer) { case 10: switch (ulMinorVer) { case 0: /* Windows 10 Preview builds starting with 9926. */ default: /* Also everything newer. */ g_enmVbgdNtVer = VBGDNTVER_WIN10; break; } break; case 6: /* Windows Vista or Windows 7 (based on minor ver) */ switch (ulMinorVer) { case 0: /* Note: Also could be Windows 2008 Server! */ g_enmVbgdNtVer = VBGDNTVER_WINVISTA; break; case 1: /* Note: Also could be Windows 2008 Server R2! */ g_enmVbgdNtVer = VBGDNTVER_WIN7; break; case 2: g_enmVbgdNtVer = VBGDNTVER_WIN8; break; case 3: g_enmVbgdNtVer = VBGDNTVER_WIN81; break; case 4: /* Windows 10 Preview builds. */ default: /* Also everything newer. */ g_enmVbgdNtVer = VBGDNTVER_WIN10; break; } break; case 5: switch (ulMinorVer) { default: case 2: g_enmVbgdNtVer = VBGDNTVER_WIN2K3; break; case 1: g_enmVbgdNtVer = VBGDNTVER_WINXP; break; case 0: g_enmVbgdNtVer = VBGDNTVER_WIN2K; break; } break; case 4: g_enmVbgdNtVer = VBGDNTVER_WINNT4; break; default: if (ulMajorVer > 6) { /* "Windows 10 mode" for Windows 8.1+. */ g_enmVbgdNtVer = VBGDNTVER_WIN10; } else { if (ulMajorVer < 4) LogRelFunc(("At least Windows NT4 required! (%u.%u)\n", ulMajorVer, ulMinorVer)); else LogRelFunc(("Unknown version %u.%u!\n", ulMajorVer, ulMinorVer)); rc = STATUS_DRIVER_UNABLE_TO_LOAD; } break; } if (NT_SUCCESS(rc)) { /* * Setup the driver entry points in pDrvObj. */ pDrvObj->DriverUnload = vbgdNtUnload; pDrvObj->MajorFunction[IRP_MJ_CREATE] = vbgdNtCreate; pDrvObj->MajorFunction[IRP_MJ_CLOSE] = vbgdNtClose; pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = vbgdNtIOCtl; pDrvObj->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = vbgdNtInternalIOCtl; pDrvObj->MajorFunction[IRP_MJ_SHUTDOWN] = vbgdNtShutdown; pDrvObj->MajorFunction[IRP_MJ_READ] = vbgdNtNotSupportedStub; pDrvObj->MajorFunction[IRP_MJ_WRITE] = vbgdNtNotSupportedStub; #ifdef TARGET_NT4 rc = vbgdNt4CreateDevice(pDrvObj, NULL /* pDevObj */, pRegPath); #else pDrvObj->MajorFunction[IRP_MJ_PNP] = vbgdNtPnP; pDrvObj->MajorFunction[IRP_MJ_POWER] = vbgdNtPower; pDrvObj->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = vbgdNtSystemControl; pDrvObj->DriverExtension->AddDevice = (PDRIVER_ADD_DEVICE)vbgdNtAddDevice; #endif } LogFlowFunc(("Returning %#x\n", rc)); return rc; } #ifndef TARGET_NT4 /** * Handle request from the Plug & Play subsystem. * * @returns NT status code * @param pDrvObj Driver object * @param pDevObj Device object */ static NTSTATUS vbgdNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj) { NTSTATUS rc; LogFlowFuncEnter(); /* * Create device. */ UNICODE_STRING DevName; RtlInitUnicodeString(&DevName, VBOXGUEST_DEVICE_NAME_NT); PDEVICE_OBJECT pDeviceObject = NULL; rc = IoCreateDevice(pDrvObj, sizeof(VBOXGUESTDEVEXTWIN), &DevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject); if (NT_SUCCESS(rc)) { /* * Create symbolic link (DOS devices). */ UNICODE_STRING DosName; RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS); rc = IoCreateSymbolicLink(&DosName, &DevName); if (NT_SUCCESS(rc)) { /* * Setup the device extension. */ PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDeviceObject->DeviceExtension; RT_ZERO(*pDevExt); KeInitializeSpinLock(&pDevExt->MouseEventAccessLock); pDevExt->pDeviceObject = pDeviceObject; pDevExt->prevDevState = STOPPED; pDevExt->devState = STOPPED; pDevExt->pNextLowerDriver = IoAttachDeviceToDeviceStack(pDeviceObject, pDevObj); if (pDevExt->pNextLowerDriver != NULL) { /* * If we reached this point we're fine with the basic driver setup, * so continue to init our own things. */ #ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION vbgdNtBugCheckCallback(pDevExt); /* Ignore failure! */ #endif if (NT_SUCCESS(rc)) { /* VBoxGuestPower is pageable; ensure we are not called at elevated IRQL */ pDeviceObject->Flags |= DO_POWER_PAGABLE; /* Driver is ready now. */ pDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; LogFlowFunc(("Returning with rc=0x%x (success)\n", rc)); return rc; } IoDetachDevice(pDevExt->pNextLowerDriver); } else { LogFunc(("IoAttachDeviceToDeviceStack did not give a nextLowerDriver!\n")); rc = STATUS_DEVICE_NOT_CONNECTED; } /* bail out */ IoDeleteSymbolicLink(&DosName); } else LogFunc(("IoCreateSymbolicLink failed with rc=%#x!\n", rc)); IoDeleteDevice(pDeviceObject); } else LogFunc(("IoCreateDevice failed with rc=%#x!\n", rc)); LogFunc(("Returning with rc=0x%x\n", rc)); return rc; } #endif /** * Debug helper to dump a device resource list. * * @param pResourceList list of device resources. */ static void vbgdNtShowDeviceResources(PCM_PARTIAL_RESOURCE_LIST pResourceList) { #ifdef LOG_ENABLED PCM_PARTIAL_RESOURCE_DESCRIPTOR pResource = pResourceList->PartialDescriptors; ULONG cResources = pResourceList->Count; for (ULONG i = 0; i < cResources; ++i, ++pResource) { ULONG uType = pResource->Type; static char const * const s_apszName[] = { "CmResourceTypeNull", "CmResourceTypePort", "CmResourceTypeInterrupt", "CmResourceTypeMemory", "CmResourceTypeDma", "CmResourceTypeDeviceSpecific", "CmResourceTypeBusNumber", "CmResourceTypeDevicePrivate", "CmResourceTypeAssignedResource", "CmResourceTypeSubAllocateFrom", }; LogFunc(("Type=%s", uType < RT_ELEMENTS(s_apszName) ? s_apszName[uType] : "Unknown")); switch (uType) { case CmResourceTypePort: case CmResourceTypeMemory: LogFunc(("Start %8X%8.8lX, length=%X\n", pResource->u.Port.Start.HighPart, pResource->u.Port.Start.LowPart, pResource->u.Port.Length)); break; case CmResourceTypeInterrupt: LogFunc(("Level=%X, vector=%X, affinity=%X\n", pResource->u.Interrupt.Level, pResource->u.Interrupt.Vector, pResource->u.Interrupt.Affinity)); break; case CmResourceTypeDma: LogFunc(("Channel %d, Port %X\n", pResource->u.Dma.Channel, pResource->u.Dma.Port)); break; default: LogFunc(("\n")); break; } } #endif } /** * Global initialisation stuff (PnP + NT4 legacy). * * @param pDevObj Device object. * @param pIrp Request packet. */ #ifndef TARGET_NT4 NTSTATUS vbgdNtInit(PDEVICE_OBJECT pDevObj, PIRP pIrp) #else NTSTATUS vbgdNtInit(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj, PUNICODE_STRING pRegPath) #endif { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; #ifndef TARGET_NT4 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); #endif LogFlowFuncEnter(); int rc = STATUS_SUCCESS; /** @todo r=bird: s/rc/rcNt/ and s/int/NTSTATUS/. gee. */ #ifdef TARGET_NT4 /* * Let's have a look at what our PCI adapter offers. */ LogFlowFunc(("Starting to scan PCI resources of VBoxGuest ...\n")); /* Assign the PCI resources. */ PCM_RESOURCE_LIST pResourceList = NULL; UNICODE_STRING classNameString; RtlInitUnicodeString(&classNameString, L"VBoxGuestAdapter"); rc = HalAssignSlotResources(pRegPath, &classNameString, pDrvObj, pDevObj, PCIBus, pDevExt->busNumber, pDevExt->slotNumber, &pResourceList); if (pResourceList && pResourceList->Count > 0) vbgdNtShowDeviceResources(&pResourceList->List[0].PartialResourceList); if (NT_SUCCESS(rc)) rc = vbgdNtScanPCIResourceList(pResourceList, pDevExt); #else if (pStack->Parameters.StartDevice.AllocatedResources->Count > 0) vbgdNtShowDeviceResources(&pStack->Parameters.StartDevice.AllocatedResources->List[0].PartialResourceList); if (NT_SUCCESS(rc)) rc = vbgdNtScanPCIResourceList(pStack->Parameters.StartDevice.AllocatedResourcesTranslated, pDevExt); #endif if (NT_SUCCESS(rc)) { /* * Map physical address of VMMDev memory into MMIO region * and init the common device extension bits. */ void *pvMMIOBase = NULL; uint32_t cbMMIO = 0; rc = vbgdNtMapVMMDevMemory(pDevExt, pDevExt->vmmDevPhysMemoryAddress, pDevExt->vmmDevPhysMemoryLength, &pvMMIOBase, &cbMMIO); if (NT_SUCCESS(rc)) { pDevExt->Core.pVMMDevMemory = (VMMDevMemory *)pvMMIOBase; LogFunc(("pvMMIOBase=0x%p, pDevExt=0x%p, pDevExt->Core.pVMMDevMemory=0x%p\n", pvMMIOBase, pDevExt, pDevExt ? pDevExt->Core.pVMMDevMemory : NULL)); int vrc = VbgdCommonInitDevExt(&pDevExt->Core, pDevExt->Core.IOPortBase, pvMMIOBase, cbMMIO, vbgdNtVersionToOSType(g_enmVbgdNtVer), VMMDEV_EVENT_MOUSE_POSITION_CHANGED); if (RT_FAILURE(vrc)) { LogFunc(("Could not init device extension, rc=%Rrc\n", vrc)); rc = STATUS_DEVICE_CONFIGURATION_ERROR; } } else LogFunc(("Could not map physical address of VMMDev, rc=0x%x\n", rc)); } if (NT_SUCCESS(rc)) { int vrc = VbglGRAlloc((VMMDevRequestHeader **)&pDevExt->pPowerStateRequest, sizeof(VMMDevPowerStateRequest), VMMDevReq_SetPowerStatus); if (RT_FAILURE(vrc)) { LogFunc(("Alloc for pPowerStateRequest failed, rc=%Rrc\n", vrc)); rc = STATUS_UNSUCCESSFUL; } } if (NT_SUCCESS(rc)) { /* * Register DPC and ISR. */ LogFlowFunc(("Initializing DPC/ISR ...\n")); IoInitializeDpcRequest(pDevExt->pDeviceObject, vbgdNtDpcHandler); #ifdef TARGET_NT4 ULONG uInterruptVector; KIRQL irqLevel; /* Get an interrupt vector. */ /* Only proceed if the device provides an interrupt. */ if ( pDevExt->interruptLevel || pDevExt->interruptVector) { LogFlowFunc(("Getting interrupt vector (HAL): Bus=%u, IRQL=%u, Vector=%u\n", pDevExt->busNumber, pDevExt->interruptLevel, pDevExt->interruptVector)); uInterruptVector = HalGetInterruptVector(PCIBus, pDevExt->busNumber, pDevExt->interruptLevel, pDevExt->interruptVector, &irqLevel, &pDevExt->interruptAffinity); LogFlowFunc(("HalGetInterruptVector returns vector=%u\n", uInterruptVector)); if (uInterruptVector == 0) LogFunc(("No interrupt vector found!\n")); } else LogFunc(("Device does not provide an interrupt!\n")); #endif if (pDevExt->interruptVector) { LogFlowFunc(("Connecting interrupt ...\n")); rc = IoConnectInterrupt(&pDevExt->pInterruptObject, /* Out: interrupt object. */ (PKSERVICE_ROUTINE)vbgdNtIsrHandler, /* Our ISR handler. */ pDevExt, /* Device context. */ NULL, /* Optional spinlock. */ #ifdef TARGET_NT4 uInterruptVector, /* Interrupt vector. */ irqLevel, /* Interrupt level. */ irqLevel, /* Interrupt level. */ #else pDevExt->interruptVector, /* Interrupt vector. */ (KIRQL)pDevExt->interruptLevel, /* Interrupt level. */ (KIRQL)pDevExt->interruptLevel, /* Interrupt level. */ #endif pDevExt->interruptMode, /* LevelSensitive or Latched. */ TRUE, /* Shareable interrupt. */ pDevExt->interruptAffinity, /* CPU affinity. */ FALSE); /* Don't save FPU stack. */ if (NT_ERROR(rc)) LogFunc(("Could not connect interrupt, rc=0x%x\n", rc)); } else LogFunc(("No interrupt vector found!\n")); } #ifdef VBOX_WITH_HGCM LogFunc(("Allocating kernel session data ...\n")); int vrc = VbgdCommonCreateKernelSession(&pDevExt->Core, &pDevExt->pKernelSession); if (RT_FAILURE(vrc)) { LogFunc(("Failed to allocated kernel session data, rc=%Rrc\n", rc)); rc = STATUS_UNSUCCESSFUL; } #endif if (RT_SUCCESS(rc)) { ULONG ulValue = 0; NTSTATUS rcNt = vbgdNtRegistryReadDWORD(RTL_REGISTRY_SERVICES, L"VBoxGuest", L"LoggingEnabled", &ulValue); if (NT_SUCCESS(rcNt)) { pDevExt->Core.fLoggingEnabled = ulValue >= 0xFF; if (pDevExt->Core.fLoggingEnabled) LogRelFunc(("Logging to host log enabled (0x%x)", ulValue)); } /* Ready to rumble! */ LogRelFunc(("Device is ready!\n")); VBOXGUEST_UPDATE_DEVSTATE(pDevExt, WORKING); } else pDevExt->pInterruptObject = NULL; /** @todo r=bird: The error cleanup here is completely missing. We'll leak a * whole bunch of things... */ LogFunc(("Returned with rc=0x%x\n", rc)); return rc; } /** * Cleans up hardware resources. * Do not delete DevExt here. * * @param pDrvObj Driver object. */ NTSTATUS vbgdNtCleanup(PDEVICE_OBJECT pDevObj) { LogFlowFuncEnter(); PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; if (pDevExt) { #if 0 /* @todo: test & enable cleaning global session data */ #ifdef VBOX_WITH_HGCM if (pDevExt->pKernelSession) { VbgdCommonCloseSession(pDevExt, pDevExt->pKernelSession); pDevExt->pKernelSession = NULL; } #endif #endif if (pDevExt->pInterruptObject) { IoDisconnectInterrupt(pDevExt->pInterruptObject); pDevExt->pInterruptObject = NULL; } /** @todo: cleanup the rest stuff */ #ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION hlpDeregisterBugCheckCallback(pDevExt); /* ignore failure! */ #endif /* According to MSDN we have to unmap previously mapped memory. */ vbgdNtUnmapVMMDevMemory(pDevExt); } return STATUS_SUCCESS; } /** * Unload the driver. * * @param pDrvObj Driver object. */ static void vbgdNtUnload(PDRIVER_OBJECT pDrvObj) { LogFlowFuncEnter(); #ifdef TARGET_NT4 vbgdNtCleanup(pDrvObj->DeviceObject); /* Destroy device extension and clean up everything else. */ if (pDrvObj->DeviceObject && pDrvObj->DeviceObject->DeviceExtension) VbgdCommonDeleteDevExt((PVBOXGUESTDEVEXT)pDrvObj->DeviceObject->DeviceExtension); /* * I don't think it's possible to unload a driver which processes have * opened, at least we'll blindly assume that here. */ UNICODE_STRING DosName; RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS); NTSTATUS rc = IoDeleteSymbolicLink(&DosName); IoDeleteDevice(pDrvObj->DeviceObject); #else /* !TARGET_NT4 */ /* On a PnP driver this routine will be called after * IRP_MN_REMOVE_DEVICE (where we already did the cleanup), * so don't do anything here (yet). */ #endif /* !TARGET_NT4 */ LogFlowFunc(("Returning\n")); } /** * Create (i.e. Open) file entry point. * * @param pDevObj Device object. * @param pIrp Request packet. */ static NTSTATUS vbgdNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp) { /** @todo AssertPtrReturn(pIrp); */ PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); /** @todo AssertPtrReturn(pStack); */ PFILE_OBJECT pFileObj = pStack->FileObject; PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; NTSTATUS rc = STATUS_SUCCESS; if (pDevExt->devState != WORKING) { LogFunc(("Device is not working currently, state=%d\n", pDevExt->devState)); rc = STATUS_UNSUCCESSFUL; } else if (pStack->Parameters.Create.Options & FILE_DIRECTORY_FILE) { /* * We are not remotely similar to a directory... * (But this is possible.) */ LogFlowFunc(("Uhm, we're not a directory!\n")); rc = STATUS_NOT_A_DIRECTORY; } else { #ifdef VBOX_WITH_HGCM if (pFileObj) { LogFlowFunc(("File object type=%d\n", pFileObj->Type)); int vrc; PVBOXGUESTSESSION pSession; if (pFileObj->Type == 5 /* File Object */) { /* * Create a session object if we have a valid file object. This session object * exists for every R3 process. */ vrc = VbgdCommonCreateUserSession(&pDevExt->Core, &pSession); } else { /* ... otherwise we've been called from R0! */ vrc = VbgdCommonCreateKernelSession(&pDevExt->Core, &pSession); } if (RT_SUCCESS(vrc)) pFileObj->FsContext = pSession; } #endif } /* Complete the request! */ pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = rc; IoCompleteRequest(pIrp, IO_NO_INCREMENT); LogFlowFunc(("Returning rc=0x%x\n", rc)); return rc; } /** * Close file entry point. * * @param pDevObj Device object. * @param pIrp Request packet. */ static NTSTATUS vbgdNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFileObj = pStack->FileObject; LogFlowFunc(("pDevExt=0x%p, pFileObj=0x%p, FsContext=0x%p\n", pDevExt, pFileObj, pFileObj->FsContext)); #ifdef VBOX_WITH_HGCM /* Close both, R0 and R3 sessions. */ PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)pFileObj->FsContext; if (pSession) VbgdCommonCloseSession(&pDevExt->Core, pSession); #endif pFileObj->FsContext = NULL; pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = STATUS_SUCCESS; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return STATUS_SUCCESS; } /** * Device I/O Control entry point. * * @param pDevObj Device object. * @param pIrp Request packet. */ static NTSTATUS vbgdNtIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp) { NTSTATUS Status = STATUS_SUCCESS; PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); unsigned int uCmd = (unsigned int)pStack->Parameters.DeviceIoControl.IoControlCode; char *pBuf = (char *)pIrp->AssociatedIrp.SystemBuffer; /* All requests are buffered. */ size_t cbData = pStack->Parameters.DeviceIoControl.InputBufferLength; size_t cbOut = 0; /* Do we have a file object associated?*/ PFILE_OBJECT pFileObj = pStack->FileObject; PVBOXGUESTSESSION pSession = NULL; if (pFileObj) /* ... then we might have a session object as well! */ pSession = (PVBOXGUESTSESSION)pFileObj->FsContext; LogFlowFunc(("uCmd=%u, pDevExt=0x%p, pSession=0x%p\n", uCmd, pDevExt, pSession)); /* We don't have a session associated with the file object? So this seems * to be a kernel call then. */ /** @todo r=bird: What on earth is this supposed to be? Each kernel session * shall have its own context of course, no hacks, pleeease. */ if (pSession == NULL) { LogFunc(("XXX: BUGBUG: FIXME: Using ugly kernel session data hack ...\n")); #ifdef DEBUG_andy RTLogBackdoorPrintf("XXX: BUGBUG: FIXME: Using ugly kernel session data hack ... Please don't forget to fix this one, Andy!\n"); #endif pSession = pDevExt->pKernelSession; } /* Verify that it's a buffered CTL. */ if ((pStack->Parameters.DeviceIoControl.IoControlCode & 0x3) == METHOD_BUFFERED) { /* * Process the common IOCtls. */ size_t cbDataReturned; int vrc = VbgdCommonIoCtl(uCmd, &pDevExt->Core, pSession, pBuf, cbData, &cbDataReturned); LogFlowFunc(("rc=%Rrc, pBuf=0x%p, cbData=%u, cbDataReturned=%u\n", vrc, pBuf, cbData, cbDataReturned)); if (RT_SUCCESS(vrc)) { if (RT_UNLIKELY( cbDataReturned > cbData || cbDataReturned > pStack->Parameters.DeviceIoControl.OutputBufferLength)) { LogFunc(("Too much output data %u - expected %u!\n", cbDataReturned, cbData)); cbDataReturned = cbData; Status = STATUS_BUFFER_TOO_SMALL; } if (cbDataReturned > 0) cbOut = cbDataReturned; } else { if ( vrc == VERR_NOT_SUPPORTED || vrc == VERR_INVALID_PARAMETER) Status = STATUS_INVALID_PARAMETER; else if (vrc == VERR_OUT_OF_RANGE) Status = STATUS_INVALID_BUFFER_SIZE; else Status = STATUS_UNSUCCESSFUL; } } else { LogFunc(("Not buffered request (%#x) - not supported\n", pStack->Parameters.DeviceIoControl.IoControlCode)); Status = STATUS_NOT_SUPPORTED; } pIrp->IoStatus.Status = Status; pIrp->IoStatus.Information = cbOut; IoCompleteRequest(pIrp, IO_NO_INCREMENT); //LogFlowFunc(("Returned cbOut=%d rc=%#x\n", cbOut, Status)); return Status; } /** * Internal Device I/O Control entry point. * * @param pDevObj Device object. * @param pIrp Request packet. */ static NTSTATUS vbgdNtInternalIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp) { NTSTATUS Status = STATUS_SUCCESS; PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp); unsigned int uCmd = (unsigned int)pStack->Parameters.DeviceIoControl.IoControlCode; bool fProcessed = false; unsigned Info = 0; /* * Override common behavior of some operations. */ /** @todo r=bird: Better to add dedicated worker functions for this! */ switch (uCmd) { case VBOXGUEST_IOCTL_SET_MOUSE_NOTIFY_CALLBACK: { PVOID pvBuf = pStack->Parameters.Others.Argument1; size_t cbData = (size_t)pStack->Parameters.Others.Argument2; fProcessed = true; if (cbData != sizeof(VBoxGuestMouseSetNotifyCallback)) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } VBoxGuestMouseSetNotifyCallback *pInfo = (VBoxGuestMouseSetNotifyCallback*)pvBuf; /* we need a lock here to avoid concurrency with the set event functionality */ KIRQL OldIrql; KeAcquireSpinLock(&pDevExt->MouseEventAccessLock, &OldIrql); pDevExt->Core.MouseNotifyCallback = *pInfo; KeReleaseSpinLock(&pDevExt->MouseEventAccessLock, OldIrql); Status = STATUS_SUCCESS; break; } default: break; } if (fProcessed) { pIrp->IoStatus.Status = Status; pIrp->IoStatus.Information = Info; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return Status; } /* * No override, go to common code. */ return vbgdNtIOCtl(pDevObj, pIrp); } /** * IRP_MJ_SYSTEM_CONTROL handler. * * @returns NT status code * @param pDevObj Device object. * @param pIrp IRP. */ NTSTATUS vbgdNtSystemControl(PDEVICE_OBJECT pDevObj, PIRP pIrp) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; LogFlowFuncEnter(); /* Always pass it on to the next driver. */ IoSkipCurrentIrpStackLocation(pIrp); return IoCallDriver(pDevExt->pNextLowerDriver, pIrp); } /** * IRP_MJ_SHUTDOWN handler. * * @returns NT status code * @param pDevObj Device object. * @param pIrp IRP. */ NTSTATUS vbgdNtShutdown(PDEVICE_OBJECT pDevObj, PIRP pIrp) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; LogFlowFuncEnter(); VMMDevPowerStateRequest *pReq = pDevExt->pPowerStateRequest; if (pReq) { pReq->header.requestType = VMMDevReq_SetPowerStatus; pReq->powerState = VMMDevPowerState_PowerOff; int rc = VbglGRPerform(&pReq->header); if (RT_FAILURE(rc)) LogFunc(("Error performing request to VMMDev, rc=%Rrc\n", rc)); } return STATUS_SUCCESS; } /** * Stub function for functions we don't implemented. * * @returns STATUS_NOT_SUPPORTED * @param pDevObj Device object. * @param pIrp IRP. */ NTSTATUS vbgdNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp) { LogFlowFuncEnter(); pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = STATUS_NOT_SUPPORTED; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return STATUS_NOT_SUPPORTED; } /** * DPC handler. * * @param pDPC DPC descriptor. * @param pDevObj Device object. * @param pIrp Interrupt request packet. * @param pContext Context specific pointer. */ void vbgdNtDpcHandler(PKDPC pDPC, PDEVICE_OBJECT pDevObj, PIRP pIrp, PVOID pContext) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension; Log3Func(("pDevExt=0x%p\n", pDevExt)); /* Test & reset the counter. */ if (ASMAtomicXchgU32(&pDevExt->Core.u32MousePosChangedSeq, 0)) { /* we need a lock here to avoid concurrency with the set event ioctl handler thread, * i.e. to prevent the event from destroyed while we're using it */ Assert(KeGetCurrentIrql() == DISPATCH_LEVEL); KeAcquireSpinLockAtDpcLevel(&pDevExt->MouseEventAccessLock); if (pDevExt->Core.MouseNotifyCallback.pfnNotify) pDevExt->Core.MouseNotifyCallback.pfnNotify(pDevExt->Core.MouseNotifyCallback.pvUser); KeReleaseSpinLockFromDpcLevel(&pDevExt->MouseEventAccessLock); } /* Process the wake-up list we were asked by the scheduling a DPC * in vbgdNtIsrHandler(). */ VbgdCommonWaitDoWakeUps(&pDevExt->Core); } /** * ISR handler. * * @return BOOLEAN Indicates whether the IRQ came from us (TRUE) or not (FALSE). * @param pInterrupt Interrupt that was triggered. * @param pServiceContext Context specific pointer. */ BOOLEAN vbgdNtIsrHandler(PKINTERRUPT pInterrupt, PVOID pServiceContext) { PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pServiceContext; if (pDevExt == NULL) return FALSE; /*Log3Func(("pDevExt=0x%p, pVMMDevMemory=0x%p\n", pDevExt, pDevExt ? pDevExt->pVMMDevMemory : NULL));*/ /* Enter the common ISR routine and do the actual work. */ BOOLEAN fIRQTaken = VbgdCommonISR(&pDevExt->Core); /* If we need to wake up some events we do that in a DPC to make * sure we're called at the right IRQL. */ if (fIRQTaken) { Log3Func(("IRQ was taken! pInterrupt=0x%p, pDevExt=0x%p\n", pInterrupt, pDevExt)); if (ASMAtomicUoReadU32( &pDevExt->Core.u32MousePosChangedSeq) || !RTListIsEmpty(&pDevExt->Core.WakeUpList)) { Log3Func(("Requesting DPC ...\n")); IoRequestDpc(pDevExt->pDeviceObject, pDevExt->pCurrentIrp, NULL); } } return fIRQTaken; } /** * Overridden routine for mouse polling events. * * @param pDevExt Device extension structure. */ void VbgdNativeISRMousePollEvent(PVBOXGUESTDEVEXT pDevExt) { NOREF(pDevExt); /* nothing to do here - i.e. since we can not KeSetEvent from ISR level, * we rely on the pDevExt->u32MousePosChangedSeq to be set to a non-zero value on a mouse event * and queue the DPC in our ISR routine in that case doing KeSetEvent from the DPC routine */ } /** * Queries (gets) a DWORD value from the registry. * * @return NTSTATUS * @param ulRoot Relative path root. See RTL_REGISTRY_SERVICES or RTL_REGISTRY_ABSOLUTE. * @param pwszPath Path inside path root. * @param pwszName Actual value name to look up. * @param puValue On input this can specify the default value (if RTL_REGISTRY_OPTIONAL is * not specified in ulRoot), on output this will retrieve the looked up * registry value if found. */ NTSTATUS vbgdNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue) { if (!pwszPath || !pwszName || !puValue) return STATUS_INVALID_PARAMETER; ULONG ulDefault = *puValue; RTL_QUERY_REGISTRY_TABLE tblQuery[2]; RtlZeroMemory(tblQuery, sizeof(tblQuery)); /** @todo Add RTL_QUERY_REGISTRY_TYPECHECK! */ tblQuery[0].Flags = RTL_QUERY_REGISTRY_DIRECT; tblQuery[0].Name = pwszName; tblQuery[0].EntryContext = puValue; tblQuery[0].DefaultType = REG_DWORD; tblQuery[0].DefaultData = &ulDefault; tblQuery[0].DefaultLength = sizeof(ULONG); return RtlQueryRegistryValues(ulRoot, pwszPath, &tblQuery[0], NULL /* Context */, NULL /* Environment */); } /** * Helper to scan the PCI resource list and remember stuff. * * @param pResList Resource list * @param pDevExt Device extension */ NTSTATUS vbgdNtScanPCIResourceList(PCM_RESOURCE_LIST pResList, PVBOXGUESTDEVEXTWIN pDevExt) { /* Enumerate the resource list. */ LogFlowFunc(("Found %d resources\n", pResList->List->PartialResourceList.Count)); NTSTATUS rc = STATUS_SUCCESS; PCM_PARTIAL_RESOURCE_DESCRIPTOR pPartialData = NULL; ULONG rangeCount = 0; ULONG cMMIORange = 0; PVBOXGUESTWINBASEADDRESS pBaseAddress = pDevExt->pciBaseAddress; for (ULONG i = 0; i < pResList->List->PartialResourceList.Count; i++) { pPartialData = &pResList->List->PartialResourceList.PartialDescriptors[i]; switch (pPartialData->Type) { case CmResourceTypePort: { /* Overflow protection. */ if (rangeCount < PCI_TYPE0_ADDRESSES) { LogFlowFunc(("I/O range: Base=%08x:%08x, length=%08x\n", pPartialData->u.Port.Start.HighPart, pPartialData->u.Port.Start.LowPart, pPartialData->u.Port.Length)); /* Save the IO port base. */ /** @todo Not so good. * Update/bird: What is not so good? That we just consider the last range? */ pDevExt->Core.IOPortBase = (RTIOPORT)pPartialData->u.Port.Start.LowPart; /* Save resource information. */ pBaseAddress->RangeStart = pPartialData->u.Port.Start; pBaseAddress->RangeLength = pPartialData->u.Port.Length; pBaseAddress->RangeInMemory = FALSE; pBaseAddress->ResourceMapped = FALSE; LogFunc(("I/O range for VMMDev found! Base=%08x:%08x, length=%08x\n", pPartialData->u.Port.Start.HighPart, pPartialData->u.Port.Start.LowPart, pPartialData->u.Port.Length)); /* Next item ... */ rangeCount++; pBaseAddress++; } break; } case CmResourceTypeInterrupt: { LogFunc(("Interrupt: Level=%x, vector=%x, mode=%x\n", pPartialData->u.Interrupt.Level, pPartialData->u.Interrupt.Vector, pPartialData->Flags)); /* Save information. */ pDevExt->interruptLevel = pPartialData->u.Interrupt.Level; pDevExt->interruptVector = pPartialData->u.Interrupt.Vector; pDevExt->interruptAffinity = pPartialData->u.Interrupt.Affinity; /* Check interrupt mode. */ if (pPartialData->Flags & CM_RESOURCE_INTERRUPT_LATCHED) pDevExt->interruptMode = Latched; else pDevExt->interruptMode = LevelSensitive; break; } case CmResourceTypeMemory: { /* Overflow protection. */ if (rangeCount < PCI_TYPE0_ADDRESSES) { LogFlowFunc(("Memory range: Base=%08x:%08x, length=%08x\n", pPartialData->u.Memory.Start.HighPart, pPartialData->u.Memory.Start.LowPart, pPartialData->u.Memory.Length)); /* We only care about read/write memory. */ /** @todo Reconsider memory type. */ if ( cMMIORange == 0 /* Only care about the first MMIO range (!!!). */ && (pPartialData->Flags & VBOX_CM_PRE_VISTA_MASK) == CM_RESOURCE_MEMORY_READ_WRITE) { /* Save physical MMIO base + length for VMMDev. */ pDevExt->vmmDevPhysMemoryAddress = pPartialData->u.Memory.Start; pDevExt->vmmDevPhysMemoryLength = (ULONG)pPartialData->u.Memory.Length; /* Save resource information. */ pBaseAddress->RangeStart = pPartialData->u.Memory.Start; pBaseAddress->RangeLength = pPartialData->u.Memory.Length; pBaseAddress->RangeInMemory = TRUE; pBaseAddress->ResourceMapped = FALSE; LogFunc(("Memory range for VMMDev found! Base = %08x:%08x, Length = %08x\n", pPartialData->u.Memory.Start.HighPart, pPartialData->u.Memory.Start.LowPart, pPartialData->u.Memory.Length)); /* Next item ... */ rangeCount++; pBaseAddress++; cMMIORange++; } else LogFunc(("Ignoring memory: Flags=%08x\n", pPartialData->Flags)); } break; } default: { LogFunc(("Unhandled resource found, type=%d\n", pPartialData->Type)); break; } } } /* Memorize the number of resources found. */ pDevExt->pciAddressCount = rangeCount; return rc; } /** * Maps the I/O space from VMMDev to virtual kernel address space. * * @return NTSTATUS * * @param pDevExt The device extension. * @param PhysAddr Physical address to map. * @param cbToMap Number of bytes to map. * @param ppvMMIOBase Pointer of mapped I/O base. * @param pcbMMIO Length of mapped I/O base. */ NTSTATUS vbgdNtMapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt, PHYSICAL_ADDRESS PhysAddr, ULONG cbToMap, void **ppvMMIOBase, uint32_t *pcbMMIO) { AssertPtrReturn(pDevExt, VERR_INVALID_POINTER); AssertPtrReturn(ppvMMIOBase, VERR_INVALID_POINTER); /* pcbMMIO is optional. */ NTSTATUS rc = STATUS_SUCCESS; if (PhysAddr.LowPart > 0) /* We're mapping below 4GB. */ { VMMDevMemory *pVMMDevMemory = (VMMDevMemory *)MmMapIoSpace(PhysAddr, cbToMap, MmNonCached); LogFlowFunc(("pVMMDevMemory = 0x%x\n", pVMMDevMemory)); if (pVMMDevMemory) { LogFunc(("VMMDevMemory: Version = 0x%x, Size = %d\n", pVMMDevMemory->u32Version, pVMMDevMemory->u32Size)); /* Check version of the structure; do we have the right memory version? */ if (pVMMDevMemory->u32Version == VMMDEV_MEMORY_VERSION) { /* Save results. */ *ppvMMIOBase = pVMMDevMemory; if (pcbMMIO) /* Optional. */ *pcbMMIO = pVMMDevMemory->u32Size; LogFlowFunc(("VMMDevMemory found and mapped! pvMMIOBase = 0x%p\n", *ppvMMIOBase)); } else { /* Not our version, refuse operation and unmap the memory. */ LogFunc(("Wrong version (%u), refusing operation!\n", pVMMDevMemory->u32Version)); vbgdNtUnmapVMMDevMemory(pDevExt); rc = STATUS_UNSUCCESSFUL; } } else rc = STATUS_UNSUCCESSFUL; } return rc; } /** * Unmaps the VMMDev I/O range from kernel space. * * @param pDevExt The device extension. */ void vbgdNtUnmapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt) { LogFlowFunc(("pVMMDevMemory = 0x%x\n", pDevExt->Core.pVMMDevMemory)); if (pDevExt->Core.pVMMDevMemory) { MmUnmapIoSpace((void*)pDevExt->Core.pVMMDevMemory, pDevExt->vmmDevPhysMemoryLength); pDevExt->Core.pVMMDevMemory = NULL; } pDevExt->vmmDevPhysMemoryAddress.QuadPart = 0; pDevExt->vmmDevPhysMemoryLength = 0; } VBOXOSTYPE vbgdNtVersionToOSType(VBGDNTVER enmNtVer) { VBOXOSTYPE enmOsType; switch (enmNtVer) { case VBGDNTVER_WINNT4: enmOsType = VBOXOSTYPE_WinNT4; break; case VBGDNTVER_WIN2K: enmOsType = VBOXOSTYPE_Win2k; break; case VBGDNTVER_WINXP: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_WinXP_x64; #else enmOsType = VBOXOSTYPE_WinXP; #endif break; case VBGDNTVER_WIN2K3: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win2k3_x64; #else enmOsType = VBOXOSTYPE_Win2k3; #endif break; case VBGDNTVER_WINVISTA: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_WinVista_x64; #else enmOsType = VBOXOSTYPE_WinVista; #endif break; case VBGDNTVER_WIN7: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win7_x64; #else enmOsType = VBOXOSTYPE_Win7; #endif break; case VBGDNTVER_WIN8: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win8_x64; #else enmOsType = VBOXOSTYPE_Win8; #endif break; case VBGDNTVER_WIN81: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win81_x64; #else enmOsType = VBOXOSTYPE_Win81; #endif break; case VBGDNTVER_WIN10: #if ARCH_BITS == 64 enmOsType = VBOXOSTYPE_Win10_x64; #else enmOsType = VBOXOSTYPE_Win10; #endif break; default: /* We don't know, therefore NT family. */ enmOsType = VBOXOSTYPE_WinNT; break; } return enmOsType; } #ifdef DEBUG /** * A quick implementation of AtomicTestAndClear for uint32_t and multiple bits. */ static uint32_t vboxugestwinAtomicBitsTestAndClear(void *pu32Bits, uint32_t u32Mask) { AssertPtrReturn(pu32Bits, 0); LogFlowFunc(("*pu32Bits=0x%x, u32Mask=0x%x\n", *(uint32_t *)pu32Bits, u32Mask)); uint32_t u32Result = 0; uint32_t u32WorkingMask = u32Mask; int iBitOffset = ASMBitFirstSetU32 (u32WorkingMask); while (iBitOffset > 0) { bool fSet = ASMAtomicBitTestAndClear(pu32Bits, iBitOffset - 1); if (fSet) u32Result |= 1 << (iBitOffset - 1); u32WorkingMask &= ~(1 << (iBitOffset - 1)); iBitOffset = ASMBitFirstSetU32 (u32WorkingMask); } LogFlowFunc(("Returning 0x%x\n", u32Result)); return u32Result; } static void vbgdNtTestAtomicTestAndClearBitsU32(uint32_t u32Mask, uint32_t u32Bits, uint32_t u32Exp) { ULONG u32Bits2 = u32Bits; uint32_t u32Result = vboxugestwinAtomicBitsTestAndClear(&u32Bits2, u32Mask); if ( u32Result != u32Exp || (u32Bits2 & u32Mask) || (u32Bits2 & u32Result) || ((u32Bits2 | u32Result) != u32Bits) ) AssertLogRelMsgFailed(("%s: TEST FAILED: u32Mask=0x%x, u32Bits (before)=0x%x, u32Bits (after)=0x%x, u32Result=0x%x, u32Exp=ox%x\n", __PRETTY_FUNCTION__, u32Mask, u32Bits, u32Bits2, u32Result)); } static void vbgdNtDoTests(void) { vbgdNtTestAtomicTestAndClearBitsU32(0x00, 0x23, 0); vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0, 0); vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x22, 0); vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x23, 0x1); vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x32, 0x10); vbgdNtTestAtomicTestAndClearBitsU32(0x22, 0x23, 0x22); } #endif /* DEBUG */ #ifdef VBOX_WITH_DPC_LATENCY_CHECKER /* * DPC latency checker. */ /** * One DPC latency sample. */ typedef struct DPCSAMPLE { LARGE_INTEGER PerfDelta; LARGE_INTEGER PerfCounter; LARGE_INTEGER PerfFrequency; uint64_t u64TSC; } DPCSAMPLE; AssertCompileSize(DPCSAMPLE, 4*8); /** * The DPC latency measurement workset. */ typedef struct DPCDATA { KDPC Dpc; KTIMER Timer; KSPIN_LOCK SpinLock; ULONG ulTimerRes; bool volatile fFinished; /** The timer interval (relative). */ LARGE_INTEGER DueTime; LARGE_INTEGER PerfCounterPrev; /** Align the sample array on a 64 byte boundrary just for the off chance * that we'll get cache line aligned memory backing this structure. */ uint32_t auPadding[ARCH_BITS == 32 ? 5 : 7]; int cSamples; DPCSAMPLE aSamples[8192]; } DPCDATA; AssertCompileMemberAlignment(DPCDATA, aSamples, 64); # define VBOXGUEST_DPC_TAG 'DPCS' /** * DPC callback routine for the DPC latency measurement code. * * @param pDpc The DPC, not used. * @param pvDeferredContext Pointer to the DPCDATA. * @param SystemArgument1 System use, ignored. * @param SystemArgument2 System use, ignored. */ static VOID vbgdNtDpcLatencyCallback(PKDPC pDpc, PVOID pvDeferredContext, PVOID SystemArgument1, PVOID SystemArgument2) { DPCDATA *pData = (DPCDATA *)pvDeferredContext; KeAcquireSpinLockAtDpcLevel(&pData->SpinLock); if (pData->cSamples >= RT_ELEMENTS(pData->aSamples)) pData->fFinished = true; else { DPCSAMPLE *pSample = &pData->aSamples[pData->cSamples++]; pSample->u64TSC = ASMReadTSC(); pSample->PerfCounter = KeQueryPerformanceCounter(&pSample->PerfFrequency); pSample->PerfDelta.QuadPart = pSample->PerfCounter.QuadPart - pData->PerfCounterPrev.QuadPart; pData->PerfCounterPrev.QuadPart = pSample->PerfCounter.QuadPart; KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc); } KeReleaseSpinLockFromDpcLevel(&pData->SpinLock); } /** * Handles the DPC latency checker request. * * @returns VBox status code. */ int VbgdNtIOCtl_DpcLatencyChecker(void) { /* * Allocate a block of non paged memory for samples and related data. */ DPCDATA *pData = (DPCDATA *)ExAllocatePoolWithTag(NonPagedPool, sizeof(DPCDATA), VBOXGUEST_DPC_TAG); if (!pData) { RTLogBackdoorPrintf("VBoxGuest: DPC: DPCDATA allocation failed.\n"); return VERR_NO_MEMORY; } /* * Initialize the data. */ KeInitializeDpc(&pData->Dpc, vbgdNtDpcLatencyCallback, pData); KeInitializeTimer(&pData->Timer); KeInitializeSpinLock(&pData->SpinLock); pData->fFinished = false; pData->cSamples = 0; pData->PerfCounterPrev.QuadPart = 0; pData->ulTimerRes = ExSetTimerResolution(1000 * 10, 1); pData->DueTime.QuadPart = -(int64_t)pData->ulTimerRes / 10; /* * Start the DPC measurements and wait for a full set. */ KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc); while (!pData->fFinished) { LARGE_INTEGER Interval; Interval.QuadPart = -100 * 1000 * 10; KeDelayExecutionThread(KernelMode, TRUE, &Interval); } ExSetTimerResolution(0, 0); /* * Log everything to the host. */ RTLogBackdoorPrintf("DPC: ulTimerRes = %d\n", pData->ulTimerRes); for (int i = 0; i < pData->cSamples; i++) { DPCSAMPLE *pSample = &pData->aSamples[i]; RTLogBackdoorPrintf("[%d] pd %lld pc %lld pf %lld t %lld\n", i, pSample->PerfDelta.QuadPart, pSample->PerfCounter.QuadPart, pSample->PerfFrequency.QuadPart, pSample->u64TSC); } ExFreePoolWithTag(pData, VBOXGUEST_DPC_TAG); return VINF_SUCCESS; } #endif /* VBOX_WITH_DPC_LATENCY_CHECKER */
Java
#Credits for the Assets Used. Please give credit to the respected authors for any assets used or redistributed. If you see any incorrect Copyright information below please file an [issue report](https://github.com/tsteinholz/SpaceShooter/issues) and any problems will be resolved as quickly as possible. ##Fonts | Font | Author / Source | Copyright | | :--: | :-------------: | :-------: | | Gtek_Technology_free.ttf | http://www.fonts2u.com/gtek-technology.font | Gtek Technology © (By Carlos Matteoli a.k.a Qbotype). 2013. All Rights Reserved | ##Music / Sounds | Song | Author / Source | Copyright | |:----:|:---------------:|:---------:| | Dawn.ogg | Rehan Choudhery | Space Shooter | | Rain.ogg | Rehan Choudhery | Space Shooter | | Wanted.ogg | Rehan Choudhery | Space Shooter | | MenuSelectionClick.wav | NenadSimic | Creative Commons | ##Images | Image | Author / Source | Copyright | | :---: | :-------------: | :-------: | | background.png | Ben Miller | Public Domain Dedication | | logo.png | Ross Owens | Space Shooter | | off-switch.png | Ross Owens | Space Shooter | | on-switch.png | Ross Owens | Space Shooter | | slick_arrow-delta.png | qubodup | Public Domain Dedication | | transparent-button.png | Ross Owens | Space Shooter | | white-button.png | Ross Owens | Space Shooter | | badlogic.png | Bad Logic Games | Apache 2 License | | favicon-black.png | Ross Owens | Space Shooter | | favicon-blue.png | Ross Owens | Space Shooter | | favicon-white.png | Ross Owens | Space Shooter | | laststand.png | Ross Owens + Thomas Steinholz | Space Shooter |
Java
#ifndef DATTO_CLIENT_DEVICE_SYNCHRONIZER_DEVICE_SYNCHRONIZER_INTERFACE_H_ #define DATTO_CLIENT_DEVICE_SYNCHRONIZER_DEVICE_SYNCHRONIZER_INTERFACE_H_ #include <memory> #include "backup/backup_coordinator.h" #include "backup_status_tracker/sync_count_handler.h" #include "block_device/block_device.h" #include "block_device/mountable_block_device.h" #include "unsynced_sector_manager/unsynced_sector_manager.h" namespace datto_linux_client { // Existance of this class allows for easier mocking in unit tests // The real work is done in DeviceSynchronizer class DeviceSynchronizerInterface { public: // Precondition: source_device must be both traced and mounted virtual void DoSync(std::shared_ptr<BackupCoordinator> coordinator, std::shared_ptr<SyncCountHandler> count_handler) = 0; virtual std::shared_ptr<const MountableBlockDevice> source_device() const = 0; virtual std::shared_ptr<const UnsyncedSectorManager> sector_manager() const = 0; virtual std::shared_ptr<const BlockDevice> destination_device() const = 0; virtual ~DeviceSynchronizerInterface() {} DeviceSynchronizerInterface(const DeviceSynchronizerInterface &) = delete; DeviceSynchronizerInterface& operator=(const DeviceSynchronizerInterface &) = delete; protected: DeviceSynchronizerInterface() {} }; } #endif // DATTO_CLIENT_DEVICE_SYNCHRONIZER_DEVICE_SYNCHRONIZER_INTERFACE_H_
Java
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions for the AF_INET socket handler. * * Version: @(#)sock.h 1.0.4 05/13/93 * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche <flla@stud.uni-sb.de> * * Fixes: * Alan Cox : Volatiles in skbuff pointers. See * skbuff comments. May be overdone, * better to prove they can be removed * than the reverse. * Alan Cox : Added a zapped field for tcp to note * a socket is reset and must stay shut up * Alan Cox : New fields for options * Pauline Middelink : identd support * Alan Cox : Eliminate low level recv/recvfrom * David S. Miller : New socket lookup architecture. * Steve Whitehouse: Default routines for sock_ops * Arnaldo C. Melo : removed net_pinfo, tp_pinfo and made * protinfo be just a void pointer, as the * protocol specific parts were moved to * respective headers and ipv4/v6, etc now * use private slabcaches for its socks * Pedro Hortas : New flags field for socket options * * * 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. */ #ifndef _SOCK_H #define _SOCK_H #include <linux/config.h> #include <linux/list.h> #include <linux/timer.h> #include <linux/cache.h> #include <linux/module.h> #include <linux/netdevice.h> #include <linux/skbuff.h> /* struct sk_buff */ #include <linux/security.h> #include <linux/filter.h> #include <asm/atomic.h> #include <net/dst.h> #include <net/checksum.h> /* * This structure really needs to be cleaned up. * Most of it is for TCP, and not used by any of * the other protocols. */ /* Define this to get the SOCK_DBG debugging facility. */ #define SOCK_DEBUGGING #ifdef SOCK_DEBUGGING #define SOCK_DEBUG(sk, msg...) do { if ((sk) && sock_flag((sk), SOCK_DBG)) \ printk(KERN_DEBUG msg); } while (0) #else #define SOCK_DEBUG(sk, msg...) do { } while (0) #endif /* This is the per-socket lock. The spinlock provides a synchronization * between user contexts and software interrupt processing, whereas the * mini-semaphore synchronizes multiple users amongst themselves. */ struct sock_iocb; typedef struct { spinlock_t slock; struct sock_iocb *owner; wait_queue_head_t wq; } socket_lock_t; #define sock_lock_init(__sk) \ do { spin_lock_init(&((__sk)->sk_lock.slock)); \ (__sk)->sk_lock.owner = NULL; \ init_waitqueue_head(&((__sk)->sk_lock.wq)); \ } while(0) struct sock; /** * struct sock_common - minimal network layer representation of sockets * @skc_family: network address family * @skc_state: Connection state * @skc_reuse: %SO_REUSEADDR setting * @skc_bound_dev_if: bound device index if != 0 * @skc_node: main hash linkage for various protocol lookup tables * @skc_bind_node: bind hash linkage for various protocol lookup tables * @skc_refcnt: reference count * * This is the minimal network layer representation of sockets, the header * for struct sock and struct tcp_tw_bucket. */ struct sock_common { unsigned short skc_family; volatile unsigned char skc_state; unsigned char skc_reuse; int skc_bound_dev_if; struct hlist_node skc_node; struct hlist_node skc_bind_node; atomic_t skc_refcnt; }; /** * struct sock - network layer representation of sockets * @__sk_common: shared layout with tcp_tw_bucket * @sk_shutdown: mask of %SEND_SHUTDOWN and/or %RCV_SHUTDOWN * @sk_userlocks: %SO_SNDBUF and %SO_RCVBUF settings * @sk_lock: synchronizer * @sk_rcvbuf: size of receive buffer in bytes * @sk_sleep: sock wait queue * @sk_dst_cache: destination cache * @sk_dst_lock: destination cache lock * @sk_policy: flow policy * @sk_rmem_alloc: receive queue bytes committed * @sk_receive_queue: incoming packets * @sk_wmem_alloc: transmit queue bytes committed * @sk_write_queue: Packet sending queue * @sk_omem_alloc: "o" is "option" or "other" * @sk_wmem_queued: persistent queue size * @sk_forward_alloc: space allocated forward * @sk_allocation: allocation mode * @sk_sndbuf: size of send buffer in bytes * @sk_flags: %SO_LINGER (l_onoff), %SO_BROADCAST, %SO_KEEPALIVE, %SO_OOBINLINE settings * @sk_no_check: %SO_NO_CHECK setting, wether or not checkup packets * @sk_route_caps: route capabilities (e.g. %NETIF_F_TSO) * @sk_lingertime: %SO_LINGER l_linger setting * @sk_hashent: hash entry in several tables (e.g. tcp_ehash) * @sk_backlog: always used with the per-socket spinlock held * @sk_callback_lock: used with the callbacks in the end of this struct * @sk_error_queue: rarely used * @sk_prot: protocol handlers inside a network family * @sk_prot_creator: sk_prot of original sock creator (see ipv6_setsockopt, IPV6_ADDRFORM for instance) * @sk_err: last error * @sk_err_soft: errors that don't cause failure but are the cause of a persistent failure not just 'timed out' * @sk_ack_backlog: current listen backlog * @sk_max_ack_backlog: listen backlog set in listen() * @sk_priority: %SO_PRIORITY setting * @sk_type: socket type (%SOCK_STREAM, etc) * @sk_protocol: which protocol this socket belongs in this network family * @sk_peercred: %SO_PEERCRED setting * @sk_rcvlowat: %SO_RCVLOWAT setting * @sk_rcvtimeo: %SO_RCVTIMEO setting * @sk_sndtimeo: %SO_SNDTIMEO setting * @sk_filter: socket filtering instructions * @sk_protinfo: private area, net family specific, when not using slab * @sk_timer: sock cleanup timer * @sk_stamp: time stamp of last packet received * @sk_socket: Identd and reporting IO signals * @sk_user_data: RPC layer private data * @sk_sndmsg_page: cached page for sendmsg * @sk_sndmsg_off: cached offset for sendmsg * @sk_send_head: front of stuff to transmit * @sk_security: used by security modules * @sk_write_pending: a write to stream socket waits to start * @sk_state_change: callback to indicate change in the state of the sock * @sk_data_ready: callback to indicate there is data to be processed * @sk_write_space: callback to indicate there is bf sending space available * @sk_error_report: callback to indicate errors (e.g. %MSG_ERRQUEUE) * @sk_backlog_rcv: callback to process the backlog * @sk_destruct: called at sock freeing time, i.e. when all refcnt == 0 */ struct sock { /* * Now struct tcp_tw_bucket also uses sock_common, so please just * don't add nothing before this first member (__sk_common) --acme */ struct sock_common __sk_common; #define sk_family __sk_common.skc_family #define sk_state __sk_common.skc_state #define sk_reuse __sk_common.skc_reuse #define sk_bound_dev_if __sk_common.skc_bound_dev_if #define sk_node __sk_common.skc_node #define sk_bind_node __sk_common.skc_bind_node #define sk_refcnt __sk_common.skc_refcnt unsigned char sk_shutdown : 2, sk_no_check : 2, sk_userlocks : 4; unsigned char sk_protocol; unsigned short sk_type; int sk_rcvbuf; socket_lock_t sk_lock; wait_queue_head_t *sk_sleep; struct dst_entry *sk_dst_cache; struct xfrm_policy *sk_policy[2]; rwlock_t sk_dst_lock; atomic_t sk_rmem_alloc; atomic_t sk_wmem_alloc; atomic_t sk_omem_alloc; struct sk_buff_head sk_receive_queue; struct sk_buff_head sk_write_queue; int sk_wmem_queued; int sk_forward_alloc; unsigned int sk_allocation; int sk_sndbuf; int sk_route_caps; int sk_hashent; unsigned long sk_flags; unsigned long sk_lingertime; /* * The backlog queue is special, it is always used with * the per-socket spinlock held and requires low latency * access. Therefore we special case it's implementation. */ struct { struct sk_buff *head; struct sk_buff *tail; } sk_backlog; struct sk_buff_head sk_error_queue; struct proto *sk_prot; struct proto *sk_prot_creator; rwlock_t sk_callback_lock; int sk_err, sk_err_soft; unsigned short sk_ack_backlog; unsigned short sk_max_ack_backlog; __u32 sk_priority; struct ucred sk_peercred; int sk_rcvlowat; long sk_rcvtimeo; long sk_sndtimeo; struct sk_filter *sk_filter; void *sk_protinfo; struct timer_list sk_timer; struct timeval sk_stamp; struct socket *sk_socket; void *sk_user_data; struct page *sk_sndmsg_page; struct sk_buff *sk_send_head; __u32 sk_sndmsg_off; int sk_write_pending; void *sk_security; void (*sk_state_change)(struct sock *sk); void (*sk_data_ready)(struct sock *sk, int bytes); void (*sk_write_space)(struct sock *sk); void (*sk_error_report)(struct sock *sk); int (*sk_backlog_rcv)(struct sock *sk, struct sk_buff *skb); void (*sk_destruct)(struct sock *sk); }; /* * Hashed lists helper routines */ static inline struct sock *__sk_head(struct hlist_head *head) { return hlist_entry(head->first, struct sock, sk_node); } static inline struct sock *sk_head(struct hlist_head *head) { return hlist_empty(head) ? NULL : __sk_head(head); } static inline struct sock *sk_next(struct sock *sk) { return sk->sk_node.next ? hlist_entry(sk->sk_node.next, struct sock, sk_node) : NULL; } static inline int sk_unhashed(struct sock *sk) { return hlist_unhashed(&sk->sk_node); } static inline int sk_hashed(struct sock *sk) { return sk->sk_node.pprev != NULL; } static __inline__ void sk_node_init(struct hlist_node *node) { node->pprev = NULL; } static __inline__ void __sk_del_node(struct sock *sk) { __hlist_del(&sk->sk_node); } static __inline__ int __sk_del_node_init(struct sock *sk) { if (sk_hashed(sk)) { __sk_del_node(sk); sk_node_init(&sk->sk_node); return 1; } return 0; } /* Grab socket reference count. This operation is valid only when sk is ALREADY grabbed f.e. it is found in hash table or a list and the lookup is made under lock preventing hash table modifications. */ static inline void sock_hold(struct sock *sk) { atomic_inc(&sk->sk_refcnt); } /* Ungrab socket in the context, which assumes that socket refcnt cannot hit zero, f.e. it is true in context of any socketcall. */ static inline void __sock_put(struct sock *sk) { atomic_dec(&sk->sk_refcnt); } static __inline__ int sk_del_node_init(struct sock *sk) { int rc = __sk_del_node_init(sk); if (rc) { /* paranoid for a while -acme */ WARN_ON(atomic_read(&sk->sk_refcnt) == 1); __sock_put(sk); } return rc; } static __inline__ void __sk_add_node(struct sock *sk, struct hlist_head *list) { hlist_add_head(&sk->sk_node, list); } static __inline__ void sk_add_node(struct sock *sk, struct hlist_head *list) { sock_hold(sk); __sk_add_node(sk, list); } static __inline__ void __sk_del_bind_node(struct sock *sk) { __hlist_del(&sk->sk_bind_node); } static __inline__ void sk_add_bind_node(struct sock *sk, struct hlist_head *list) { hlist_add_head(&sk->sk_bind_node, list); } #define sk_for_each(__sk, node, list) \ hlist_for_each_entry(__sk, node, list, sk_node) #define sk_for_each_from(__sk, node) \ if (__sk && ({ node = &(__sk)->sk_node; 1; })) \ hlist_for_each_entry_from(__sk, node, sk_node) #define sk_for_each_continue(__sk, node) \ if (__sk && ({ node = &(__sk)->sk_node; 1; })) \ hlist_for_each_entry_continue(__sk, node, sk_node) #define sk_for_each_safe(__sk, node, tmp, list) \ hlist_for_each_entry_safe(__sk, node, tmp, list, sk_node) #define sk_for_each_bound(__sk, node, list) \ hlist_for_each_entry(__sk, node, list, sk_bind_node) /* Sock flags */ enum sock_flags { SOCK_DEAD, SOCK_DONE, SOCK_URGINLINE, SOCK_KEEPOPEN, SOCK_LINGER, SOCK_DESTROY, SOCK_BROADCAST, SOCK_TIMESTAMP, SOCK_ZAPPED, SOCK_USE_WRITE_QUEUE, /* whether to call sk->sk_write_space in sock_wfree */ SOCK_DBG, /* %SO_DEBUG setting */ SOCK_RCVTSTAMP, /* %SO_TIMESTAMP setting */ SOCK_NO_LARGESEND, /* whether to sent large segments or not */ SOCK_LOCALROUTE, /* route locally only, %SO_DONTROUTE setting */ SOCK_QUEUE_SHRUNK, /* write queue has been shrunk recently */ }; static inline void sock_copy_flags(struct sock *nsk, struct sock *osk) { nsk->sk_flags = osk->sk_flags; } static inline void sock_set_flag(struct sock *sk, enum sock_flags flag) { __set_bit(flag, &sk->sk_flags); } static inline void sock_reset_flag(struct sock *sk, enum sock_flags flag) { __clear_bit(flag, &sk->sk_flags); } static inline int sock_flag(struct sock *sk, enum sock_flags flag) { return test_bit(flag, &sk->sk_flags); } static inline void sk_acceptq_removed(struct sock *sk) { sk->sk_ack_backlog--; } static inline void sk_acceptq_added(struct sock *sk) { sk->sk_ack_backlog++; } static inline int sk_acceptq_is_full(struct sock *sk) { return sk->sk_ack_backlog > sk->sk_max_ack_backlog; } /* * Compute minimal free write space needed to queue new packets. */ static inline int sk_stream_min_wspace(struct sock *sk) { return sk->sk_wmem_queued / 2; } static inline int sk_stream_wspace(struct sock *sk) { return sk->sk_sndbuf - sk->sk_wmem_queued; } extern void sk_stream_write_space(struct sock *sk); static inline int sk_stream_memory_free(struct sock *sk) { return sk->sk_wmem_queued < sk->sk_sndbuf; } extern void sk_stream_rfree(struct sk_buff *skb); static inline void sk_stream_set_owner_r(struct sk_buff *skb, struct sock *sk) { skb->sk = sk; skb->destructor = sk_stream_rfree; atomic_add(skb->truesize, &sk->sk_rmem_alloc); sk->sk_forward_alloc -= skb->truesize; } static inline void sk_stream_free_skb(struct sock *sk, struct sk_buff *skb) { sock_set_flag(sk, SOCK_QUEUE_SHRUNK); sk->sk_wmem_queued -= skb->truesize; sk->sk_forward_alloc += skb->truesize; __kfree_skb(skb); } /* The per-socket spinlock must be held here. */ #define sk_add_backlog(__sk, __skb) \ do { if (!(__sk)->sk_backlog.tail) { \ (__sk)->sk_backlog.head = \ (__sk)->sk_backlog.tail = (__skb); \ } else { \ ((__sk)->sk_backlog.tail)->next = (__skb); \ (__sk)->sk_backlog.tail = (__skb); \ } \ (__skb)->next = NULL; \ } while(0) #define sk_wait_event(__sk, __timeo, __condition) \ ({ int rc; \ release_sock(__sk); \ rc = __condition; \ if (!rc) { \ *(__timeo) = schedule_timeout(*(__timeo)); \ rc = __condition; \ } \ lock_sock(__sk); \ rc; \ }) extern int sk_stream_wait_connect(struct sock *sk, long *timeo_p); extern int sk_stream_wait_memory(struct sock *sk, long *timeo_p); extern void sk_stream_wait_close(struct sock *sk, long timeo_p); extern int sk_stream_error(struct sock *sk, int flags, int err); extern void sk_stream_kill_queues(struct sock *sk); extern int sk_wait_data(struct sock *sk, long *timeo); struct request_sock_ops; /* Networking protocol blocks we attach to sockets. * socket layer -> transport layer interface * transport -> network interface is defined by struct inet_proto */ struct proto { void (*close)(struct sock *sk, long timeout); int (*connect)(struct sock *sk, struct sockaddr *uaddr, int addr_len); int (*disconnect)(struct sock *sk, int flags); struct sock * (*accept) (struct sock *sk, int flags, int *err); int (*ioctl)(struct sock *sk, int cmd, unsigned long arg); int (*init)(struct sock *sk); int (*destroy)(struct sock *sk); void (*shutdown)(struct sock *sk, int how); int (*setsockopt)(struct sock *sk, int level, int optname, char __user *optval, int optlen); int (*getsockopt)(struct sock *sk, int level, int optname, char __user *optval, int __user *option); int (*sendmsg)(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len); int (*recvmsg)(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len); int (*sendpage)(struct sock *sk, struct page *page, int offset, size_t size, int flags); int (*bind)(struct sock *sk, struct sockaddr *uaddr, int addr_len); int (*backlog_rcv) (struct sock *sk, struct sk_buff *skb); /* Keeping track of sk's, looking them up, and port selection methods. */ void (*hash)(struct sock *sk); void (*unhash)(struct sock *sk); int (*get_port)(struct sock *sk, unsigned short snum); /* Memory pressure */ void (*enter_memory_pressure)(void); atomic_t *memory_allocated; /* Current allocated memory. */ atomic_t *sockets_allocated; /* Current number of sockets. */ /* * Pressure flag: try to collapse. * Technical note: it is used by multiple contexts non atomically. * All the sk_stream_mem_schedule() is of this nature: accounting * is strict, actions are advisory and have some latency. */ int *memory_pressure; int *sysctl_mem; int *sysctl_wmem; int *sysctl_rmem; int max_header; kmem_cache_t *slab; unsigned int obj_size; struct request_sock_ops *rsk_prot; struct module *owner; char name[32]; struct list_head node; struct { int inuse; u8 __pad[SMP_CACHE_BYTES - sizeof(int)]; } stats[NR_CPUS]; }; extern int proto_register(struct proto *prot, int alloc_slab); extern void proto_unregister(struct proto *prot); /* Called with local bh disabled */ static __inline__ void sock_prot_inc_use(struct proto *prot) { prot->stats[smp_processor_id()].inuse++; } static __inline__ void sock_prot_dec_use(struct proto *prot) { prot->stats[smp_processor_id()].inuse--; } /* About 10 seconds */ #define SOCK_DESTROY_TIME (10*HZ) /* Sockets 0-1023 can't be bound to unless you are superuser */ #define PROT_SOCK 1024 #define SHUTDOWN_MASK 3 #define RCV_SHUTDOWN 1 #define SEND_SHUTDOWN 2 #define SOCK_SNDBUF_LOCK 1 #define SOCK_RCVBUF_LOCK 2 #define SOCK_BINDADDR_LOCK 4 #define SOCK_BINDPORT_LOCK 8 /* sock_iocb: used to kick off async processing of socket ios */ struct sock_iocb { struct list_head list; int flags; int size; struct socket *sock; struct sock *sk; struct scm_cookie *scm; struct msghdr *msg, async_msg; struct iovec async_iov; struct kiocb *kiocb; }; static inline struct sock_iocb *kiocb_to_siocb(struct kiocb *iocb) { return (struct sock_iocb *)iocb->private; } static inline struct kiocb *siocb_to_kiocb(struct sock_iocb *si) { return si->kiocb; } struct socket_alloc { struct socket socket; struct inode vfs_inode; }; static inline struct socket *SOCKET_I(struct inode *inode) { return &container_of(inode, struct socket_alloc, vfs_inode)->socket; } static inline struct inode *SOCK_INODE(struct socket *socket) { return &container_of(socket, struct socket_alloc, socket)->vfs_inode; } extern void __sk_stream_mem_reclaim(struct sock *sk); extern int sk_stream_mem_schedule(struct sock *sk, int size, int kind); #define SK_STREAM_MEM_QUANTUM ((int)PAGE_SIZE) static inline int sk_stream_pages(int amt) { return (amt + SK_STREAM_MEM_QUANTUM - 1) / SK_STREAM_MEM_QUANTUM; } static inline void sk_stream_mem_reclaim(struct sock *sk) { if (sk->sk_forward_alloc >= SK_STREAM_MEM_QUANTUM) __sk_stream_mem_reclaim(sk); } static inline void sk_stream_writequeue_purge(struct sock *sk) { struct sk_buff *skb; while ((skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) sk_stream_free_skb(sk, skb); sk_stream_mem_reclaim(sk); } static inline int sk_stream_rmem_schedule(struct sock *sk, struct sk_buff *skb) { return (int)skb->truesize <= sk->sk_forward_alloc || sk_stream_mem_schedule(sk, skb->truesize, 1); } /* Used by processes to "lock" a socket state, so that * interrupts and bottom half handlers won't change it * from under us. It essentially blocks any incoming * packets, so that we won't get any new data or any * packets that change the state of the socket. * * While locked, BH processing will add new packets to * the backlog queue. This queue is processed by the * owner of the socket lock right before it is released. * * Since ~2.3.5 it is also exclusive sleep lock serializing * accesses from user process context. */ #define sock_owned_by_user(sk) ((sk)->sk_lock.owner) extern void FASTCALL(lock_sock(struct sock *sk)); extern void FASTCALL(release_sock(struct sock *sk)); /* BH context may only use the following locking interface. */ #define bh_lock_sock(__sk) spin_lock(&((__sk)->sk_lock.slock)) #define bh_unlock_sock(__sk) spin_unlock(&((__sk)->sk_lock.slock)) extern struct sock *sk_alloc(int family, unsigned int __nocast priority, struct proto *prot, int zero_it); extern void sk_free(struct sock *sk); extern struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, unsigned int __nocast priority); extern struct sk_buff *sock_rmalloc(struct sock *sk, unsigned long size, int force, unsigned int __nocast priority); extern void sock_wfree(struct sk_buff *skb); extern void sock_rfree(struct sk_buff *skb); extern int sock_setsockopt(struct socket *sock, int level, int op, char __user *optval, int optlen); extern int sock_getsockopt(struct socket *sock, int level, int op, char __user *optval, int __user *optlen); extern struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size, int noblock, int *errcode); extern void *sock_kmalloc(struct sock *sk, int size, unsigned int __nocast priority); extern void sock_kfree_s(struct sock *sk, void *mem, int size); extern void sk_send_sigurg(struct sock *sk); /* * Functions to fill in entries in struct proto_ops when a protocol * does not implement a particular function. */ extern int sock_no_bind(struct socket *, struct sockaddr *, int); extern int sock_no_connect(struct socket *, struct sockaddr *, int, int); extern int sock_no_socketpair(struct socket *, struct socket *); extern int sock_no_accept(struct socket *, struct socket *, int); extern int sock_no_getname(struct socket *, struct sockaddr *, int *, int); extern unsigned int sock_no_poll(struct file *, struct socket *, struct poll_table_struct *); extern int sock_no_ioctl(struct socket *, unsigned int, unsigned long); extern int sock_no_listen(struct socket *, int); extern int sock_no_shutdown(struct socket *, int); extern int sock_no_getsockopt(struct socket *, int , int, char __user *, int __user *); extern int sock_no_setsockopt(struct socket *, int, int, char __user *, int); extern int sock_no_sendmsg(struct kiocb *, struct socket *, struct msghdr *, size_t); extern int sock_no_recvmsg(struct kiocb *, struct socket *, struct msghdr *, size_t, int); extern int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma); extern ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags); /* * Functions to fill in entries in struct proto_ops when a protocol * uses the inet style. */ extern int sock_common_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen); extern int sock_common_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags); extern int sock_common_setsockopt(struct socket *sock, int level, int optname, char __user *optval, int optlen); extern void sk_common_release(struct sock *sk); /* * Default socket callbacks and setup code */ /* Initialise core socket variables */ extern void sock_init_data(struct socket *sock, struct sock *sk); /** * sk_filter - run a packet through a socket filter * @sk: sock associated with &sk_buff * @skb: buffer to filter * @needlock: set to 1 if the sock is not locked by caller. * * Run the filter code and then cut skb->data to correct size returned by * sk_run_filter. If pkt_len is 0 we toss packet. If skb->len is smaller * than pkt_len we keep whole skb->data. This is the socket level * wrapper to sk_run_filter. It returns 0 if the packet should * be accepted or -EPERM if the packet should be tossed. * */ static inline int sk_filter(struct sock *sk, struct sk_buff *skb, int needlock) { int err; err = security_sock_rcv_skb(sk, skb); if (err) return err; if (sk->sk_filter) { struct sk_filter *filter; if (needlock) bh_lock_sock(sk); filter = sk->sk_filter; if (filter) { int pkt_len = sk_run_filter(skb, filter->insns, filter->len); if (!pkt_len) err = -EPERM; else skb_trim(skb, pkt_len); } if (needlock) bh_unlock_sock(sk); } return err; } /** * sk_filter_release: Release a socket filter * @sk: socket * @fp: filter to remove * * Remove a filter from a socket and release its resources. */ static inline void sk_filter_release(struct sock *sk, struct sk_filter *fp) { unsigned int size = sk_filter_len(fp); atomic_sub(size, &sk->sk_omem_alloc); if (atomic_dec_and_test(&fp->refcnt)) kfree(fp); } static inline void sk_filter_charge(struct sock *sk, struct sk_filter *fp) { atomic_inc(&fp->refcnt); atomic_add(sk_filter_len(fp), &sk->sk_omem_alloc); } /* * Socket reference counting postulates. * * * Each user of socket SHOULD hold a reference count. * * Each access point to socket (an hash table bucket, reference from a list, * running timer, skb in flight MUST hold a reference count. * * When reference count hits 0, it means it will never increase back. * * When reference count hits 0, it means that no references from * outside exist to this socket and current process on current CPU * is last user and may/should destroy this socket. * * sk_free is called from any context: process, BH, IRQ. When * it is called, socket has no references from outside -> sk_free * may release descendant resources allocated by the socket, but * to the time when it is called, socket is NOT referenced by any * hash tables, lists etc. * * Packets, delivered from outside (from network or from another process) * and enqueued on receive/error queues SHOULD NOT grab reference count, * when they sit in queue. Otherwise, packets will leak to hole, when * socket is looked up by one cpu and unhasing is made by another CPU. * It is true for udp/raw, netlink (leak to receive and error queues), tcp * (leak to backlog). Packet socket does all the processing inside * BR_NETPROTO_LOCK, so that it has not this race condition. UNIX sockets * use separate SMP lock, so that they are prone too. */ /* Ungrab socket and destroy it, if it was the last reference. */ static inline void sock_put(struct sock *sk) { if (atomic_dec_and_test(&sk->sk_refcnt)) sk_free(sk); } /* Detach socket from process context. * Announce socket dead, detach it from wait queue and inode. * Note that parent inode held reference count on this struct sock, * we do not release it in this function, because protocol * probably wants some additional cleanups or even continuing * to work with this socket (TCP). */ static inline void sock_orphan(struct sock *sk) { write_lock_bh(&sk->sk_callback_lock); sock_set_flag(sk, SOCK_DEAD); sk->sk_socket = NULL; sk->sk_sleep = NULL; write_unlock_bh(&sk->sk_callback_lock); } static inline void sock_graft(struct sock *sk, struct socket *parent) { write_lock_bh(&sk->sk_callback_lock); sk->sk_sleep = &parent->wait; parent->sk = sk; sk->sk_socket = parent; write_unlock_bh(&sk->sk_callback_lock); } extern int sock_i_uid(struct sock *sk); extern unsigned long sock_i_ino(struct sock *sk); static inline struct dst_entry * __sk_dst_get(struct sock *sk) { return sk->sk_dst_cache; } static inline struct dst_entry * sk_dst_get(struct sock *sk) { struct dst_entry *dst; read_lock(&sk->sk_dst_lock); dst = sk->sk_dst_cache; if (dst) dst_hold(dst); read_unlock(&sk->sk_dst_lock); return dst; } static inline void __sk_dst_set(struct sock *sk, struct dst_entry *dst) { struct dst_entry *old_dst; old_dst = sk->sk_dst_cache; sk->sk_dst_cache = dst; dst_release(old_dst); } static inline void sk_dst_set(struct sock *sk, struct dst_entry *dst) { write_lock(&sk->sk_dst_lock); __sk_dst_set(sk, dst); write_unlock(&sk->sk_dst_lock); } static inline void __sk_dst_reset(struct sock *sk) { struct dst_entry *old_dst; old_dst = sk->sk_dst_cache; sk->sk_dst_cache = NULL; dst_release(old_dst); } static inline void sk_dst_reset(struct sock *sk) { write_lock(&sk->sk_dst_lock); __sk_dst_reset(sk); write_unlock(&sk->sk_dst_lock); } static inline struct dst_entry * __sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk->sk_dst_cache; if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk->sk_dst_cache = NULL; dst_release(dst); return NULL; } return dst; } static inline struct dst_entry * sk_dst_check(struct sock *sk, u32 cookie) { struct dst_entry *dst = sk_dst_get(sk); if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) { sk_dst_reset(sk); dst_release(dst); return NULL; } return dst; } static inline void sk_charge_skb(struct sock *sk, struct sk_buff *skb) { sk->sk_wmem_queued += skb->truesize; sk->sk_forward_alloc -= skb->truesize; } static inline int skb_copy_to_page(struct sock *sk, char __user *from, struct sk_buff *skb, struct page *page, int off, int copy) { if (skb->ip_summed == CHECKSUM_NONE) { int err = 0; unsigned int csum = csum_and_copy_from_user(from, page_address(page) + off, copy, 0, &err); if (err) return err; skb->csum = csum_block_add(skb->csum, csum, skb->len); } else if (copy_from_user(page_address(page) + off, from, copy)) return -EFAULT; skb->len += copy; skb->data_len += copy; skb->truesize += copy; sk->sk_wmem_queued += copy; sk->sk_forward_alloc -= copy; return 0; } /* * Queue a received datagram if it will fit. Stream and sequenced * protocols can't normally use this as they need to fit buffers in * and play with them. * * Inlined as it's very short and called for pretty much every * packet ever received. */ static inline void skb_set_owner_w(struct sk_buff *skb, struct sock *sk) { sock_hold(sk); skb->sk = sk; skb->destructor = sock_wfree; atomic_add(skb->truesize, &sk->sk_wmem_alloc); } static inline void skb_set_owner_r(struct sk_buff *skb, struct sock *sk) { skb->sk = sk; skb->destructor = sock_rfree; atomic_add(skb->truesize, &sk->sk_rmem_alloc); } extern void sk_reset_timer(struct sock *sk, struct timer_list* timer, unsigned long expires); extern void sk_stop_timer(struct sock *sk, struct timer_list* timer); static inline int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err = 0; int skb_len; /* Cast skb->rcvbuf to unsigned... It's pointless, but reduces number of warnings when compiling with -W --ANK */ if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned)sk->sk_rcvbuf) { err = -ENOMEM; goto out; } /* It would be deadlock, if sock_queue_rcv_skb is used with socket lock! We assume that users of this function are lock free. */ err = sk_filter(sk, skb, 1); if (err) goto out; skb->dev = NULL; skb_set_owner_r(skb, sk); /* Cache the SKB length before we tack it onto the receive * queue. Once it is added it no longer belongs to us and * may be freed by other threads of control pulling packets * from the queue. */ skb_len = skb->len; skb_queue_tail(&sk->sk_receive_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb_len); out: return err; } static inline int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb) { /* Cast skb->rcvbuf to unsigned... It's pointless, but reduces number of warnings when compiling with -W --ANK */ if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned)sk->sk_rcvbuf) return -ENOMEM; skb_set_owner_r(skb, sk); skb_queue_tail(&sk->sk_error_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 0; } /* * Recover an error report and clear atomically */ static inline int sock_error(struct sock *sk) { int err = xchg(&sk->sk_err, 0); return -err; } static inline unsigned long sock_wspace(struct sock *sk) { int amt = 0; if (!(sk->sk_shutdown & SEND_SHUTDOWN)) { amt = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc); if (amt < 0) amt = 0; } return amt; } static inline void sk_wake_async(struct sock *sk, int how, int band) { if (sk->sk_socket && sk->sk_socket->fasync_list) sock_wake_async(sk->sk_socket, how, band); } #define SOCK_MIN_SNDBUF 2048 #define SOCK_MIN_RCVBUF 256 static inline void sk_stream_moderate_sndbuf(struct sock *sk) { if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK)) { sk->sk_sndbuf = min(sk->sk_sndbuf, sk->sk_wmem_queued / 2); sk->sk_sndbuf = max(sk->sk_sndbuf, SOCK_MIN_SNDBUF); } } static inline struct sk_buff *sk_stream_alloc_pskb(struct sock *sk, int size, int mem, unsigned int __nocast gfp) { struct sk_buff *skb; int hdr_len; hdr_len = SKB_DATA_ALIGN(sk->sk_prot->max_header); skb = alloc_skb(size + hdr_len, gfp); if (skb) { skb->truesize += mem; if (sk->sk_forward_alloc >= (int)skb->truesize || sk_stream_mem_schedule(sk, skb->truesize, 0)) { skb_reserve(skb, hdr_len); return skb; } __kfree_skb(skb); } else { sk->sk_prot->enter_memory_pressure(); sk_stream_moderate_sndbuf(sk); } return NULL; } static inline struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, unsigned int __nocast gfp) { return sk_stream_alloc_pskb(sk, size, 0, gfp); } static inline struct page *sk_stream_alloc_page(struct sock *sk) { struct page *page = NULL; if (sk->sk_forward_alloc >= (int)PAGE_SIZE || sk_stream_mem_schedule(sk, PAGE_SIZE, 0)) page = alloc_pages(sk->sk_allocation, 0); else { sk->sk_prot->enter_memory_pressure(); sk_stream_moderate_sndbuf(sk); } return page; } #define sk_stream_for_retrans_queue(skb, sk) \ for (skb = (sk)->sk_write_queue.next; \ (skb != (sk)->sk_send_head) && \ (skb != (struct sk_buff *)&(sk)->sk_write_queue); \ skb = skb->next) /* * Default write policy as shown to user space via poll/select/SIGIO */ static inline int sock_writeable(const struct sock *sk) { return atomic_read(&sk->sk_wmem_alloc) < (sk->sk_sndbuf / 2); } static inline unsigned int __nocast gfp_any(void) { return in_softirq() ? GFP_ATOMIC : GFP_KERNEL; } static inline long sock_rcvtimeo(const struct sock *sk, int noblock) { return noblock ? 0 : sk->sk_rcvtimeo; } static inline long sock_sndtimeo(const struct sock *sk, int noblock) { return noblock ? 0 : sk->sk_sndtimeo; } static inline int sock_rcvlowat(const struct sock *sk, int waitall, int len) { return (waitall ? len : min_t(int, sk->sk_rcvlowat, len)) ? : 1; } /* Alas, with timeout socket operations are not restartable. * Compare this to poll(). */ static inline int sock_intr_errno(long timeo) { return timeo == MAX_SCHEDULE_TIMEOUT ? -ERESTARTSYS : -EINTR; } static __inline__ void sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { struct timeval *stamp = &skb->stamp; if (sock_flag(sk, SOCK_RCVTSTAMP)) { /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (stamp->tv_sec == 0) do_gettimeofday(stamp); put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP, sizeof(struct timeval), stamp); } else sk->sk_stamp = *stamp; } /** * sk_eat_skb - Release a skb if it is no longer needed * @sk: socket to eat this skb from * @skb: socket buffer to eat * * This routine must be called with interrupts disabled or with the socket * locked so that the sk_buff queue operation is ok. */ static inline void sk_eat_skb(struct sock *sk, struct sk_buff *skb) { __skb_unlink(skb, &sk->sk_receive_queue); __kfree_skb(skb); } extern void sock_enable_timestamp(struct sock *sk); extern int sock_get_timestamp(struct sock *, struct timeval __user *); /* * Enable debug/info messages */ #if 0 #define NETDEBUG(x) do { } while (0) #define LIMIT_NETDEBUG(x) do {} while(0) #else #define NETDEBUG(x) do { x; } while (0) #define LIMIT_NETDEBUG(x) do { if (net_ratelimit()) { x; } } while(0) #endif /* * Macros for sleeping on a socket. Use them like this: * * SOCK_SLEEP_PRE(sk) * if (condition) * schedule(); * SOCK_SLEEP_POST(sk) * * N.B. These are now obsolete and were, afaik, only ever used in DECnet * and when the last use of them in DECnet has gone, I'm intending to * remove them. */ #define SOCK_SLEEP_PRE(sk) { struct task_struct *tsk = current; \ DECLARE_WAITQUEUE(wait, tsk); \ tsk->state = TASK_INTERRUPTIBLE; \ add_wait_queue((sk)->sk_sleep, &wait); \ release_sock(sk); #define SOCK_SLEEP_POST(sk) tsk->state = TASK_RUNNING; \ remove_wait_queue((sk)->sk_sleep, &wait); \ lock_sock(sk); \ } static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } extern __u32 sysctl_wmem_max; extern __u32 sysctl_rmem_max; #ifdef CONFIG_NET int siocdevprivate_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg); #else static inline int siocdevprivate_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { return -ENODEV; } #endif #endif /* _SOCK_H */
Java
/*********************************************************************************** * Smooth Tasks * Copyright (C) 2009 Mathias Panzenböck <grosser.meister.morti@gmx.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***********************************************************************************/ #include "SmoothTasks/FixedItemCountTaskbarLayout.h" #include <QApplication> #include <cmath> namespace SmoothTasks { void FixedItemCountTaskbarLayout::setItemsPerRow(int itemsPerRow) { if (m_itemsPerRow != itemsPerRow) { m_itemsPerRow = itemsPerRow; invalidate(); } } int FixedItemCountTaskbarLayout::optimumCapacity() const { return m_itemsPerRow * maximumRows(); } void FixedItemCountTaskbarLayout::doLayout() { // I think this way the loops can be optimized by the compiler. // (lifting out the comparison and making two loops; TODO: find out whether this is true): const bool isVertical = orientation() == Qt::Vertical; const QList<TaskbarItem*>& items = this->items(); const int N = items.size(); // if there is nothing to layout fill in some dummy data and leave if (N == 0) { stopAnimation(); QRectF rect(geometry()); m_rows = 1; if (isVertical) { m_cellHeight = rect.width(); } else { m_cellHeight = rect.height(); } QSizeF newPreferredSize(qMin(10.0, rect.width()), qMin(10.0, rect.height())); if (newPreferredSize != m_preferredSize) { m_preferredSize = newPreferredSize; emit sizeHintChanged(Qt::PreferredSize); } return; } const QRectF effectiveRect(effectiveGeometry()); const qreal availableWidth = isVertical ? effectiveRect.height() : effectiveRect.width(); const qreal availableHeight = isVertical ? effectiveRect.width() : effectiveRect.height(); const qreal spacing = this->spacing(); #define CELL_HEIGHT(ROWS) (((availableHeight + spacing) / ((qreal) (ROWS))) - spacing) int itemsPerRow = m_itemsPerRow; int rows = maximumRows(); if (itemsPerRow * rows < N) { itemsPerRow = std::ceil(((qreal) N) / rows); } else { rows = std::ceil(((qreal) N) / itemsPerRow); } qreal cellHeight = CELL_HEIGHT(rows); qreal cellWidth = cellHeight * aspectRatio(); QList<RowInfo> rowInfos; qreal maxPreferredRowWidth = 0; buildRows(itemsPerRow, cellWidth, rowInfos, rows, maxPreferredRowWidth); cellHeight = CELL_HEIGHT(rows); updateLayout(rows, cellWidth, cellHeight, availableWidth, maxPreferredRowWidth, rowInfos, effectiveRect); #undef CELL_HEIGHT } } // namespace SmoothTasks
Java
#ifndef _HEAD_HACK_CLIENT #define _HEAD_HACK_CLIENT #define SOCKET_SEND_MAXLEN 1024 int init_client_connect(); int handle_send(int sock_fd, const char *msg); #endif
Java
'use strict'; var env = process.env.NODE_ENV || 'development', config = require('./config'), B = require('bluebird'), _ = require('underscore'), L = require('./logger'), S = require('underscore.string'), nodemailer = require('nodemailer'), smtpTransport = require('nodemailer-smtp-pool'); var Mailer = function (options) { var opts = _.extend({}, config.mail, options); this.transporter = B.promisifyAll(nodemailer.createTransport(smtpTransport(opts))); }; Mailer.prototype.send = function (options) { var that = this; return that.transporter.sendMailAsync(options); }; module.exports = Mailer;
Java
/* Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 <linux/kernel.h> #include <linux/irq.h> #include <linux/gpio.h> #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/bootmem.h> #include <linux/io.h> #ifdef CONFIG_SPI_QSD #include <linux/spi/spi.h> #endif #include <linux/mfd/pmic8058.h> #include <linux/mfd/marimba.h> #include <linux/i2c.h> #include <linux/input.h> #ifdef CONFIG_SMSC911X #include <linux/smsc911x.h> #endif #include <linux/ofn_atlab.h> #include <linux/power_supply.h> #include <linux/input/pmic8058-keypad.h> #include <linux/i2c/isa1200.h> #include <linux/pwm.h> #include <linux/pmic8058-pwm.h> #include <linux/i2c/tsc2007.h> #include <linux/input/kp_flip_switch.h> #include <linux/leds-pmic8058.h> #include <linux/input/cy8c_ts.h> #include <linux/msm_adc.h> #include <linux/dma-mapping.h> #ifdef CONFIG_KEYBOARD_GPIO #include <linux/gpio_keys.h> // DIV2-SW2-BSP-FBx-BUTTONS #endif #ifdef CONFIG_PMIC8058_VIBRATOR #include <linux/pmic8058-vibrator.h> // DIV2-SW2-BSP-FBx-VIB #endif #include <linux/gps_fm_lna.h> /* AlbertYCFang, 2011.06.13, FM */ #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/setup.h> #include <mach/mpp.h> #include <mach/board.h> #include <mach/camera.h> #include <mach/memory.h> #include <mach/msm_iomap.h> #include <mach/msm_hsusb.h> #include <mach/rpc_hsusb.h> #include <mach/msm_spi.h> #include <mach/qdsp5v2/msm_lpa.h> #include <mach/dma.h> #include <linux/android_pmem.h> #include <linux/input/msm_ts.h> #include <mach/pmic.h> #include <mach/rpc_pmapp.h> #include <mach/qdsp5v2/aux_pcm.h> #include <mach/qdsp5v2/mi2s.h> #include <mach/qdsp5v2/audio_dev_ctl.h> #ifdef CONFIG_BATTERY_MSM #include <mach/msm_battery.h> #endif #include <mach/rpc_server_handset.h> #include <mach/msm_tsif.h> #include <mach/socinfo.h> #include <linux/cyttsp.h> #include <asm/mach/mmc.h> #include <asm/mach/flash.h> #include <mach/vreg.h> #include "devices.h" #include "timer.h" #ifdef CONFIG_USB_ANDROID #include <linux/usb/android_composite.h> #endif #include "pm.h" #include "spm.h" #include <linux/msm_kgsl.h> #include <mach/dal_axi.h> #include <mach/msm_serial_hs.h> #include <mach/msm_reqs.h> #include <mach/qdsp5v2/mi2s.h> #include <mach/qdsp5v2/audio_dev_ctl.h> #include <mach/sdio_al.h> #include "smd_private.h" #include <linux/fih_hw_info.h> //FIHTDC, Div2-SW2-BSP /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL #undef HDMI_RESET #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ #include <linux/bma150.h> #ifdef CONFIG_LEDS_FIH_FBX_PWM #include <mach/leds-fbx-pwm.h> // DIV2-SW2-BSP-FBx-LEDS #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 {+ #ifdef CONFIG_KEYBOARD_SF4H8 #include <mach/sf8_kybd.h> #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 -} #ifdef CONFIG_DS2482 #include <mach/ds2482.h> // DIV2-SW2-BSP-FBx-BATT #endif #ifdef CONFIG_BATTERY_FIH_DS2784 #include <mach/ds2784.h> // DIV2-SW2-BSP-FBx-BATT #endif #ifdef CONFIG_BATTERY_FIH_MSM #include <mach/fih_msm_battery.h> // DIV2-SW2-BSP-FBx-BATT #endif #ifdef CONFIG_BATTERY_BQ275X0 #include <mach/bq275x0_battery.h> // DIV2-SW2-BSP-FBx-BATT #endif /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ #include <linux/switch.h> /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ /* FIHTDC, Div2-SW2-BSP, Penho, USB_ACCESORIES { */ #ifdef CONFIG_USB_ANDROID_ACCESSORY #include <linux/usb/f_accessory.h> #endif // CONFIG_USB_ANDROID_ACCESSORY /* } FIHTDC, Div2-SW2-BSP, Penho, USB_ACCESORIES */ /* FIHTDC, Div2-SW2-BSP, Ming, PMEM { */ /* Enlarge PMEM_SF to 30 MB for WVGA */ #define MSM_PMEM_SF_SIZE 0x1E00000 //0x1700000 /* } FIHTDC, Div2-SW2-BSP, Ming, PMEM */ /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL #define MSM_FB_SIZE 0x500000 #else #define MSM_FB_SIZE 0xA00000 ///0x500000 #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ #define MSM_PMEM_ADSP_SIZE 0x2400000 //0x1800000 //SW4-L1-HL-Camera-FixCTS_2.3_R4_FailIssue-00* #define MSM_FLUID_PMEM_ADSP_SIZE 0x2800000 #define PMEM_KERNEL_EBI1_SIZE 0x600000 #define MSM_PMEM_AUDIO_SIZE 0x200000 #define PMIC_GPIO_INT 27 #define PMIC_VREG_WLAN_LEVEL 2900 #define PMIC_GPIO_SD_DET 36 #define PMIC_GPIO_SDC4_EN_N 17 /* PMIC GPIO Number 18 */ /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL #define PMIC_GPIO_HDMI_5V_EN_V3 32 /* PMIC GPIO for V3 H/W */ #define PMIC_GPIO_HDMI_5V_EN_V2 39 /* PMIC GPIO for V2 H/W */ #define ADV7520_I2C_ADDR 0x39 #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL #define PMIC_GPIO_HDMI_18V_EN 32 /* PMIC GPIO Number 33 */ #define GPIO_HDMI_5V_EN \ GPIO_CFG(34, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_4MA) #define HDMI_INT 180 static bool hdmi_init_done = false; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ /* FIHTDC, Div2-SW2-BSP, Ming, LCM { */ #define PMIC_GPIO_LCM_V1P8_EN 35 /* PMIC GPIO Number 36 */ /* } FIHTDC, Div2-SW2-BSP, Ming, LCM */ #define FPGA_SDCC_STATUS 0x8E0001A8 #define FPGA_OPTNAV_GPIO_ADDR 0x8E000026 #define OPTNAV_I2C_SLAVE_ADDR (0xB0 >> 1) #define OPTNAV_IRQ 20 #define OPTNAV_CHIP_SELECT 19 /* Macros assume PMIC GPIOs start at 0 */ #define PM8058_GPIO_PM_TO_SYS(pm_gpio) (pm_gpio + NR_GPIO_IRQS) #define PM8058_GPIO_SYS_TO_PM(sys_gpio) (sys_gpio - NR_GPIO_IRQS) #define PMIC_GPIO_FLASH_BOOST_ENABLE 15 /* PMIC GPIO Number 16 */ #define PMIC_GPIO_HAP_ENABLE 16 /* PMIC GPIO Number 17 */ #define PMIC_GPIO_WLAN_EXT_POR 22 /* PMIC GPIO NUMBER 23 */ #define BMA150_GPIO_INT 1 #define HAP_LVL_SHFT_MSM_GPIO 24 #define PMIC_GPIO_QUICKVX_CLK 37 /* PMIC GPIO 38 */ #define PM_FLIP_MPP 5 /* PMIC MPP 06 */ /* +++ AlbertYCFang, 2011.06.13,FM +++ */ //SQ01.FC-73: Change QTR8200 WCN clock source(32M) from PMIC-D0 to PMIC-A1 #if defined(CONFIG_FIH_PROJECT_SF4V5) || defined(CONFIG_FIH_PROJECT_SF4Y6) #define QTR8x00_WCN_CLK PMAPP_CLOCK_ID_DO #else #define QTR8x00_WCN_CLK PMAPP_CLOCK_ID_A1 #endif /* --- AlbertYCFang, 2011.06.13,FM --- */ // DIV2-SW2-BSP-FBx-BUTTONS+ #ifdef CONFIG_KEYBOARD_GPIO #define PM_GPIO_CAMF 1 #define PM_GPIO_CAMT 2 #define PM_GPIO_VOLUP 3 #define PM_GPIO_VOLDN 4 #define KEY_NUM 4 #define KEY_FOCUS KEY_F13 #define KEY_DEBOUNCE_INTERVAL 2 // ms static struct gpio_keys_button gpio_buttons[KEY_NUM] = { { .code = KEY_VOLUMEUP, .gpio = PM8058_GPIO_PM_TO_SYS(PM_GPIO_VOLUP), .active_low = 0, .desc = "Vol Up Key", .type = EV_KEY, .wakeup = 0, .debounce_interval = KEY_DEBOUNCE_INTERVAL }, { .code = KEY_VOLUMEDOWN, .gpio = PM8058_GPIO_PM_TO_SYS(PM_GPIO_VOLDN), .active_low = 0, .desc = "Vol Dn Key", .type = EV_KEY, .wakeup = 0, .debounce_interval = KEY_DEBOUNCE_INTERVAL }, { .code = KEY_FOCUS, .gpio = PM8058_GPIO_PM_TO_SYS(PM_GPIO_CAMF), .active_low = 0, .desc = "Focus Key", .type = EV_KEY, .wakeup = 0, .debounce_interval = KEY_DEBOUNCE_INTERVAL }, { .code = KEY_CAMERA, .gpio = PM8058_GPIO_PM_TO_SYS(PM_GPIO_CAMT), .active_low = 0, .desc = "Camera Key", .type = EV_KEY, .wakeup = 0, .debounce_interval = KEY_DEBOUNCE_INTERVAL }, }; static struct gpio_keys_platform_data gpio_buttons_pdata = { .buttons = gpio_buttons, .nbuttons = KEY_NUM - 2, .rep = 0 }; static struct platform_device gpio_buttons_device = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &gpio_buttons_pdata, }, }; #endif // DIV2-SW2-BSP-FBx-BUTTONS- /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ bool m_HsAmpOn=false; bool m_SpkAmpOn=false; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ int sd_detect_pin = 0; int sd_enable_pin = 0; static int pm8058_gpios_init(void) { int rc; /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL int pmic_gpio_hdmi_5v_en; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ /* remove redundant code*/ #if 0 #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION struct pm8058_gpio sdcc_det = { .direction = PM_GPIO_DIR_IN, .pull = PM_GPIO_PULL_UP_1P5, .vin_sel = 2, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, }; #endif #endif struct pm8058_gpio sdc4_en = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_L5, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, .out_strength = PM_GPIO_STRENGTH_LOW, .output_value = 0, }; struct pm8058_gpio haptics_enable = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, .vin_sel = 2, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 0, }; /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL struct pm8058_gpio hdmi_5V_en = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_VPH, .function = PM_GPIO_FUNC_NORMAL, .out_strength = PM_GPIO_STRENGTH_LOW, .output_value = 0, }; #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL struct pm8058_gpio hdmi_18V_en = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .pull = PM_GPIO_PULL_NO, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_NORMAL, }; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ /* FIHTDC, Div2-SW2-BSP, Ming, LCM { */ struct pm8058_gpio lcm_v1p8_en ={ .direction = PM_GPIO_DIR_OUT, //Let the pin be an output one. .output_buffer = PM_GPIO_OUT_BUF_CMOS, //HW suggestion .output_value = 1, //You also can set 0, but it seems useless. .out_strength = PM_GPIO_STRENGTH_HIGH, //There are three options for this, LOW, MED, and HIGH, but I don!|t know the actual effect. .function = PM_GPIO_FUNC_NORMAL, //Let the pin be a general GPIO. }; /* } FIHTDC, Div2-SW2-BSP, Ming, LCM */ struct pm8058_gpio flash_boost_enable = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 0, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S3, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_2, }; struct pm8058_gpio gpio23 = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 0, .pull = PM_GPIO_PULL_NO, .vin_sel = 2, .out_strength = PM_GPIO_STRENGTH_LOW, .function = PM_GPIO_FUNC_NORMAL, }; // DIV2-SW2-BSP-FBx-BUTTONS+ #ifdef CONFIG_KEYBOARD_GPIO struct pm8058_gpio button_configuration = { .direction = PM_GPIO_DIR_IN, .pull = PM_GPIO_PULL_DN, .vin_sel = 2, .out_strength = PM_GPIO_STRENGTH_NO, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, }; #endif // DIV2-SW2-BSP-FBx-BUTTONS- /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa() || machine_is_msm7x30_fluid()) pmic_gpio_hdmi_5v_en = PMIC_GPIO_HDMI_5V_EN_V2 ; else pmic_gpio_hdmi_5v_en = PMIC_GPIO_HDMI_5V_EN_V3 ; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ if (machine_is_msm7x30_fluid()) { rc = pm8058_gpio_config(PMIC_GPIO_HAP_ENABLE, &haptics_enable); if (rc) { pr_err("%s: PMIC GPIO %d write failed\n", __func__, (PMIC_GPIO_HAP_ENABLE + 1)); return rc; } rc = pm8058_gpio_config(PMIC_GPIO_FLASH_BOOST_ENABLE, &flash_boost_enable); if (rc) { pr_err("%s: PMIC GPIO %d write failed\n", __func__, (PMIC_GPIO_FLASH_BOOST_ENABLE + 1)); return rc; } } /*remove redundant code*/ #if 0 #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION if (machine_is_msm7x30_fluid()) sdcc_det.inv_int_pol = 1; rc = pm8058_gpio_config(PMIC_GPIO_SD_DET - 1, &sdcc_det); if (rc) { pr_err("%s PMIC_GPIO_SD_DET config failed\n", __func__); return rc; } #endif #endif /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL rc = pm8058_gpio_config(pmic_gpio_hdmi_5v_en, &hdmi_5V_en); if (rc) { pr_err("%s PMIC_GPIO_HDMI_5V_EN config failed\n", __func__); return rc; } #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL rc = pm8058_gpio_config(PMIC_GPIO_HDMI_18V_EN, &hdmi_18V_en); if (rc) { pr_err("%s PMIC_GPIO_HDMI_1.8V_EN config failed\n", __func__); return rc; } rc = gpio_request(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_HDMI_18V_EN), "hdmi_18V_en"); if (rc) { pr_err("%s PMIC_GPIO_HDMI_1.8V_EN gpio_request failed\n", __func__); return rc; } gpio_set_value_cansleep( PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_HDMI_18V_EN), 1); #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ /* Deassert GPIO#23 (source for Ext_POR on WLAN-Volans) */ rc = pm8058_gpio_config(PMIC_GPIO_WLAN_EXT_POR, &gpio23); if (rc) { pr_err("%s PMIC_GPIO_WLAN_EXT_POR config failed\n", __func__); return rc; } if (machine_is_msm7x30_fluid()) { rc = pm8058_gpio_config(PMIC_GPIO_SDC4_EN_N, &sdc4_en); if (rc) { pr_err("%s PMIC_GPIO_SDC4_EN_N config failed\n", __func__); return rc; } rc = gpio_request(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_SDC4_EN_N), "sdc4_en"); if (rc) { pr_err("%s PMIC_GPIO_SDC4_EN_N gpio_request failed\n", __func__); return rc; } gpio_set_value_cansleep( PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_SDC4_EN_N), 0); } /* FIHTDC, Div2-SW2-BSP, Ming, LCM { */ rc = pm8058_gpio_config(PMIC_GPIO_LCM_V1P8_EN, &lcm_v1p8_en); if (rc) { pr_err("%s PMIC_GPIO_LCM_V1P8_EN config failed\n", __func__); return rc; } /* } FIHTDC, Div2-SW2-BSP, Ming, LCM */ // DIV2-SW2-BSP-FBx-BUTTONS+ #ifdef CONFIG_KEYBOARD_GPIO rc = pm8058_gpio_config(PM_GPIO_VOLUP, &button_configuration); if (rc < 0) { printk(KERN_INFO "gpio %d configured failed\n", PM_GPIO_VOLUP); return rc; } rc = pm8058_gpio_config(PM_GPIO_VOLDN, &button_configuration); if (rc < 0) { printk(KERN_INFO "gpio %d configured failed\n", PM_GPIO_VOLDN); return rc; } if (fih_get_product_phase() == Product_PR1 || fih_get_product_phase() == Product_EVB) { rc = pm8058_gpio_config(PM_GPIO_CAMF, &button_configuration); if (rc < 0) { printk(KERN_INFO "gpio %d configured failed\n", PM_GPIO_CAMF); return rc; } rc = pm8058_gpio_config(PM_GPIO_CAMT, &button_configuration); if (rc < 0) { printk(KERN_INFO "gpio %d configured failed\n", PM_GPIO_CAMT); return rc; } gpio_buttons_pdata.nbuttons = KEY_NUM; } #endif // DIV2-SW2-BSP-FBx-BUTTONS- return 0; } /*virtual key support */ static ssize_t tma300_vkeys_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, __stringify(EV_KEY) ":" __stringify(KEY_BACK) ":50:842:80:100" ":" __stringify(EV_KEY) ":" __stringify(KEY_MENU) ":170:842:80:100" ":" __stringify(EV_KEY) ":" __stringify(KEY_HOME) ":290:842:80:100" ":" __stringify(EV_KEY) ":" __stringify(KEY_SEARCH) ":410:842:80:100" "\n"); } static struct kobj_attribute tma300_vkeys_attr = { .attr = { .mode = S_IRUGO, }, .show = &tma300_vkeys_show, }; static struct attribute *tma300_properties_attrs[] = { &tma300_vkeys_attr.attr, NULL }; static struct attribute_group tma300_properties_attr_group = { .attrs = tma300_properties_attrs, }; static struct kobject *properties_kobj; #define CYTTSP_TS_GPIO_IRQ 150 static int cyttsp_platform_init(struct i2c_client *client) { int rc = -EINVAL; struct vreg *vreg_ldo8, *vreg_ldo15; vreg_ldo8 = vreg_get(NULL, "gp7"); if (!vreg_ldo8) { pr_err("%s: VREG L8 get failed\n", __func__); return rc; } rc = vreg_set_level(vreg_ldo8, 1800); if (rc) { pr_err("%s: VREG L8 set failed\n", __func__); goto l8_put; } rc = vreg_enable(vreg_ldo8); if (rc) { pr_err("%s: VREG L8 enable failed\n", __func__); goto l8_put; } vreg_ldo15 = vreg_get(NULL, "gp6"); if (!vreg_ldo15) { pr_err("%s: VREG L15 get failed\n", __func__); goto l8_disable; } rc = vreg_set_level(vreg_ldo15, 3050); if (rc) { pr_err("%s: VREG L15 set failed\n", __func__); goto l8_disable; } rc = vreg_enable(vreg_ldo15); if (rc) { pr_err("%s: VREG L15 enable failed\n", __func__); goto l8_disable; } /* check this device active by reading first byte/register */ rc = i2c_smbus_read_byte_data(client, 0x01); if (rc < 0) { pr_err("%s: i2c sanity check failed\n", __func__); goto l8_disable; } rc = gpio_tlmm_config(GPIO_CFG(CYTTSP_TS_GPIO_IRQ, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_6MA), GPIO_CFG_ENABLE); if (rc) { pr_err("%s: Could not configure gpio %d\n", __func__, CYTTSP_TS_GPIO_IRQ); goto l8_disable; } rc = gpio_request(CYTTSP_TS_GPIO_IRQ, "ts_irq"); if (rc) { pr_err("%s: unable to request gpio %d (%d)\n", __func__, CYTTSP_TS_GPIO_IRQ, rc); goto l8_disable; } /* virtual keys */ tma300_vkeys_attr.attr.name = "virtualkeys.cyttsp-i2c"; properties_kobj = kobject_create_and_add("board_properties", NULL); if (properties_kobj) rc = sysfs_create_group(properties_kobj, &tma300_properties_attr_group); if (!properties_kobj || rc) pr_err("%s: failed to create board_properties\n", __func__); return CY_OK; l8_disable: vreg_disable(vreg_ldo8); l8_put: vreg_put(vreg_ldo8); return rc; } static int cyttsp_platform_resume(struct i2c_client *client) { /* add any special code to strobe a wakeup pin or chip reset */ mdelay(10); return CY_OK; } static struct cyttsp_platform_data cyttsp_data = { .panel_maxx = 479, .panel_maxy = 799, .disp_maxx = 469, .disp_maxy = 799, .disp_minx = 10, .disp_miny = 0, .flags = 0, .gen = CY_GEN3, /* or */ .use_st = CY_USE_ST, .use_mt = CY_USE_MT, .use_hndshk = CY_SEND_HNDSHK, .use_trk_id = CY_USE_TRACKING_ID, .use_sleep = CY_USE_SLEEP, .use_gestures = CY_USE_GESTURES, /* activate up to 4 groups * and set active distance */ .gest_set = CY_GEST_GRP1 | CY_GEST_GRP2 | CY_GEST_GRP3 | CY_GEST_GRP4 | CY_ACT_DIST, /* change act_intrvl to customize the Active power state * scanning/processing refresh interval for Operating mode */ .act_intrvl = CY_ACT_INTRVL_DFLT, /* change tch_tmout to customize the touch timeout for the * Active power state for Operating mode */ .tch_tmout = CY_TCH_TMOUT_DFLT, /* change lp_intrvl to customize the Low Power power state * scanning/processing refresh interval for Operating mode */ .lp_intrvl = CY_LP_INTRVL_DFLT, .resume = cyttsp_platform_resume, .init = cyttsp_platform_init, }; static int pm8058_pwm_config(struct pwm_device *pwm, int ch, int on) { struct pm8058_gpio pwm_gpio_config = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 0, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S3, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_2, }; int rc = -EINVAL; int id, mode, max_mA; id = mode = max_mA = 0; switch (ch) { case 0: case 1: case 2: if (on) { id = 24 + ch; rc = pm8058_gpio_config(id - 1, &pwm_gpio_config); if (rc) pr_err("%s: pm8058_gpio_config(%d): rc=%d\n", __func__, id, rc); } break; case 3: id = PM_PWM_LED_KPD; mode = PM_PWM_CONF_DTEST3; max_mA = 200; break; case 4: id = PM_PWM_LED_0; mode = PM_PWM_CONF_PWM1; max_mA = 40; break; // DIV2-SW2-BSP-FBx-LEDS+ #ifdef CONFIG_LEDS_FIH_FBX_PWM case 5: id = PM_PWM_LED_1; mode = PM_PWM_CONF_PWM2; max_mA = 40; break; case 6: id = PM_PWM_LED_2; mode = PM_PWM_CONF_PWM3; max_mA = 40; break; #else #ifdef CONFIG_FIH_PROJECT_SF4Y6 //OwenHung Add+ case 5: id = PM_PWM_LED_1; mode = PM_PWM_CONF_PWM2; max_mA = 10; break; case 6: id = PM_PWM_LED_2; mode = PM_PWM_CONF_PWM3; max_mA = 10; break; #else case 5: id = PM_PWM_LED_2; mode = PM_PWM_CONF_PWM2; max_mA = 40; break; case 6: id = PM_PWM_LED_FLASH; mode = PM_PWM_CONF_DTEST3; max_mA = 200; break; #endif #endif // DIV2-SW2-BSP-FBx-LEDS- default: break; } if (ch >= 3 && ch <= 6) { if (!on) { mode = PM_PWM_CONF_NONE; max_mA = 0; } rc = pm8058_pwm_config_led(pwm, id, mode, max_mA); if (rc) pr_err("%s: pm8058_pwm_config_led(ch=%d): rc=%d\n", __func__, ch, rc); } return rc; } static int pm8058_pwm_enable(struct pwm_device *pwm, int ch, int on) { int rc; switch (ch) { case 7: rc = pm8058_pwm_set_dtest(pwm, on); if (rc) pr_err("%s: pwm_set_dtest(%d): rc=%d\n", __func__, on, rc); break; default: rc = -EINVAL; break; } return rc; } #ifdef CONFIG_KEYBOARD_PMIC8058 static const unsigned int fluid_keymap[] = { KEY(0, 0, KEY_7), KEY(0, 1, KEY_ENTER), KEY(0, 2, KEY_UP), /* drop (0,3) as it always shows up in pair with(0,2) */ KEY(0, 4, KEY_DOWN), KEY(1, 0, KEY_CAMERA_SNAPSHOT), KEY(1, 1, KEY_SELECT), KEY(1, 2, KEY_1), KEY(1, 3, KEY_VOLUMEUP), KEY(1, 4, KEY_VOLUMEDOWN), }; static const unsigned int surf_keymap[] = { KEY(0, 0, KEY_7), KEY(0, 1, KEY_DOWN), KEY(0, 2, KEY_UP), KEY(0, 3, KEY_RIGHT), KEY(0, 4, KEY_ENTER), KEY(0, 5, KEY_L), KEY(0, 6, KEY_BACK), KEY(0, 7, KEY_M), KEY(1, 0, KEY_LEFT), KEY(1, 1, KEY_SEND), KEY(1, 2, KEY_1), KEY(1, 3, KEY_4), KEY(1, 4, KEY_CLEAR), KEY(1, 5, KEY_MSDOS), KEY(1, 6, KEY_SPACE), KEY(1, 7, KEY_COMMA), KEY(2, 0, KEY_6), KEY(2, 1, KEY_5), KEY(2, 2, KEY_8), KEY(2, 3, KEY_3), KEY(2, 4, KEY_NUMERIC_STAR), KEY(2, 5, KEY_UP), KEY(2, 6, KEY_DOWN), /* SYN */ KEY(2, 7, KEY_LEFTSHIFT), KEY(3, 0, KEY_9), KEY(3, 1, KEY_NUMERIC_POUND), KEY(3, 2, KEY_0), KEY(3, 3, KEY_2), KEY(3, 4, KEY_SLEEP), KEY(3, 5, KEY_F1), KEY(3, 6, KEY_F2), KEY(3, 7, KEY_F3), KEY(4, 0, KEY_BACK), KEY(4, 1, KEY_HOME), KEY(4, 2, KEY_MENU), KEY(4, 3, KEY_VOLUMEUP), KEY(4, 4, KEY_VOLUMEDOWN), KEY(4, 5, KEY_F4), KEY(4, 6, KEY_F5), KEY(4, 7, KEY_F6), KEY(5, 0, KEY_R), KEY(5, 1, KEY_T), KEY(5, 2, KEY_Y), KEY(5, 3, KEY_LEFTALT), KEY(5, 4, KEY_KPENTER), KEY(5, 5, KEY_Q), KEY(5, 6, KEY_W), KEY(5, 7, KEY_E), KEY(6, 0, KEY_F), KEY(6, 1, KEY_G), KEY(6, 2, KEY_H), KEY(6, 3, KEY_CAPSLOCK), KEY(6, 4, KEY_PAGEUP), KEY(6, 5, KEY_A), KEY(6, 6, KEY_S), KEY(6, 7, KEY_D), KEY(7, 0, KEY_V), KEY(7, 1, KEY_B), KEY(7, 2, KEY_N), KEY(7, 3, KEY_MENU), /* REVISIT - SYM */ KEY(7, 4, KEY_PAGEDOWN), KEY(7, 5, KEY_Z), KEY(7, 6, KEY_X), KEY(7, 7, KEY_C), KEY(8, 0, KEY_P), KEY(8, 1, KEY_J), KEY(8, 2, KEY_K), KEY(8, 3, KEY_INSERT), KEY(8, 4, KEY_LINEFEED), KEY(8, 5, KEY_U), KEY(8, 6, KEY_I), KEY(8, 7, KEY_O), KEY(9, 0, KEY_4), KEY(9, 1, KEY_5), KEY(9, 2, KEY_6), KEY(9, 3, KEY_7), KEY(9, 4, KEY_8), KEY(9, 5, KEY_1), KEY(9, 6, KEY_2), KEY(9, 7, KEY_3), KEY(10, 0, KEY_F7), KEY(10, 1, KEY_F8), KEY(10, 2, KEY_F9), KEY(10, 3, KEY_F10), KEY(10, 4, KEY_FN), KEY(10, 5, KEY_9), KEY(10, 6, KEY_0), KEY(10, 7, KEY_DOT), KEY(11, 0, KEY_LEFTCTRL), KEY(11, 1, KEY_F11), /* START */ KEY(11, 2, KEY_ENTER), KEY(11, 3, KEY_SEARCH), KEY(11, 4, KEY_DELETE), KEY(11, 5, KEY_RIGHT), KEY(11, 6, KEY_LEFT), KEY(11, 7, KEY_RIGHTSHIFT), }; static struct resource resources_keypad[] = { { .start = PM8058_KEYPAD_IRQ(PMIC8058_IRQ_BASE), .end = PM8058_KEYPAD_IRQ(PMIC8058_IRQ_BASE), .flags = IORESOURCE_IRQ, }, { .start = PM8058_KEYSTUCK_IRQ(PMIC8058_IRQ_BASE), .end = PM8058_KEYSTUCK_IRQ(PMIC8058_IRQ_BASE), .flags = IORESOURCE_IRQ, }, }; static struct matrix_keymap_data surf_keymap_data = { .keymap_size = ARRAY_SIZE(surf_keymap), .keymap = surf_keymap, }; static struct pmic8058_keypad_data surf_keypad_data = { .input_name = "surf_keypad", .input_phys_device = "surf_keypad/input0", .num_rows = 12, .num_cols = 8, .rows_gpio_start = 8, .cols_gpio_start = 0, .debounce_ms = {8, 10}, .scan_delay_ms = 32, .row_hold_ns = 91500, .wakeup = 1, .keymap_data = &surf_keymap_data, }; static struct matrix_keymap_data fluid_keymap_data = { .keymap_size = ARRAY_SIZE(fluid_keymap), .keymap = fluid_keymap, }; static struct pmic8058_keypad_data fluid_keypad_data = { .input_name = "fluid-keypad", .input_phys_device = "fluid-keypad/input0", .num_rows = 5, .num_cols = 5, .rows_gpio_start = 8, .cols_gpio_start = 0, .debounce_ms = {8, 10}, .scan_delay_ms = 32, .row_hold_ns = 91500, .wakeup = 1, .keymap_data = &fluid_keymap_data, }; #endif static struct pm8058_pwm_pdata pm8058_pwm_data = { .config = pm8058_pwm_config, .enable = pm8058_pwm_enable, }; /* Put sub devices with fixed location first in sub_devices array */ #define PM8058_SUBDEV_KPD 0 #define PM8058_SUBDEV_LED 1 static struct pm8058_gpio_platform_data pm8058_gpio_data = { .gpio_base = PM8058_GPIO_PM_TO_SYS(0), .irq_base = PM8058_GPIO_IRQ(PMIC8058_IRQ_BASE, 0), .init = pm8058_gpios_init, }; static struct pm8058_gpio_platform_data pm8058_mpp_data = { .gpio_base = PM8058_GPIO_PM_TO_SYS(PM8058_GPIOS), .irq_base = PM8058_MPP_IRQ(PMIC8058_IRQ_BASE, 0), }; #ifdef CONFIG_LEDS_PM8058 static struct pmic8058_led pmic8058_ffa_leds[] = { [0] = { .name = "keyboard-backlight", .max_brightness = 15, .id = PMIC8058_ID_LED_KB_LIGHT, }, }; static struct pmic8058_leds_platform_data pm8058_ffa_leds_data = { .num_leds = ARRAY_SIZE(pmic8058_ffa_leds), .leds = pmic8058_ffa_leds, }; static struct pmic8058_led pmic8058_surf_leds[] = { [0] = { .name = "keyboard-backlight", .max_brightness = 15, .id = PMIC8058_ID_LED_KB_LIGHT, }, [1] = { .name = "voice:red", .max_brightness = 20, .id = PMIC8058_ID_LED_0, }, [2] = { .name = "wlan:green", .max_brightness = 20, .id = PMIC8058_ID_LED_2, }, }; #endif // DIV2-SW2-BSP-FBx-VIB+ #ifdef CONFIG_PMIC8058_VIBRATOR static struct pmic8058_vibrator_pdata pmic_vib_pdata = { .initial_vibrate_ms = 0, .level_mV = 3000, .max_timeout_ms = 15000, }; #endif // DIV2-SW2-BSP-FBx-VIB- static struct mfd_cell pm8058_subdevs[] = { #ifdef CONFIG_KEYBOARD_PMIC8058 { .name = "pm8058-keypad", .id = -1, .num_resources = ARRAY_SIZE(resources_keypad), .resources = resources_keypad, }, #endif #ifdef CONFIG_LEDS_PMIC8058 { .name = "pm8058-led", .id = -1, }, #endif { .name = "pm8058-gpio", .id = -1, .platform_data = &pm8058_gpio_data, .data_size = sizeof(pm8058_gpio_data), }, { .name = "pm8058-mpp", .id = -1, .platform_data = &pm8058_mpp_data, .data_size = sizeof(pm8058_mpp_data), }, { .name = "pm8058-pwm", .id = -1, .platform_data = &pm8058_pwm_data, .data_size = sizeof(pm8058_pwm_data), }, { .name = "pm8058-nfc", .id = -1, }, { .name = "pm8058-upl", .id = -1, }, // DIV2-SW2-BSP-FBx-VIB+ #ifdef CONFIG_PMIC8058_VIBRATOR { .name = "pm8058-vib", .id = -1, .platform_data = &pmic_vib_pdata, .data_size = sizeof(pmic_vib_pdata), }, #endif // DIV2-SW2-BSP-FBx-VIB- }; #ifdef CONFIG_LEDS_PM8058 static struct pmic8058_leds_platform_data pm8058_surf_leds_data = { .num_leds = ARRAY_SIZE(pmic8058_surf_leds), .leds = pmic8058_surf_leds, }; static struct pmic8058_led pmic8058_fluid_leds[] = { [0] = { .name = "keyboard-backlight", .max_brightness = 15, .id = PMIC8058_ID_LED_KB_LIGHT, }, [1] = { .name = "flash:led_0", .max_brightness = 15, .id = PMIC8058_ID_FLASH_LED_0, }, [2] = { .name = "flash:led_1", .max_brightness = 15, .id = PMIC8058_ID_FLASH_LED_1, }, }; static struct pmic8058_leds_platform_data pm8058_fluid_leds_data = { .num_leds = ARRAY_SIZE(pmic8058_fluid_leds), .leds = pmic8058_fluid_leds, }; #endif /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ static struct gpio_switch_platform_data headset_sensor_device_data = { .name = "headset_sensor", .gpio = 26, .name_on = "", .name_off = "", .state_on = "", .state_off = "", }; static struct platform_device headset_sensor_device = { .name = "switch_gpio", .id = -1, .dev = { .platform_data = &headset_sensor_device_data }, }; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ static struct pm8058_platform_data pm8058_7x30_data = { .irq_base = PMIC8058_IRQ_BASE, .num_subdevs = ARRAY_SIZE(pm8058_subdevs), .sub_devices = pm8058_subdevs, .irq_trigger_flags = IRQF_TRIGGER_LOW, }; static struct i2c_board_info pm8058_boardinfo[] __initdata = { { I2C_BOARD_INFO("pm8058-core", 0x55), .irq = MSM_GPIO_TO_INT(PMIC_GPIO_INT), .platform_data = &pm8058_7x30_data, }, }; static struct i2c_board_info cy8info[] __initdata = { { I2C_BOARD_INFO(CY_I2C_NAME, 0x24), .platform_data = &cyttsp_data, #ifndef CY_USE_TIMER .irq = MSM_GPIO_TO_INT(CYTTSP_TS_GPIO_IRQ), #endif /* CY_USE_TIMER */ }, }; static struct i2c_board_info msm_camera_boardinfo[] __initdata = { #ifdef CONFIG_FIH_MT9P111 { I2C_BOARD_INFO("mt9p111", 0x78 >> 1), }, #endif #ifdef CONFIG_FIH_HM0356 { I2C_BOARD_INFO("hm0356", 0x68 >> 1), }, #endif #ifdef CONFIG_FIH_HM0357 { I2C_BOARD_INFO("hm0357", 0x60 >> 1), }, #endif #ifdef CONFIG_FIH_TCM9001MD { I2C_BOARD_INFO("tcm9001md", 0x7C >> 1), }, #endif #ifdef CONFIG_MT9D112 { I2C_BOARD_INFO("mt9d112", 0x78 >> 1), }, #endif #ifdef CONFIG_S5K3E2FX { I2C_BOARD_INFO("s5k3e2fx", 0x20 >> 1), }, #endif #ifdef CONFIG_MT9P012 { I2C_BOARD_INFO("mt9p012", 0x6C >> 1), }, #endif #ifdef CONFIG_VX6953 { I2C_BOARD_INFO("vx6953", 0x20), }, #endif #ifdef CONFIG_MT9E013 { I2C_BOARD_INFO("mt9e013", 0x6C >> 2), }, #endif #ifdef CONFIG_SN12M0PZ { I2C_BOARD_INFO("sn12m0pz", 0x34 >> 1), }, #endif #if defined(CONFIG_MT9T013) || defined(CONFIG_SENSORS_MT9T013) { I2C_BOARD_INFO("mt9t013", 0x6C), }, #endif }; #ifdef CONFIG_MSM_CAMERA #define CAM_STNDBY 143 static uint32_t camera_off_vcm_gpio_table[] = { //GPIO_CFG(1, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* VCM */ }; static uint32_t camera_off_gpio_table[] = { /* parallel CAMERA interfaces */ //GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* RST */ //GPIO_CFG(2, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT2 */ //GPIO_CFG(3, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT3 */ GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), GPIO_CFG(4, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT4 */ GPIO_CFG(5, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT5 */ GPIO_CFG(6, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT6 */ GPIO_CFG(7, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT7 */ GPIO_CFG(8, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT8 */ GPIO_CFG(9, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT9 */ GPIO_CFG(10, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT10 */ GPIO_CFG(11, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT11 */ GPIO_CFG(12, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* PCLK */ GPIO_CFG(13, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* HSYNC_IN */ GPIO_CFG(14, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* VSYNC_IN */ GPIO_CFG(15, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* MCLK */ #ifdef CONFIG_FIH_AAT1272 #ifdef CONFIG_FIH_PROJECT_SF4Y6 GPIO_CFG(30, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLASHLED_DRV_EN PIN*/ #else GPIO_CFG(39, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLASHLED_DRV_EN PIN*/ #endif #endif //GPIO_CFG(50, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* SWITCH PIN*/ }; static uint32_t camera_on_vcm_gpio_table[] = { //GPIO_CFG(1, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), /* VCM */ }; static uint32_t camera_on_gpio_table[] = { /* parallel CAMERA interfaces */ //GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* RST */ //GPIO_CFG(2, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT2 */ //GPIO_CFG(3, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT3 */ GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), //GPIO_CFG(1, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), //GPIO_CFG(2, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG(4, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT4 */ GPIO_CFG(5, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT5 */ GPIO_CFG(6, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT6 */ GPIO_CFG(7, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT7 */ GPIO_CFG(8, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT8 */ GPIO_CFG(9, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT9 */ GPIO_CFG(10, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT10 */ GPIO_CFG(11, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* DAT11 */ GPIO_CFG(12, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* PCLK */ GPIO_CFG(13, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* HSYNC_IN */ GPIO_CFG(14, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* VSYNC_IN */ GPIO_CFG(15, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* MCLK */ #ifdef CONFIG_FIH_AAT1272 #ifdef CONFIG_FIH_PROJECT_SF4Y6 GPIO_CFG(30, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLASHLED_DRV_EN PIN*/ #else GPIO_CFG(39, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLASHLED_DRV_EN PIN*/ #endif #endif //GPIO_CFG(50, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* SWITCH PIN*/ }; static uint32_t camera_off_gpio_fluid_table[] = { /* FLUID: CAM_VGA_RST_N */ GPIO_CFG(31, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLUID: CAMIF_STANDBY */ GPIO_CFG(CAM_STNDBY, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) }; static uint32_t camera_on_gpio_fluid_table[] = { /* FLUID: CAM_VGA_RST_N */ GPIO_CFG(31, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), /* FLUID: CAMIF_STANDBY */ GPIO_CFG(CAM_STNDBY, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) }; static void config_gpio_table(uint32_t *table, int len) { int n, rc; for (n = 0; n < len; n++) { rc = gpio_tlmm_config(table[n], GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, table[n], rc); break; } } } static int config_camera_on_gpios(void) { config_gpio_table(camera_on_gpio_table, ARRAY_SIZE(camera_on_gpio_table)); if (adie_get_detected_codec_type() != TIMPANI_ID) /* GPIO1 is shared also used in Timpani RF card so only configure it for non-Timpani RF card */ config_gpio_table(camera_on_vcm_gpio_table, ARRAY_SIZE(camera_on_vcm_gpio_table)); if (machine_is_msm7x30_fluid()) { config_gpio_table(camera_on_gpio_fluid_table, ARRAY_SIZE(camera_on_gpio_fluid_table)); /* FLUID: turn on 5V booster */ gpio_set_value( PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_FLASH_BOOST_ENABLE), 1); /* FLUID: drive high to put secondary sensor to STANDBY */ gpio_set_value(CAM_STNDBY, 1); } return 0; } static void config_camera_off_gpios(void) { config_gpio_table(camera_off_gpio_table, ARRAY_SIZE(camera_off_gpio_table)); if (adie_get_detected_codec_type() != TIMPANI_ID) /* GPIO1 is shared also used in Timpani RF card so only configure it for non-Timpani RF card */ config_gpio_table(camera_off_vcm_gpio_table, ARRAY_SIZE(camera_off_vcm_gpio_table)); if (machine_is_msm7x30_fluid()) { config_gpio_table(camera_off_gpio_fluid_table, ARRAY_SIZE(camera_off_gpio_fluid_table)); /* FLUID: turn off 5V booster */ gpio_set_value( PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_FLASH_BOOST_ENABLE), 0); } } struct resource msm_camera_resources[] = { { .start = 0xA6000000, .end = 0xA6000000 + SZ_1M - 1, .flags = IORESOURCE_MEM, }, { .start = INT_VFE, .end = INT_VFE, .flags = IORESOURCE_IRQ, }, { .flags = IORESOURCE_DMA, } }; struct msm_camera_device_platform_data msm_camera_device_data = { .camera_gpio_on = config_camera_on_gpios, .camera_gpio_off = config_camera_off_gpios, .ioext.camifpadphy = 0xAB000000, .ioext.camifpadsz = 0x00000400, .ioext.csiphy = 0xA6100000, .ioext.csisz = 0x00000400, .ioext.csiirq = INT_CSI, .ioclk.mclk_clk_rate = 24000000, .ioclk.vfe_clk_rate = 122880000, }; static struct msm_camera_sensor_flash_src msm_flash_src_pwm = { .flash_sr_type = MSM_CAMERA_FLASH_SRC_PWM, ._fsrc.pwm_src.freq = 1000, ._fsrc.pwm_src.max_load = 300, ._fsrc.pwm_src.low_load = 30, ._fsrc.pwm_src.high_load = 100, ._fsrc.pwm_src.channel = 7, }; #ifdef CONFIG_FIH_MT9P111 static struct msm_camera_sensor_flash_data flash_mt9p111 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_parameters_data parameters_mt9p111 = { }; static struct msm_camera_sensor_info msm_camera_sensor_mt9p111_data = { .sensor_name = "mt9p111", .sensor_reset = 1, .sensor_pwd = 2, .sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_90, .vcm_pwd = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9p111, .parameters_data = &parameters_mt9p111, .csi_if = 0, /* Declare for camea pins */ .MCLK_PIN =15 , .mclk_sw_pin = 0xffff, .pwdn_pin = 0xffff, .rst_pin = 0xffff, .vga_pwdn_pin = 0xffff, .vga_rst_pin = 0xffff, .vga_power_en_pin = 0xffff, .standby_pin = 0xffff, .GPIO_FLASHLED = 0xffff, .GPIO_FLASHLED_DRV_EN = 0xffff, /* Declare for camera power */ .AF_pmic_en_pin= 0xffff, .cam_v2p8_en_pin = 0xffff, .cam_vreg_vddio_id = "NoVreg", .cam_vreg_acore_id = "NoVreg", /* Flash LED setting */ .flash_target_addr = 0xffff, .flash_target = 0xffff, .flash_bright = 0xffff, .flash_main_waittime = 0, .flash_main_starttime = 0, .flash_second_waittime = 0, .preflash_light = 0x31, .torch_light = 0x34, .fast_af_retest_target = 0xffff }; static struct platform_device msm_camera_sensor_mt9p111 = { .name = "msm_camera_mt9p111", .dev = { .platform_data = &msm_camera_sensor_mt9p111_data, }, }; #endif #ifdef CONFIG_FIH_HM0356 static struct msm_camera_sensor_flash_data flash_hm0356 = { .flash_type = MSM_CAMERA_FLASH_NONE, .flash_src = &msm_flash_src_pwm }; static struct msm_parameters_data parameters_hm0356 = { }; static struct msm_camera_sensor_info msm_camera_sensor_hm0356_data = { .sensor_name = "hm0356", .sensor_pwd = 0, .sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_hm0356, .parameters_data = &parameters_hm0356, .csi_if = 0, /* Declare for camea pins */ .MCLK_PIN =15 , .mclk_sw_pin = 0xffff, .pwdn_pin = 0xffff, .rst_pin = 0xffff, .vga_pwdn_pin = 0xffff, .vga_rst_pin = 0xffff, .vga_power_en_pin = 0xffff, .standby_pin = 0xffff, .GPIO_FLASHLED = 0xffff, .GPIO_FLASHLED_DRV_EN = 0xffff, /* Declare for camera power */ .AF_pmic_en_pin= 0xffff, .cam_v2p8_en_pin = 0xffff, .cam_vreg_vddio_id = "NoVreg", .cam_vreg_acore_id = "NoVreg" }; static struct platform_device msm_camera_sensor_hm0356 = { .name = "msm_camera_hm0356", .dev = { .platform_data = &msm_camera_sensor_hm0356_data, }, }; #endif #ifdef CONFIG_FIH_HM0357 static struct msm_camera_sensor_flash_data flash_hm0357 = { .flash_type = MSM_CAMERA_FLASH_NONE, .flash_src = &msm_flash_src_pwm }; static struct msm_parameters_data parameters_hm0357 = { }; static struct msm_camera_sensor_info msm_camera_sensor_hm0357_data = { .sensor_name = "hm0357", .sensor_pwd = 0, .sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_90, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_hm0357, .parameters_data = &parameters_hm0357, .csi_if = 0, /* Declare for camea pins */ .MCLK_PIN =15 , .mclk_sw_pin = 0xffff, .pwdn_pin = 0xffff, .rst_pin = 0xffff, .vga_pwdn_pin = 0xffff, .vga_rst_pin = 0xffff, .vga_power_en_pin = 0xffff, .standby_pin = 0xffff, .GPIO_FLASHLED = 0xffff, .GPIO_FLASHLED_DRV_EN = 0xffff, /* Declare for camera power */ .AF_pmic_en_pin= 0xffff, .cam_v2p8_en_pin = 0xffff, .cam_vreg_vddio_id = "NoVreg", .cam_vreg_acore_id = "NoVreg" }; static struct platform_device msm_camera_sensor_hm0357 = { .name = "msm_camera_hm0357", .dev = { .platform_data = &msm_camera_sensor_hm0357_data, }, }; #endif #ifdef CONFIG_FIH_TCM9001MD static struct msm_camera_sensor_flash_data flash_tcm9001md = { .flash_type = MSM_CAMERA_FLASH_NONE, .flash_src = &msm_flash_src_pwm }; static struct msm_parameters_data parameters_tcm9001md = { }; static struct msm_camera_sensor_info msm_camera_sensor_tcm9001md_data = { .sensor_name = "tcm9001md", .sensor_reset = 19, .sensor_pwd = 0, .sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_tcm9001md, .parameters_data = &parameters_tcm9001md, .csi_if = 0, /* Declare for camea pins */ .MCLK_PIN =15 , .mclk_sw_pin = 0xffff, .pwdn_pin = 0xffff, .rst_pin = 0xffff, .vga_pwdn_pin = 0xffff, .vga_rst_pin = 0xffff, .vga_power_en_pin = 0xffff, .standby_pin = 0xffff, .GPIO_FLASHLED = 0xffff, .GPIO_FLASHLED_DRV_EN = 0xffff, /* Declare for camera power */ .AF_pmic_en_pin= 0xffff, .cam_v2p8_en_pin = 0xffff, .cam_vreg_vddio_id = "NoVreg", .cam_vreg_acore_id = "NoVreg" }; static struct platform_device msm_camera_sensor_tcm9001md = { .name = "msm_camera_tcm9001md", .dev = { .platform_data = &msm_camera_sensor_tcm9001md_data, }, }; #endif #ifdef CONFIG_MT9D112 static struct msm_camera_sensor_flash_data flash_mt9d112 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_mt9d112_data = { .sensor_name = "mt9d112", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9d112, .csi_if = 0 }; static struct platform_device msm_camera_sensor_mt9d112 = { .name = "msm_camera_mt9d112", .dev = { .platform_data = &msm_camera_sensor_mt9d112_data, }, }; #endif #ifdef CONFIG_S5K3E2FX static struct msm_camera_sensor_flash_data flash_s5k3e2fx = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm, }; static struct msm_camera_sensor_info msm_camera_sensor_s5k3e2fx_data = { .sensor_name = "s5k3e2fx", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_s5k3e2fx, .csi_if = 0 }; static struct platform_device msm_camera_sensor_s5k3e2fx = { .name = "msm_camera_s5k3e2fx", .dev = { .platform_data = &msm_camera_sensor_s5k3e2fx_data, }, }; #endif #ifdef CONFIG_MT9P012 static struct msm_camera_sensor_flash_data flash_mt9p012 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_mt9p012_data = { .sensor_name = "mt9p012", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 1, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9p012, .csi_if = 0 }; static struct platform_device msm_camera_sensor_mt9p012 = { .name = "msm_camera_mt9p012", .dev = { .platform_data = &msm_camera_sensor_mt9p012_data, }, }; #endif #ifdef CONFIG_MT9E013 static struct msm_camera_sensor_flash_data flash_mt9e013 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_mt9e013_data = { .sensor_name = "mt9e013", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 1, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9e013, .csi_if = 1 }; static struct platform_device msm_camera_sensor_mt9e013 = { .name = "msm_camera_mt9e013", .dev = { .platform_data = &msm_camera_sensor_mt9e013_data, }, }; #endif #ifdef CONFIG_VX6953 static struct msm_camera_sensor_flash_data flash_vx6953 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_vx6953_data = { .sensor_name = "vx6953", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_vx6953, .csi_if = 1 }; static struct platform_device msm_camera_sensor_vx6953 = { .name = "msm_camera_vx6953", .dev = { .platform_data = &msm_camera_sensor_vx6953_data, }, }; #endif #ifdef CONFIG_SN12M0PZ static struct msm_camera_sensor_flash_src msm_flash_src_current_driver = { .flash_sr_type = MSM_CAMERA_FLASH_SRC_CURRENT_DRIVER, ._fsrc.current_driver_src.low_current = 210, ._fsrc.current_driver_src.high_current = 700, #ifdef CONFIG_LEDS_PMIC8058 ._fsrc.current_driver_src.driver_channel = &pm8058_fluid_leds_data, #endif }; static struct msm_camera_sensor_flash_data flash_sn12m0pz = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_current_driver }; static struct msm_camera_sensor_info msm_camera_sensor_sn12m0pz_data = { .sensor_name = "sn12m0pz", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 1, .pdata = &msm_camera_device_data, .flash_data = &flash_sn12m0pz, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .csi_if = 0 }; static struct platform_device msm_camera_sensor_sn12m0pz = { .name = "msm_camera_sn12m0pz", .dev = { .platform_data = &msm_camera_sensor_sn12m0pz_data, }, }; #endif #ifdef CONFIG_MT9T013 static struct msm_camera_sensor_flash_data flash_mt9t013 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src_pwm }; static struct msm_camera_sensor_info msm_camera_sensor_mt9t013_data = { .sensor_name = "mt9t013", .sensor_reset = 0, .sensor_pwd = 85, .vcm_pwd = 1, .vcm_enable = 0, .pdata = &msm_camera_device_data, .resource = msm_camera_resources, .num_resources = ARRAY_SIZE(msm_camera_resources), .flash_data = &flash_mt9t013, .csi_if = 1 }; static struct platform_device msm_camera_sensor_mt9t013 = { .name = "msm_camera_mt9t013", .dev = { .platform_data = &msm_camera_sensor_mt9t013_data, }, }; #endif #ifdef CONFIG_MSM_GEMINI static struct resource msm_gemini_resources[] = { { .start = 0xA3A00000, .end = 0xA3A00000 + 0x0150 - 1, .flags = IORESOURCE_MEM, }, { .start = INT_JPEG, .end = INT_JPEG, .flags = IORESOURCE_IRQ, }, }; static struct platform_device msm_gemini_device = { .name = "msm_gemini", .resource = msm_gemini_resources, .num_resources = ARRAY_SIZE(msm_gemini_resources), }; #endif #ifdef CONFIG_MSM_VPE static struct resource msm_vpe_resources[] = { { .start = 0xAD200000, .end = 0xAD200000 + SZ_1M - 1, .flags = IORESOURCE_MEM, }, { .start = INT_VPE, .end = INT_VPE, .flags = IORESOURCE_IRQ, }, }; static struct platform_device msm_vpe_device = { .name = "msm_vpe", .id = 0, .num_resources = ARRAY_SIZE(msm_vpe_resources), .resource = msm_vpe_resources, }; #endif void camera_sensor_hwpin_init(void) { int pid = 0; int phid = 0; pid = fih_get_product_id(); phid = fih_get_product_phase(); #ifdef CONFIG_FIH_MT9P111 #if 1 if (pid == Product_SF5) { /* Declare for camea pins */ if (phid <= Product_PR2) { msm_camera_sensor_mt9p111_data.rst_pin = 1; } else { msm_camera_sensor_mt9p111_data.rst_pin = 120; } msm_camera_sensor_mt9p111_data.pwdn_pin = 2; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 0; msm_camera_sensor_mt9p111_data.standby_pin=33; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED = 3; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED_DRV_EN = 39; /* Declare for camera power */ msm_camera_sensor_mt9p111_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_mt9p111_data.cam_vreg_acore_id = "gp10"; /* Flash LED setting */ msm_camera_sensor_mt9p111_data.flash_target_addr = 0xB80C; msm_camera_sensor_mt9p111_data.flash_target = 0x07BE; msm_camera_sensor_mt9p111_data.flash_bright = 0x20; msm_camera_sensor_mt9p111_data.flash_main_waittime = 150; msm_camera_sensor_mt9p111_data.flash_main_starttime = 150; msm_camera_sensor_mt9p111_data.flash_second_waittime = 200; /*Fast AF*/ msm_camera_sensor_mt9p111_data.fast_af_retest_target = 0x2000; } else if (pid == Product_SF6) { msm_camera_sensor_mt9p111_data.sensor_Orientation=MSM_CAMERA_SENSOR_ORIENTATION_270; /* Declare for camea pins */ msm_camera_sensor_mt9p111_data.rst_pin = 3; msm_camera_sensor_mt9p111_data.pwdn_pin = 2; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 0; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED = 164; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED_DRV_EN = 30; /* Declare for camera power */ msm_camera_sensor_mt9p111_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_mt9p111_data.cam_vreg_acore_id = "gp10"; /* Flash LED setting */ msm_camera_sensor_mt9p111_data.flash_target_addr = 0xB80C; msm_camera_sensor_mt9p111_data.flash_target = 0x2E00; msm_camera_sensor_mt9p111_data.flash_bright = 0x20; msm_camera_sensor_mt9p111_data.flash_main_waittime = 100; msm_camera_sensor_mt9p111_data.flash_main_starttime = 200; msm_camera_sensor_mt9p111_data.flash_second_waittime = 200; /*Fast AF*/ msm_camera_sensor_mt9p111_data.fast_af_retest_target = 0x3800; } else if (IS_SF8_SERIES_PRJ()) { /* Declare for camea pins */ if (pid == Product_SF8 && phid < Product_PR2) { msm_camera_sensor_mt9p111_data.rst_pin = 1; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 0; } else { msm_camera_sensor_mt9p111_data.rst_pin = 173; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 174; } msm_camera_sensor_mt9p111_data.pwdn_pin = 2; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED = 177; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED_DRV_EN = 3; /* Declare for camera power */ msm_camera_sensor_mt9p111_data.cam_v2p8_en_pin = 120; msm_camera_sensor_mt9p111_data.cam_vreg_vddio_id = "gp10"; msm_camera_sensor_mt9p111_data.cam_vreg_acore_id = "NoVreg"; /* Flash LED setting */ msm_camera_sensor_mt9p111_data.flash_target_addr = 0x3012; msm_camera_sensor_mt9p111_data.flash_target = 0x9C4; msm_camera_sensor_mt9p111_data.flash_bright = 0x30; msm_camera_sensor_mt9p111_data.flash_main_waittime = 100; msm_camera_sensor_mt9p111_data.flash_main_starttime = 200; msm_camera_sensor_mt9p111_data.flash_second_waittime = 200; /*Fast AF*/ msm_camera_sensor_mt9p111_data.fast_af_retest_target = 0x2000; } else// For FBx and FDx series project #endif { /* Declare for camea pins */ msm_camera_sensor_mt9p111_data.rst_pin = 1; msm_camera_sensor_mt9p111_data.pwdn_pin = 2; msm_camera_sensor_mt9p111_data.vga_pwdn_pin = 0; msm_camera_sensor_mt9p111_data.standby_pin=33; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED = 3; msm_camera_sensor_mt9p111_data.GPIO_FLASHLED_DRV_EN = 39; msm_camera_sensor_mt9p111_data.AF_pmic_en_pin=16; msm_camera_sensor_mt9p111_data.mclk_sw_pin = 50; /* Declare for camera power */ msm_camera_sensor_mt9p111_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_mt9p111_data.cam_vreg_acore_id = "gp10"; /* Flash LED setting */ msm_camera_sensor_mt9p111_data.flash_target_addr = 0x3012; msm_camera_sensor_mt9p111_data.flash_target = 0x7AA; msm_camera_sensor_mt9p111_data.flash_bright = 0x14; msm_camera_sensor_mt9p111_data.flash_main_waittime = 300; msm_camera_sensor_mt9p111_data.flash_main_starttime = 90; msm_camera_sensor_mt9p111_data.flash_second_waittime = 200; /*Fast AF*/ msm_camera_sensor_mt9p111_data.fast_af_retest_target = 0x2000; #if 1 if(pid ==Product_FD1 ) { msm_camera_sensor_mt9p111_data.flash_target = 0x7D0; msm_camera_sensor_mt9p111_data.flash_main_starttime = 90; msm_camera_sensor_mt9p111_data.flash_main_waittime = 700; } if(pid ==Product_FB3 ) { msm_camera_sensor_mt9p111_data.torch_light = 0x3E; msm_camera_sensor_mt9p111_data.preflash_light=0x3E; } #endif } #endif #ifdef CONFIG_FIH_HM0356 /*Setting camera pins */ #if 1 if (IS_SF8_SERIES_PRJ()) { if (pid == Product_SF8 && phid < Product_PR2) { msm_camera_sensor_hm0356_data.rst_pin = 1; msm_camera_sensor_hm0356_data.vga_pwdn_pin = 0; } else { msm_camera_sensor_hm0356_data.rst_pin = 173; msm_camera_sensor_hm0356_data.vga_pwdn_pin = 174; } msm_camera_sensor_hm0356_data.pwdn_pin = 2; msm_camera_sensor_hm0356_data.mclk_sw_pin = 0xffff; /* Declare for camera power */ msm_camera_sensor_hm0356_data.cam_v2p8_en_pin = 120; msm_camera_sensor_hm0356_data.cam_vreg_vddio_id="gp10"; msm_camera_sensor_hm0356_data.cam_vreg_acore_id="NoVreg"; } else if (pid == Product_SF6) { msm_camera_sensor_hm0356_data.sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_180, msm_camera_sensor_hm0356_data.rst_pin = 3; msm_camera_sensor_hm0356_data.pwdn_pin = 2; msm_camera_sensor_hm0356_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0356_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_hm0356_data.cam_vreg_acore_id = "gp10"; } else// For FBx and FDx series project #endif { msm_camera_sensor_hm0356_data.rst_pin = 1; msm_camera_sensor_hm0356_data.pwdn_pin = 2; msm_camera_sensor_hm0356_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0356_data.mclk_sw_pin = 50; msm_camera_sensor_hm0356_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_hm0356_data.cam_vreg_acore_id = "gp10"; } #endif #ifdef CONFIG_FIH_HM0357 /*Setting camera pins */ #if 1 if (IS_SF8_SERIES_PRJ()) { if (pid == Product_SF8 && phid < Product_PR2) { msm_camera_sensor_hm0357_data.rst_pin = 1; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 0; } else { msm_camera_sensor_hm0357_data.rst_pin = 173; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 174; } msm_camera_sensor_hm0357_data.sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_270, msm_camera_sensor_hm0357_data.pwdn_pin = 2; msm_camera_sensor_hm0357_data.mclk_sw_pin = 0xffff; /* Declare for camera power */ msm_camera_sensor_hm0357_data.cam_v2p8_en_pin = 120; msm_camera_sensor_hm0357_data.cam_vreg_vddio_id="gp10"; msm_camera_sensor_hm0357_data.cam_vreg_acore_id="NoVreg"; } else if (pid == Product_SF6) { msm_camera_sensor_hm0357_data.sensor_Orientation = MSM_CAMERA_SENSOR_ORIENTATION_180, msm_camera_sensor_hm0357_data.rst_pin = 3; msm_camera_sensor_hm0357_data.pwdn_pin = 2; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0357_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_hm0357_data.cam_vreg_acore_id = "gp10"; } else if (pid == Product_SF5) { msm_camera_sensor_hm0357_data.rst_pin = 120; msm_camera_sensor_hm0357_data.pwdn_pin = 2; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0357_data.vga_power_en_pin = 98; } else// For FBx and FDx series project #endif { msm_camera_sensor_hm0357_data.rst_pin = 1; msm_camera_sensor_hm0357_data.pwdn_pin = 2; msm_camera_sensor_hm0357_data.vga_pwdn_pin = 0; msm_camera_sensor_hm0357_data.mclk_sw_pin = 50; msm_camera_sensor_hm0357_data.cam_vreg_vddio_id = "gp7"; msm_camera_sensor_hm0357_data.cam_vreg_acore_id = "gp10"; } #endif #if 1 #ifdef CONFIG_FIH_TCM9001MD if (pid == Product_SF5) { /*5M sensor pins*/ if (phid <= Product_PR2) { msm_camera_sensor_tcm9001md_data.rst_pin = 1; } else { msm_camera_sensor_tcm9001md_data.rst_pin = 120; } msm_camera_sensor_tcm9001md_data.pwdn_pin = 2; /*VGA sensor pins*/ msm_camera_sensor_tcm9001md_data.vga_rst_pin = 19; msm_camera_sensor_tcm9001md_data.vga_pwdn_pin = 0; msm_camera_sensor_tcm9001md_data.vga_power_en_pin = 98; } else { /*5M sensor pins*/ if (phid <= Product_PR2) { msm_camera_sensor_tcm9001md_data.rst_pin = 1; } else { msm_camera_sensor_tcm9001md_data.rst_pin = 120; } msm_camera_sensor_tcm9001md_data.pwdn_pin = 2; /*VGA sensor pins*/ msm_camera_sensor_tcm9001md_data.vga_rst_pin = 19; msm_camera_sensor_tcm9001md_data.vga_pwdn_pin = 0; msm_camera_sensor_tcm9001md_data.vga_power_en_pin = 98; } #endif #endif } #endif /*CONFIG_MSM_CAMERA*/ #ifdef CONFIG_MSM7KV2_AUDIO static uint32_t audio_pamp_gpio_config = GPIO_CFG(82, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); static uint32_t audio_fluid_icodec_tx_config = GPIO_CFG(85, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ int SPK1_AMP = 36; int SPK2_AMP = 37; int HS_AMP = 55; static uint32_t audio_pamp_spk1_amp_gpio_config = 0; static uint32_t audio_pamp_spk2_amp_gpio_config = 0; static uint32_t audio_pamp_hs_amp_gpio_config = 0; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ static int __init snddev_poweramp_gpio_init(void) { int rc; /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ int pid =0; pid = fih_get_product_id(); if((pid==Product_SF5)||IS_SF8_SERIES_PRJ()) { SPK1_AMP = 36; } else if(pid==Product_SF6) { SPK1_AMP = 37; } else { SPK1_AMP = 36; SPK2_AMP = 37; } audio_pamp_spk1_amp_gpio_config = GPIO_CFG(SPK1_AMP, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); audio_pamp_spk2_amp_gpio_config = GPIO_CFG(SPK2_AMP, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); audio_pamp_hs_amp_gpio_config = GPIO_CFG(HS_AMP, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); pr_info("snddev_poweramp_gpio_init \n"); rc = gpio_tlmm_config(audio_pamp_spk1_amp_gpio_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_pamp_spk1_amp_gpio_config, rc); } rc = gpio_tlmm_config(audio_pamp_spk2_amp_gpio_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_pamp_spk2_amp_gpio_config, rc); } rc = gpio_tlmm_config(audio_pamp_hs_amp_gpio_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_pamp_hs_amp_gpio_config, rc); } /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ pr_info("snddev_poweramp_gpio_init \n"); rc = gpio_tlmm_config(audio_pamp_gpio_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_pamp_gpio_config, rc); } return rc; } void msm_snddev_tx_route_config(void) { int rc; pr_debug("%s()\n", __func__); if (machine_is_msm7x30_fluid()) { rc = gpio_tlmm_config(audio_fluid_icodec_tx_config, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_fluid_icodec_tx_config, rc); } else gpio_set_value(85, 0); } } void msm_snddev_tx_route_deconfig(void) { int rc; pr_debug("%s()\n", __func__); if (machine_is_msm7x30_fluid()) { rc = gpio_tlmm_config(audio_fluid_icodec_tx_config, GPIO_CFG_DISABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, audio_fluid_icodec_tx_config, rc); } } } void msm_snddev_poweramp_on(void) { /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ pr_info("%s: power on amplifier\n", __func__); m_SpkAmpOn=true; /* enable spkr poweramp */ /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ } void msm_snddev_poweramp_off(void) { /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ pr_info("%s: power off amplifier\n", __func__); m_SpkAmpOn=false; /* disable spkr poweramp */ /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ } /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ #ifndef CONFIG_FIH_FBX_AUDIO static struct vreg *snddev_vreg_ncp, *snddev_vreg_gp4; #endif // CONFIG_FIH_FBX_AUDIO /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ void msm_snddev_hsed_voltage_on(void) { /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ #ifndef CONFIG_FIH_FBX_AUDIO int rc; snddev_vreg_gp4 = vreg_get(NULL, "gp4"); if (IS_ERR(snddev_vreg_gp4)) { pr_err("%s: vreg_get(%s) failed (%ld)\n", __func__, "gp4", PTR_ERR(snddev_vreg_gp4)); return; } rc = vreg_enable(snddev_vreg_gp4); if (rc) pr_err("%s: vreg_enable(gp4) failed (%d)\n", __func__, rc); snddev_vreg_ncp = vreg_get(NULL, "ncp"); if (IS_ERR(snddev_vreg_ncp)) { pr_err("%s: vreg_get(%s) failed (%ld)\n", __func__, "ncp", PTR_ERR(snddev_vreg_ncp)); return; } rc = vreg_enable(snddev_vreg_ncp); if (rc) pr_err("%s: vreg_enable(ncp) failed (%d)\n", __func__, rc); #endif // CONFIG_FIH_FBX_AUDIO /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ m_HsAmpOn=true; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ } void msm_snddev_hsed_voltage_off(void) { /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ #ifndef CONFIG_FIH_FBX_AUDIO int rc; if (IS_ERR(snddev_vreg_ncp)) { pr_err("%s: vreg_get(%s) failed (%ld)\n", __func__, "ncp", PTR_ERR(snddev_vreg_ncp)); return; } rc = vreg_disable(snddev_vreg_ncp); if (rc) pr_err("%s: vreg_disable(ncp) failed (%d)\n", __func__, rc); vreg_put(snddev_vreg_ncp); if (IS_ERR(snddev_vreg_gp4)) { pr_err("%s: vreg_get(%s) failed (%ld)\n", __func__, "gp4", PTR_ERR(snddev_vreg_gp4)); return; } rc = vreg_disable(snddev_vreg_gp4); if (rc) pr_err("%s: vreg_disable(gp4) failed (%d)\n", __func__, rc); vreg_put(snddev_vreg_gp4); #endif // CONFIG_FIH_FBX_AUDIO /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ m_HsAmpOn=false; /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ } static unsigned aux_pcm_gpio_on[] = { GPIO_CFG(138, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* PCM_DOUT */ GPIO_CFG(139, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* PCM_DIN */ GPIO_CFG(140, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* PCM_SYNC */ GPIO_CFG(141, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), /* PCM_CLK */ }; static int __init aux_pcm_gpio_init(void) { int pin, rc; pr_info("aux_pcm_gpio_init \n"); for (pin = 0; pin < ARRAY_SIZE(aux_pcm_gpio_on); pin++) { rc = gpio_tlmm_config(aux_pcm_gpio_on[pin], GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, aux_pcm_gpio_on[pin], rc); } } return rc; } static struct msm_gpio mi2s_clk_gpios[] = { { GPIO_CFG(145, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_SCLK"}, { GPIO_CFG(144, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_WS"}, }; //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+{ static struct msm_gpio mi2s_mclk_gpios[] = { { GPIO_CFG(120, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_MCLK_A"}, }; //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+} static struct msm_gpio mi2s_rx_data_lines_gpios[] = { { GPIO_CFG(121, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD0_A"}, { GPIO_CFG(122, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD1_A"}, { GPIO_CFG(123, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD2_A"}, { GPIO_CFG(146, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD3"}, }; static struct msm_gpio mi2s_tx_data_lines_gpios[] = { { GPIO_CFG(146, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MI2S_DATA_SD3"}, }; int mi2s_config_clk_gpio(void) { //MM-RC-ChangeFMPath-00*{ if(!IS_SF8_SERIES_PRJ()){ int rc = 0; rc = msm_gpios_request_enable(mi2s_clk_gpios, ARRAY_SIZE(mi2s_clk_gpios)); if (rc) { pr_err("%s: enable mi2s clk gpios failed\n", __func__); return rc; } //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+{ if ((fih_get_product_id() != Product_SF5) || (fih_get_product_phase() != Product_PCR)) { rc = msm_gpios_request_enable(mi2s_mclk_gpios, ARRAY_SIZE(mi2s_mclk_gpios)); if (rc) { pr_err("%s: enable mi2s clk gpios failed\n", __func__); return rc; } } //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+} } //MM-RC-ChangeFMPath-00*} return 0; } int mi2s_unconfig_data_gpio(u32 direction, u8 sd_line_mask) { int i, rc = 0; //MM-RC-ChangeFMPath-01*{ if(IS_SF8_SERIES_PRJ()) return rc; //MM-RC-ChangeFMPath-01*} sd_line_mask &= MI2S_SD_LINE_MASK; switch (direction) { case DIR_TX: msm_gpios_disable_free(mi2s_tx_data_lines_gpios, 1); break; case DIR_RX: i = 0; while (sd_line_mask) { if (sd_line_mask & 0x1) msm_gpios_disable_free( mi2s_rx_data_lines_gpios + i , 1); sd_line_mask = sd_line_mask >> 1; i++; } break; default: pr_err("%s: Invaild direction direction = %u\n", __func__, direction); rc = -EINVAL; break; } return rc; } int mi2s_config_data_gpio(u32 direction, u8 sd_line_mask) { int i , rc = 0; u8 sd_config_done_mask = 0; //MM-RC-ChangeFMPath-01*{ if(IS_SF8_SERIES_PRJ()) return rc; //MM-RC-ChangeFMPath-01*} sd_line_mask &= MI2S_SD_LINE_MASK; switch (direction) { case DIR_TX: if ((sd_line_mask & MI2S_SD_0) || (sd_line_mask & MI2S_SD_1) || (sd_line_mask & MI2S_SD_2) || !(sd_line_mask & MI2S_SD_3)) { pr_err("%s: can not use SD0 or SD1 or SD2 for TX" ".only can use SD3. sd_line_mask = 0x%x\n", __func__ , sd_line_mask); rc = -EINVAL; } else { rc = msm_gpios_request_enable(mi2s_tx_data_lines_gpios, 1); if (rc) pr_err("%s: enable mi2s gpios for TX failed\n", __func__); } break; case DIR_RX: i = 0; while (sd_line_mask && (rc == 0)) { if (sd_line_mask & 0x1) { rc = msm_gpios_request_enable( mi2s_rx_data_lines_gpios + i , 1); if (rc) { pr_err("%s: enable mi2s gpios for" "RX failed. SD line = %s\n", __func__, (mi2s_rx_data_lines_gpios + i)->label); mi2s_unconfig_data_gpio(DIR_RX, sd_config_done_mask); } else sd_config_done_mask |= (1 << i); } sd_line_mask = sd_line_mask >> 1; i++; } break; default: pr_err("%s: Invaild direction direction = %u\n", __func__, direction); rc = -EINVAL; break; } return rc; } int mi2s_unconfig_clk_gpio(void) { //MM-RC-ChangeFMPath-00*{ if(!IS_SF8_SERIES_PRJ()){ msm_gpios_disable_free(mi2s_clk_gpios, ARRAY_SIZE(mi2s_clk_gpios)); //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+{ if ((fih_get_product_id() != Product_SF5) || (fih_get_product_phase() != Product_PCR)) { msm_gpios_disable_free(mi2s_mclk_gpios, ARRAY_SIZE(mi2s_mclk_gpios)); } //SW4-L1-HL-Camera-FixCameraCrashAfterOpenFM-00+} } //MM-RC-ChangeFMPath-00*} return 0; } #endif /* CONFIG_MSM7KV2_AUDIO */ static int __init buses_init(void) { if (gpio_tlmm_config(GPIO_CFG(PMIC_GPIO_INT, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE)) pr_err("%s: gpio_tlmm_config (gpio=%d) failed\n", __func__, PMIC_GPIO_INT); #ifdef CONFIG_KEYBOARD_PMIC8058 if (machine_is_msm7x30_fluid()) { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_KPD].platform_data = &fluid_keypad_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_KPD].data_size = sizeof(fluid_keypad_data); } else { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_KPD].platform_data = &surf_keypad_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_KPD].data_size = sizeof(surf_keypad_data); } #endif i2c_register_board_info(6 /* I2C_SSBI ID */, pm8058_boardinfo, ARRAY_SIZE(pm8058_boardinfo)); return 0; } #define TIMPANI_RESET_GPIO 1 struct bahama_config_register{ u8 reg; u8 value; u8 mask; }; enum version{ VER_1_0, VER_2_0, VER_UNSUPPORTED = 0xFF }; static struct vreg *vreg_marimba_1; static struct vreg *vreg_marimba_2; static struct vreg *vreg_marimba_3; static struct msm_gpio timpani_reset_gpio_cfg[] = { { GPIO_CFG(TIMPANI_RESET_GPIO, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "timpani_reset"} }; static u8 read_bahama_ver(void) { int rc; struct marimba config = { .mod_id = SLAVE_ID_BAHAMA }; u8 bahama_version; rc = marimba_read_bit_mask(&config, 0x00, &bahama_version, 1, 0x1F); if (rc < 0) { printk(KERN_ERR "%s: version read failed: %d\n", __func__, rc); return rc; } else { printk(KERN_INFO "%s: version read got: 0x%x\n", __func__, bahama_version); } switch (bahama_version) { case 0x08: /* varient of bahama v1 */ case 0x10: case 0x00: return VER_1_0; case 0x09: /* variant of bahama v2 */ return VER_2_0; default: return VER_UNSUPPORTED; } } static int config_timpani_reset(void) { int rc; rc = msm_gpios_request_enable(timpani_reset_gpio_cfg, ARRAY_SIZE(timpani_reset_gpio_cfg)); if (rc < 0) { printk(KERN_ERR "%s: msm_gpios_request_enable failed (%d)\n", __func__, rc); } return rc; } static unsigned int msm_timpani_setup_power(void) { int rc; rc = config_timpani_reset(); if (rc < 0) goto out; rc = vreg_enable(vreg_marimba_1); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d\n", __func__, rc); goto out; } rc = vreg_enable(vreg_marimba_2); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d\n", __func__, rc); goto fail_disable_vreg_marimba_1; } rc = gpio_direction_output(TIMPANI_RESET_GPIO, 1); if (rc < 0) { printk(KERN_ERR "%s: gpio_direction_output failed (%d)\n", __func__, rc); msm_gpios_free(timpani_reset_gpio_cfg, ARRAY_SIZE(timpani_reset_gpio_cfg)); vreg_disable(vreg_marimba_2); } else goto out; fail_disable_vreg_marimba_1: vreg_disable(vreg_marimba_1); out: return rc; }; static void msm_timpani_shutdown_power(void) { int rc; rc = vreg_disable(vreg_marimba_1); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } rc = vreg_disable(vreg_marimba_2); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } rc = gpio_direction_output(TIMPANI_RESET_GPIO, 0); if (rc < 0) { printk(KERN_ERR "%s: gpio_direction_output failed (%d)\n", __func__, rc); } msm_gpios_free(timpani_reset_gpio_cfg, ARRAY_SIZE(timpani_reset_gpio_cfg)); }; static unsigned int msm_bahama_core_config(int type) { int rc = 0; if (type == BAHAMA_ID) { int i; struct marimba config = { .mod_id = SLAVE_ID_BAHAMA }; const struct bahama_config_register v20_init[] = { /* reg, value, mask */ { 0xF4, 0x84, 0xFF }, /* AREG */ { 0xF0, 0x04, 0xFF } /* DREG */ }; if (read_bahama_ver() == VER_2_0) { for (i = 0; i < ARRAY_SIZE(v20_init); i++) { u8 value = v20_init[i].value; rc = marimba_write_bit_mask(&config, v20_init[i].reg, &value, sizeof(v20_init[i].value), v20_init[i].mask); if (rc < 0) { printk(KERN_ERR "%s: reg %d write failed: %d\n", __func__, v20_init[i].reg, rc); return rc; } printk(KERN_INFO "%s: reg 0x%02x value 0x%02x" " mask 0x%02x\n", __func__, v20_init[i].reg, v20_init[i].value, v20_init[i].mask); } } } printk(KERN_INFO "core type: %d\n", type); return rc; } static unsigned int msm_bahama_setup_power(void) { int rc; rc = vreg_enable(vreg_marimba_3); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d\n", __func__, rc); } return rc; }; static unsigned int msm_bahama_shutdown_power(int value) { int rc = 0; if (value != BAHAMA_ID) { rc = vreg_disable(vreg_marimba_3); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } } return rc; }; static struct msm_gpio marimba_svlte_config_clock[] = { { GPIO_CFG(34, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "MARIMBA_SVLTE_CLOCK_ENABLE" }, }; static unsigned int msm_marimba_gpio_config_svlte(int gpio_cfg_marimba) { if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { if (gpio_cfg_marimba) gpio_set_value(GPIO_PIN (marimba_svlte_config_clock->gpio_cfg), 1); else gpio_set_value(GPIO_PIN (marimba_svlte_config_clock->gpio_cfg), 0); } return 0; }; static unsigned int msm_marimba_setup_power(void) { int rc; rc = vreg_enable(vreg_marimba_1); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); goto out; } rc = vreg_enable(vreg_marimba_2); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); goto out; } if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = msm_gpios_request_enable(marimba_svlte_config_clock, ARRAY_SIZE(marimba_svlte_config_clock)); if (rc < 0) { printk(KERN_ERR "%s: msm_gpios_request_enable failed (%d)\n", __func__, rc); return rc; } rc = gpio_direction_output(GPIO_PIN (marimba_svlte_config_clock->gpio_cfg), 0); if (rc < 0) { printk(KERN_ERR "%s: gpio_direction_output failed (%d)\n", __func__, rc); return rc; } } out: return rc; }; static void msm_marimba_shutdown_power(void) { int rc; rc = vreg_disable(vreg_marimba_1); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } rc = vreg_disable(vreg_marimba_2); if (rc) { printk(KERN_ERR "%s: return val: %d \n", __func__, rc); } }; static int bahama_present(void) { int id; switch (id = adie_get_detected_connectivity_type()) { case BAHAMA_ID: return 1; case MARIMBA_ID: return 0; case TIMPANI_ID: default: printk(KERN_ERR "%s: unexpected adie connectivity type: %d\n", __func__, id); return -ENODEV; } } /* +++ AlbertYCFang, 2011.06.13, FM +++ */ #ifdef CONFIG_FIH_FM_LNA //FB0 add LNA in FM, so we need to control FM_LNA_EN and GPS_FM_LNA_2V8_EN to turn on/off FM LNA. #define FM_LNA_EN 78 static struct msm_gpio fm_gpio_table[] = { //{ GPIO_CFG(GPS_FM_LNA_2V8_EN, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "gps_fm_lna_2v8_en" }, { GPIO_CFG(FM_LNA_EN, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "fm_lna_en" }, }; #endif /* --- AlbertYCFang, 2011.06.13, FM --- */ struct vreg *fm_regulator; struct vreg *fm_gp16; static int fm_radio_setup(struct marimba_fm_platform_data *pdata) { int rc; uint32_t irqcfg; const char *id = "FMPW"; int bahama_not_marimba = bahama_present(); /* +++ AlbertYCFang, 2011.06.13, FM +++ */ fm_gp16 = vreg_get(NULL, "gp16"); if (IS_ERR(fm_gp16)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(fm_gp16)); return -1; } rc = vreg_enable(fm_gp16); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); return rc; } /* --- AlbertYCFang, 2011.06.13, FM --- */ if (bahama_not_marimba == -1) { printk(KERN_WARNING "%s: bahama_present: %d\n", __func__, bahama_not_marimba); return -ENODEV; } if (bahama_not_marimba) fm_regulator = vreg_get(NULL, "s3"); else fm_regulator = vreg_get(NULL, "s2"); if (IS_ERR(fm_regulator)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(fm_regulator)); return -1; } if (!bahama_not_marimba) { rc = pmapp_vreg_level_vote(id, PMAPP_VREG_S2, 1300); if (rc < 0) { printk(KERN_ERR "%s: voltage level vote failed (%d)\n", __func__, rc); return rc; } } rc = vreg_enable(fm_regulator); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d\n", __func__, rc); return rc; } /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_ON); } else { /* +++ AlbertYCFang, 2011.06.13, FM +++ */ rc = pmapp_clock_vote(id, /*PMAPP_CLOCK_ID_DO*/QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_ON); /* --- AlbertYCFang, 2011.06.13, FM --- */ } if (rc < 0) { printk(KERN_ERR "%s: clock vote failed (%d)\n", __func__, rc); goto fm_clock_vote_fail; } /*Request the Clock Using GPIO34/AP2MDM_MRMBCK_EN in case of svlte*/ if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = marimba_gpio_config(1); if (rc < 0) printk(KERN_ERR "%s: clock enable for svlte : %d\n", __func__, rc); } irqcfg = GPIO_CFG(147, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); rc = gpio_tlmm_config(irqcfg, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, irqcfg, rc); rc = -EIO; goto fm_gpio_config_fail; } /* +++ AlbertYCFang, 2011.06.13, FM +++ */ #ifdef CONFIG_FIH_FM_LNA //FB0 add LNA in FM, so we need to control FM_LNA_EN and GPS_FM_LNA_2V8_EN to turn LNA. printk(KERN_INFO "%s : config and enable FM LNA control.\n", __func__); rc = msm_gpios_enable(fm_gpio_table, ARRAY_SIZE(fm_gpio_table)); if (rc<0) goto fm_gpio_config_fail; /* FB0.B-396 */ rc = enable_gps_fm_lna(true); if (rc<0) goto fm_gpio_config_fail; gpio_set_value(FM_LNA_EN, 1); #endif /* --- AlbertYCFang, 2011.06.13, FM --- */ return 0; fm_gpio_config_fail: /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_OFF); } else { pmapp_clock_vote(id, /*PMAPP_CLOCK_ID_DO*/QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_OFF); } fm_clock_vote_fail: vreg_disable(fm_regulator); vreg_disable(fm_gp16); return rc; }; static void fm_radio_shutdown(struct marimba_fm_platform_data *pdata) { int rc; const char *id = "FMPW"; uint32_t irqcfg = GPIO_CFG(147, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA); int bahama_not_marimba = bahama_present(); /* +++ AlbertYCFang, 2011.06.13, FM +++ */ #ifdef CONFIG_FIH_FM_LNA /* FB0 add LNA in FM, so we need to control FM_LNA_EN and GPS_FM_LNA_2V8_EN to turn LNA. FB0.B-396 */ enable_gps_fm_lna(false); gpio_set_value(FM_LNA_EN, 0); #endif /* --- AlbertYCFang, 2011.06.13, FM --- */ if (bahama_not_marimba == -1) { printk(KERN_WARNING "%s: bahama_present: %d\n", __func__, bahama_not_marimba); return; } rc = gpio_tlmm_config(irqcfg, GPIO_CFG_ENABLE); if (rc) { printk(KERN_ERR "%s: gpio_tlmm_config(%#x)=%d\n", __func__, irqcfg, rc); } if (fm_regulator != NULL) { rc = vreg_disable(fm_regulator); if (rc) { printk(KERN_ERR "%s: return val: %d\n", __func__, rc); } fm_regulator = NULL; } /* +++ AlbertYCFang, 2011.06.13, FM +++ */ rc = vreg_disable(fm_gp16); if (rc) { printk(KERN_ERR "%s: return val: %d \n", __func__, rc); } /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_OFF); } else { rc = pmapp_clock_vote(id, /*PMAPP_CLOCK_ID_DO*/QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_OFF); } /* --- AlbertYCFang, 2011.06.13, FM --- */ if (rc < 0) printk(KERN_ERR "%s: clock_vote return val: %d\n", __func__, rc); /*Disable the Clock Using GPIO34/AP2MDM_MRMBCK_EN in case of svlte*/ if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = marimba_gpio_config(0); if (rc < 0) printk(KERN_ERR "%s: clock disable for svlte : %d\n", __func__, rc); } if (!bahama_not_marimba) { rc = pmapp_vreg_level_vote(id, PMAPP_VREG_S2, 0); if (rc < 0) printk(KERN_ERR "%s: vreg level vote return val: %d\n", __func__, rc); } } static struct marimba_fm_platform_data marimba_fm_pdata = { .fm_setup = fm_radio_setup, .fm_shutdown = fm_radio_shutdown, .irq = MSM_GPIO_TO_INT(147), .vreg_s2 = NULL, .vreg_xo_out = NULL, }; /* Slave id address for FM/CDC/QMEMBIST * Values can be programmed using Marimba slave id 0 * should there be a conflict with other I2C devices * */ #define MARIMBA_SLAVE_ID_FM_ADDR 0x2A #define MARIMBA_SLAVE_ID_CDC_ADDR 0x77 #define MARIMBA_SLAVE_ID_QMEMBIST_ADDR 0X66 #define BAHAMA_SLAVE_ID_FM_ADDR 0x2A #define BAHAMA_SLAVE_ID_QMEMBIST_ADDR 0x7B static const char *tsadc_id = "MADC"; static const char *vregs_tsadc_name[] = { "gp12", "s2", }; static struct vreg *vregs_tsadc[ARRAY_SIZE(vregs_tsadc_name)]; static const char *vregs_timpani_tsadc_name[] = { "s3", "gp12", "gp16" }; static struct vreg *vregs_timpani_tsadc[ARRAY_SIZE(vregs_timpani_tsadc_name)]; static int marimba_tsadc_power(int vreg_on) { int i, rc = 0; int tsadc_adie_type = adie_get_detected_codec_type(); if (tsadc_adie_type == TIMPANI_ID) { for (i = 0; i < ARRAY_SIZE(vregs_timpani_tsadc_name); i++) { if (!vregs_timpani_tsadc[i]) { pr_err("%s: vreg_get %s failed(%d)\n", __func__, vregs_timpani_tsadc_name[i], rc); goto vreg_fail; } rc = vreg_on ? vreg_enable(vregs_timpani_tsadc[i]) : vreg_disable(vregs_timpani_tsadc[i]); if (rc < 0) { pr_err("%s: vreg %s %s failed(%d)\n", __func__, vregs_timpani_tsadc_name[i], vreg_on ? "enable" : "disable", rc); goto vreg_fail; } } /* Vote for D0 and D1 buffer */ /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(tsadc_id, PMAPP_CLOCK_ID_DO, vreg_on ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); } else { rc = pmapp_clock_vote(tsadc_id, /*PMAPP_CLOCK_ID_D1*/QTR8x00_WCN_CLK, vreg_on ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); } if (rc) { pr_err("%s: unable to %svote for d1 clk\n", __func__, vreg_on ? "" : "de-"); goto do_vote_fail; } rc = pmapp_clock_vote(tsadc_id, PMAPP_CLOCK_ID_DO, vreg_on ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); if (rc) { pr_err("%s: unable to %svote for d1 clk\n", __func__, vreg_on ? "" : "de-"); goto do_vote_fail; } } else if (tsadc_adie_type == MARIMBA_ID) { for (i = 0; i < ARRAY_SIZE(vregs_tsadc_name); i++) { if (!vregs_tsadc[i]) { pr_err("%s: vreg_get %s failed (%d)\n", __func__, vregs_tsadc_name[i], rc); goto vreg_fail; } rc = vreg_on ? vreg_enable(vregs_tsadc[i]) : vreg_disable(vregs_tsadc[i]); if (rc < 0) { pr_err("%s: vreg %s %s failed (%d)\n", __func__, vregs_tsadc_name[i], vreg_on ? "enable" : "disable", rc); goto vreg_fail; } } /* If marimba vote for DO buffer */ rc = pmapp_clock_vote(tsadc_id, PMAPP_CLOCK_ID_DO, vreg_on ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); if (rc) { pr_err("%s: unable to %svote for d0 clk\n", __func__, vreg_on ? "" : "de-"); goto do_vote_fail; } } else { pr_err("%s:Adie %d not supported\n", __func__, tsadc_adie_type); return -ENODEV; } msleep(5); /* ensure power is stable */ return 0; do_vote_fail: vreg_fail: while (i) { if (vreg_on) { if (tsadc_adie_type == TIMPANI_ID) vreg_disable(vregs_timpani_tsadc[--i]); else if (tsadc_adie_type == MARIMBA_ID) vreg_disable(vregs_tsadc[--i]); } else { if (tsadc_adie_type == TIMPANI_ID) vreg_enable(vregs_timpani_tsadc[--i]); else if (tsadc_adie_type == MARIMBA_ID) vreg_enable(vregs_tsadc[--i]); } } return rc; } static int marimba_tsadc_vote(int vote_on) { int rc = 0; if (adie_get_detected_codec_type() == MARIMBA_ID) { int level = vote_on ? 1300 : 0; rc = pmapp_vreg_level_vote(tsadc_id, PMAPP_VREG_S2, level); if (rc < 0) pr_err("%s: vreg level %s failed (%d)\n", __func__, vote_on ? "on" : "off", rc); } return rc; } static int marimba_tsadc_init(void) { int i, rc = 0; int tsadc_adie_type = adie_get_detected_codec_type(); if (tsadc_adie_type == TIMPANI_ID) { for (i = 0; i < ARRAY_SIZE(vregs_timpani_tsadc_name); i++) { vregs_timpani_tsadc[i] = vreg_get(NULL, vregs_timpani_tsadc_name[i]); if (IS_ERR(vregs_timpani_tsadc[i])) { pr_err("%s: vreg get %s failed (%ld)\n", __func__, vregs_timpani_tsadc_name[i], PTR_ERR(vregs_timpani_tsadc[i])); rc = PTR_ERR(vregs_timpani_tsadc[i]); goto vreg_get_fail; } } } else if (tsadc_adie_type == MARIMBA_ID) { for (i = 0; i < ARRAY_SIZE(vregs_tsadc_name); i++) { vregs_tsadc[i] = vreg_get(NULL, vregs_tsadc_name[i]); if (IS_ERR(vregs_tsadc[i])) { pr_err("%s: vreg get %s failed (%ld)\n", __func__, vregs_tsadc_name[i], PTR_ERR(vregs_tsadc[i])); rc = PTR_ERR(vregs_tsadc[i]); goto vreg_get_fail; } } } else { pr_err("%s:Adie %d not supported\n", __func__, tsadc_adie_type); return -ENODEV; } return 0; vreg_get_fail: while (i) { if (tsadc_adie_type == TIMPANI_ID) vreg_put(vregs_timpani_tsadc[--i]); else if (tsadc_adie_type == MARIMBA_ID) vreg_put(vregs_tsadc[--i]); } return rc; } static int marimba_tsadc_exit(void) { int i, rc = 0; int tsadc_adie_type = adie_get_detected_codec_type(); if (tsadc_adie_type == TIMPANI_ID) { for (i = 0; i < ARRAY_SIZE(vregs_timpani_tsadc_name); i++) { if (vregs_tsadc[i]) vreg_put(vregs_timpani_tsadc[i]); } } else if (tsadc_adie_type == MARIMBA_ID) { for (i = 0; i < ARRAY_SIZE(vregs_tsadc_name); i++) { if (vregs_tsadc[i]) vreg_put(vregs_tsadc[i]); } rc = pmapp_vreg_level_vote(tsadc_id, PMAPP_VREG_S2, 0); if (rc < 0) pr_err("%s: vreg level off failed (%d)\n", __func__, rc); } else { pr_err("%s:Adie %d not supported\n", __func__, tsadc_adie_type); rc = -ENODEV; } return rc; } static struct msm_ts_platform_data msm_ts_data = { .min_x = 0, .max_x = 4096, .min_y = 0, .max_y = 4096, .min_press = 0, .max_press = 255, .inv_x = 4096, .inv_y = 4096, .can_wakeup = false, }; static struct marimba_tsadc_platform_data marimba_tsadc_pdata = { .marimba_tsadc_power = marimba_tsadc_power, .init = marimba_tsadc_init, .exit = marimba_tsadc_exit, .level_vote = marimba_tsadc_vote, .tsadc_prechg_en = true, .can_wakeup = false, .setup = { .pen_irq_en = true, .tsadc_en = true, }, .params2 = { .input_clk_khz = 2400, .sample_prd = TSADC_CLK_3, }, .params3 = { .prechg_time_nsecs = 6400, .stable_time_nsecs = 6400, .tsadc_test_mode = 0, }, .tssc_data = &msm_ts_data, }; static struct vreg *vreg_codec_s4; static int msm_marimba_codec_power(int vreg_on) { int rc = 0; if (!vreg_codec_s4) { vreg_codec_s4 = vreg_get(NULL, "s4"); if (IS_ERR(vreg_codec_s4)) { printk(KERN_ERR "%s: vreg_get() failed (%ld)\n", __func__, PTR_ERR(vreg_codec_s4)); rc = PTR_ERR(vreg_codec_s4); goto vreg_codec_s4_fail; } } if (vreg_on) { rc = vreg_enable(vreg_codec_s4); if (rc) printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); goto vreg_codec_s4_fail; } else { rc = vreg_disable(vreg_codec_s4); if (rc) printk(KERN_ERR "%s: vreg_disable() = %d \n", __func__, rc); goto vreg_codec_s4_fail; } vreg_codec_s4_fail: return rc; } static struct marimba_codec_platform_data mariba_codec_pdata = { .marimba_codec_power = msm_marimba_codec_power, #ifdef CONFIG_MARIMBA_CODEC .snddev_profile_init = msm_snddev_init, #endif }; static struct marimba_platform_data marimba_pdata = { .slave_id[MARIMBA_SLAVE_ID_FM] = MARIMBA_SLAVE_ID_FM_ADDR, .slave_id[MARIMBA_SLAVE_ID_CDC] = MARIMBA_SLAVE_ID_CDC_ADDR, .slave_id[MARIMBA_SLAVE_ID_QMEMBIST] = MARIMBA_SLAVE_ID_QMEMBIST_ADDR, .slave_id[SLAVE_ID_BAHAMA_FM] = BAHAMA_SLAVE_ID_FM_ADDR, .slave_id[SLAVE_ID_BAHAMA_QMEMBIST] = BAHAMA_SLAVE_ID_QMEMBIST_ADDR, .marimba_setup = msm_marimba_setup_power, .marimba_shutdown = msm_marimba_shutdown_power, .bahama_setup = msm_bahama_setup_power, .bahama_shutdown = msm_bahama_shutdown_power, .marimba_gpio_config = msm_marimba_gpio_config_svlte, .bahama_core_config = msm_bahama_core_config, .fm = &marimba_fm_pdata, .codec = &mariba_codec_pdata, }; static void __init msm7x30_init_marimba(void) { int rc; vreg_marimba_1 = vreg_get(NULL, "s3"); if (IS_ERR(vreg_marimba_1)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_marimba_1)); return; } rc = vreg_set_level(vreg_marimba_1, 1800); vreg_marimba_2 = vreg_get(NULL, "gp16"); if (IS_ERR(vreg_marimba_1)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_marimba_1)); return; } rc = vreg_set_level(vreg_marimba_2, 1200); vreg_marimba_3 = vreg_get(NULL, "usb2"); if (IS_ERR(vreg_marimba_3)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_marimba_3)); return; } rc = vreg_set_level(vreg_marimba_3, 1800); } static struct marimba_codec_platform_data timpani_codec_pdata = { .marimba_codec_power = msm_marimba_codec_power, #ifdef CONFIG_TIMPANI_CODEC .snddev_profile_init = msm_snddev_init_timpani, #endif }; static struct marimba_platform_data timpani_pdata = { .slave_id[MARIMBA_SLAVE_ID_CDC] = MARIMBA_SLAVE_ID_CDC_ADDR, .slave_id[MARIMBA_SLAVE_ID_QMEMBIST] = MARIMBA_SLAVE_ID_QMEMBIST_ADDR, .marimba_setup = msm_timpani_setup_power, .marimba_shutdown = msm_timpani_shutdown_power, .codec = &timpani_codec_pdata, .tsadc = &marimba_tsadc_pdata, }; #define TIMPANI_I2C_SLAVE_ADDR 0xD static struct i2c_board_info msm_i2c_gsbi7_timpani_info[] = { { I2C_BOARD_INFO("timpani", TIMPANI_I2C_SLAVE_ADDR), .platform_data = &timpani_pdata, }, }; #ifdef CONFIG_MSM7KV2_AUDIO static struct resource msm_aictl_resources[] = { { .name = "aictl", .start = 0xa5000100, .end = 0xa5000100, .flags = IORESOURCE_MEM, } }; static struct resource msm_mi2s_resources[] = { { .name = "hdmi", .start = 0xac900000, .end = 0xac900038, .flags = IORESOURCE_MEM, }, { .name = "codec_rx", .start = 0xac940040, .end = 0xac940078, .flags = IORESOURCE_MEM, }, { .name = "codec_tx", .start = 0xac980080, .end = 0xac9800B8, .flags = IORESOURCE_MEM, } }; static struct msm_lpa_platform_data lpa_pdata = { .obuf_hlb_size = 0x2BFF8, .dsp_proc_id = 0, .app_proc_id = 2, .nosb_config = { .llb_min_addr = 0, .llb_max_addr = 0x3ff8, .sb_min_addr = 0, .sb_max_addr = 0, }, .sb_config = { .llb_min_addr = 0, .llb_max_addr = 0x37f8, .sb_min_addr = 0x3800, .sb_max_addr = 0x3ff8, } }; static struct resource msm_lpa_resources[] = { { .name = "lpa", .start = 0xa5000000, .end = 0xa50000a0, .flags = IORESOURCE_MEM, } }; static struct resource msm_aux_pcm_resources[] = { { .name = "aux_codec_reg_addr", .start = 0xac9c00c0, .end = 0xac9c00c8, .flags = IORESOURCE_MEM, }, { .name = "aux_pcm_dout", .start = 138, .end = 138, .flags = IORESOURCE_IO, }, { .name = "aux_pcm_din", .start = 139, .end = 139, .flags = IORESOURCE_IO, }, { .name = "aux_pcm_syncout", .start = 140, .end = 140, .flags = IORESOURCE_IO, }, { .name = "aux_pcm_clkin_a", .start = 141, .end = 141, .flags = IORESOURCE_IO, }, }; static struct platform_device msm_aux_pcm_device = { .name = "msm_aux_pcm", .id = 0, .num_resources = ARRAY_SIZE(msm_aux_pcm_resources), .resource = msm_aux_pcm_resources, }; struct platform_device msm_aictl_device = { .name = "audio_interct", .id = 0, .num_resources = ARRAY_SIZE(msm_aictl_resources), .resource = msm_aictl_resources, }; struct platform_device msm_mi2s_device = { .name = "mi2s", .id = 0, .num_resources = ARRAY_SIZE(msm_mi2s_resources), .resource = msm_mi2s_resources, }; struct platform_device msm_lpa_device = { .name = "lpa", .id = 0, .num_resources = ARRAY_SIZE(msm_lpa_resources), .resource = msm_lpa_resources, .dev = { .platform_data = &lpa_pdata, }, }; #endif /* CONFIG_MSM7KV2_AUDIO */ #define DEC0_FORMAT ((1<<MSM_ADSP_CODEC_MP3)| \ (1<<MSM_ADSP_CODEC_AAC)|(1<<MSM_ADSP_CODEC_WMA)| \ (1<<MSM_ADSP_CODEC_WMAPRO)|(1<<MSM_ADSP_CODEC_AMRWB)| \ (1<<MSM_ADSP_CODEC_AMRNB)|(1<<MSM_ADSP_CODEC_WAV)| \ (1<<MSM_ADSP_CODEC_ADPCM)|(1<<MSM_ADSP_CODEC_YADPCM)| \ (1<<MSM_ADSP_CODEC_EVRC)|(1<<MSM_ADSP_CODEC_QCELP)) #define DEC1_FORMAT ((1<<MSM_ADSP_CODEC_MP3)| \ (1<<MSM_ADSP_CODEC_AAC)|(1<<MSM_ADSP_CODEC_WMA)| \ (1<<MSM_ADSP_CODEC_WMAPRO)|(1<<MSM_ADSP_CODEC_AMRWB)| \ (1<<MSM_ADSP_CODEC_AMRNB)|(1<<MSM_ADSP_CODEC_WAV)| \ (1<<MSM_ADSP_CODEC_ADPCM)|(1<<MSM_ADSP_CODEC_YADPCM)| \ (1<<MSM_ADSP_CODEC_EVRC)|(1<<MSM_ADSP_CODEC_QCELP)) #define DEC2_FORMAT ((1<<MSM_ADSP_CODEC_MP3)| \ (1<<MSM_ADSP_CODEC_AAC)|(1<<MSM_ADSP_CODEC_WMA)| \ (1<<MSM_ADSP_CODEC_WMAPRO)|(1<<MSM_ADSP_CODEC_AMRWB)| \ (1<<MSM_ADSP_CODEC_AMRNB)|(1<<MSM_ADSP_CODEC_WAV)| \ (1<<MSM_ADSP_CODEC_ADPCM)|(1<<MSM_ADSP_CODEC_YADPCM)| \ (1<<MSM_ADSP_CODEC_EVRC)|(1<<MSM_ADSP_CODEC_QCELP)) #define DEC3_FORMAT ((1<<MSM_ADSP_CODEC_MP3)| \ (1<<MSM_ADSP_CODEC_AAC)|(1<<MSM_ADSP_CODEC_WMA)| \ (1<<MSM_ADSP_CODEC_WMAPRO)|(1<<MSM_ADSP_CODEC_AMRWB)| \ (1<<MSM_ADSP_CODEC_AMRNB)|(1<<MSM_ADSP_CODEC_WAV)| \ (1<<MSM_ADSP_CODEC_ADPCM)|(1<<MSM_ADSP_CODEC_YADPCM)| \ (1<<MSM_ADSP_CODEC_EVRC)|(1<<MSM_ADSP_CODEC_QCELP)) #define DEC4_FORMAT (1<<MSM_ADSP_CODEC_MIDI) static unsigned int dec_concurrency_table[] = { /* Audio LP */ 0, (DEC3_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_MODE_LP)| (1<<MSM_ADSP_OP_DM)), /* Concurrency 1 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 2 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 3 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 4 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 5 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_TUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), /* Concurrency 6 */ (DEC4_FORMAT), (DEC3_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC2_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC1_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), (DEC0_FORMAT|(1<<MSM_ADSP_MODE_NONTUNNEL)|(1<<MSM_ADSP_OP_DM)), }; #define DEC_INFO(name, queueid, decid, nr_codec) { .module_name = name, \ .module_queueid = queueid, .module_decid = decid, \ .nr_codec_support = nr_codec} #define DEC_INSTANCE(max_instance_same, max_instance_diff) { \ .max_instances_same_dec = max_instance_same, \ .max_instances_diff_dec = max_instance_diff} static struct msm_adspdec_info dec_info_list[] = { DEC_INFO("AUDPLAY4TASK", 17, 4, 1), /* AudPlay4BitStreamCtrlQueue */ DEC_INFO("AUDPLAY3TASK", 16, 3, 11), /* AudPlay3BitStreamCtrlQueue */ DEC_INFO("AUDPLAY2TASK", 15, 2, 11), /* AudPlay2BitStreamCtrlQueue */ DEC_INFO("AUDPLAY1TASK", 14, 1, 11), /* AudPlay1BitStreamCtrlQueue */ DEC_INFO("AUDPLAY0TASK", 13, 0, 11), /* AudPlay0BitStreamCtrlQueue */ }; static struct dec_instance_table dec_instance_list[][MSM_MAX_DEC_CNT] = { /* Non Turbo Mode */ { DEC_INSTANCE(4, 3), /* WAV */ DEC_INSTANCE(4, 3), /* ADPCM */ DEC_INSTANCE(4, 2), /* MP3 */ DEC_INSTANCE(0, 0), /* Real Audio */ DEC_INSTANCE(4, 2), /* WMA */ DEC_INSTANCE(3, 2), /* AAC */ DEC_INSTANCE(0, 0), /* Reserved */ DEC_INSTANCE(0, 0), /* MIDI */ DEC_INSTANCE(4, 3), /* YADPCM */ DEC_INSTANCE(4, 3), /* QCELP */ DEC_INSTANCE(4, 3), /* AMRNB */ DEC_INSTANCE(1, 1), /* AMRWB/WB+ */ DEC_INSTANCE(4, 3), /* EVRC */ DEC_INSTANCE(1, 1), /* WMAPRO */ }, /* Turbo Mode */ { DEC_INSTANCE(4, 3), /* WAV */ DEC_INSTANCE(4, 3), /* ADPCM */ DEC_INSTANCE(4, 3), /* MP3 */ DEC_INSTANCE(0, 0), /* Real Audio */ DEC_INSTANCE(4, 3), /* WMA */ DEC_INSTANCE(4, 3), /* AAC */ DEC_INSTANCE(0, 0), /* Reserved */ DEC_INSTANCE(0, 0), /* MIDI */ DEC_INSTANCE(4, 3), /* YADPCM */ DEC_INSTANCE(4, 3), /* QCELP */ DEC_INSTANCE(4, 3), /* AMRNB */ DEC_INSTANCE(2, 3), /* AMRWB/WB+ */ DEC_INSTANCE(4, 3), /* EVRC */ DEC_INSTANCE(1, 2), /* WMAPRO */ }, }; static struct msm_adspdec_database msm_device_adspdec_database = { .num_dec = ARRAY_SIZE(dec_info_list), .num_concurrency_support = (ARRAY_SIZE(dec_concurrency_table) / \ ARRAY_SIZE(dec_info_list)), .dec_concurrency_table = dec_concurrency_table, .dec_info_list = dec_info_list, .dec_instance_list = &dec_instance_list[0][0], }; static struct platform_device msm_device_adspdec = { .name = "msm_adspdec", .id = -1, .dev = { .platform_data = &msm_device_adspdec_database }, }; /* Div2-SW2-BSP-FBX-OW { */ #ifdef CONFIG_SMC91X static struct resource smc91x_resources[] = { [0] = { .start = 0x8A000300, .end = 0x8A0003ff, .flags = IORESOURCE_MEM, }, [1] = { .start = MSM_GPIO_TO_INT(156), .end = MSM_GPIO_TO_INT(156), .flags = IORESOURCE_IRQ, }, }; static struct platform_device smc91x_device = { .name = "smc91x", .id = 0, .num_resources = ARRAY_SIZE(smc91x_resources), .resource = smc91x_resources, }; #endif #ifdef CONFIG_SMSC911X static struct smsc911x_platform_config smsc911x_config = { .phy_interface = PHY_INTERFACE_MODE_MII, .irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW, .irq_type = SMSC911X_IRQ_TYPE_PUSH_PULL, .flags = SMSC911X_USE_32BIT, }; static struct resource smsc911x_resources[] = { [0] = { .start = 0x8D000000, .end = 0x8D000100, .flags = IORESOURCE_MEM, }, [1] = { .start = MSM_GPIO_TO_INT(88), .end = MSM_GPIO_TO_INT(88), .flags = IORESOURCE_IRQ, }, }; static struct platform_device smsc911x_device = { .name = "smsc911x", .id = -1, .num_resources = ARRAY_SIZE(smsc911x_resources), .resource = smsc911x_resources, .dev = { .platform_data = &smsc911x_config, }, }; static struct msm_gpio smsc911x_gpios[] = { { GPIO_CFG(172, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr6" }, { GPIO_CFG(173, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr5" }, { GPIO_CFG(174, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr4" }, { GPIO_CFG(175, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr3" }, { GPIO_CFG(176, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr2" }, { GPIO_CFG(177, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr1" }, { GPIO_CFG(178, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "ebi2_addr0" }, { GPIO_CFG(88, 2, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "smsc911x_irq" }, }; static void msm7x30_cfg_smsc911x(void) { int rc; rc = msm_gpios_request_enable(smsc911x_gpios, ARRAY_SIZE(smsc911x_gpios)); if (rc) pr_err("%s: unable to enable gpios\n", __func__); } #endif /* } Div2-SW2-BSP-FBX-OW */ #ifdef CONFIG_USB_FUNCTION static struct usb_mass_storage_platform_data usb_mass_storage_pdata = { .nluns = 0x02, .buf_size = 16384, .vendor = "GOOGLE", .product = "Mass storage", .release = 0xffff, }; static struct platform_device mass_storage_device = { .name = "usb_mass_storage", .id = -1, .dev = { .platform_data = &usb_mass_storage_pdata, }, }; #endif #ifdef CONFIG_USB_ANDROID static char *usb_functions_default[] = { "diag", "modem", "nmea", "rmnet", "usb_mass_storage", }; static char *usb_functions_default_adb[] = { "diag", "adb", "modem", "nmea", "rmnet", "usb_mass_storage", }; static char *fusion_usb_functions_default[] = { "diag", "nmea", "usb_mass_storage", }; static char *fusion_usb_functions_default_adb[] = { "diag", "adb", "nmea", "usb_mass_storage", }; static char *usb_functions_rndis[] = { "rndis", }; static char *usb_functions_rndis_adb[] = { "rndis", "adb", }; static char *usb_functions_rndis_diag[] = { "rndis", "diag", }; static char *usb_functions_rndis_adb_diag[] = { "rndis", "diag", "adb", }; /* FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid { */ #ifdef CONFIG_FIH_FXX static char *usb_functions_c000[] = { "nmea", "modem", "adb", "diag", "usb_mass_storage", }; static char *usb_functions_c001[] = { "modem", "adb", "usb_mass_storage", }; static char *usb_functions_c002[] = { "diag", }; static char *usb_functions_c003[] = { "modem", }; static char *usb_functions_c004[] = { "usb_mass_storage", }; static char *usb_functions_c007[] = { "rndis", "adb", "diag", }; static char *usb_functions_c008[] = { "rndis", "adb", }; #ifdef CONFIG_USB_ANDROID_ACCESSORY static char *usb_functions_accessory[] = { "accessory" }; static char *usb_functions_accessory_adb[] = { "accessory", "adb" }; #endif // CONFIG_USB_ANDROID_ACCESSORY static char *usb_functions_all[] = { #ifdef CONFIG_USB_ANDROID_RNDIS "rndis", #endif #ifdef CONFIG_USB_ANDROID_ACCESSORY "accessory", #endif // CONFIG_USB_ANDROID_ACCESSORY "usb_mass_storage", #ifdef CONFIG_USB_ANDROID_DIAG "diag", #endif "adb", #ifdef CONFIG_USB_F_SERIAL "modem", "nmea", #endif #ifdef CONFIG_USB_ANDROID_RMNET "rmnet", #endif #ifdef CONFIG_USB_ANDROID_ACM "acm", #endif }; #else // CONFIG_FIH_FXX static char *usb_functions_all[] = { #ifdef CONFIG_USB_ANDROID_RNDIS "rndis", #endif #ifdef CONFIG_USB_ANDROID_DIAG "diag", #endif "adb", #ifdef CONFIG_USB_F_SERIAL "modem", "nmea", #endif #ifdef CONFIG_USB_ANDROID_RMNET "rmnet", #endif "usb_mass_storage", #ifdef CONFIG_USB_ANDROID_ACM "acm", #endif }; #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid */ static struct android_usb_product usb_products[] = { /* FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid { */ #ifdef CONFIG_FIH_FXX { /* RNDIS + ADB */ .product_id = 0xC008, .num_functions = ARRAY_SIZE(usb_functions_c008), .functions = usb_functions_c008, }, { /* RNDIS + ADB + DIAG */ .product_id = 0xC007, .num_functions = ARRAY_SIZE(usb_functions_c007), .functions = usb_functions_c007, }, { /* USB_MASS_STORAGE */ .product_id = 0xC004, .num_functions = ARRAY_SIZE(usb_functions_c004), .functions = usb_functions_c004, }, { /* MODEM */ .product_id = 0xC003, .num_functions = ARRAY_SIZE(usb_functions_c003), .functions = usb_functions_c003, }, { /* DIAG */ .product_id = 0xC002, .num_functions = ARRAY_SIZE(usb_functions_c002), .functions = usb_functions_c002, }, { /* MODEM + ADB + USB_MASS_STORAGE */ .product_id = 0xC001, .num_functions = ARRAY_SIZE(usb_functions_c001), .functions = usb_functions_c001, }, { /* NMEA + MODEM + ADB + DIAG + USB_MASS_STORAGE */ .product_id = 0xC000, .num_functions = ARRAY_SIZE(usb_functions_c000), .functions = usb_functions_c000, }, #ifdef CONFIG_USB_ANDROID_ACCESSORY { .vendor_id = USB_ACCESSORY_VENDOR_ID, .product_id = USB_ACCESSORY_PRODUCT_ID, .num_functions = ARRAY_SIZE(usb_functions_accessory), .functions = usb_functions_accessory, }, { .vendor_id = USB_ACCESSORY_VENDOR_ID, .product_id = USB_ACCESSORY_ADB_PRODUCT_ID, .num_functions = ARRAY_SIZE(usb_functions_accessory_adb), .functions = usb_functions_accessory_adb, }, #endif // CONFIG_USB_ANDROID_ACCESSORY #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid */ { .product_id = 0x9026, .num_functions = ARRAY_SIZE(usb_functions_default), .functions = usb_functions_default, }, { .product_id = 0x9025, .num_functions = ARRAY_SIZE(usb_functions_default_adb), .functions = usb_functions_default_adb, }, { /* RNDIS + DIAG */ .product_id = 0x902C, .num_functions = ARRAY_SIZE(usb_functions_rndis_diag), .functions = usb_functions_rndis_diag, }, { /* RNDIS + ADB + DIAG */ .product_id = 0x902D, .num_functions = ARRAY_SIZE(usb_functions_rndis_adb_diag), .functions = usb_functions_rndis_adb_diag, }, }; /* FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized { */ #ifdef CONFIG_FIH_FXX /*Huawei*/ static struct android_usb_product usb_products_12d1[] = { { .product_id = 0x1028, .num_functions = ARRAY_SIZE(usb_functions_c008), .functions = usb_functions_c008, }, { .product_id = 0x1027, .num_functions = ARRAY_SIZE(usb_functions_c007), .functions = usb_functions_c007, }, { .product_id = 0x1024, .num_functions = ARRAY_SIZE(usb_functions_c004), .functions = usb_functions_c004, }, { .product_id = 0x1023, .num_functions = ARRAY_SIZE(usb_functions_c003), .functions = usb_functions_c003, }, { .product_id = 0x1022, .num_functions = ARRAY_SIZE(usb_functions_c002), .functions = usb_functions_c002, }, { .product_id = 0x103c, .num_functions = ARRAY_SIZE(usb_functions_c001), .functions = usb_functions_c001, }, { .product_id = 0x1021, .num_functions = ARRAY_SIZE(usb_functions_c000), .functions = usb_functions_c000, }, }; #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized */ static struct android_usb_product fusion_usb_products[] = { { .product_id = 0x9028, .num_functions = ARRAY_SIZE(fusion_usb_functions_default), .functions = fusion_usb_functions_default, }, { .product_id = 0x9029, .num_functions = ARRAY_SIZE(fusion_usb_functions_default_adb), .functions = fusion_usb_functions_default_adb, }, { .product_id = 0xf00e, .num_functions = ARRAY_SIZE(usb_functions_rndis), .functions = usb_functions_rndis, }, { .product_id = 0x9024, .num_functions = ARRAY_SIZE(usb_functions_rndis_adb), .functions = usb_functions_rndis_adb, }, }; static struct usb_mass_storage_platform_data mass_storage_pdata = { /* FIHTDC, Div2-SW2-BSP, Penho, PCtool { */ #ifdef CONFIG_FIH_FXX .nluns = 2, #else // CONFIG_FIH_FXX .nluns = 1, #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, PCtool */ .vendor = "Qualcomm Incorporated", .product = "Mass storage", .release = 0x0100, .can_stall = 1, }; static struct platform_device usb_mass_storage_device = { .name = "usb_mass_storage", .id = -1, .dev = { .platform_data = &mass_storage_pdata, }, }; static struct usb_ether_platform_data rndis_pdata = { /* ethaddr is filled by board_serialno_setup */ .vendorID = 0x05C6, .vendorDescr = "Qualcomm Incorporated", }; static struct platform_device rndis_device = { .name = "rndis", .id = -1, .dev = { .platform_data = &rndis_pdata, }, }; static struct android_usb_platform_data android_usb_pdata = { /* FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid { */ #ifdef CONFIG_FIH_FXX .vendor_id = 0x0489, .product_id = 0xC001, #else // CONFIG_FIH_FXX .vendor_id = 0x05C6, .product_id = 0x9026, #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbPidVid */ .version = 0x0100, .product_name = "Qualcomm HSUSB Device", .manufacturer_name = "Qualcomm Incorporated", .num_products = ARRAY_SIZE(usb_products), .products = usb_products, .num_functions = ARRAY_SIZE(usb_functions_all), .functions = usb_functions_all, .serial_number = "1234567890ABCDEF", }; static struct platform_device android_usb_device = { .name = "android_usb", .id = -1, .dev = { .platform_data = &android_usb_pdata, }, }; static int __init board_serialno_setup(char *serialno) { int i; char *src = serialno; /* create a fake MAC address from our serial number. * first byte is 0x02 to signify locally administered. */ rndis_pdata.ethaddr[0] = 0x02; for (i = 0; *src; i++) { /* XOR the USB serial across the remaining bytes */ rndis_pdata.ethaddr[i % (ETH_ALEN - 1) + 1] ^= *src++; } android_usb_pdata.serial_number = serialno; return 1; } __setup("androidboot.serialno=", board_serialno_setup); #endif static struct msm_gpio optnav_config_data[] = { { GPIO_CFG(OPTNAV_CHIP_SELECT, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "optnav_chip_select" }, }; static void __iomem *virtual_optnav; static int optnav_gpio_setup(void) { int rc = -ENODEV; rc = msm_gpios_request_enable(optnav_config_data, ARRAY_SIZE(optnav_config_data)); /* Configure the FPGA for GPIOs */ virtual_optnav = ioremap(FPGA_OPTNAV_GPIO_ADDR, 0x4); if (!virtual_optnav) { pr_err("%s:Could not ioremap region\n", __func__); return -ENOMEM; } /* * Configure the FPGA to set GPIO 19 as * normal, active(enabled), output(MSM to SURF) */ writew(0x311E, virtual_optnav); return rc; } static void optnav_gpio_release(void) { msm_gpios_disable_free(optnav_config_data, ARRAY_SIZE(optnav_config_data)); iounmap(virtual_optnav); } static struct vreg *vreg_gp7; static struct vreg *vreg_gp4; static struct vreg *vreg_gp9; static struct vreg *vreg_usb3_3; static int optnav_enable(void) { int rc; /* * Enable the VREGs L8(gp7), L10(gp4), L12(gp9), L6(usb) * for I2C communication with keyboard. */ vreg_gp7 = vreg_get(NULL, "gp7"); rc = vreg_set_level(vreg_gp7, 1800); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_gp7; } rc = vreg_enable(vreg_gp7); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_gp7; } vreg_gp4 = vreg_get(NULL, "gp4"); rc = vreg_set_level(vreg_gp4, 2600); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_gp4; } rc = vreg_enable(vreg_gp4); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_gp4; } vreg_gp9 = vreg_get(NULL, "gp9"); rc = vreg_set_level(vreg_gp9, 1800); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_gp9; } rc = vreg_enable(vreg_gp9); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_gp9; } vreg_usb3_3 = vreg_get(NULL, "usb"); rc = vreg_set_level(vreg_usb3_3, 3300); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_3_3; } rc = vreg_enable(vreg_usb3_3); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_3_3; } /* Enable the chip select GPIO */ gpio_set_value(OPTNAV_CHIP_SELECT, 1); gpio_set_value(OPTNAV_CHIP_SELECT, 0); return 0; fail_vreg_3_3: vreg_disable(vreg_gp9); fail_vreg_gp9: vreg_disable(vreg_gp4); fail_vreg_gp4: vreg_disable(vreg_gp7); fail_vreg_gp7: return rc; } static void optnav_disable(void) { vreg_disable(vreg_usb3_3); vreg_disable(vreg_gp9); vreg_disable(vreg_gp4); vreg_disable(vreg_gp7); gpio_set_value(OPTNAV_CHIP_SELECT, 1); } static struct ofn_atlab_platform_data optnav_data = { .gpio_setup = optnav_gpio_setup, .gpio_release = optnav_gpio_release, .optnav_on = optnav_enable, .optnav_off = optnav_disable, .rotate_xy = 0, .function1 = { .no_motion1_en = true, .touch_sensor_en = true, .ofn_en = true, .clock_select_khz = 1500, .cpi_selection = 1200, }, .function2 = { .invert_y = false, .invert_x = true, .swap_x_y = false, .hold_a_b_en = true, .motion_filter_en = true, }, }; /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static int hdmi_comm_power(int on, int show); static int hdmi_init_irq(void); static int hdmi_enable_5v(int on); static int hdmi_core_power(int on, int show); static int hdmi_cec_power(int on); static bool hdmi_check_hdcp_hw_support(void); static struct msm_hdmi_platform_data adv7520_hdmi_data = { .irq = MSM_GPIO_TO_INT(18), .comm_power = hdmi_comm_power, .init_irq = hdmi_init_irq, .enable_5v = hdmi_enable_5v, .core_power = hdmi_core_power, .cec_power = hdmi_cec_power, .check_hdcp_hw_support = hdmi_check_hdcp_hw_support, }; #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL static void hdmi_setup_int_power(int on) { gpio_tlmm_config(GPIO_HDMI_5V_EN, GPIO_CFG_ENABLE); if (on) gpio_set_value(GPIO_PIN(GPIO_HDMI_5V_EN), 1); else gpio_set_value(GPIO_PIN(GPIO_HDMI_5V_EN), 0); } static int hdmi_interrupt_detect(void) { return gpio_get_value(HDMI_INT); } static struct msm_hdmi_platform_data adv7525_hdmi_data = { .irq = MSM_GPIO_TO_INT(HDMI_INT), .intr_detect = hdmi_interrupt_detect, .setup_int_power = hdmi_setup_int_power, }; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ #ifdef CONFIG_BOSCH_BMA150 static struct vreg *vreg_gp6; static int sensors_ldo_enable(void) { int rc; /* * Enable the VREGs L8(gp7), L15(gp6) * for I2C communication with sensors. */ pr_info("sensors_ldo_enable called!!\n"); vreg_gp7 = vreg_get(NULL, "gp7"); if (IS_ERR(vreg_gp7)) { pr_err("%s: vreg_get gp7 failed\n", __func__); rc = PTR_ERR(vreg_gp7); goto fail_gp7_get; } rc = vreg_set_level(vreg_gp7, 1800); if (rc) { pr_err("%s: vreg_set_level gp7 failed\n", __func__); goto fail_gp7_level; } rc = vreg_enable(vreg_gp7); if (rc) { pr_err("%s: vreg_enable gp7 failed\n", __func__); goto fail_gp7_level; } vreg_gp6 = vreg_get(NULL, "gp6"); if (IS_ERR(vreg_gp6)) { pr_err("%s: vreg_get gp6 failed\n", __func__); rc = PTR_ERR(vreg_gp6); goto fail_gp6_get; } rc = vreg_set_level(vreg_gp6, 2800); if (rc) { pr_err("%s: vreg_set_level gp6 failed\n", __func__); goto fail_gp6_level; } rc = vreg_enable(vreg_gp6); if (rc) { pr_err("%s: vreg_enable gp6 failed\n", __func__); goto fail_gp6_level; } return 0; fail_gp6_level: vreg_put(vreg_gp6); fail_gp6_get: vreg_disable(vreg_gp7); fail_gp7_level: vreg_put(vreg_gp7); fail_gp7_get: return rc; } static void sensors_ldo_disable(void) { pr_info("sensors_ldo_disable called!!\n"); vreg_disable(vreg_gp6); vreg_put(vreg_gp6); vreg_disable(vreg_gp7); vreg_put(vreg_gp7); } static struct bma150_platform_data bma150_data = { .power_on = sensors_ldo_enable, .power_off = sensors_ldo_disable, }; static struct i2c_board_info bma150_board_info[] __initdata = { { I2C_BOARD_INFO("bma150", 0x38), .flags = I2C_CLIENT_WAKE, .irq = MSM_GPIO_TO_INT(BMA150_GPIO_INT), .platform_data = &bma150_data, }, }; #endif static struct i2c_board_info msm_i2c_board_info[] = { { I2C_BOARD_INFO("m33c01", OPTNAV_I2C_SLAVE_ADDR), .irq = MSM_GPIO_TO_INT(OPTNAV_IRQ), .platform_data = &optnav_data, }, /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL { I2C_BOARD_INFO("adv7520", ADV7520_I2C_ADDR), .platform_data = &adv7520_hdmi_data, }, #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL { I2C_BOARD_INFO("adv7525", 0x72 >> 1), .platform_data = &adv7525_hdmi_data, }, #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ //Div2-SW2-BSP-Touch, Vincent + #ifdef CONFIG_FIH_TOUCHSCREEN_INNOLUX { I2C_BOARD_INFO("innolux_ts", 0x09), }, #endif #ifdef CONFIG_FIH_TOUCHSCREEN_BU21018MWV { I2C_BOARD_INFO("bu21018mwv", 0x5C), }, #endif #ifdef CONFIG_FIH_TOUCHSCREEN_BI041P { I2C_BOARD_INFO("bi041p", 0x08), .irq = MSM_GPIO_TO_INT(42), }, #endif //Div2-SW2-BSP-Touch, Vincent - //Div2-D5-Peripheral-FG-4H8TouchPorting-00+[ #ifdef CONFIG_FIH_TOUCHSCREEN_ATMEL_MXT165 { I2C_BOARD_INFO("atmel_mxt165", 0x4A), }, #endif //Div2-D5-Peripheral-FG-4H8TouchPorting-00+] #ifdef CONFIG_FIH_AAT1272 { I2C_BOARD_INFO("aat1272", 0x37), }, #endif //Div2D5-OwenHuang-BSP4040_Sensors_Porting-00+{ #ifdef CONFIG_INPUT_YAS529 { I2C_BOARD_INFO("yas529", 0x2E), //yamaha yas529 }, #endif #ifdef CONFIG_INPUT_BMA150 { I2C_BOARD_INFO("bma150", 0x38), //bosch bma150/bosch bma023 }, #endif //Div2D5-OwenHuang-SF8_Sensor_Porting-00+{ #ifdef CONFIG_SENSORS_CM3623 { #ifdef CONFIG_SENSORS_CM3623_IS_AD I2C_BOARD_INFO("cm3623", 0x49), #else I2C_BOARD_INFO("cm3623", 0x11), #endif }, #endif //Div2D5-OwenHuang-SF8_Sensor_Porting-00+} #ifdef CONFIG_SENSORS_LTR502ALS { #ifdef CONFIG_FIH_PROJECT_SF4V5 I2C_BOARD_INFO("ltr502als", 0x1c), .irq = MSM_GPIO_TO_INT(20), #else I2C_BOARD_INFO("ltr502als", 0x1d), .irq = MSM_GPIO_TO_INT(49), #endif }, #endif //Div2D5-OwenHuang-BSP4040_Sensors_Porting-00+} }; static struct i2c_board_info msm_marimba_board_info[] = { { I2C_BOARD_INFO("marimba", 0xc), .platform_data = &marimba_pdata, } }; #ifdef CONFIG_USB_FUNCTION static struct usb_function_map usb_functions_map[] = { {"diag", 0}, {"adb", 1}, {"modem", 2}, {"nmea", 3}, {"mass_storage", 4}, {"ethernet", 5}, }; static struct usb_composition usb_func_composition[] = { { .product_id = 0x9012, .functions = 0x5, /* 0101 */ }, { .product_id = 0x9013, .functions = 0x15, /* 10101 */ }, { .product_id = 0x9014, .functions = 0x30, /* 110000 */ }, { .product_id = 0x9016, .functions = 0xD, /* 01101 */ }, { .product_id = 0x9017, .functions = 0x1D, /* 11101 */ }, { .product_id = 0xF000, .functions = 0x10, /* 10000 */ }, { .product_id = 0xF009, .functions = 0x20, /* 100000 */ }, { .product_id = 0x9018, .functions = 0x1F, /* 011111 */ }, }; static struct msm_hsusb_platform_data msm_hsusb_pdata = { .version = 0x0100, .phy_info = USB_PHY_INTEGRATED | USB_PHY_MODEL_45NM, .vendor_id = 0x5c6, .product_name = "Qualcomm HSUSB Device", .serial_number = "1234567890ABCDEF", .manufacturer_name = "Qualcomm Incorporated", .compositions = usb_func_composition, .num_compositions = ARRAY_SIZE(usb_func_composition), .function_map = usb_functions_map, .num_functions = ARRAY_SIZE(usb_functions_map), .core_clk = 1, }; #endif static struct msm_handset_platform_data hs_platform_data = { .hs_name = "7k_handset", //SW2-5-1-MP-Force_Ramdump-00*[ // .pwr_key_delay_ms = 500, /* 0 will disable end key */ .pwr_key_delay_ms = 0, /* 0 will disable end key */ //SW2-5-1-MP-Force_Ramdump-00*] }; static struct platform_device hs_device = { .name = "msm-handset", .id = -1, .dev = { .platform_data = &hs_platform_data, }, }; static struct msm_pm_platform_data msm_pm_data[MSM_PM_SLEEP_MODE_NR] = { [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].supported = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].suspend_enabled = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].idle_enabled = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].latency = 8594, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE].residency = 23740, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].supported = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].suspend_enabled = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].idle_enabled = 1, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].latency = 4594, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_NO_XO_SHUTDOWN].residency = 23740, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].supported = 1, #ifdef CONFIG_MSM_STANDALONE_POWER_COLLAPSE [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].suspend_enabled = 0, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].idle_enabled = 1, #else /*CONFIG_MSM_STANDALONE_POWER_COLLAPSE*/ [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].suspend_enabled = 0, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].idle_enabled = 0, #endif /*CONFIG_MSM_STANDALONE_POWER_COLLAPSE*/ [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].latency = 500, [MSM_PM_SLEEP_MODE_POWER_COLLAPSE_STANDALONE].residency = 6000, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].supported = 1, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].suspend_enabled = 1, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].idle_enabled = 0, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].latency = 443, [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].residency = 1098, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].supported = 1, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].suspend_enabled = 1, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].idle_enabled = 1, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].latency = 2, [MSM_PM_SLEEP_MODE_WAIT_FOR_INTERRUPT].residency = 0, }; static struct resource qsd_spi_resources[] = { { .name = "spi_irq_in", .start = INT_SPI_INPUT, .end = INT_SPI_INPUT, .flags = IORESOURCE_IRQ, }, { .name = "spi_irq_out", .start = INT_SPI_OUTPUT, .end = INT_SPI_OUTPUT, .flags = IORESOURCE_IRQ, }, { .name = "spi_irq_err", .start = INT_SPI_ERROR, .end = INT_SPI_ERROR, .flags = IORESOURCE_IRQ, }, { .name = "spi_base", .start = 0xA8000000, .end = 0xA8000000 + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .name = "spidm_channels", .flags = IORESOURCE_DMA, }, { .name = "spidm_crci", .flags = IORESOURCE_DMA, }, }; #define AMDH0_BASE_PHYS 0xAC200000 #define ADMH0_GP_CTL (ct_adm_base + 0x3D8) static int msm_qsd_spi_dma_config(void) { void __iomem *ct_adm_base = 0; u32 spi_mux = 0; int ret = 0; ct_adm_base = ioremap(AMDH0_BASE_PHYS, PAGE_SIZE); if (!ct_adm_base) { pr_err("%s: Could not remap %x\n", __func__, AMDH0_BASE_PHYS); return -ENOMEM; } spi_mux = (ioread32(ADMH0_GP_CTL) & (0x3 << 12)) >> 12; qsd_spi_resources[4].start = DMOV_USB_CHAN; qsd_spi_resources[4].end = DMOV_TSIF_CHAN; switch (spi_mux) { case (1): qsd_spi_resources[5].start = DMOV_HSUART1_RX_CRCI; qsd_spi_resources[5].end = DMOV_HSUART1_TX_CRCI; break; case (2): qsd_spi_resources[5].start = DMOV_HSUART2_RX_CRCI; qsd_spi_resources[5].end = DMOV_HSUART2_TX_CRCI; break; case (3): qsd_spi_resources[5].start = DMOV_CE_OUT_CRCI; qsd_spi_resources[5].end = DMOV_CE_IN_CRCI; break; default: ret = -ENOENT; } iounmap(ct_adm_base); return ret; } static struct platform_device qsd_device_spi = { .name = "spi_qsd", .id = 0, .num_resources = ARRAY_SIZE(qsd_spi_resources), .resource = qsd_spi_resources, }; #ifdef CONFIG_SPI_QSD static struct spi_board_info lcdc_sharp_spi_board_info[] __initdata = { { .modalias = "lcdc_sharp_ls038y7dx01", .mode = SPI_MODE_1, .bus_num = 0, .chip_select = 0, .max_speed_hz = 26331429, } }; static struct spi_board_info lcdc_toshiba_spi_board_info[] __initdata = { { .modalias = "lcdc_toshiba_ltm030dd40", .mode = SPI_MODE_3|SPI_CS_HIGH, .bus_num = 0, .chip_select = 0, .max_speed_hz = 9963243, } }; #endif static struct msm_gpio qsd_spi_gpio_config_data[] = { { GPIO_CFG(45, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_clk" }, { GPIO_CFG(46, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_cs0" }, { GPIO_CFG(47, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), "spi_mosi" }, { GPIO_CFG(48, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_miso" }, }; static int msm_qsd_spi_gpio_config(void) { return msm_gpios_request_enable(qsd_spi_gpio_config_data, ARRAY_SIZE(qsd_spi_gpio_config_data)); } static void msm_qsd_spi_gpio_release(void) { msm_gpios_disable_free(qsd_spi_gpio_config_data, ARRAY_SIZE(qsd_spi_gpio_config_data)); } static struct msm_spi_platform_data qsd_spi_pdata = { .max_clock_speed = 26331429, .clk_name = "spi_clk", .pclk_name = "spi_pclk", .gpio_config = msm_qsd_spi_gpio_config, .gpio_release = msm_qsd_spi_gpio_release, .dma_config = msm_qsd_spi_dma_config, }; static void __init msm_qsd_spi_init(void) { qsd_device_spi.dev.platform_data = &qsd_spi_pdata; } #ifdef CONFIG_USB_EHCI_MSM static void msm_hsusb_vbus_power(unsigned phy_info, int on) { int rc; static int vbus_is_on; struct pm8058_gpio usb_vbus = { .direction = PM_GPIO_DIR_OUT, .pull = PM_GPIO_PULL_NO, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .vin_sel = 2, .out_strength = PM_GPIO_STRENGTH_MED, .function = PM_GPIO_FUNC_NORMAL, .inv_int_pol = 0, }; /* If VBUS is already on (or off), do nothing. */ if (unlikely(on == vbus_is_on)) return; if (on) { rc = pm8058_gpio_config(36, &usb_vbus); if (rc) { pr_err("%s PMIC GPIO 36 write failed\n", __func__); return; } } else { gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(36), 0); } vbus_is_on = on; } static struct msm_usb_host_platform_data msm_usb_host_pdata = { .phy_info = (USB_PHY_INTEGRATED | USB_PHY_MODEL_45NM), .vbus_power = msm_hsusb_vbus_power, .power_budget = 180, }; #endif #ifdef CONFIG_USB_MSM_OTG_72K static int hsusb_rpc_connect(int connect) { if (connect) return msm_hsusb_rpc_connect(); else return msm_hsusb_rpc_close(); } #endif #ifdef CONFIG_USB_MSM_OTG_72K static struct vreg *vreg_3p3; static int msm_hsusb_ldo_init(int init) { uint32_t version = 0; int def_vol = 3400; version = socinfo_get_version(); if (SOCINFO_VERSION_MAJOR(version) >= 2 && SOCINFO_VERSION_MINOR(version) >= 1) { def_vol = 3075; pr_debug("%s: default voltage:%d\n", __func__, def_vol); } if (init) { vreg_3p3 = vreg_get(NULL, "usb"); if (IS_ERR(vreg_3p3)) return PTR_ERR(vreg_3p3); vreg_set_level(vreg_3p3, def_vol); } else vreg_put(vreg_3p3); return 0; } static int msm_hsusb_ldo_enable(int enable) { static int ldo_status; if (!vreg_3p3 || IS_ERR(vreg_3p3)) return -ENODEV; if (ldo_status == enable) return 0; ldo_status = enable; if (enable) return vreg_enable(vreg_3p3); return vreg_disable(vreg_3p3); } static int msm_hsusb_ldo_set_voltage(int mV) { static int cur_voltage = 3400; if (!vreg_3p3 || IS_ERR(vreg_3p3)) return -ENODEV; if (cur_voltage == mV) return 0; cur_voltage = mV; pr_debug("%s: (%d)\n", __func__, mV); return vreg_set_level(vreg_3p3, mV); } #endif #ifndef CONFIG_USB_EHCI_MSM static int msm_hsusb_pmic_notif_init(void (*callback)(int online), int init); #endif static struct msm_otg_platform_data msm_otg_pdata = { .rpc_connect = hsusb_rpc_connect, #ifndef CONFIG_USB_EHCI_MSM .pmic_vbus_notif_init = msm_hsusb_pmic_notif_init, #else .vbus_power = msm_hsusb_vbus_power, #endif .core_clk = 1, .pemp_level = PRE_EMPHASIS_WITH_20_PERCENT, .cdr_autoreset = CDR_AUTO_RESET_DISABLE, .drv_ampl = HS_DRV_AMPLITUDE_DEFAULT, .se1_gating = SE1_GATING_DISABLE, .chg_vbus_draw = hsusb_chg_vbus_draw, .chg_connected = hsusb_chg_connected, .chg_init = hsusb_chg_init, .ldo_enable = msm_hsusb_ldo_enable, .ldo_init = msm_hsusb_ldo_init, .ldo_set_voltage = msm_hsusb_ldo_set_voltage, }; #ifdef CONFIG_USB_GADGET static struct msm_hsusb_gadget_platform_data msm_gadget_pdata = { .is_phy_status_timer_on = 1, }; #endif #ifndef CONFIG_USB_EHCI_MSM typedef void (*notify_vbus_state) (int); notify_vbus_state notify_vbus_state_func_ptr; int vbus_on_irq; static irqreturn_t pmic_vbus_on_irq(int irq, void *data) { pr_info("%s: vbus notification from pmic\n", __func__); (*notify_vbus_state_func_ptr) (1); return IRQ_HANDLED; } static int msm_hsusb_pmic_notif_init(void (*callback)(int online), int init) { int ret; if (init) { if (!callback) return -ENODEV; notify_vbus_state_func_ptr = callback; vbus_on_irq = platform_get_irq_byname(&msm_device_otg, "vbus_on"); if (vbus_on_irq <= 0) { pr_err("%s: unable to get vbus on irq\n", __func__); return -ENODEV; } ret = request_any_context_irq(vbus_on_irq, pmic_vbus_on_irq, IRQF_TRIGGER_RISING, "msm_otg_vbus_on", NULL); if (ret < 0) { pr_info("%s: request_irq for vbus_on" "interrupt failed\n", __func__); return ret; } msm_otg_pdata.pmic_vbus_irq = vbus_on_irq; return 0; } else { free_irq(vbus_on_irq, 0); notify_vbus_state_func_ptr = NULL; return 0; } } #endif static struct android_pmem_platform_data android_pmem_pdata = { .name = "pmem", .allocator_type = PMEM_ALLOCATORTYPE_ALLORNOTHING, .cached = 1, }; static struct platform_device android_pmem_device = { .name = "android_pmem", .id = 0, .dev = { .platform_data = &android_pmem_pdata }, }; //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 #ifndef CONFIG_SPI_QSD static int lcdc_gpio_array_num[] = { 45, /* spi_clk */ 46, /* spi_cs */ 47, /* spi_mosi */ 48, /* spi_miso */ }; static struct msm_gpio lcdc_gpio_config_data[] = { { GPIO_CFG(45, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_clk" }, { GPIO_CFG(46, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_cs0" }, { GPIO_CFG(47, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_mosi" }, { GPIO_CFG(48, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_miso" }, }; static void lcdc_config_gpios(int enable) { if (enable) { msm_gpios_request_enable(lcdc_gpio_config_data, ARRAY_SIZE( lcdc_gpio_config_data)); } else msm_gpios_disable_free(lcdc_gpio_config_data, ARRAY_SIZE( lcdc_gpio_config_data)); } #endif static struct msm_panel_common_pdata lcdc_sharp_panel_data = { #ifndef CONFIG_SPI_QSD .panel_config_gpio = lcdc_config_gpios, .gpio_num = lcdc_gpio_array_num, #endif .gpio = 2, /* LPG PMIC_GPIO26 channel number */ }; static struct platform_device lcdc_sharp_panel_device = { .name = "lcdc_sharp_wvga", .id = 0, .dev = { .platform_data = &lcdc_sharp_panel_data, } }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00- /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static struct msm_gpio dtv_panel_irq_gpios[] = { { GPIO_CFG(18, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "hdmi_int" }, }; #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL static struct msm_gpio hdmi_panel_gpios[] = { { GPIO_CFG(34, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_4MA), "hdmi_5v_en" }, { GPIO_CFG(HDMI_INT, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "hdmi_int" }, }; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ #if defined(CONFIG_FB_MSM_HDMI_ADV7525_PANEL) || defined(CONFIG_FB_MSM_HDMI_ADV7520_PANEL) static struct msm_gpio dtv_panel_gpios[] = { { GPIO_CFG(120, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "wca_mclk" }, { GPIO_CFG(121, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "wca_sd0" }, { GPIO_CFG(122, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "wca_sd1" }, { GPIO_CFG(123, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "wca_sd2" }, { GPIO_CFG(124, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA), "dtv_pclk" }, { GPIO_CFG(125, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_en" }, { GPIO_CFG(126, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_vsync" }, { GPIO_CFG(127, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_hsync" }, { GPIO_CFG(128, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data0" }, { GPIO_CFG(129, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data1" }, { GPIO_CFG(130, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data2" }, { GPIO_CFG(131, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data3" }, { GPIO_CFG(132, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data4" }, { GPIO_CFG(160, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data5" }, { GPIO_CFG(161, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data6" }, { GPIO_CFG(162, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data7" }, { GPIO_CFG(163, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data8" }, { GPIO_CFG(164, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_data9" }, { GPIO_CFG(165, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat10" }, { GPIO_CFG(166, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat11" }, { GPIO_CFG(167, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat12" }, { GPIO_CFG(168, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat13" }, { GPIO_CFG(169, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat14" }, { GPIO_CFG(170, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat15" }, { GPIO_CFG(171, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat16" }, { GPIO_CFG(172, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat17" }, { GPIO_CFG(173, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat18" }, { GPIO_CFG(174, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat19" }, { GPIO_CFG(175, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat20" }, { GPIO_CFG(176, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat21" }, { GPIO_CFG(177, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat22" }, { GPIO_CFG(178, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_4MA), "dtv_dat23" }, }; #endif #ifdef HDMI_RESET static unsigned dtv_reset_gpio = GPIO_CFG(37, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static int gpio_set(const char *label, const char *name, int level, int on) { struct vreg *vreg = vreg_get(NULL, label); int rc; if (IS_ERR(vreg)) { rc = PTR_ERR(vreg); pr_err("%s: vreg %s get failed (%d)\n", __func__, name, rc); return rc; } rc = vreg_set_level(vreg, level); if (rc) { pr_err("%s: vreg %s set level failed (%d)\n", __func__, name, rc); return rc; } if (on) rc = vreg_enable(vreg); else rc = vreg_disable(vreg); if (rc) pr_err("%s: vreg %s enable failed (%d)\n", __func__, name, rc); return rc; } #endif ///#if defined(CONFIG_FB_MSM_HDMI_ADV7520_PANEL) || defined(CONFIG_BOSCH_BMA150) /* there is an i2c address conflict between adv7520 and bma150 sensor after * power up on fluid. As a solution, the default address of adv7520's packet * memory is changed as soon as possible */ #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static int __init fluid_i2c_address_fixup(void) { unsigned char wBuff[16]; unsigned char rBuff[16]; struct i2c_msg msgs[3]; int res; int rc = -EINVAL; struct vreg *vreg_ldo8; struct i2c_adapter *adapter; if (machine_is_msm7x30_fluid()) { adapter = i2c_get_adapter(0); if (!adapter) { pr_err("%s: invalid i2c adapter\n", __func__); return PTR_ERR(adapter); } /* turn on LDO8 */ vreg_ldo8 = vreg_get(NULL, "gp7"); if (!vreg_ldo8) { pr_err("%s: VREG L8 get failed\n", __func__); goto adapter_put; } rc = vreg_set_level(vreg_ldo8, 1800); if (rc) { pr_err("%s: VREG L8 set failed\n", __func__); goto ldo8_put; } rc = vreg_enable(vreg_ldo8); if (rc) { pr_err("%s: VREG L8 enable failed\n", __func__); goto ldo8_put; } /* change packet memory address to 0x74 */ wBuff[0] = 0x45; wBuff[1] = 0x74; msgs[0].addr = ADV7520_I2C_ADDR; msgs[0].flags = 0; msgs[0].buf = (unsigned char *) wBuff; msgs[0].len = 2; res = i2c_transfer(adapter, msgs, 1); if (res != 1) { pr_err("%s: error writing adv7520\n", __func__); goto ldo8_disable; } /* powerdown adv7520 using bit 6 */ /* i2c read first */ wBuff[0] = 0x41; msgs[0].addr = ADV7520_I2C_ADDR; msgs[0].flags = 0; msgs[0].buf = (unsigned char *) wBuff; msgs[0].len = 1; msgs[1].addr = ADV7520_I2C_ADDR; msgs[1].flags = I2C_M_RD; msgs[1].buf = rBuff; msgs[1].len = 1; res = i2c_transfer(adapter, msgs, 2); if (res != 2) { pr_err("%s: error reading adv7520\n", __func__); goto ldo8_disable; } /* i2c write back */ wBuff[0] = 0x41; wBuff[1] = rBuff[0] | 0x40; msgs[0].addr = ADV7520_I2C_ADDR; msgs[0].flags = 0; msgs[0].buf = (unsigned char *) wBuff; msgs[0].len = 2; res = i2c_transfer(adapter, msgs, 1); if (res != 1) { pr_err("%s: error writing adv7520\n", __func__); goto ldo8_disable; } /* for successful fixup, we release the i2c adapter */ /* but leave ldo8 on so that the adv7520 is not repowered */ i2c_put_adapter(adapter); pr_info("%s: fluid i2c address conflict resolved\n", __func__); } return 0; ldo8_disable: vreg_disable(vreg_ldo8); ldo8_put: vreg_put(vreg_ldo8); adapter_put: i2c_put_adapter(adapter); return rc; } subsys_initcall_sync(fluid_i2c_address_fixup); #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7520_PANEL static int hdmi_comm_power(int on, int show) { int rc = gpio_set("gp7", "LDO8", 1800, on); if (rc) { pr_warning("hdmi_comm_power: LDO8 gpio failed: rc=%d\n", rc); return rc; } rc = gpio_set("gp4", "LDO10", 2600, on); if (rc) pr_warning("hdmi_comm_power: LDO10 gpio failed: rc=%d\n", rc); if (show) pr_info("%s: i2c comm: %d <LDO8+LDO10>\n", __func__, on); return rc; } static int hdmi_init_irq(void) { int rc = msm_gpios_enable(dtv_panel_irq_gpios, ARRAY_SIZE(dtv_panel_irq_gpios)); if (rc < 0) { pr_err("%s: gpio enable failed: %d\n", __func__, rc); return rc; } pr_info("%s\n", __func__); return 0; } static int hdmi_enable_5v(int on) { int pmic_gpio_hdmi_5v_en ; if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa() || machine_is_msm7x30_fluid()) pmic_gpio_hdmi_5v_en = PMIC_GPIO_HDMI_5V_EN_V2 ; else pmic_gpio_hdmi_5v_en = PMIC_GPIO_HDMI_5V_EN_V3 ; pr_info("%s: %d\n", __func__, on); if (on) { int rc; rc = gpio_request(PM8058_GPIO_PM_TO_SYS(pmic_gpio_hdmi_5v_en), "hdmi_5V_en"); if (rc) { pr_err("%s PMIC_GPIO_HDMI_5V_EN gpio_request failed\n", __func__); return rc; } gpio_set_value_cansleep( PM8058_GPIO_PM_TO_SYS(pmic_gpio_hdmi_5v_en), 1); } else { gpio_set_value_cansleep( PM8058_GPIO_PM_TO_SYS(pmic_gpio_hdmi_5v_en), 0); gpio_free(PM8058_GPIO_PM_TO_SYS(pmic_gpio_hdmi_5v_en)); } return 0; } static int hdmi_core_power(int on, int show) { if (show) pr_info("%s: %d <LDO8>\n", __func__, on); return gpio_set("gp7", "LDO8", 1800, on); } static int hdmi_cec_power(int on) { pr_info("%s: %d <LDO17>\n", __func__, on); return gpio_set("gp11", "LDO17", 2600, on); } static bool hdmi_check_hdcp_hw_support(void) { if (machine_is_msm7x30_fluid()) return false; else return true; } static int dtv_panel_power(int on) { int flag_on = !!on; static int dtv_power_save_on; int rc; if (dtv_power_save_on == flag_on) return 0; dtv_power_save_on = flag_on; pr_info("%s: %d\n", __func__, on); #ifdef HDMI_RESET if (on) { /* reset Toshiba WeGA chip -- toggle reset pin -- gpio_180 */ rc = gpio_tlmm_config(dtv_reset_gpio, GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, dtv_reset_gpio, rc); return rc; } /* bring reset line low to hold reset*/ gpio_set_value(37, 0); } #endif if (on) { rc = msm_gpios_enable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); return rc; } } else { rc = msm_gpios_disable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio disable failed: %d\n", __func__, rc); return rc; } } mdelay(5); /* ensure power is stable */ #ifdef HDMI_RESET if (on) { gpio_set_value(37, 1); /* bring reset line high */ mdelay(10); /* 10 msec before IO can be accessed */ } #endif return rc; } #endif /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL static int dtv_panel_power(int on) { int flag_on = !!on; static int dtv_power_save_on; int rc; struct vreg *vreg_ldo11; if (dtv_power_save_on == flag_on) return 0; dtv_power_save_on = flag_on; pr_info("%s: %d >>\n", __func__, on); if(!on){ rc = msm_gpios_disable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio disable failed: %d\n", __func__, rc); return rc; } printk("dtv_panel_power always turn on\n"); return 0; }else if(hdmi_init_done){ rc = msm_gpios_enable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); return rc; } return 0; } if (on) { rc = msm_gpios_enable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); return rc; } rc = msm_gpios_enable(hdmi_panel_gpios, ARRAY_SIZE(hdmi_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); return rc; } } else { rc = msm_gpios_disable(dtv_panel_gpios, ARRAY_SIZE(dtv_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio disable failed: %d\n", __func__, rc); return rc; } } /* VDDIO 1.8V -- LDO11*/ vreg_ldo11 = vreg_get(NULL, "gp2"); if (IS_ERR(vreg_ldo11)) { rc = PTR_ERR(vreg_ldo11); printk("%s: gp2 vreg get failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo11, 1800); if (rc) { printk("%s: vreg LDO11 set level failed (%d)\n", __func__, rc); return rc; } if (on) rc = vreg_enable(vreg_ldo11); else rc = vreg_disable(vreg_ldo11); if (rc) { printk("%s: LDO11 vreg enable failed (%d)\n", __func__, rc); return rc; } mdelay(5); gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_HDMI_18V_EN), on); gpio_tlmm_config(GPIO_HDMI_5V_EN, GPIO_CFG_ENABLE); if (on) gpio_set_value(GPIO_PIN(GPIO_HDMI_5V_EN), 1); else { printk("dtv_panel_power 5V always turn on\n"); ///gpio_set_value(GPIO_PIN(GPIO_HDMI_5V_EN), 0); } mdelay(5); /* ensure power is stable */ pr_info("%s: %d <<\n", __func__, on); hdmi_init_done = true; return rc; } #endif #if defined(CONFIG_FB_MSM_HDMI_ADV7525_PANEL) || defined(CONFIG_FB_MSM_HDMI_ADV7520_PANEL) static struct lcdc_platform_data dtv_pdata = { .lcdc_power_save = dtv_panel_power, }; #endif #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL static struct platform_device hdmi_adv7525_panel_device = { .name = "adv7525", .id = 0, }; #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ static struct msm_serial_hs_platform_data msm_uart_dm1_pdata = { .inject_rx_on_wakeup = 1, .rx_to_inject = 0xFD, }; static struct resource msm_fb_resources[] = { { .flags = IORESOURCE_DMA, } }; static int msm_fb_detect_panel(const char *name) { if (machine_is_msm7x30_fluid()) { if (!strcmp(name, "lcdc_sharp_wvga_pt")) return 0; } else { if (!strncmp(name, "mddi_toshiba_wvga_pt", 20)) return -EPERM; else if (!strncmp(name, "lcdc_toshiba_wvga_pt", 20)) return 0; else if (!strcmp(name, "mddi_orise")) return -EPERM; else if (!strcmp(name, "mddi_quickvx")) return -EPERM; } return -ENODEV; } static struct msm_fb_platform_data msm_fb_pdata = { .detect_client = msm_fb_detect_panel, .mddi_prescan = 1, }; static struct platform_device msm_fb_device = { .name = "msm_fb", .id = 0, .num_resources = ARRAY_SIZE(msm_fb_resources), .resource = msm_fb_resources, .dev = { .platform_data = &msm_fb_pdata, } }; static struct platform_device msm_migrate_pages_device = { .name = "msm_migrate_pages", .id = -1, }; static struct android_pmem_platform_data android_pmem_kernel_ebi1_pdata = { .name = PMEM_KERNEL_EBI1_DATA_NAME, /* if no allocator_type, defaults to PMEM_ALLOCATORTYPE_BITMAP, * the only valid choice at this time. The board structure is * set to all zeros by the C runtime initialization and that is now * the enum value of PMEM_ALLOCATORTYPE_BITMAP, now forced to 0 in * include/linux/android_pmem.h. */ .cached = 0, }; static struct android_pmem_platform_data android_pmem_adsp_pdata = { .name = "pmem_adsp", .allocator_type = PMEM_ALLOCATORTYPE_BITMAP, .cached = 0, }; static struct android_pmem_platform_data android_pmem_audio_pdata = { .name = "pmem_audio", .allocator_type = PMEM_ALLOCATORTYPE_BITMAP, .cached = 0, }; static struct platform_device android_pmem_kernel_ebi1_device = { .name = "android_pmem", .id = 1, .dev = { .platform_data = &android_pmem_kernel_ebi1_pdata }, }; static struct platform_device android_pmem_adsp_device = { .name = "android_pmem", .id = 2, .dev = { .platform_data = &android_pmem_adsp_pdata }, }; static struct platform_device android_pmem_audio_device = { .name = "android_pmem", .id = 4, .dev = { .platform_data = &android_pmem_audio_pdata }, }; static struct resource kgsl_3d0_resources[] = { { .name = KGSL_3D0_REG_MEMORY, .start = 0xA3500000, /* 3D GRP address */ .end = 0xA351ffff, .flags = IORESOURCE_MEM, }, { .name = KGSL_3D0_IRQ, .start = INT_GRP_3D, .end = INT_GRP_3D, .flags = IORESOURCE_IRQ, }, }; static struct kgsl_device_platform_data kgsl_3d0_pdata = { .pwrlevel = { { .gpu_freq = 245760000, .bus_freq = 192000000, }, { .gpu_freq = 192000000, .bus_freq = 153000000, }, { .gpu_freq = 192000000, .bus_freq = 0, }, }, .init_level = 0, .num_levels = 3, .set_grp_async = set_grp3d_async, .idle_timeout = HZ/20, .nap_allowed = true, .clk = { .clk = "grp_clk", .pclk = "grp_pclk", }, .imem_clk_name = { .clk = "imem_clk", .pclk = NULL, }, }; static struct platform_device msm_kgsl_3d0 = { .name = "kgsl-3d0", .id = 0, .num_resources = ARRAY_SIZE(kgsl_3d0_resources), .resource = kgsl_3d0_resources, .dev = { .platform_data = &kgsl_3d0_pdata, }, }; #ifdef CONFIG_MSM_KGSL_2D static struct resource kgsl_2d0_resources[] = { { .name = KGSL_2D0_REG_MEMORY, .start = 0xA3900000, /* Z180 base address */ .end = 0xA3900FFF, .flags = IORESOURCE_MEM, }, { .name = KGSL_2D0_IRQ, .start = INT_GRP_2D, .end = INT_GRP_2D, .flags = IORESOURCE_IRQ, }, }; static struct kgsl_device_platform_data kgsl_2d0_pdata = { .pwrlevel = { { .gpu_freq = 0, .bus_freq = 192000000, }, }, .init_level = 0, .num_levels = 1, /* HW workaround, run Z180 SYNC @ 192 MHZ */ .set_grp_async = NULL, .idle_timeout = HZ/10, .nap_allowed = true, .clk = { .clk = "grp_2d_clk", .pclk = "grp_2d_pclk", }, }; static struct platform_device msm_kgsl_2d0 = { .name = "kgsl-2d0", .id = 0, .num_resources = ARRAY_SIZE(kgsl_2d0_resources), .resource = kgsl_2d0_resources, .dev = { .platform_data = &kgsl_2d0_pdata, }, }; #endif //SW2-D5-OwenHung-SF4V5/SF4Y6 keypad backlight+ #if defined(CONFIG_FIH_PROJECT_SF4V5) || defined(CONFIG_FIH_PROJECT_SF4Y6) || defined(CONFIG_FIH_PROJECT_SF8) static struct platform_device msm_device_pmic_leds = { .name = "pmic-leds", .id = -1, }; #endif //SW2-D5-OwenHung-SF4V5/SF4Y6 keypad backlight- #if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \ defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE) || \ defined(CONFIG_CRYPTO_DEV_QCEDEV) || \ defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE) #define QCE_SIZE 0x10000 #define QCE_0_BASE 0xA8400000 #define QCE_HW_KEY_SUPPORT 1 #define QCE_SHARE_CE_RESOURCE 0 #define QCE_CE_SHARED 0 static struct resource qce_resources[] = { [0] = { .start = QCE_0_BASE, .end = QCE_0_BASE + QCE_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .name = "crypto_channels", .start = DMOV_CE_IN_CHAN, .end = DMOV_CE_OUT_CHAN, .flags = IORESOURCE_DMA, }, [2] = { .name = "crypto_crci_in", .start = DMOV_CE_IN_CRCI, .end = DMOV_CE_IN_CRCI, .flags = IORESOURCE_DMA, }, [3] = { .name = "crypto_crci_out", .start = DMOV_CE_OUT_CRCI, .end = DMOV_CE_OUT_CRCI, .flags = IORESOURCE_DMA, }, [4] = { .name = "crypto_crci_hash", .start = DMOV_CE_HASH_CRCI, .end = DMOV_CE_HASH_CRCI, .flags = IORESOURCE_DMA, }, }; #endif #if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \ defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE) static struct msm_ce_hw_support qcrypto_ce_hw_suppport = { .ce_shared = QCE_CE_SHARED, .shared_ce_resource = QCE_SHARE_CE_RESOURCE, .hw_key_support = QCE_HW_KEY_SUPPORT, }; static struct platform_device qcrypto_device = { .name = "qcrypto", .id = 0, .num_resources = ARRAY_SIZE(qce_resources), .resource = qce_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &qcrypto_ce_hw_suppport, }, }; #endif #if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \ defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE) static struct msm_ce_hw_support qcedev_ce_hw_suppport = { .ce_shared = QCE_CE_SHARED, .shared_ce_resource = QCE_SHARE_CE_RESOURCE, .hw_key_support = QCE_HW_KEY_SUPPORT, }; static struct platform_device qcedev_device = { .name = "qce", .id = 0, .num_resources = ARRAY_SIZE(qce_resources), .resource = qce_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &qcedev_ce_hw_suppport, }, }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 static int mddi_toshiba_pmic_bl(int level) { int ret = -EPERM; // DIV2-SW2-BSP-FBx-LEDS+ #ifndef CONFIG_LEDS_FIH_FBX_PWM ret = pmic_set_led_intensity(LED_LCD, level); #endif // DIV2-SW2-BSP-FBx-LEDS- if (ret) printk(KERN_WARNING "%s: can't set lcd backlight!\n", __func__); return ret; } static struct msm_panel_common_pdata mddi_toshiba_pdata = { .pmic_backlight = mddi_toshiba_pmic_bl, }; static struct platform_device mddi_toshiba_device = { .name = "mddi_toshiba", .id = 0, .dev = { .platform_data = &mddi_toshiba_pdata, } }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00- #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static unsigned lcdc_reset_gpio = GPIO_CFG(35, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA); static int display_common_power(int on) { int rc = 0, flag_on = !!on; static int display_common_power_save_on = 0; struct vreg *vreg_ldo11, *vreg_ldo15 = NULL; printk(KERN_INFO "[DISPLAY] %s(%d): current power status = %d.\n", __func__, on, display_common_power_save_on); if (display_common_power_save_on == flag_on) return 0; display_common_power_save_on = flag_on; if (on) { /* reset LCM -- toggle reset pin -- gpio_35 */ rc = gpio_tlmm_config(lcdc_reset_gpio, GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, lcdc_reset_gpio, rc); return rc; } gpio_set_value(35, 0); /* bring reset line low to hold reset*/ mdelay(1); /* wait 1 ms */ } else { /* Hard Reset, Reset Pin from high to low */ gpio_set_value(35, 0); } /* LCM power -- has 2 power source */ /* VDDIO 1.8V -- LDO11*/ vreg_ldo11 = vreg_get(NULL, "gp2"); if (IS_ERR(vreg_ldo11)) { pr_err("%s: gp2 vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_ldo11)); return rc; } /* VDC 3.05V -- LDO15 */ vreg_ldo15 = vreg_get(NULL, "gp6"); if (IS_ERR(vreg_ldo15)) { rc = PTR_ERR(vreg_ldo15); pr_err("%s: gp6 vreg get failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo11, 1800); if (rc) { pr_err("%s: vreg LDO11 set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo15, 3050); if (rc) { pr_err("%s: vreg LDO15 set level failed (%d)\n", __func__, rc); return rc; } if (on) { rc = vreg_enable(vreg_ldo11); /* PMIC GPIO VREG_LCM_V1P8_EN pull high */ gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_LCM_V1P8_EN), 1); } else { /* Use PMIC_GPIO_LCM_V1P8_EN to control LCM_V1P8 when display off */ //rc = vreg_disable(vreg_ldo11); /* PMIC GPIO VREG_LCM_V1P8_EN pull low */ gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_LCM_V1P8_EN), 0); } if (rc) { pr_err("%s: LDO11 vreg enable failed (%d)\n", __func__, rc); return rc; } if (on) { rc = vreg_enable(vreg_ldo15); } else { rc = vreg_disable(vreg_ldo15); } if (rc) { pr_err("%s: LDO15 vreg enable failed (%d)\n", __func__, rc); return rc; } if (on) { mdelay(1); /* wait 1 ms */ /* Div2-SW2-BSP,JOE HSU,Add LCM reset line hi -> lo -> hi */ gpio_set_value(35, 1); /* bring reset line high */ mdelay(5); /* 10 msec before IO can be accessed */ gpio_set_value(35, 0); mdelay(5); gpio_set_value(35, 1); mdelay(5); } if (on) { rc = pmapp_display_clock_config(1); if (rc) { pr_err("%s pmapp_display_clock_config rc=%d\n", __func__, rc); return rc; } } else { rc = pmapp_display_clock_config(0); if (rc) { pr_err("%s pmapp_display_clock_config rc=%d\n", __func__, rc); return rc; } } return rc; } #endif // CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT #if 0 static unsigned wega_reset_gpio = GPIO_CFG(180, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); static struct msm_gpio fluid_vee_reset_gpio[] = { { GPIO_CFG(20, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "vee_reset" }, }; #endif static unsigned char quickvx_mddi_client = 1; #if 0 static unsigned quickvx_vlp_gpio = GPIO_CFG(97, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); static struct pm8058_gpio pmic_quickvx_clk_gpio = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S3, .out_strength = PM_GPIO_STRENGTH_HIGH, .function = PM_GPIO_FUNC_2, }; #endif #if 0 static int display_common_power(int on) { int rc = 0, flag_on = !!on; static int display_common_power_save_on; struct vreg *vreg_ldo12, *vreg_ldo15 = NULL; struct vreg *vreg_ldo20, *vreg_ldo16, *vreg_ldo8 = NULL; if (display_common_power_save_on == flag_on) return 0; display_common_power_save_on = flag_on; if (on) { /* reset Toshiba WeGA chip -- toggle reset pin -- gpio_180 */ rc = gpio_tlmm_config(wega_reset_gpio, GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, wega_reset_gpio, rc); return rc; } /* bring reset line low to hold reset*/ gpio_set_value(180, 0); if (quickvx_mddi_client) { /* QuickVX chip -- VLP pin -- gpio 97 */ rc = gpio_tlmm_config(quickvx_vlp_gpio, GPIO_CFG_ENABLE); if (rc) { pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, quickvx_vlp_gpio, rc); return rc; } /* bring QuickVX VLP line low */ gpio_set_value(97, 0); rc = pm8058_gpio_config(PMIC_GPIO_QUICKVX_CLK, &pmic_quickvx_clk_gpio); if (rc) { pr_err("%s: pm8058_gpio_config(%#x)=%d\n", __func__, PMIC_GPIO_QUICKVX_CLK + 1, rc); return rc; } gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS( PMIC_GPIO_QUICKVX_CLK), 0); } } /* Toshiba WeGA power -- has 3 power source */ /* 1.5V -- LDO20*/ vreg_ldo20 = vreg_get(NULL, "gp13"); if (IS_ERR(vreg_ldo20)) { rc = PTR_ERR(vreg_ldo20); pr_err("%s: gp13 vreg get failed (%d)\n", __func__, rc); return rc; } /* 1.8V -- LDO12 */ vreg_ldo12 = vreg_get(NULL, "gp9"); if (IS_ERR(vreg_ldo12)) { rc = PTR_ERR(vreg_ldo12); pr_err("%s: gp9 vreg get failed (%d)\n", __func__, rc); return rc; } /* 2.6V -- LDO16 */ vreg_ldo16 = vreg_get(NULL, "gp10"); if (IS_ERR(vreg_ldo16)) { rc = PTR_ERR(vreg_ldo16); pr_err("%s: gp10 vreg get failed (%d)\n", __func__, rc); return rc; } if (machine_is_msm7x30_fluid()) { /* 1.8V -- LDO8 */ vreg_ldo8 = vreg_get(NULL, "gp7"); if (IS_ERR(vreg_ldo8)) { rc = PTR_ERR(vreg_ldo8); pr_err("%s: gp7 vreg get failed (%d)\n", __func__, rc); return rc; } } else { /* lcd panel power */ /* 3.1V -- LDO15 */ vreg_ldo15 = vreg_get(NULL, "gp6"); if (IS_ERR(vreg_ldo15)) { rc = PTR_ERR(vreg_ldo15); pr_err("%s: gp6 vreg get failed (%d)\n", __func__, rc); return rc; } } /* For QuickLogic chip, LDO20 requires 1.8V */ /* Toshiba chip requires 1.5V, but can tolerate 1.8V since max is 3V */ if (quickvx_mddi_client) rc = vreg_set_level(vreg_ldo20, 1800); else rc = vreg_set_level(vreg_ldo20, 1500); if (rc) { pr_err("%s: vreg LDO20 set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo12, 1800); if (rc) { pr_err("%s: vreg LDO12 set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo16, 2600); if (rc) { pr_err("%s: vreg LDO16 set level failed (%d)\n", __func__, rc); return rc; } if (machine_is_msm7x30_fluid()) { rc = vreg_set_level(vreg_ldo8, 1800); if (rc) { pr_err("%s: vreg LDO8 set level failed (%d)\n", __func__, rc); return rc; } } else { rc = vreg_set_level(vreg_ldo15, 3100); if (rc) { pr_err("%s: vreg LDO15 set level failed (%d)\n", __func__, rc); return rc; } } if (on) { rc = vreg_enable(vreg_ldo20); if (rc) { pr_err("%s: LDO20 vreg enable failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_ldo12); if (rc) { pr_err("%s: LDO12 vreg enable failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_ldo16); if (rc) { pr_err("%s: LDO16 vreg enable failed (%d)\n", __func__, rc); return rc; } if (machine_is_msm7x30_fluid()) { rc = vreg_enable(vreg_ldo8); if (rc) { pr_err("%s: LDO8 vreg enable failed (%d)\n", __func__, rc); return rc; } } else { rc = vreg_enable(vreg_ldo15); if (rc) { pr_err("%s: LDO15 vreg enable failed (%d)\n", __func__, rc); return rc; } } mdelay(5); /* ensure power is stable */ if (machine_is_msm7x30_fluid()) { rc = msm_gpios_request_enable(fluid_vee_reset_gpio, ARRAY_SIZE(fluid_vee_reset_gpio)); if (rc) pr_err("%s gpio_request_enable failed rc=%d\n", __func__, rc); else { /* assert vee reset_n */ gpio_set_value(20, 1); gpio_set_value(20, 0); mdelay(1); gpio_set_value(20, 1); } } gpio_set_value(180, 1); /* bring reset line high */ mdelay(10); /* 10 msec before IO can be accessed */ if (quickvx_mddi_client) { gpio_set_value(97, 1); msleep(2); gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS( PMIC_GPIO_QUICKVX_CLK), 1); msleep(2); } rc = pmapp_display_clock_config(1); if (rc) { pr_err("%s pmapp_display_clock_config rc=%d\n", __func__, rc); return rc; } } else { rc = vreg_disable(vreg_ldo20); if (rc) { pr_err("%s: LDO20 vreg enable failed (%d)\n", __func__, rc); return rc; } rc = vreg_disable(vreg_ldo16); if (rc) { pr_err("%s: LDO16 vreg enable failed (%d)\n", __func__, rc); return rc; } gpio_set_value(180, 0); /* bring reset line low */ if (quickvx_mddi_client) { gpio_set_value(97, 0); gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS( PMIC_GPIO_QUICKVX_CLK), 0); } if (machine_is_msm7x30_fluid()) { rc = vreg_disable(vreg_ldo8); if (rc) { pr_err("%s: LDO8 vreg enable failed (%d)\n", __func__, rc); return rc; } } else { rc = vreg_disable(vreg_ldo15); if (rc) { pr_err("%s: LDO15 vreg enable failed (%d)\n", __func__, rc); return rc; } } mdelay(5); /* ensure power is stable */ rc = vreg_disable(vreg_ldo12); if (rc) { pr_err("%s: LDO12 vreg enable failed (%d)\n", __func__, rc); return rc; } if (machine_is_msm7x30_fluid()) { msm_gpios_disable_free(fluid_vee_reset_gpio, ARRAY_SIZE(fluid_vee_reset_gpio)); } rc = pmapp_display_clock_config(0); if (rc) { pr_err("%s pmapp_display_clock_config rc=%d\n", __func__, rc); return rc; } } return rc; } #endif // static int msm_fb_mddi_sel_clk(u32 *clk_rate) { *clk_rate *= 2; return 0; } static int msm_fb_mddi_client_power(u32 client_id) { struct vreg *vreg_ldo20; int rc; printk(KERN_NOTICE "\n client_id = 0x%x", client_id); /* Check if it is Quicklogic client */ if (client_id == 0xc5835800) printk(KERN_NOTICE "\n Quicklogic MDDI client"); else { printk(KERN_NOTICE "\n Non-Quicklogic MDDI client"); quickvx_mddi_client = 0; gpio_set_value(97, 0); gpio_set_value_cansleep(PM8058_GPIO_PM_TO_SYS( PMIC_GPIO_QUICKVX_CLK), 0); vreg_ldo20 = vreg_get(NULL, "gp13"); if (IS_ERR(vreg_ldo20)) { rc = PTR_ERR(vreg_ldo20); pr_err("%s: gp13 vreg get failed (%d)\n", __func__, rc); return rc; } rc = vreg_set_level(vreg_ldo20, 1500); if (rc) { pr_err("%s: vreg LDO20 set level failed (%d)\n", __func__, rc); return rc; } } return 0; } static struct mddi_platform_data mddi_pdata = { #ifndef CONFIG_FIH_CONFIG_GROUP .mddi_power_save = display_common_power, #endif .mddi_sel_clk = msm_fb_mddi_sel_clk, .mddi_client_power = msm_fb_mddi_client_power, }; int mdp_core_clk_rate_table[] = { 122880000, 122880000, 192000000, 192000000, }; static struct msm_panel_common_pdata mdp_pdata = { .hw_revision_addr = 0xac001270, // DIV2-SW2-BSP-FBx-LEDS+ #ifndef CONFIG_LEDS_FIH_FBX_PWM .gpio = 30, #endif // DIV2-SW2-BSP-FBx-LEDS- .mdp_core_clk_rate = 122880000, .mdp_core_clk_table = mdp_core_clk_rate_table, .num_mdp_clk = ARRAY_SIZE(mdp_core_clk_rate_table), }; /* FIHTDC, Div2-SW2-BSP, Ming, LCM { */ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static int lcd_panel_spi_gpio_num[] = { 45, /* spi_clk */ 46, /* spi_cs */ 47, /* spi_mosi */ 48, /* spi_miso */ }; static struct msm_gpio lcd_panel_gpios[] = { { GPIO_CFG(18, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn0" }, { GPIO_CFG(19, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn1" }, { GPIO_CFG(20, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu0" }, { GPIO_CFG(21, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu1" }, { GPIO_CFG(22, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu2" }, { GPIO_CFG(23, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red0" }, { GPIO_CFG(24, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red1" }, { GPIO_CFG(25, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red2" }, { GPIO_CFG(45, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "spi_clk" }, { GPIO_CFG(46, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), "spi_cs0" }, { GPIO_CFG(47, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "spi_mosi" }, { GPIO_CFG(48, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "spi_miso" }, { GPIO_CFG(90, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_4MA), "lcdc_pclk" }, // FIHTDC-Div2-SW2-BSP, Ming, 4mA /// { GPIO_CFG(91, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_en" }, { GPIO_CFG(92, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_vsync" }, { GPIO_CFG(93, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_hsync" }, { GPIO_CFG(94, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn2" }, { GPIO_CFG(95, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn3" }, { GPIO_CFG(96, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn4" }, { GPIO_CFG(97, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_grn5" }, /// { GPIO_CFG(98, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn6" }, /// { GPIO_CFG(99, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn7" }, { GPIO_CFG(100, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu3" }, { GPIO_CFG(101, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu4" }, { GPIO_CFG(102, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_blu5" }, /// { GPIO_CFG(103, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu6" }, /// { GPIO_CFG(104, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu7" }, { GPIO_CFG(105, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red3" }, { GPIO_CFG(106, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red4" }, { GPIO_CFG(107, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "lcdc_red5" }, /// { GPIO_CFG(108, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red6" }, /// { GPIO_CFG(109, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red7" }, }; #endif // CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT #if 0 static struct msm_gpio lcd_panel_gpios[] = { /* Workaround, since HDMI_INT is using the same GPIO line (18), and is used as * input. if there is a hardware revision; we should reassign this GPIO to a * new open line; and removing it will just ensure that this will be missed in * the future. { GPIO_CFG(18, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn0" }, */ { GPIO_CFG(19, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn1" }, { GPIO_CFG(20, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu0" }, { GPIO_CFG(21, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu1" }, { GPIO_CFG(22, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu2" }, { GPIO_CFG(23, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red0" }, { GPIO_CFG(24, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red1" }, { GPIO_CFG(25, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red2" }, #ifndef CONFIG_SPI_QSD { GPIO_CFG(45, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_clk" }, { GPIO_CFG(46, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_cs0" }, { GPIO_CFG(47, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_mosi" }, { GPIO_CFG(48, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "spi_miso" }, #endif { GPIO_CFG(90, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_pclk" }, { GPIO_CFG(91, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_en" }, { GPIO_CFG(92, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_vsync" }, { GPIO_CFG(93, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_hsync" }, { GPIO_CFG(94, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn2" }, { GPIO_CFG(95, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn3" }, { GPIO_CFG(96, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn4" }, { GPIO_CFG(97, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn5" }, { GPIO_CFG(98, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn6" }, { GPIO_CFG(99, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn7" }, { GPIO_CFG(100, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu3" }, { GPIO_CFG(101, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu4" }, { GPIO_CFG(102, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu5" }, { GPIO_CFG(103, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu6" }, { GPIO_CFG(104, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu7" }, { GPIO_CFG(105, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red3" }, { GPIO_CFG(106, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red4" }, { GPIO_CFG(107, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red5" }, { GPIO_CFG(108, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red6" }, { GPIO_CFG(109, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red7" }, }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 static struct msm_gpio lcd_sharp_panel_gpios[] = { { GPIO_CFG(22, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu2" }, { GPIO_CFG(25, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red2" }, { GPIO_CFG(90, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_pclk" }, { GPIO_CFG(91, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_en" }, { GPIO_CFG(92, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_vsync" }, { GPIO_CFG(93, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_hsync" }, { GPIO_CFG(94, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn2" }, { GPIO_CFG(95, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn3" }, { GPIO_CFG(96, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn4" }, { GPIO_CFG(97, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn5" }, { GPIO_CFG(98, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn6" }, { GPIO_CFG(99, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_grn7" }, { GPIO_CFG(100, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu3" }, { GPIO_CFG(101, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu4" }, { GPIO_CFG(102, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu5" }, { GPIO_CFG(103, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu6" }, { GPIO_CFG(104, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_blu7" }, { GPIO_CFG(105, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red3" }, { GPIO_CFG(106, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red4" }, { GPIO_CFG(107, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red5" }, { GPIO_CFG(108, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red6" }, { GPIO_CFG(109, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "lcdc_red7" }, }; #endif //SW2-6-MM-JH-Unused_Display_Codes-00- //SW2-6-MM-JH-Display_Flag-00+ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static int lcdc_toshiba_panel_power(int on) { int rc, i; struct msm_gpio *gp; rc = display_common_power(on); if (rc < 0) { printk(KERN_ERR "%s display_common_power failed: %d\n", __func__, rc); return rc; } if (on) { rc = msm_gpios_enable(lcd_panel_gpios, ARRAY_SIZE(lcd_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); } } else { /* off */ gp = lcd_panel_gpios; for (i = 0; i < ARRAY_SIZE(lcd_panel_gpios); i++) { /* ouput low */ gpio_set_value(GPIO_PIN(gp->gpio_cfg), 0); gp++; } } return rc; } #endif //SW2-6-MM-JH-Display_Flag-00- //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 static int lcdc_sharp_panel_power(int on) { int rc, i; struct msm_gpio *gp; rc = display_common_power(on); if (rc < 0) { printk(KERN_ERR "%s display_common_power failed: %d\n", __func__, rc); return rc; } if (on) { rc = msm_gpios_enable(lcd_sharp_panel_gpios, ARRAY_SIZE(lcd_sharp_panel_gpios)); if (rc < 0) { printk(KERN_ERR "%s: gpio enable failed: %d\n", __func__, rc); } } else { /* off */ gp = lcd_sharp_panel_gpios; for (i = 0; i < ARRAY_SIZE(lcd_sharp_panel_gpios); i++) { /* ouput low */ gpio_set_value(GPIO_PIN(gp->gpio_cfg), 0); gp++; } } return rc; } #endif //SW2-6-MM-JH-Unused_Display_Codes-00- //SW2-6-MM-JH-Display_Flag-00+ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static int lcdc_panel_power(int on) { int flag_on = !!on; static int lcdc_power_save_on; if (lcdc_power_save_on == flag_on) return 0; lcdc_power_save_on = flag_on; quickvx_mddi_client = 0; //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 if (machine_is_msm7x30_fluid()) return lcdc_sharp_panel_power(on); else return lcdc_toshiba_panel_power(on); #else return lcdc_toshiba_panel_power(on); #endif //SW2-6-MM-JH-Unused_Display_Codes-00- } #endif // CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT //SW2-6-MM-JH-Display_Flag-00- static struct lcdc_platform_data lcdc_pdata = { #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT .lcdc_power_save = lcdc_panel_power, #endif }; static int atv_dac_power(int on) { int rc = 0; struct vreg *vreg_s4, *vreg_ldo9; vreg_s4 = vreg_get(NULL, "s4"); if (IS_ERR(vreg_s4)) { rc = PTR_ERR(vreg_s4); pr_err("%s: s4 vreg get failed (%d)\n", __func__, rc); return -1; } vreg_ldo9 = vreg_get(NULL, "gp1"); if (IS_ERR(vreg_ldo9)) { rc = PTR_ERR(vreg_ldo9); pr_err("%s: ldo9 vreg get failed (%d)\n", __func__, rc); return rc; } if (on) { rc = vreg_enable(vreg_s4); if (rc) { pr_err("%s: s4 vreg enable failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_ldo9); if (rc) { pr_err("%s: ldo9 vreg enable failed (%d)\n", __func__, rc); return rc; } } else { rc = vreg_disable(vreg_ldo9); if (rc) { pr_err("%s: ldo9 vreg disable failed (%d)\n", __func__, rc); return rc; } rc = vreg_disable(vreg_s4); if (rc) { pr_err("%s: s4 vreg disable failed (%d)\n", __func__, rc); return rc; } } return rc; } static struct tvenc_platform_data atv_pdata = { .poll = 1, .pm_vid_en = atv_dac_power, }; static void __init msm_fb_add_devices(void) { msm_fb_register_device("mdp", &mdp_pdata); msm_fb_register_device("pmdh", &mddi_pdata); msm_fb_register_device("lcdc", &lcdc_pdata); #if defined(CONFIG_FB_MSM_HDMI_ADV7525_PANEL) || defined(CONFIG_FB_MSM_HDMI_ADV7520_PANEL) msm_fb_register_device("dtv", &dtv_pdata); #endif msm_fb_register_device("tvenc", &atv_pdata); #ifdef CONFIG_FB_MSM_TVOUT msm_fb_register_device("tvout_device", NULL); #endif } //SW2-6-MM-JH-Display_Flag-00+ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT static struct msm_panel_common_pdata lcdc_toshiba_panel_data = { .gpio_num = lcd_panel_spi_gpio_num, }; static struct platform_device lcdc_toshiba_panel_device = { .name = "lcdc_toshiba_wvga", .id = 0, .dev = { .platform_data = &lcdc_toshiba_panel_data, } }; #endif // CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT //SW2-6-MM-JH-Display_Flag-00- // FIHTDC-SW2-Div6-CW-Project BCM4329 For SF8 +[ #if defined(CONFIG_BROADCOM_BCM4329) && \ (defined(CONFIG_BROADCOM_BCM4329_BLUETOOTH_POWER) || defined(CONFIG_BROADCOM_BCM4329_WLAN_POWER)) #define BT_MASK 0x01 #define WLAN_MASK 0x02 #define FM_MASK 0x04 #define GPIO_WLAN_BT_REG_ON 168 static unsigned int bcm4329_power_status = 0; #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 For SF8 +] // FIHTDC-SW2-Div6-CW-Project BCM4329 Bluetooth driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_BLUETOOTH_POWER #define GPIO_BTUART_RFR 134 #define GPIO_BTUART_CTS 135 #define GPIO_BTUART_RX 136 #define GPIO_BTUART_TX 137 #define GPIO_PCM_DIN 138 #define GPIO_PCM_DOUT 139 #define GPIO_PCM_SYNC 140 #define GPIO_PCM_BCLK 141 #define GPIO_BT_RST_N 144 #define GPIO_BT_IRQ 147 #define GPIO_BT_WAKEUP 170 static struct platform_device bcm4329_bt_power_device = { .name = "bcm4329_bt_power", .id = -1 }; static struct msm_gpio bt_config_power_on[] = { { GPIO_CFG(GPIO_BTUART_RFR, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_RFR" }, { GPIO_CFG(GPIO_BTUART_CTS, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_CTS" }, { GPIO_CFG(GPIO_BTUART_RX, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_RX" }, { GPIO_CFG(GPIO_BTUART_TX, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_TX" }, { GPIO_CFG(GPIO_BT_IRQ, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "BT_HOST_WAKE" }, { GPIO_CFG(GPIO_BT_WAKEUP, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "BT_WAKE" } }; static struct msm_gpio bt_config_power_off[] = { { GPIO_CFG(GPIO_BTUART_RFR, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_RFR" }, { GPIO_CFG(GPIO_BTUART_CTS, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_CTS" }, { GPIO_CFG(GPIO_BTUART_RX, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_RX" }, { GPIO_CFG(GPIO_BTUART_TX, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_TX" }, { GPIO_CFG(GPIO_BT_IRQ, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "BT_HOST_WAKE" }, { GPIO_CFG(GPIO_BT_WAKEUP, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "BT_WAKE" } }; static int bluetooth_fm_power(int on) { int rc; printk("KERN_DEBUG %s: POWER %s\r\n", __FUNCTION__, on?"ON":"OFF"); if (on) { rc = msm_gpios_enable(bt_config_power_on, ARRAY_SIZE(bt_config_power_on)); if (rc < 0) { printk(KERN_DEBUG "%s: Power ON bluetooth failed.\r\n", __FUNCTION__); return rc; } if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL UP GPIO_WLAN_BT_REG_ON\r\n", __FUNCTION__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 1); mdelay(20); } gpio_set_value(GPIO_BT_RST_N, 0); mdelay(20); gpio_set_value(GPIO_BT_RST_N, 1); mdelay(100); printk(KERN_DEBUG "%s: GPIO_BT_RST (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_BT_RST_N)?"HIGH":"LOW"); printk(KERN_DEBUG "%s: GPIO_WLAN_BT_REG_ON (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_BT_REG_ON)?"HIGH":"LOW"); } else { rc = msm_gpios_enable(bt_config_power_off, ARRAY_SIZE(bt_config_power_off)); if (rc < 0) { printk(KERN_DEBUG "%s: Power OFF bluetooth failed.\r\n", __FUNCTION__); return rc; } gpio_set_value(GPIO_BT_RST_N, 0); if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL DOWN GPIO_WLAN_BT_REG_ON\r\n", __FUNCTION__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); } mdelay(100); printk(KERN_DEBUG "%s: GPIO_BT_RST (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_BT_RST_N)?"HIGH":"LOW"); printk(KERN_DEBUG "%s: GPIO_WLAN_BT_REG_ON (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_BT_REG_ON)?"HIGH":"LOW"); } return 0; } static int bluetooth_power(int on) { int ret = 0; printk("KERN_DEBUG %s: POWER %s\r\n", __FUNCTION__, on?"ON":"OFF"); if (on) { if ((bcm4329_power_status & ~WLAN_MASK) != 0) { printk("KERN_DEBUG %s: FM has been enable the power\r\n", __FUNCTION__); bcm4329_power_status |= BT_MASK; return 0; } ret = bluetooth_fm_power(on); if (ret < 0) { printk(KERN_DEBUG "%s: Power ON bluetooth failed.\r\n", __FUNCTION__); return ret; } bcm4329_power_status |= BT_MASK; } else { if ((bcm4329_power_status & ~(WLAN_MASK | BT_MASK)) != 0) { printk("KERN_DEBUG %s: FM enabled, can't turn bcm4329 bt/fm power\r\n", __FUNCTION__); bcm4329_power_status &= ~BT_MASK; return 0; } bcm4329_power_status &= ~BT_MASK; ret = bluetooth_fm_power(on); if (ret < 0) { printk(KERN_DEBUG "%s: Power ON bluetooth failed.\r\n", __FUNCTION__); return ret; } } return 0; } static void __init bcm4329_bt_power_init(void) { gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); gpio_set_value(GPIO_BT_RST_N, 0); bcm4329_bt_power_device.dev.platform_data = &bluetooth_power; } #else //#define bt_power_init(x) do {} while (0) #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 Bluetooth driver For SF8 +] #if defined(CONFIG_BROADCOM_BCM4329) static struct platform_device bcm4329_fm_power_device = { .name = "bcm4329_fm_power", .id = -1 }; static int fm_power(int on) { int ret = 0; printk("KERN_DEBUG %s: POWER %s\r\n", __FUNCTION__, on?"ON":"OFF"); if (on) { if ((bcm4329_power_status & ~WLAN_MASK) != 0) { printk("KERN_DEBUG %s: Bluetooth has been enable the power\r\n", __FUNCTION__); bcm4329_power_status |= FM_MASK; return 0; } ret = bluetooth_fm_power(on); if (ret < 0) { printk(KERN_DEBUG "%s: Power ON FM failed.\r\n", __FUNCTION__); return ret; } bcm4329_power_status |= FM_MASK; } else { if ((bcm4329_power_status & ~(WLAN_MASK | FM_MASK)) != 0) { printk("KERN_DEBUG %s: Bluetooth enabled, can't turn bcm4329 bt/fm power\r\n", __FUNCTION__); bcm4329_power_status &= ~FM_MASK; return 0; } bcm4329_power_status &= ~FM_MASK; ret = bluetooth_fm_power(on); if (ret < 0) { printk(KERN_DEBUG "%s: Power ON FM failed.\r\n", __FUNCTION__); return ret; } } return 0; } static void __init bcm4329_fm_power_init(void) { bcm4329_fm_power_device.dev.platform_data = &fm_power; } #endif #if defined(CONFIG_BROADCOM_BCM4329) static struct resource bluesleep_resources[] = { { .name = "gpio_host_wake", .start = GPIO_BT_IRQ, .end = GPIO_BT_IRQ, .flags = IORESOURCE_IO, }, { .name = "gpio_ext_wake", .start = GPIO_BT_WAKEUP, .end = GPIO_BT_WAKEUP, .flags = IORESOURCE_IO, }, { .name = "host_wake", .start = MSM_GPIO_TO_INT(GPIO_BT_IRQ), .end = MSM_GPIO_TO_INT(GPIO_BT_IRQ), .flags = IORESOURCE_IO, }, }; static struct platform_device msm_bluesleep_device = { .name = "bluesleep", .id = -1, .num_resources = ARRAY_SIZE(bluesleep_resources), .resource = bluesleep_resources, }; #endif // FihtdcCode@20110908 WeiChu add for WiFi porting begin // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_WLAN_POWER #define GPIO_WLAN_RST_N 146 #define GPIO_WLAN_IRQ 145 #define GPIO_WLAN_WAKEUP 169 static struct platform_device bcm4329_wifi_power_device = { .name = "bcm4329_wifi_power", .id = -1 }; int wifi_power(int on) //SW5-PT1-Connectivity_FredYu_FixPowerSequence { printk(KERN_DEBUG "%s: POWER %s\r\n", __FUNCTION__, on?"ON":"OFF"); if (on) { if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL UP GPIO_WLAN_BT_REG_ON\r\n", __FUNCTION__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 1); mdelay(20); } gpio_set_value(GPIO_WLAN_RST_N, 1); mdelay(20); bcm4329_power_status |= WLAN_MASK; printk(KERN_DEBUG "%s: GPIO_WLAN_RST (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_RST_N)?"HIGH":"LOW"); printk(KERN_DEBUG "%s: GPIO_WLAN_BT_REG_ON (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_BT_REG_ON)?"HIGH":"LOW"); } else { bcm4329_power_status &= ~WLAN_MASK; gpio_set_value(GPIO_WLAN_RST_N, 0); if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL DOWN GPIO_WLAN_BT_REG_ON\r\n", __FUNCTION__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); } printk(KERN_DEBUG "%s: GPIO_WLAN_RST (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_RST_N)?"HIGH":"LOW"); printk(KERN_DEBUG "%s: GPIO_WLAN_BT_REG_ON (%s)\r\n", __FUNCTION__, gpio_get_value(GPIO_WLAN_BT_REG_ON)?"HIGH":"LOW"); } return 0; } EXPORT_SYMBOL(wifi_power); //SW5-PT1-Connectivity_FredYu_FixPowerSequence int bcm4329_wifi_resume(void) { printk(KERN_DEBUG "%s: START bcm4329_power_status=0x%x\r\n", __func__, bcm4329_power_status); if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL UP GPIO_WLAN_BT_REG_ON\r\n", __func__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 1); mdelay(45); } gpio_set_value(GPIO_WLAN_RST_N, 1); mdelay(20); bcm4329_power_status |= WLAN_MASK; return 0; } EXPORT_SYMBOL(bcm4329_wifi_resume); int bcm4329_wifi_suspend(void) { printk(KERN_DEBUG "%s: START bcm4329_power_status=0x%x\r\n", __func__, bcm4329_power_status); bcm4329_power_status &= ~WLAN_MASK; gpio_set_value(GPIO_WLAN_RST_N, 0); if (bcm4329_power_status == 0) { printk(KERN_DEBUG "%s: PULL DOWN GPIO_WLAN_BT_REG_ON\r\n", __func__); gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); } return 0; } EXPORT_SYMBOL(bcm4329_wifi_suspend); static void __init bcm4329_wifi_power_init(void) { gpio_set_value(GPIO_WLAN_BT_REG_ON, 0); gpio_set_value(GPIO_WLAN_RST_N, 0); bcm4329_wifi_power_device.dev.platform_data = &wifi_power; } #else #define wifi_power_init(x) do {} while (0) #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +] // FihtdcCode@20110908 WeiChu add for WiFi porting end #if defined(CONFIG_MARIMBA_CORE) && \ (defined(CONFIG_MSM_BT_POWER) || defined(CONFIG_MSM_BT_POWER_MODULE)) static struct platform_device msm_bt_power_device = { .name = "bt_power", .id = -1 }; enum { BT_RFR, BT_CTS, BT_RX, BT_TX, }; static struct msm_gpio bt_config_power_on[] = { { GPIO_CFG(134, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_RFR" }, { GPIO_CFG(135, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_CTS" }, { GPIO_CFG(136, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_Rx" }, { GPIO_CFG(137, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "UART1DM_Tx" } }; static struct msm_gpio bt_config_power_off[] = { { GPIO_CFG(134, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_RFR" }, { GPIO_CFG(135, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_CTS" }, { GPIO_CFG(136, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_Rx" }, { GPIO_CFG(137, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART1DM_Tx" } }; static const char *vregs_bt_marimba_name[] = { "s3", "s2", "gp16", "wlan" }; static struct vreg *vregs_bt_marimba[ARRAY_SIZE(vregs_bt_marimba_name)]; static const char *vregs_bt_bahama_name[] = { "s3", "usb2", "s2", "wlan" }; static struct vreg *vregs_bt_bahama[ARRAY_SIZE(vregs_bt_bahama_name)]; static u8 bahama_version; static int marimba_bt(int on) { int rc; int i; struct marimba config = { .mod_id = MARIMBA_SLAVE_ID_MARIMBA }; struct marimba_config_register { u8 reg; u8 value; u8 mask; }; struct marimba_variant_register { const size_t size; const struct marimba_config_register *set; }; const struct marimba_config_register *p; u8 version; const struct marimba_config_register v10_bt_on[] = { { 0xE5, 0x0B, 0x0F }, { 0x05, 0x02, 0x07 }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x21, 0x21 }, { 0xE3, 0x38, 0xFF }, { 0xE4, 0x06, 0xFF }, }; const struct marimba_config_register v10_bt_off[] = { { 0xE5, 0x0B, 0x0F }, { 0x05, 0x08, 0x0F }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x00, 0x21 }, { 0xE3, 0x00, 0xFF }, { 0xE4, 0x00, 0xFF }, }; const struct marimba_config_register v201_bt_on[] = { { 0x05, 0x08, 0x07 }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x21, 0x21 }, { 0xE3, 0x38, 0xFF }, { 0xE4, 0x06, 0xFF }, }; const struct marimba_config_register v201_bt_off[] = { { 0x05, 0x08, 0x07 }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x00, 0x21 }, { 0xE3, 0x00, 0xFF }, { 0xE4, 0x00, 0xFF }, }; const struct marimba_config_register v210_bt_on[] = { { 0xE9, 0x01, 0x01 }, { 0x06, 0x88, 0xFF }, { 0xE7, 0x21, 0x21 }, { 0xE3, 0x38, 0xFF }, { 0xE4, 0x06, 0xFF }, }; const struct marimba_config_register v210_bt_off[] = { { 0x06, 0x88, 0xFF }, { 0xE7, 0x00, 0x21 }, { 0xE9, 0x00, 0x01 }, { 0xE3, 0x00, 0xFF }, { 0xE4, 0x00, 0xFF }, }; const struct marimba_variant_register bt_marimba[2][4] = { { { ARRAY_SIZE(v10_bt_off), v10_bt_off }, { 0, NULL }, { ARRAY_SIZE(v201_bt_off), v201_bt_off }, { ARRAY_SIZE(v210_bt_off), v210_bt_off } }, { { ARRAY_SIZE(v10_bt_on), v10_bt_on }, { 0, NULL }, { ARRAY_SIZE(v201_bt_on), v201_bt_on }, { ARRAY_SIZE(v210_bt_on), v210_bt_on } } }; on = on ? 1 : 0; rc = marimba_read_bit_mask(&config, 0x11, &version, 1, 0x1F); if (rc < 0) { printk(KERN_ERR "%s: version read failed: %d\n", __func__, rc); return rc; } if ((version >= ARRAY_SIZE(bt_marimba[on])) || (bt_marimba[on][version].size == 0)) { printk(KERN_ERR "%s: unsupported version\n", __func__); return -EIO; } p = bt_marimba[on][version].set; printk(KERN_INFO "%s: found version %d\n", __func__, version); for (i = 0; i < bt_marimba[on][version].size; i++) { u8 value = (p+i)->value; rc = marimba_write_bit_mask(&config, (p+i)->reg, &value, sizeof((p+i)->value), (p+i)->mask); if (rc < 0) { printk(KERN_ERR "%s: reg %d write failed: %d\n", __func__, (p+i)->reg, rc); return rc; } printk(KERN_INFO "%s: reg 0x%02x value 0x%02x mask 0x%02x\n", __func__, (p+i)->reg, value, (p+i)->mask); } return 0; } static int bahama_bt(int on) { int rc; int i; struct marimba config = { .mod_id = SLAVE_ID_BAHAMA }; struct bahama_variant_register { const size_t size; const struct bahama_config_register *set; }; const struct bahama_config_register *p; const struct bahama_config_register v10_bt_on[] = { { 0xE9, 0x00, 0xFF }, { 0xF4, 0x80, 0xFF }, { 0xF0, 0x06, 0xFF }, { 0xE4, 0x00, 0xFF }, { 0xE5, 0x00, 0x0F }, #ifdef CONFIG_WLAN { 0xE6, 0x38, 0x7F }, { 0xE7, 0x06, 0xFF }, #endif { 0x11, 0x13, 0xFF }, { 0xE9, 0x21, 0xFF }, { 0x01, 0x0C, 0x1F }, { 0x01, 0x08, 0x1F }, }; const struct bahama_config_register v20_bt_on_fm_off[] = { { 0x11, 0x0C, 0xFF }, { 0x13, 0x01, 0xFF }, { 0xF4, 0x80, 0xFF }, { 0xF0, 0x00, 0xFF }, { 0xE9, 0x00, 0xFF }, #ifdef CONFIG_WLAN { 0x81, 0x00, 0xFF }, { 0x82, 0x00, 0xFF }, { 0xE6, 0x38, 0x7F }, { 0xE7, 0x06, 0xFF }, #endif { 0xE9, 0x21, 0xFF } }; const struct bahama_config_register v20_bt_on_fm_on[] = { { 0x11, 0x0C, 0xFF }, { 0x13, 0x01, 0xFF }, { 0xF4, 0x86, 0xFF }, { 0xF0, 0x06, 0xFF }, { 0xE9, 0x00, 0xFF }, #ifdef CONFIG_WLAN { 0x81, 0x00, 0xFF }, { 0x82, 0x00, 0xFF }, { 0xE6, 0x38, 0x7F }, { 0xE7, 0x06, 0xFF }, #endif { 0xE9, 0x21, 0xFF } }; const struct bahama_config_register v10_bt_off[] = { { 0xE9, 0x00, 0xFF }, }; const struct bahama_config_register v20_bt_off_fm_off[] = { { 0xF4, 0x84, 0xFF }, { 0xF0, 0x04, 0xFF }, { 0xE9, 0x00, 0xFF } }; const struct bahama_config_register v20_bt_off_fm_on[] = { { 0xF4, 0x86, 0xFF }, { 0xF0, 0x06, 0xFF }, { 0xE9, 0x00, 0xFF } }; const struct bahama_variant_register bt_bahama[2][3] = { { { ARRAY_SIZE(v10_bt_off), v10_bt_off }, { ARRAY_SIZE(v20_bt_off_fm_off), v20_bt_off_fm_off }, { ARRAY_SIZE(v20_bt_off_fm_on), v20_bt_off_fm_on } }, { { ARRAY_SIZE(v10_bt_on), v10_bt_on }, { ARRAY_SIZE(v20_bt_on_fm_off), v20_bt_on_fm_off }, { ARRAY_SIZE(v20_bt_on_fm_on), v20_bt_on_fm_on } } }; u8 offset = 0; /* index into bahama configs */ /* Init mutex to get/set FM/BT status respectively */ mutex_init(&config.xfer_lock); on = on ? 1 : 0; bahama_version = read_bahama_ver(); if (bahama_version == VER_UNSUPPORTED) { dev_err(&msm_bt_power_device.dev, "%s: unsupported version\n", __func__); return -EIO; } if (bahama_version == VER_2_0) { if (marimba_get_fm_status(&config)) offset = 0x01; } p = bt_bahama[on][bahama_version + offset].set; dev_info(&msm_bt_power_device.dev, "%s: found version %d\n", __func__, bahama_version); for (i = 0; i < bt_bahama[on][bahama_version + offset].size; i++) { u8 value = (p+i)->value; rc = marimba_write_bit_mask(&config, (p+i)->reg, &value, sizeof((p+i)->value), (p+i)->mask); if (rc < 0) { dev_err(&msm_bt_power_device.dev, "%s: reg %d write failed: %d\n", __func__, (p+i)->reg, rc); return rc; } dev_info(&msm_bt_power_device.dev, "%s: reg 0x%02x write value 0x%02x mask 0x%02x\n", __func__, (p+i)->reg, value, (p+i)->mask); } /* Update BT status */ if (on) marimba_set_bt_status(&config, true); else marimba_set_bt_status(&config, false); /* Destory mutex */ mutex_destroy(&config.xfer_lock); if (bahama_version == VER_2_0 && on) { /* variant of bahama v2 */ /* Disable s2 as bahama v2 uses internal LDO regulator */ for (i = 0; i < ARRAY_SIZE(vregs_bt_bahama_name); i++) { if (!strcmp(vregs_bt_bahama_name[i], "s2")) { rc = vreg_disable(vregs_bt_bahama[i]); if (rc < 0) { printk(KERN_ERR "%s: vreg %s disable " "failed (%d)\n", __func__, vregs_bt_bahama_name[i], rc); return -EIO; } rc = pmapp_vreg_level_vote("BTPW", PMAPP_VREG_S2, 0); if (rc < 0) { printk(KERN_ERR "%s: vreg " "level off failed (%d)\n", __func__, rc); return -EIO; } printk(KERN_INFO "%s: vreg disable & " "level off successful (%d)\n", __func__, rc); } } } return 0; } static int bluetooth_power_regulators(int on, int bahama_not_marimba) { int i, rc; const char **vregs_name; struct vreg **vregs; int vregs_size; if (bahama_not_marimba) { vregs_name = vregs_bt_bahama_name; vregs = vregs_bt_bahama; vregs_size = ARRAY_SIZE(vregs_bt_bahama_name); } else { vregs_name = vregs_bt_marimba_name; vregs = vregs_bt_marimba; vregs_size = ARRAY_SIZE(vregs_bt_marimba_name); } for (i = 0; i < vregs_size; i++) { if (bahama_not_marimba && (bahama_version == VER_2_0) && !on && !strcmp(vregs_bt_bahama_name[i], "s2")) continue; rc = on ? vreg_enable(vregs[i]) : vreg_disable(vregs[i]); if (rc < 0) { printk(KERN_ERR "%s: vreg %s %s failed (%d)\n", __func__, vregs_name[i], on ? "enable" : "disable", rc); return -EIO; } } return 0; } static int bluetooth_power(int on) { int rc; const char *id = "BTPW"; int bahama_not_marimba = bahama_present(); if (bahama_not_marimba == -1) { printk(KERN_WARNING "%s: bahama_present: %d\n", __func__, bahama_not_marimba); return -ENODEV; } if (on) { rc = pmapp_vreg_level_vote(id, PMAPP_VREG_S2, 1300); if (rc < 0) { printk(KERN_ERR "%s: vreg level on failed (%d)\n", __func__, rc); return rc; } rc = bluetooth_power_regulators(on, bahama_not_marimba); if (rc < 0) return -EIO; /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_ON); } else { rc = pmapp_clock_vote(id, QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_ON); } if (rc < 0) return -EIO; if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = marimba_gpio_config(1); if (rc < 0) return -EIO; } rc = (bahama_not_marimba ? bahama_bt(on) : marimba_bt(on)); if (rc < 0) return -EIO; msleep(10); /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_PIN_CTRL); } else { rc = pmapp_clock_vote(id, QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_PIN_CTRL); } if (rc < 0) return -EIO; if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = marimba_gpio_config(0); if (rc < 0) return -EIO; } rc = msm_gpios_enable(bt_config_power_on, ARRAY_SIZE(bt_config_power_on)); if (rc < 0) return rc; } else { rc = msm_gpios_enable(bt_config_power_off, ARRAY_SIZE(bt_config_power_off)); if (rc < 0) return rc; /* check for initial RFKILL block (power off) */ if (platform_get_drvdata(&msm_bt_power_device) == NULL) goto out; rc = (bahama_not_marimba ? bahama_bt(on) : marimba_bt(on)); if (rc < 0) return -EIO; /* FIHTDC, Div2-SW2-BSP Godfrey */ if ((fih_get_product_id() == Product_FD1) && ((fih_get_product_phase() != Product_PR1) && (fih_get_product_phase() != Product_PR2p5) && (fih_get_product_phase() != Product_PR230) && (fih_get_product_phase() != Product_PR232) && (fih_get_product_phase() != Product_PR3) && (fih_get_product_phase() != Product_PR4))) { rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_DO, PMAPP_CLOCK_VOTE_OFF); } else { rc = pmapp_clock_vote(id, QTR8x00_WCN_CLK, PMAPP_CLOCK_VOTE_OFF); } if (rc < 0) return -EIO; rc = bluetooth_power_regulators(on, bahama_not_marimba); if (rc < 0) return -EIO; if (bahama_version == VER_1_0) { rc = pmapp_vreg_level_vote(id, PMAPP_VREG_S2, 0); if (rc < 0) { printk(KERN_ERR "%s: vreg level off failed " "(%d)\n", __func__, rc); return -EIO; } } } out: printk(KERN_DEBUG "Bluetooth power switch: %d\n", on); return 0; } static void __init bt_power_init(void) { int i; for (i = 0; i < ARRAY_SIZE(vregs_bt_marimba_name); i++) { vregs_bt_marimba[i] = vreg_get(NULL, vregs_bt_marimba_name[i]); if (IS_ERR(vregs_bt_marimba[i])) { printk(KERN_ERR "%s: vreg get %s failed (%ld)\n", __func__, vregs_bt_marimba_name[i], PTR_ERR(vregs_bt_marimba[i])); return; } } for (i = 0; i < ARRAY_SIZE(vregs_bt_bahama_name); i++) { vregs_bt_bahama[i] = vreg_get(NULL, vregs_bt_bahama_name[i]); if (IS_ERR(vregs_bt_bahama[i])) { printk(KERN_ERR "%s: vreg get %s failed (%ld)\n", __func__, vregs_bt_bahama_name[i], PTR_ERR(vregs_bt_bahama[i])); return; } } msm_bt_power_device.dev.platform_data = &bluetooth_power; } #else #define bt_power_init(x) do {} while (0) #endif #if defined(CONFIG_BATTERY_FIH_MSM) || defined(CONFIG_BATTERY_MSM) static struct msm_psy_batt_pdata msm_psy_batt_data = { .voltage_min_design = 2800, .voltage_max_design = 4300, .avail_chg_sources = AC_CHG | USB_CHG , .batt_technology = POWER_SUPPLY_TECHNOLOGY_LION, // DIV2-SW2-BSP-FBx-BATT+[ #ifdef CONFIG_BATTERY_FIH_MSM .batt_info_if = { .get_chg_source = msm_batt_get_chg_source, .get_batt_status = msm_batt_get_batt_status, .get_batt_capacity = msm_batt_info_not_support, .get_batt_health = msm_batt_info_not_support, .get_batt_temp = msm_batt_info_not_support, .get_batt_voltage = msm_batt_info_not_support, }, #endif // DIV2-SW2-BSP-FBX-BATT+] }; static struct platform_device msm_batt_device = { .name = "msm-battery", .id = -1, .dev.platform_data = &msm_psy_batt_data, }; #endif // DIV2-SW2-BSP-FBx-BATT+[ #ifdef CONFIG_BATTERY_FIH_MSM enum { HWMODEL_GAUGE_DS2784, HWMODEL_GAUGE_BQ27500, }; #ifdef CONFIG_DS2482 static struct ds2482_platform_data ds2482_pdata = { .pmic_gpio_ds2482_SLPZ = 31, .sys_gpio_ds2482_SLPZ = PM8058_GPIO_PM_TO_SYS(31) - 1, .sys_gpio_gauge_ls_en = 88, }; #endif #ifdef CONFIG_BATTERY_BQ275X0 struct bq275x0_platform_data bq275x0_pdata = { #if defined(CONFIG_FIH_PROJECT_FB0) || defined(CONFIG_FIH_PROJECT_SF4Y6) .pmic_BATLOW = 12, #else .pmic_BATLOW = 16, #endif .pmic_BATGD = 19, }; #endif static struct i2c_board_info fih_battery_i2c_board_info[] = { #ifdef CONFIG_DS2482 { I2C_BOARD_INFO("ds2482", 0x30 >> 1), .platform_data = &ds2482_pdata, }, #endif #ifdef CONFIG_BATTERY_BQ275X0 { I2C_BOARD_INFO("bq275x0-battery", 0xAA >> 1), .platform_data = &bq275x0_pdata, }, #ifdef CONFIG_BQ275X0_ROMMODE { I2C_BOARD_INFO("bq275x0-RomMode", 0x16 >> 1), }, #endif #endif }; static int fih_battery_hw_model(void) { int product_id = fih_get_product_id(); int product_phase = fih_get_product_phase(); if (product_id == Product_FB0 || product_id == Product_FD1) if (product_phase >= Product_EVB && product_phase < Product_PR231) return HWMODEL_GAUGE_DS2784; else return HWMODEL_GAUGE_BQ27500; else return HWMODEL_GAUGE_BQ27500; } /* * Assign caculate_capacity and get_battery_status function by HWID */ static void __init fih_battery_driver_init(void) { switch(fih_battery_hw_model()) { case HWMODEL_GAUGE_DS2784: #ifdef CONFIG_DS2482 i2c_register_board_info(0, &fih_battery_i2c_board_info[0], 1); #ifdef CONFIG_BATTERY_FIH_DS2784 msm_psy_batt_data.batt_info_if.get_batt_capacity = ds2784_batt_get_batt_capacity; msm_psy_batt_data.batt_info_if.get_batt_health = ds2784_batt_set_batt_health; msm_psy_batt_data.batt_info_if.get_batt_temp = ds2784_batt_get_batt_temp; msm_psy_batt_data.batt_info_if.get_batt_voltage = ds2784_batt_get_batt_voltage; #endif #endif break; case HWMODEL_GAUGE_BQ27500: default: #ifdef CONFIG_BATTERY_BQ275X0 #ifdef CONFIG_DS2482 i2c_register_board_info(0, &fih_battery_i2c_board_info[1], 1); #ifdef CONFIG_BQ275X0_ROMMODE i2c_register_board_info(0, &fih_battery_i2c_board_info[2], 1); #endif #else i2c_register_board_info(0, &fih_battery_i2c_board_info[0], 1); #ifdef CONFIG_BQ275X0_ROMMODE i2c_register_board_info(0, &fih_battery_i2c_board_info[1], 1); #endif #endif msm_psy_batt_data.batt_info_if.get_batt_capacity = bq275x0_battery_soc; msm_psy_batt_data.batt_info_if.get_batt_health = bq275x0_battery_health; msm_psy_batt_data.batt_info_if.get_batt_temp = bq275x0_battery_temperature; msm_psy_batt_data.batt_info_if.get_batt_voltage = bq275x0_battery_voltage; #endif } } #endif // DIV2-SW2-BSP-FBx-BATT+] static char *msm_adc_fluid_device_names[] = { "LTC_ADC1", "LTC_ADC2", "LTC_ADC3", }; static char *msm_adc_surf_device_names[] = { "XO_ADC", }; static struct msm_adc_platform_data msm_adc_pdata; static struct platform_device msm_adc_device = { .name = "msm_adc", .id = -1, .dev = { .platform_data = &msm_adc_pdata, }, }; #ifdef CONFIG_MSM_SDIO_AL static struct msm_gpio mdm2ap_status = { GPIO_CFG(77, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "mdm2ap_status" }; static int configure_mdm2ap_status(int on) { if (on) return msm_gpios_request_enable(&mdm2ap_status, 1); else { msm_gpios_disable_free(&mdm2ap_status, 1); return 0; } } static int get_mdm2ap_status(void) { return gpio_get_value(GPIO_PIN(mdm2ap_status.gpio_cfg)); } static struct sdio_al_platform_data sdio_al_pdata = { .config_mdm2ap_status = configure_mdm2ap_status, .get_mdm2ap_status = get_mdm2ap_status, .allow_sdioc_version_major_2 = 1, .peer_sdioc_version_minor = 0x0001, .peer_sdioc_version_major = 0x0003, .peer_sdioc_boot_version_minor = 0x0001, .peer_sdioc_boot_version_major = 0x0002, }; struct platform_device msm_device_sdio_al = { .name = "msm_sdio_al", .id = -1, .dev = { .platform_data = &sdio_al_pdata, }, }; #endif /* CONFIG_MSM_SDIO_AL */ // DIV2-SW2-BSP-FBx-LEDS+ #ifdef CONFIG_LEDS_FIH_FBX_PWM static struct leds_fbx_pwm_platform_data fbx_leds_pwm_pdata = { .r_led_ctl = 30 }; static struct platform_device fbx_leds_pwm_device = { .name = "fbx-leds-pwm", .id = -1, .dev = { .platform_data = &fbx_leds_pwm_pdata, }, }; #endif // DIV2-SW2-BSP-FBx-LEDS- //FIHTDC, Port keypad, MayLi, 2011.09.21 {+ #ifdef CONFIG_KEYBOARD_SF4H8 static struct sf8_kybd_platform_data sf8_kybd_pdata = { .pmic_gpio_vol_up = 0, .pmic_gpio_vol_dn = 1, .pmic_gpio_cover_det= 2, .sys_gpio_vol_up = PM8058_GPIO_PM_TO_SYS(0), .sys_gpio_vol_dn = PM8058_GPIO_PM_TO_SYS(1), .sys_gpio_cover_det = PM8058_GPIO_PM_TO_SYS(2), }; static struct platform_device sf8_kybd_device = { .name = "sf8_kybd", .id = -1, .dev = { .platform_data = &sf8_kybd_pdata, }, }; #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 -} //SW2-5-1-MP-DbgCfgTool-00+[ #ifdef CONFIG_ANDROID_RAM_CONSOLE #define RAM_CONSOLE_PHYS 0x7A00000 #define RAM_CONSOLE_SIZE 0x00020000 static struct resource ram_console_resources[1] = { [0] = { .start = RAM_CONSOLE_PHYS, .end = RAM_CONSOLE_PHYS + RAM_CONSOLE_SIZE - 1, .flags = IORESOURCE_MEM, }, }; static struct platform_device ram_console_device = { .name = "ram_console", .id = 0, .num_resources = ARRAY_SIZE(ram_console_resources), .resource = ram_console_resources, }; #endif #ifdef CONFIG_FIH_LAST_ALOG #ifdef CONFIG_ANDROID_RAM_CONSOLE #define ALOG_RAM_CONSOLE_PHYS_MAIN (RAM_CONSOLE_PHYS + RAM_CONSOLE_SIZE) #else #define ALOG_RAM_CONSOLE_PHYS_MAIN 0x7A20000 #endif #define ALOG_RAM_CONSOLE_SIZE_MAIN 0x00020000 //128KB #define ALOG_RAM_CONSOLE_PHYS_RADIO (ALOG_RAM_CONSOLE_PHYS_MAIN + ALOG_RAM_CONSOLE_SIZE_MAIN) #define ALOG_RAM_CONSOLE_SIZE_RADIO 0x00020000 //128KB #define ALOG_RAM_CONSOLE_PHYS_EVENTS (ALOG_RAM_CONSOLE_PHYS_RADIO + ALOG_RAM_CONSOLE_SIZE_RADIO) #define ALOG_RAM_CONSOLE_SIZE_EVENTS 0x00020000 //128KB #define ALOG_RAM_CONSOLE_PHYS_SYSTEM (ALOG_RAM_CONSOLE_PHYS_EVENTS + ALOG_RAM_CONSOLE_SIZE_EVENTS) #define ALOG_RAM_CONSOLE_SIZE_SYSTEM 0x00020000 //128KB static struct resource alog_ram_console_resources[4] = { [0] = { .name = "alog_main_buffer", .start = ALOG_RAM_CONSOLE_PHYS_MAIN, .end = ALOG_RAM_CONSOLE_PHYS_MAIN + ALOG_RAM_CONSOLE_SIZE_MAIN - 1, .flags = IORESOURCE_MEM, }, [1] = { .name = "alog_radio_buffer", .start = ALOG_RAM_CONSOLE_PHYS_RADIO, .end = ALOG_RAM_CONSOLE_PHYS_RADIO + ALOG_RAM_CONSOLE_SIZE_RADIO - 1, .flags = IORESOURCE_MEM, }, [2] = { .name = "alog_events_buffer", .start = ALOG_RAM_CONSOLE_PHYS_EVENTS, .end = ALOG_RAM_CONSOLE_PHYS_EVENTS + ALOG_RAM_CONSOLE_SIZE_EVENTS - 1, .flags = IORESOURCE_MEM, }, [3] = { .name = "alog_system_buffer", .start = ALOG_RAM_CONSOLE_PHYS_SYSTEM, .end = ALOG_RAM_CONSOLE_PHYS_SYSTEM + ALOG_RAM_CONSOLE_SIZE_SYSTEM - 1, .flags = IORESOURCE_MEM, }, }; static struct platform_device alog_ram_console_device = { .name = "alog_ram_console", .id = 0, .num_resources = ARRAY_SIZE(alog_ram_console_resources), .resource = alog_ram_console_resources, }; #endif //SW2-5-1-MP-DbgCfgTool-00+] static struct platform_device *devices[] __initdata = { #if defined(CONFIG_SERIAL_MSM) || defined(CONFIG_MSM_SERIAL_DEBUGGER) &msm_device_uart2, #endif &msm_device_smd, &msm_device_dmov, /* Div2-SW2-BSP-FBX-OW { */ #ifdef CONFIG_SMC91X &smc91x_device, #endif #ifdef CONFIG_SMSC911X &smsc911x_device, #endif /* } Div2-SW2-BSP-FBX-OW */ &msm_device_nand, #ifdef CONFIG_USB_FUNCTION &msm_device_hsusb_peripheral, &mass_storage_device, #endif #ifdef CONFIG_USB_MSM_OTG_72K &msm_device_otg, #ifdef CONFIG_USB_GADGET &msm_device_gadget_peripheral, #endif #endif #ifdef CONFIG_USB_ANDROID &usb_mass_storage_device, &rndis_device, #ifdef CONFIG_USB_ANDROID_DIAG &usb_diag_device, #endif &android_usb_device, #endif &qsd_device_spi, #ifdef CONFIG_I2C_SSBI &msm_device_ssbi6, &msm_device_ssbi7, #endif &android_pmem_device, &msm_fb_device, &msm_migrate_pages_device, //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 &mddi_toshiba_device, #endif //SW2-6-MM-JH-Unused_Display_Codes-00- //SW2-6-MM-JH-Display_Flag-00+ #ifdef CONFIG_FIH_LCDC_TOSHIBA_WVGA_PT &lcdc_toshiba_panel_device, #endif //SW2-6-MM-JH-Display_Flag-00- #ifdef CONFIG_MSM_ROTATOR &msm_rotator_device, #endif //SW2-6-MM-JH-Unused_Display_Codes-00+ #if 0 &lcdc_sharp_panel_device, #endif //SW2-6-MM-JH-Unused_Display_Codes-00- /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ #ifdef CONFIG_FB_MSM_HDMI_ADV7525_PANEL &hdmi_adv7525_panel_device, #endif /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ &android_pmem_kernel_ebi1_device, &android_pmem_adsp_device, &android_pmem_audio_device, &msm_device_i2c, &msm_device_i2c_2, &msm_device_uart_dm1, &hs_device, #ifdef CONFIG_MSM7KV2_AUDIO &msm_aictl_device, &msm_mi2s_device, &msm_lpa_device, &msm_aux_pcm_device, #endif &msm_device_adspdec, &qup_device_i2c, #if defined(CONFIG_MARIMBA_CORE) && \ (defined(CONFIG_MSM_BT_POWER) || defined(CONFIG_MSM_BT_POWER_MODULE)) &msm_bt_power_device, #endif // FihtdcCode@20110908 WeiChu add for WiFi porting begin // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_WLAN_POWER &bcm4329_wifi_power_device, #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +] // FIHTDC-SW2-Div6-CW-Project BCM4329 BLUETOOTH driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_BLUETOOTH_POWER &bcm4329_bt_power_device, &bcm4329_fm_power_device, #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 BLUETOOTH driver For SF8 +] // FihtdcCode@20110908 WeiChu add for WiFi porting end &msm_kgsl_3d0, #ifdef CONFIG_MSM_KGSL_2D &msm_kgsl_2d0, #endif #ifdef CONFIG_FIH_MT9P111 &msm_camera_sensor_mt9p111, #endif #ifdef CONFIG_FIH_HM0356 &msm_camera_sensor_hm0356, #endif #ifdef CONFIG_FIH_HM0357 &msm_camera_sensor_hm0357, #endif #ifdef CONFIG_FIH_TCM9001MD &msm_camera_sensor_tcm9001md, #endif #ifdef CONFIG_MT9T013 &msm_camera_sensor_mt9t013, #endif #ifdef CONFIG_MT9D112 &msm_camera_sensor_mt9d112, #endif #ifdef CONFIG_S5K3E2FX &msm_camera_sensor_s5k3e2fx, #endif #ifdef CONFIG_MT9P012 &msm_camera_sensor_mt9p012, #endif #ifdef CONFIG_MT9E013 &msm_camera_sensor_mt9e013, #endif #ifdef CONFIG_VX6953 &msm_camera_sensor_vx6953, #endif #ifdef CONFIG_SN12M0PZ &msm_camera_sensor_sn12m0pz, #endif &msm_device_vidc_720p, #ifdef CONFIG_MSM_GEMINI &msm_gemini_device, #endif #ifdef CONFIG_MSM_VPE &msm_vpe_device, #endif #if defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) &msm_device_tsif, #endif #ifdef CONFIG_MSM_SDIO_AL &msm_device_sdio_al, #endif #if defined(CONFIG_CRYPTO_DEV_QCRYPTO) || \ defined(CONFIG_CRYPTO_DEV_QCRYPTO_MODULE) &qcrypto_device, #endif #if defined(CONFIG_CRYPTO_DEV_QCEDEV) || \ defined(CONFIG_CRYPTO_DEV_QCEDEV_MODULE) &qcedev_device, #endif //SW2-D5-AriesHuang-SF4V5/SF4H8 porting keypad backlight +{ #if defined(CONFIG_FIH_PROJECT_SF4V5) || defined(CONFIG_FIH_PROJECT_SF4Y6) || defined(CONFIG_FIH_PROJECT_SF8) &msm_device_pmic_leds, #endif //SW2-D5-AriesHuang-SF4V5/SF4H8 porting keypad backlight +} &msm_batt_device, &msm_adc_device, &msm_ebi0_thermal, &msm_ebi1_thermal, #ifdef CONFIG_KEYBOARD_GPIO &gpio_buttons_device, // DIV2-SW2-BSP-FBx-BUTTONS #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 {+ #ifdef CONFIG_KEYBOARD_SF4H8 &sf8_kybd_device, #endif //FIHTDC, Port keypad, MayLi, 2011.09.21 -} #ifdef CONFIG_LEDS_FIH_FBX_PWM &fbx_leds_pwm_device, // DIV2-SW2-BSP-FBx-LEDS #endif /* FIHTDC, Div2-SW2-BSP, Peter, Audio { */ &headset_sensor_device, /* } FIHTDC, Div2-SW2-BSP, Peter, Audio */ //SW2-5-1-MP-DbgCfgTool-00+[ #ifdef CONFIG_ANDROID_RAM_CONSOLE &ram_console_device, #endif #ifdef CONFIG_FIH_LAST_ALOG &alog_ram_console_device, #endif // FihtdcCode@20110908 WeiChu add for WiFi porting begin #if defined(CONFIG_BROADCOM_BCM4329) &msm_bluesleep_device, #endif // FihtdcCode@20110908 WeiChu add for WiFi porting end //SW2-5-1-MP-DbgCftTool-00+] }; static struct msm_gpio msm_i2c_gpios_hw[] = { { GPIO_CFG(70, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "i2c_scl" }, { GPIO_CFG(71, 1, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "i2c_sda" }, }; static struct msm_gpio msm_i2c_gpios_io[] = { { GPIO_CFG(70, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "i2c_scl" }, { GPIO_CFG(71, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "i2c_sda" }, }; static struct msm_gpio qup_i2c_gpios_io[] = { { GPIO_CFG(16, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "qup_scl" }, { GPIO_CFG(17, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "qup_sda" }, }; static struct msm_gpio qup_i2c_gpios_hw[] = { { GPIO_CFG(16, 2, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "qup_scl" }, { GPIO_CFG(17, 2, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "qup_sda" }, }; static void msm_i2c_gpio_config(int adap_id, int config_type) { struct msm_gpio *msm_i2c_table; /* Each adapter gets 2 lines from the table */ if (adap_id > 0) return; if (config_type) msm_i2c_table = &msm_i2c_gpios_hw[adap_id*2]; else msm_i2c_table = &msm_i2c_gpios_io[adap_id*2]; msm_gpios_enable(msm_i2c_table, 2); } /*This needs to be enabled only for OEMS*/ #ifndef CONFIG_QUP_EXCLUSIVE_TO_CAMERA static struct vreg *qup_vreg; #endif static void qup_i2c_gpio_config(int adap_id, int config_type) { int rc = 0; struct msm_gpio *qup_i2c_table; /* Each adapter gets 2 lines from the table */ if (adap_id != 4) return; if (config_type) qup_i2c_table = qup_i2c_gpios_hw; else qup_i2c_table = qup_i2c_gpios_io; rc = msm_gpios_enable(qup_i2c_table, 2); if (rc < 0) printk(KERN_ERR "QUP GPIO enable failed: %d\n", rc); /*This needs to be enabled only for OEMS*/ #ifndef CONFIG_QUP_EXCLUSIVE_TO_CAMERA if (qup_vreg) { int rc = vreg_set_level(qup_vreg, 1800); if (rc) { pr_err("%s: vreg LVS1 set level failed (%d)\n", __func__, rc); } rc = vreg_enable(qup_vreg); if (rc) { pr_err("%s: vreg_enable() = %d \n", __func__, rc); } } #endif } static struct msm_i2c_platform_data msm_i2c_pdata = { .clk_freq = 100000, .pri_clk = 70, .pri_dat = 71, .rmutex = 1, .rsl_id = "D:I2C02000021", .msm_i2c_config_gpio = msm_i2c_gpio_config, }; /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ static void __init msm_device_i2c_power_domain(void) { struct vreg *vreg_ldo12; struct vreg *vreg_ldo8; ///i2c_gpio_power //DIV5-BSP-CH-SF6-SENSOR-PORTING00++[ //Div2D5-OwenHuang-I2C-Enable_Bus_VDDIO-00+{ #if defined(CONFIG_FIH_PROJECT_SF4Y6) || defined(CONFIG_FIH_PROJECT_SF4V5) //Div2D5-OwenHuang-SF5_ALSPS_Vreg_GP7_Setting-01* //Div2D5-OwenHuang-SF5_Reset_L8-00* struct vreg *vreg_gp7; #endif //Div2D5-OwenHuang-I2C-Enable_Bus_VDDIO-00+} //DIV5-BSP-CH-SF6-SENSOR-PORTING00++] int rc; /* 1.8V -- LDO12 */ vreg_ldo12 = vreg_get(NULL, "gp9"); if (IS_ERR(vreg_ldo12)) { pr_err("%s: gp9 vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_ldo12)); return; } rc = vreg_set_level(vreg_ldo12, 3000); if (rc) { pr_err("%s: vreg LDO12 set level failed (%d)\n", __func__, rc); return; } rc = vreg_enable(vreg_ldo12); if (rc) { pr_err("%s: LDO12 vreg enable failed (%d)\n", __func__, rc); return; } /* VDDIO 1.8V -- LDO8*/ ///i2c_gpio_power vreg_ldo8 = vreg_get(NULL, "gp7"); if (IS_ERR(vreg_ldo8)) { rc = PTR_ERR(vreg_ldo8); printk("%s: gp7 vreg get failed (%d)\n", __func__, rc); return; } rc = vreg_set_level(vreg_ldo8, 1800); if (rc) { printk("%s: vreg LDO8 set level failed (%d)\n", __func__, rc); return; } rc = vreg_enable(vreg_ldo8); if (rc) { pr_err("%s: LDO8 vreg enable failed (%d)\n", __func__, rc); return; } //DIV5-BSP-CH-SF6-SENSOR-PORTING00++[ //Div2D5-OwenHuang-I2C-Enable_Bus_VDDIO-00+{ #if defined(CONFIG_FIH_PROJECT_SF4Y6) || defined(CONFIG_FIH_PROJECT_SF4V5) //Div2D5-OwenHuang-SF5_ALSPS_Vreg_GP7_Setting-01* //Div2D5-OwenHuang-SF5_Reset_L8-00* vreg_gp7 = vreg_get(NULL, "gp7"); if (IS_ERR(vreg_gp7)) { pr_err("%s: gp7 vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_gp7)); return; } rc = vreg_set_level(vreg_gp7, 1800); if (rc) { pr_err("%s: vreg gp7 set level failed (%d)\n", __func__, rc); return; } //Div2D5-OwenHuang-SF5_Reset_L8-00-{ /*rc = vreg_enable(vreg_gp7); if (rc) { pr_err("%s: gp7 vreg enable failed (%d)\n", __func__, rc); return; }*/ //Div2D5-OwenHuang-SF5_Reset_L8-00-} vreg_pull_down_switch(vreg_gp7, 1); //Div2D5-OwenHuang-SF5_Reset_L8-00+ //Div2D5-OwenHuang-SF6_AKM8975C-Framework_Porting-04+{ //reset again to ensure light sensor can initialize successfully rc = vreg_disable(vreg_gp7); if (rc) { pr_err("%s: gp7 vreg enable failed (%d)\n", __func__, rc); return; } printk(KERN_INFO "%s, shutdown vreg_gp7\n", __func__); msleep(100); printk(KERN_INFO "%s, Power-on vreg_gp7\n", __func__); rc = vreg_enable(vreg_gp7); if (rc) { pr_err("%s: gp7 vreg enable failed (%d)\n", __func__, rc); return; } //Div2D5-OwenHuang-SF6_AKM8975C-Framework_Porting-04+} vreg_gp7 = NULL; #endif //Div2D5-OwenHuang-I2C-Enable_Bus_VDDIO-00+} //DIV5-BSP-CH-SF6-SENSOR-PORTING00++] } /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ static void __init msm_device_i2c_init(void) { if (msm_gpios_request(msm_i2c_gpios_hw, ARRAY_SIZE(msm_i2c_gpios_hw))) pr_err("failed to request I2C gpios\n"); msm_device_i2c.dev.platform_data = &msm_i2c_pdata; } static struct msm_i2c_platform_data msm_i2c_2_pdata = { .clk_freq = 100000, .rmutex = 1, .rsl_id = "D:I2C02000022", .msm_i2c_config_gpio = msm_i2c_gpio_config, }; static void __init msm_device_i2c_2_init(void) { msm_device_i2c_2.dev.platform_data = &msm_i2c_2_pdata; } static struct msm_i2c_platform_data qup_i2c_pdata = { .clk_freq = 384000, .pclk = "camif_pad_pclk", .msm_i2c_config_gpio = qup_i2c_gpio_config, }; static void __init qup_device_i2c_init(void) { if (msm_gpios_request(qup_i2c_gpios_hw, ARRAY_SIZE(qup_i2c_gpios_hw))) pr_err("failed to request I2C gpios\n"); qup_device_i2c.dev.platform_data = &qup_i2c_pdata; /*This needs to be enabled only for OEMS*/ #ifndef CONFIG_QUP_EXCLUSIVE_TO_CAMERA qup_vreg = vreg_get(NULL, "lvsw1"); if (IS_ERR(qup_vreg)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(qup_vreg)); } #endif } #ifdef CONFIG_I2C_SSBI static struct msm_ssbi_platform_data msm_i2c_ssbi6_pdata = { .rsl_id = "D:PMIC_SSBI", .controller_type = MSM_SBI_CTRL_SSBI2, }; static struct msm_ssbi_platform_data msm_i2c_ssbi7_pdata = { .rsl_id = "D:CODEC_SSBI", .controller_type = MSM_SBI_CTRL_SSBI, }; #endif static struct msm_acpu_clock_platform_data msm7x30_clock_data = { .acpu_switch_time_us = 50, .vdd_switch_time_us = 62, }; static void __init msm7x30_init_irq(void) { msm_init_irq(); } static struct msm_gpio msm_nand_ebi2_cfg_data[] = { {GPIO_CFG(86, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "ebi2_cs1"}, {GPIO_CFG(115, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "ebi2_busy1"}, }; struct vreg *vreg_s3; struct vreg *vreg_mmc; #if (defined(CONFIG_MMC_MSM_SDC1_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC2_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC3_SUPPORT)\ || defined(CONFIG_MMC_MSM_SDC4_SUPPORT)) struct sdcc_gpio { struct msm_gpio *cfg_data; uint32_t size; struct msm_gpio *sleep_cfg_data; }; #if defined(CONFIG_MMC_MSM_SDC1_SUPPORT) static struct msm_gpio sdc1_lvlshft_cfg_data[] = { {GPIO_CFG(35, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_16MA), "sdc1_lvlshft"}, }; #endif static struct msm_gpio sdc1_cfg_data[] = { {GPIO_CFG(38, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "sdc1_clk"}, #ifndef CONFIG_FIH_AAT1272 {GPIO_CFG(39, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_cmd"}, #endif {GPIO_CFG(39, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_cmd"}, {GPIO_CFG(40, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_dat_3"}, {GPIO_CFG(41, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_dat_2"}, {GPIO_CFG(42, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_dat_1"}, {GPIO_CFG(43, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc1_dat_0"}, }; static struct msm_gpio sdc2_cfg_data[] = { {GPIO_CFG(64, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "sdc2_clk"}, {GPIO_CFG(65, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_cmd"}, {GPIO_CFG(66, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_3"}, {GPIO_CFG(67, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_2"}, {GPIO_CFG(68, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_1"}, {GPIO_CFG(69, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_0"}, #ifdef CONFIG_MMC_MSM_SDC2_8_BIT_SUPPORT {GPIO_CFG(115, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_4"}, {GPIO_CFG(114, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_5"}, {GPIO_CFG(113, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_6"}, {GPIO_CFG(112, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc2_dat_7"}, #endif }; static struct msm_gpio sdc3_cfg_data[] = { {GPIO_CFG(110, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "sdc3_clk"}, {GPIO_CFG(111, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_cmd"}, {GPIO_CFG(116, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_dat_3"}, {GPIO_CFG(117, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_dat_2"}, {GPIO_CFG(118, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_dat_1"}, {GPIO_CFG(119, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc3_dat_0"}, }; static struct msm_gpio sdc3_sleep_cfg_data[] = { {GPIO_CFG(110, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_clk"}, {GPIO_CFG(111, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_cmd"}, {GPIO_CFG(116, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_dat_3"}, {GPIO_CFG(117, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_dat_2"}, {GPIO_CFG(118, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_dat_1"}, {GPIO_CFG(119, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "sdc3_dat_0"}, }; static struct msm_gpio sdc4_cfg_data[] = { {GPIO_CFG(58, 1, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "sdc4_clk"}, {GPIO_CFG(59, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_cmd"}, {GPIO_CFG(60, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_dat_3"}, {GPIO_CFG(61, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_dat_2"}, {GPIO_CFG(62, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_dat_1"}, {GPIO_CFG(63, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA), "sdc4_dat_0"}, }; static struct sdcc_gpio sdcc_cfg_data[] = { { .cfg_data = sdc1_cfg_data, .size = ARRAY_SIZE(sdc1_cfg_data), .sleep_cfg_data = NULL, }, { .cfg_data = sdc2_cfg_data, .size = ARRAY_SIZE(sdc2_cfg_data), .sleep_cfg_data = NULL, }, { .cfg_data = sdc3_cfg_data, .size = ARRAY_SIZE(sdc3_cfg_data), .sleep_cfg_data = sdc3_sleep_cfg_data, }, { .cfg_data = sdc4_cfg_data, .size = ARRAY_SIZE(sdc4_cfg_data), .sleep_cfg_data = NULL, }, }; struct sdcc_vreg { struct vreg *vreg_data; unsigned level; }; static struct sdcc_vreg sdcc_vreg_data[4]; static unsigned long vreg_sts, gpio_sts; static uint32_t msm_sdcc_setup_gpio(int dev_id, unsigned int enable) { int rc = 0; struct sdcc_gpio *curr; curr = &sdcc_cfg_data[dev_id - 1]; if (!(test_bit(dev_id, &gpio_sts)^enable)) return rc; if (enable) { set_bit(dev_id, &gpio_sts); rc = msm_gpios_request_enable(curr->cfg_data, curr->size); if (rc) printk(KERN_ERR "%s: Failed to turn on GPIOs for slot %d\n", __func__, dev_id); } else { clear_bit(dev_id, &gpio_sts); if (curr->sleep_cfg_data) { msm_gpios_enable(curr->sleep_cfg_data, curr->size); msm_gpios_free(curr->sleep_cfg_data, curr->size); } else { msm_gpios_disable_free(curr->cfg_data, curr->size); } } return rc; } static uint32_t msm_sdcc_setup_vreg(int dev_id, unsigned int enable) { int rc = 0; struct sdcc_vreg *curr; static int enabled_once[] = {0, 0, 0, 0}; curr = &sdcc_vreg_data[dev_id - 1]; if (!(test_bit(dev_id, &vreg_sts)^enable)) return rc; if (!enable || enabled_once[dev_id - 1]) return 0; if (enable) { set_bit(dev_id, &vreg_sts); rc = vreg_set_level(curr->vreg_data, curr->level); if (rc) { printk(KERN_ERR "%s: vreg_set_level() = %d \n", __func__, rc); } rc = vreg_enable(curr->vreg_data); if (rc) { printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); } enabled_once[dev_id - 1] = 1; } else { clear_bit(dev_id, &vreg_sts); rc = vreg_disable(curr->vreg_data); if (rc) { printk(KERN_ERR "%s: vreg_disable() = %d \n", __func__, rc); } } return rc; } static uint32_t msm_sdcc_setup_power(struct device *dv, unsigned int vdd) { int rc = 0; struct platform_device *pdev; pdev = container_of(dv, struct platform_device, dev); rc = msm_sdcc_setup_gpio(pdev->id, (vdd ? 1 : 0)); if (rc) goto out; if (pdev->id == 4) /* S3 is always ON and cannot be disabled */ rc = msm_sdcc_setup_vreg(pdev->id, (vdd ? 1 : 0)); out: return rc; } #if defined(CONFIG_MMC_MSM_SDC1_SUPPORT) && \ defined(CONFIG_CSDIO_VENDOR_ID) && \ defined(CONFIG_CSDIO_DEVICE_ID) && \ (CONFIG_CSDIO_VENDOR_ID == 0x70 && CONFIG_CSDIO_DEVICE_ID == 0x1117) #define MBP_ON 1 #define MBP_OFF 0 #define MBP_RESET_N \ GPIO_CFG(44, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_8MA) #define MBP_INT0 \ GPIO_CFG(46, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_8MA) #define MBP_MODE_CTRL_0 \ GPIO_CFG(35, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) #define MBP_MODE_CTRL_1 \ GPIO_CFG(36, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) #define MBP_MODE_CTRL_2 \ GPIO_CFG(34, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA) #define TSIF_EN \ GPIO_CFG(35, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_DATA \ GPIO_CFG(36, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_CLK \ GPIO_CFG(34, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) static struct msm_gpio mbp_cfg_data[] = { {GPIO_CFG(44, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "mbp_reset"}, {GPIO_CFG(85, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_16MA), "mbp_io_voltage"}, }; static int mbp_config_gpios_pre_init(int enable) { int rc = 0; if (enable) { rc = msm_gpios_request_enable(mbp_cfg_data, ARRAY_SIZE(mbp_cfg_data)); if (rc) { printk(KERN_ERR "%s: Failed to turnon GPIOs for mbp chip(%d)\n", __func__, rc); } } else msm_gpios_disable_free(mbp_cfg_data, ARRAY_SIZE(mbp_cfg_data)); return rc; } static int mbp_setup_rf_vregs(int state) { struct vreg *vreg_rf = NULL; struct vreg *vreg_rf_switch = NULL; int rc; vreg_rf = vreg_get(NULL, "s2"); if (IS_ERR(vreg_rf)) { pr_err("%s: s2 vreg get failed (%ld)", __func__, PTR_ERR(vreg_rf)); return -EFAULT; } vreg_rf_switch = vreg_get(NULL, "rf"); if (IS_ERR(vreg_rf_switch)) { pr_err("%s: rf vreg get failed (%ld)", __func__, PTR_ERR(vreg_rf_switch)); return -EFAULT; } if (state) { rc = vreg_set_level(vreg_rf, 1300); if (rc) { pr_err("%s: vreg s2 set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_rf); if (rc) { printk(KERN_ERR "%s: vreg_enable(s2) = %d\n", __func__, rc); } rc = vreg_set_level(vreg_rf_switch, 2600); if (rc) { pr_err("%s: vreg rf switch set level failed (%d)\n", __func__, rc); return rc; } rc = vreg_enable(vreg_rf_switch); if (rc) { printk(KERN_ERR "%s: vreg_enable(rf) = %d\n", __func__, rc); } } else { (void) vreg_disable(vreg_rf); (void) vreg_disable(vreg_rf_switch); } return 0; } static int mbp_setup_vregs(int state) { struct vreg *vreg_analog = NULL; struct vreg *vreg_io = NULL; int rc; vreg_analog = vreg_get(NULL, "gp4"); if (IS_ERR(vreg_analog)) { pr_err("%s: gp4 vreg get failed (%ld)", __func__, PTR_ERR(vreg_analog)); return -EFAULT; } vreg_io = vreg_get(NULL, "s3"); if (IS_ERR(vreg_io)) { pr_err("%s: s3 vreg get failed (%ld)", __func__, PTR_ERR(vreg_io)); return -EFAULT; } if (state) { rc = vreg_set_level(vreg_analog, 2600); if (rc) { pr_err("%s: vreg_set_level failed (%d)", __func__, rc); } rc = vreg_enable(vreg_analog); if (rc) { pr_err("%s: analog vreg enable failed (%d)", __func__, rc); } rc = vreg_set_level(vreg_io, 1800); if (rc) { pr_err("%s: vreg_set_level failed (%d)", __func__, rc); } rc = vreg_enable(vreg_io); if (rc) { pr_err("%s: io vreg enable failed (%d)", __func__, rc); } } else { rc = vreg_disable(vreg_analog); if (rc) { pr_err("%s: analog vreg disable failed (%d)", __func__, rc); } rc = vreg_disable(vreg_io); if (rc) { pr_err("%s: io vreg disable failed (%d)", __func__, rc); } } return rc; } static int mbp_set_tcxo_en(int enable) { int rc; const char *id = "UBMC"; struct vreg *vreg_analog = NULL; rc = pmapp_clock_vote(id, PMAPP_CLOCK_ID_A1, enable ? PMAPP_CLOCK_VOTE_ON : PMAPP_CLOCK_VOTE_OFF); if (rc < 0) { printk(KERN_ERR "%s: unable to %svote for a1 clk\n", __func__, enable ? "" : "de-"); return -EIO; } if (!enable) { vreg_analog = vreg_get(NULL, "gp4"); if (IS_ERR(vreg_analog)) { pr_err("%s: gp4 vreg get failed (%ld)", __func__, PTR_ERR(vreg_analog)); return -EFAULT; } (void) vreg_disable(vreg_analog); } return rc; } static void mbp_set_freeze_io(int state) { if (state) gpio_set_value(85, 0); else gpio_set_value(85, 1); } static int mbp_set_core_voltage_en(int enable) { int rc; struct vreg *vreg_core1p2 = NULL; vreg_core1p2 = vreg_get(NULL, "gp16"); if (IS_ERR(vreg_core1p2)) { pr_err("%s: gp16 vreg get failed (%ld)", __func__, PTR_ERR(vreg_core1p2)); return -EFAULT; } if (enable) { rc = vreg_set_level(vreg_core1p2, 1200); if (rc) { pr_err("%s: vreg_set_level failed (%d)", __func__, rc); } (void) vreg_enable(vreg_core1p2); return 80; } else { gpio_set_value(85, 1); return 0; } return rc; } static void mbp_set_reset(int state) { if (state) gpio_set_value(GPIO_PIN(MBP_RESET_N), 0); else gpio_set_value(GPIO_PIN(MBP_RESET_N), 1); } static int mbp_config_interface_mode(int state) { if (state) { gpio_tlmm_config(MBP_MODE_CTRL_0, GPIO_CFG_ENABLE); gpio_tlmm_config(MBP_MODE_CTRL_1, GPIO_CFG_ENABLE); gpio_tlmm_config(MBP_MODE_CTRL_2, GPIO_CFG_ENABLE); gpio_set_value(GPIO_PIN(MBP_MODE_CTRL_0), 0); gpio_set_value(GPIO_PIN(MBP_MODE_CTRL_1), 1); gpio_set_value(GPIO_PIN(MBP_MODE_CTRL_2), 0); } else { gpio_tlmm_config(MBP_MODE_CTRL_0, GPIO_CFG_DISABLE); gpio_tlmm_config(MBP_MODE_CTRL_1, GPIO_CFG_DISABLE); gpio_tlmm_config(MBP_MODE_CTRL_2, GPIO_CFG_DISABLE); } return 0; } static int mbp_setup_adc_vregs(int state) { struct vreg *vreg_adc = NULL; int rc; vreg_adc = vreg_get(NULL, "s4"); if (IS_ERR(vreg_adc)) { pr_err("%s: s4 vreg get failed (%ld)", __func__, PTR_ERR(vreg_adc)); return -EFAULT; } if (state) { rc = vreg_set_level(vreg_adc, 2200); if (rc) { pr_err("%s: vreg_set_level failed (%d)", __func__, rc); } rc = vreg_enable(vreg_adc); if (rc) { pr_err("%s: enable vreg adc failed (%d)", __func__, rc); } } else { rc = vreg_disable(vreg_adc); if (rc) { pr_err("%s: disable vreg adc failed (%d)", __func__, rc); } } return rc; } static int mbp_power_up(void) { int rc; rc = mbp_config_gpios_pre_init(MBP_ON); if (rc) goto exit; pr_debug("%s: mbp_config_gpios_pre_init() done\n", __func__); rc = mbp_setup_vregs(MBP_ON); if (rc) goto exit; pr_debug("%s: gp4 (2.6) and s3 (1.8) done\n", __func__); rc = mbp_set_tcxo_en(MBP_ON); if (rc) goto exit; pr_debug("%s: tcxo clock done\n", __func__); mbp_set_freeze_io(MBP_OFF); pr_debug("%s: set gpio 85 to 1 done\n", __func__); udelay(100); mbp_set_reset(MBP_ON); udelay(300); rc = mbp_config_interface_mode(MBP_ON); if (rc) goto exit; pr_debug("%s: mbp_config_interface_mode() done\n", __func__); udelay(100 + mbp_set_core_voltage_en(MBP_ON)); pr_debug("%s: power gp16 1.2V done\n", __func__); mbp_set_freeze_io(MBP_ON); pr_debug("%s: set gpio 85 to 0 done\n", __func__); udelay(100); rc = mbp_setup_rf_vregs(MBP_ON); if (rc) goto exit; pr_debug("%s: s2 1.3V and rf 2.6V done\n", __func__); rc = mbp_setup_adc_vregs(MBP_ON); if (rc) goto exit; pr_debug("%s: s4 2.2V done\n", __func__); udelay(200); mbp_set_reset(MBP_OFF); pr_debug("%s: close gpio 44 done\n", __func__); msleep(20); exit: return rc; } static int mbp_power_down(void) { int rc; struct vreg *vreg_adc = NULL; vreg_adc = vreg_get(NULL, "s4"); if (IS_ERR(vreg_adc)) { pr_err("%s: s4 vreg get failed (%ld)", __func__, PTR_ERR(vreg_adc)); return -EFAULT; } mbp_set_reset(MBP_ON); pr_debug("%s: mbp_set_reset(MBP_ON) done\n", __func__); udelay(100); rc = mbp_setup_adc_vregs(MBP_OFF); if (rc) goto exit; pr_debug("%s: vreg_disable(vreg_adc) done\n", __func__); udelay(5); rc = mbp_setup_rf_vregs(MBP_OFF); if (rc) goto exit; pr_debug("%s: mbp_setup_rf_vregs(MBP_OFF) done\n", __func__); udelay(5); mbp_set_freeze_io(MBP_OFF); pr_debug("%s: mbp_set_freeze_io(MBP_OFF) done\n", __func__); udelay(100); rc = mbp_set_core_voltage_en(MBP_OFF); if (rc) goto exit; pr_debug("%s: mbp_set_core_voltage_en(MBP_OFF) done\n", __func__); gpio_set_value(85, 1); rc = mbp_set_tcxo_en(MBP_OFF); if (rc) goto exit; pr_debug("%s: mbp_set_tcxo_en(MBP_OFF) done\n", __func__); rc = mbp_config_gpios_pre_init(MBP_OFF); if (rc) goto exit; exit: return rc; } static void (*mbp_status_notify_cb)(int card_present, void *dev_id); static void *mbp_status_notify_cb_devid; static int mbp_power_status; static int mbp_power_init_done; static uint32_t mbp_setup_power(struct device *dv, unsigned int power_status) { int rc = 0; struct platform_device *pdev; pdev = container_of(dv, struct platform_device, dev); if (power_status == mbp_power_status) goto exit; if (power_status) { pr_debug("turn on power of mbp slot"); rc = mbp_power_up(); mbp_power_status = 1; } else { pr_debug("turn off power of mbp slot"); rc = mbp_power_down(); mbp_power_status = 0; } exit: return rc; }; int mbp_register_status_notify(void (*callback)(int, void *), void *dev_id) { mbp_status_notify_cb = callback; mbp_status_notify_cb_devid = dev_id; return 0; } static unsigned int mbp_status(struct device *dev) { return mbp_power_status; } static uint32_t msm_sdcc_setup_power_mbp(struct device *dv, unsigned int vdd) { struct platform_device *pdev; uint32_t rc = 0; pdev = container_of(dv, struct platform_device, dev); rc = msm_sdcc_setup_power(dv, vdd); if (rc) { pr_err("%s: Failed to setup power (%d)\n", __func__, rc); goto out; } if (!mbp_power_init_done) { mbp_setup_power(dv, 1); mbp_setup_power(dv, 0); mbp_power_init_done = 1; } if (vdd >= 0x8000) { rc = mbp_setup_power(dv, (0x8000 == vdd) ? 0 : 1); if (rc) { pr_err("%s: Failed to config mbp chip power (%d)\n", __func__, rc); goto out; } if (mbp_status_notify_cb) { mbp_status_notify_cb(mbp_power_status, mbp_status_notify_cb_devid); } } out: /* should return 0 only */ return 0; } #endif #endif #ifdef CONFIG_MMC_MSM_SDC4_SUPPORT #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION static unsigned int msm7x30_sdcc_slot_status(struct device *dev) { return (unsigned int)!gpio_get_value(sd_detect_pin); } #endif static void msm_sdcc_sdio_lpm_gpio(struct device *dv, unsigned int active) { pr_debug("%s not implemented\n", __func__); } static int msm_sdcc_get_wpswitch(struct device *dv) { void __iomem *wp_addr = 0; uint32_t ret = 0; struct platform_device *pdev; if (!(machine_is_msm7x30_surf())) return -1; pdev = container_of(dv, struct platform_device, dev); wp_addr = ioremap(FPGA_SDCC_STATUS, 4); if (!wp_addr) { pr_err("%s: Could not remap %x\n", __func__, FPGA_SDCC_STATUS); return -ENOMEM; } ret = (((readl(wp_addr) >> 4) >> (pdev->id-1)) & 0x01); pr_info("%s: WP Status for Slot %d = 0x%x \n", __func__, pdev->id, ret); iounmap(wp_addr); return ret; } #endif #if defined(CONFIG_MMC_MSM_SDC1_SUPPORT) #if defined(CONFIG_CSDIO_VENDOR_ID) && \ defined(CONFIG_CSDIO_DEVICE_ID) && \ (CONFIG_CSDIO_VENDOR_ID == 0x70 && CONFIG_CSDIO_DEVICE_ID == 0x1117) static struct mmc_platform_data msm7x30_sdc1_data = { .ocr_mask = MMC_VDD_165_195 | MMC_VDD_27_28 | MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power_mbp, .mmc_bus_width = MMC_CAP_4_BIT_DATA, .status = mbp_status, .register_status_notify = mbp_register_status_notify, #ifdef CONFIG_MMC_MSM_SDC1_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 24576000, .nonremovable = 0, }; #else static struct mmc_platform_data msm7x30_sdc1_data = { .ocr_mask = MMC_VDD_165_195, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, #ifdef CONFIG_MMC_MSM_SDC1_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 0, }; #endif #endif #ifdef CONFIG_MMC_MSM_SDC2_SUPPORT static struct mmc_platform_data msm7x30_sdc2_data = { .ocr_mask = MMC_VDD_165_195 | MMC_VDD_27_28, .translate_vdd = msm_sdcc_setup_power, #ifdef CONFIG_MMC_MSM_SDC2_8_BIT_SUPPORT .mmc_bus_width = MMC_CAP_8_BIT_DATA, #else .mmc_bus_width = MMC_CAP_4_BIT_DATA, #endif #ifdef CONFIG_MMC_MSM_SDC2_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 1, }; #endif #ifdef CONFIG_MMC_MSM_SDC3_SUPPORT static struct mmc_platform_data msm7x30_sdc3_data = { .ocr_mask = MMC_VDD_27_28 | MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT .sdiowakeup_irq = MSM_GPIO_TO_INT(118), #endif #ifdef CONFIG_MMC_MSM_SDC3_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 0, }; #endif #ifdef CONFIG_MMC_MSM_SDC4_SUPPORT static struct mmc_platform_data msm7x30_sdc4_data = { .ocr_mask = MMC_VDD_27_28 | MMC_VDD_28_29, .translate_vdd = msm_sdcc_setup_power, .mmc_bus_width = MMC_CAP_4_BIT_DATA, #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION .status = msm7x30_sdcc_slot_status, .status_irq = PM8058_GPIO_IRQ(PMIC8058_IRQ_BASE, PMIC_GPIO_SD_DET - 1), .irq_flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, #endif .wpswitch = msm_sdcc_get_wpswitch, #ifdef CONFIG_MMC_MSM_SDC4_DUMMY52_REQUIRED .dummy52_required = 1, #endif .msmsdcc_fmin = 144000, .msmsdcc_fmid = 24576000, .msmsdcc_fmax = 49152000, .nonremovable = 0, }; #endif #ifdef CONFIG_MMC_MSM_SDC1_SUPPORT static void msm_sdc1_lvlshft_enable(void) { int rc; /* Enable LDO5, an input to the FET that powers slot 1 */ rc = vreg_set_level(vreg_mmc, 2850); if (rc) printk(KERN_ERR "%s: vreg_set_level() = %d \n", __func__, rc); rc = vreg_enable(vreg_mmc); if (rc) printk(KERN_ERR "%s: vreg_enable() = %d \n", __func__, rc); /* Enable GPIO 35, to turn on the FET that powers slot 1 */ rc = msm_gpios_request_enable(sdc1_lvlshft_cfg_data, ARRAY_SIZE(sdc1_lvlshft_cfg_data)); if (rc) printk(KERN_ERR "%s: Failed to enable GPIO 35\n", __func__); rc = gpio_direction_output(GPIO_PIN(sdc1_lvlshft_cfg_data[0].gpio_cfg), 1); if (rc) printk(KERN_ERR "%s: Failed to turn on GPIO 35\n", __func__); } #endif /* FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized { */ #ifdef CONFIG_FIH_FXX #include <linux/ctype.h> //Div6D1-JL-FixWrongID #include "proc_comm.h" #define NV_PRD_ID_I 50001 #define NV_FIH_USB_DEVICE_CUSTOMER_I 50034 int fih_usb_full_func = 0xC000; struct usb_device_custom_nv { uint32_t magic_num; uint16_t vendor_id; uint16_t product_id; char product_name[32]; char manufacturer_name[32]; char reserved[52]; }; static int sync_from_custom_nv(void) { uint32_t smem_proc_comm_oem_cmd1 = PCOM_CUSTOMER_CMD1; uint32_t smem_proc_comm_oem_data1 = SMEM_PROC_COMM_OEM_NV_READ; uint32_t smem_proc_comm_oem_data2 = NV_PRD_ID_I; uint32_t product_id[32]; char serial_number[32]; struct usb_device_custom_nv usb_product;//Div2-5-3-Peripheral-LL-UsbCustomized-00+ struct smem_host_oem_info *usb_type_info = NULL; unsigned int info_size; int len = 0; int i; char *src; char *k_serial; usb_type_info = smem_get_entry(SMEM_ID_VENDOR2, &info_size); if(usb_type_info) { android_usb_pdata.product_id = usb_type_info->host_usb_id; } if(msm_proc_comm_oem(smem_proc_comm_oem_cmd1, &smem_proc_comm_oem_data1, product_id, &smem_proc_comm_oem_data2) == 0) { memcpy(serial_number, product_id, sizeof(serial_number)); len = strlen(serial_number); if(len > 0) { //strlcpy(serial_number, (char*)product_id, sizeof(serial_number)); printk(KERN_INFO"%s: read serial number (%s)\n",__func__, serial_number); src = serial_number; //eliminate space char from string start index while(isspace(*src)) { src++; } k_serial = (char*)kzalloc(16, GFP_KERNEL); strlcpy(k_serial, src, 16+1); src = k_serial; //end of non alpha and number character while(isalnum(*src)) { src++; } *src = '\0'; if(strlen(k_serial)){ android_usb_pdata.serial_number = k_serial; } } } src = android_usb_pdata.serial_number; rndis_pdata.ethaddr[0] = 0x02; for (i = 0; *src; i++) { /* XOR the USB serial across the remaining bytes */ rndis_pdata.ethaddr[i % (ETH_ALEN - 1) + 1] ^= *src++; } //Div2-5-3-Peripheral-LL-UsbCustomized-01*{ smem_proc_comm_oem_data2 = NV_FIH_USB_DEVICE_CUSTOMER_I; if(msm_proc_comm_oem(smem_proc_comm_oem_cmd1, &smem_proc_comm_oem_data1, product_id, &smem_proc_comm_oem_data2) == 0) { memcpy(&usb_product, product_id, sizeof(usb_product)); printk(KERN_INFO"%s: USB MAGIC NUMBER (%d)", __func__, usb_product.magic_num); if(usb_product.magic_num == 0x12345678) {//magic number must be 0x12345678 could be effective printk(KERN_INFO"%s: USB CUSTOMIZED VID(0X%X) PID(0X%X) PRODUCT(%s) MANUFACTURER(%s)\n", __func__, usb_product.vendor_id, usb_product.product_id, usb_product.product_name, usb_product.manufacturer_name); if(usb_product.vendor_id && usb_product.product_id) { android_usb_pdata.vendor_id = usb_product.vendor_id; if(android_usb_pdata.vendor_id == 0x12d1) {//huawei fih_usb_full_func = 0x1021;//open all usb functions android_usb_pdata.num_products = ARRAY_SIZE(usb_products_12d1); android_usb_pdata.products = usb_products_12d1; if(android_usb_pdata.product_id == 0xc002) {//recovery mode android_usb_pdata.product_id = 0x1022; } else if(android_usb_pdata.product_id == 0xc000) {//diag debug mode enable android_usb_pdata.product_id = 0x1021; } else { android_usb_pdata.product_id = usb_product.product_id; } } } if(strlen(usb_product.product_name)) { k_serial = (char*)kzalloc(32, GFP_KERNEL); strlcpy(k_serial, usb_product.product_name, sizeof(usb_product.product_name)); src = k_serial; while(isalnum(*src)||isspace(*src)) { src++; } *src = '\0'; if(strlen(k_serial)) { android_usb_pdata.product_name = k_serial; } } if(strlen(usb_product.manufacturer_name)) { k_serial = (char*)kzalloc(32, GFP_KERNEL); strlcpy(k_serial, usb_product.manufacturer_name, sizeof(usb_product.manufacturer_name)); src = k_serial; while(isalnum(*src)||isspace(*src)) { src++; } *src = '\0'; if(strlen(k_serial)) { android_usb_pdata.manufacturer_name = k_serial; rndis_pdata.vendorDescr = k_serial; mass_storage_pdata.vendor = k_serial; } } } } #ifdef CONFIG_FIH_FTM if(android_usb_pdata.vendor_id == 0x12d1) {//Huawei android_usb_pdata.product_id = 0x1023; } else if(android_usb_pdata.vendor_id == 0x489) {//FIH android_usb_pdata.product_id = 0xc003; } android_usb_pdata.serial_number = 0; //set serial number NULL #endif printk(KERN_INFO"%s: USB VID(0x%X) PID(0x%X) PRODUCT(%s) MANUFACTURER(%s) SN(%s)\n", __func__, android_usb_pdata.vendor_id, android_usb_pdata.product_id, android_usb_pdata.product_name, android_usb_pdata.manufacturer_name, android_usb_pdata.serial_number); //Div2-5-3-Peripheral-LL-UsbCustomized-01*} return 1; } #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized */ static void __init msm7x30_init_mmc(void) { vreg_s3 = vreg_get(NULL, "s3"); if (IS_ERR(vreg_s3)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_s3)); return; } vreg_mmc = vreg_get(NULL, "mmc"); if (IS_ERR(vreg_mmc)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_mmc)); return; } #ifdef CONFIG_MMC_MSM_SDC1_SUPPORT if (machine_is_msm7x30_fluid()) { msm7x30_sdc1_data.ocr_mask = MMC_VDD_27_28 | MMC_VDD_28_29; msm_sdc1_lvlshft_enable(); } sdcc_vreg_data[0].vreg_data = vreg_s3; sdcc_vreg_data[0].level = 1800; msm_add_sdcc(1, &msm7x30_sdc1_data); #endif #ifdef CONFIG_MMC_MSM_SDC2_SUPPORT if (machine_is_msm8x55_svlte_surf()) msm7x30_sdc2_data.msmsdcc_fmax = 24576000; if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { msm7x30_sdc2_data.sdio_lpm_gpio_setup = msm_sdcc_sdio_lpm_gpio; #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT msm7x30_sdc2_data.sdiowakeup_irq = MSM_GPIO_TO_INT(68); #ifdef CONFIG_MSM_SDIO_AL msm7x30_sdc2_data.is_sdio_al_client = 1; #endif #endif } sdcc_vreg_data[1].vreg_data = vreg_s3; sdcc_vreg_data[1].level = 1800; msm_add_sdcc(2, &msm7x30_sdc2_data); #endif #ifdef CONFIG_MMC_MSM_SDC3_SUPPORT sdcc_vreg_data[2].vreg_data = vreg_s3; sdcc_vreg_data[2].level = 1800; msm_sdcc_setup_gpio(3, 1); msm_add_sdcc(3, &msm7x30_sdc3_data); #endif #ifdef CONFIG_MMC_MSM_SDC4_SUPPORT sdcc_vreg_data[3].vreg_data = vreg_mmc; sdcc_vreg_data[3].level = 2850; #ifdef CONFIG_MMC_MSM_CARD_HW_DETECTION switch(fih_get_product_id()) { case Product_FB0: { if(fih_get_product_phase() ==Product_PR1) sd_detect_pin = 38; else sd_detect_pin = 142; } break; case Product_FB1: case Product_FB3: case Product_FD1: { sd_detect_pin = 142; } break; case Product_SF6: { if(fih_get_product_phase() ==Product_PR3 || fih_get_product_phase() == Product_PCR) sd_detect_pin = 143; else sd_detect_pin = 142; } break; case Product_SFH: { sd_detect_pin = 142; } break; case Product_SF8: case Product_SH8: case Product_SFC: { sd_detect_pin = 0; } break; default: sd_detect_pin = 142; break; } if(sd_detect_pin) { gpio_tlmm_config(GPIO_CFG(sd_detect_pin, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA), GPIO_CFG_ENABLE); msm7x30_sdc4_data.status_irq = MSM_GPIO_TO_INT(sd_detect_pin); } else { msm7x30_sdc4_data.status = NULL; msm7x30_sdc4_data.status_irq = 0; } #endif switch(fih_get_product_id()) { case Product_FB0: case Product_FB1: case Product_FB3: case Product_SF6: case Product_FD1: { sd_enable_pin = 85; } break; case Product_SF5: { sd_enable_pin = 100; } break; case Product_SF8: case Product_SFH: case Product_SH8: case Product_SFC: { sd_enable_pin = 175; } break; default: sd_enable_pin = 85; break; } gpio_tlmm_config(GPIO_CFG(sd_enable_pin, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); printk("[SD] id:%d, phase:%d, sd_enable_pin:%d, sd_detect_pin:%d\n", fih_get_product_id(), fih_get_product_phase(), sd_enable_pin, sd_detect_pin); msm_add_sdcc(4, &msm7x30_sdc4_data); #endif } static void __init msm7x30_init_nand(void) { char *build_id; struct flash_platform_data *plat_data; build_id = socinfo_get_build_id(); if (build_id == NULL) { pr_err("%s: Build ID not available from socinfo\n", __func__); return; } if (build_id[8] == 'C' && !msm_gpios_request_enable(msm_nand_ebi2_cfg_data, ARRAY_SIZE(msm_nand_ebi2_cfg_data))) { plat_data = msm_device_nand.dev.platform_data; plat_data->interleave = 1; printk(KERN_INFO "%s: Interleave mode Build ID found\n", __func__); } } #ifdef CONFIG_SERIAL_MSM_CONSOLE static struct msm_gpio uart2_config_data[] = { { GPIO_CFG(49, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART2_RFR"}, //{ GPIO_CFG(50, 2, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART2_CTS"}, { GPIO_CFG(51, 2, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART2_Rx"}, { GPIO_CFG(52, 2, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), "UART2_Tx"}, }; static void msm7x30_init_uart2(void) { msm_gpios_request_enable(uart2_config_data, ARRAY_SIZE(uart2_config_data)); } #endif /* TSIF begin */ #if defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) #define TSIF_B_SYNC GPIO_CFG(37, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_B_DATA GPIO_CFG(36, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_B_EN GPIO_CFG(35, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define TSIF_B_CLK GPIO_CFG(34, 1, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) static const struct msm_gpio tsif_gpios[] = { { .gpio_cfg = TSIF_B_CLK, .label = "tsif_clk", }, { .gpio_cfg = TSIF_B_EN, .label = "tsif_en", }, { .gpio_cfg = TSIF_B_DATA, .label = "tsif_data", }, { .gpio_cfg = TSIF_B_SYNC, .label = "tsif_sync", }, }; static struct msm_tsif_platform_data tsif_platform_data = { .num_gpios = ARRAY_SIZE(tsif_gpios), .gpios = tsif_gpios, .tsif_pclk = "tsif_pclk", .tsif_ref_clk = "tsif_ref_clk", }; #endif /* defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) */ /* TSIF end */ #ifdef CONFIG_LEDS_PM8058 static void __init pmic8058_leds_init(void) { if (machine_is_msm7x30_surf()) { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].platform_data = &pm8058_surf_leds_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].data_size = sizeof(pm8058_surf_leds_data); } else if (!machine_is_msm7x30_fluid()) { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].platform_data = &pm8058_ffa_leds_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].data_size = sizeof(pm8058_ffa_leds_data); } else if (machine_is_msm7x30_fluid()) { pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].platform_data = &pm8058_fluid_leds_data; pm8058_7x30_data.sub_devices[PM8058_SUBDEV_LED].data_size = sizeof(pm8058_fluid_leds_data); } } #endif static struct msm_spm_platform_data msm_spm_data __initdata = { .reg_base_addr = MSM_SAW_BASE, .reg_init_values[MSM_SPM_REG_SAW_CFG] = 0x05, .reg_init_values[MSM_SPM_REG_SAW_SPM_CTL] = 0x18, .reg_init_values[MSM_SPM_REG_SAW_SPM_SLP_TMR_DLY] = 0x00006666, .reg_init_values[MSM_SPM_REG_SAW_SPM_WAKE_TMR_DLY] = 0xFF000666, .reg_init_values[MSM_SPM_REG_SAW_SLP_CLK_EN] = 0x01, .reg_init_values[MSM_SPM_REG_SAW_SLP_HSFS_PRECLMP_EN] = 0x03, .reg_init_values[MSM_SPM_REG_SAW_SLP_HSFS_POSTCLMP_EN] = 0x00, .reg_init_values[MSM_SPM_REG_SAW_SLP_CLMP_EN] = 0x01, .reg_init_values[MSM_SPM_REG_SAW_SLP_RST_EN] = 0x00, .reg_init_values[MSM_SPM_REG_SAW_SPM_MPM_CFG] = 0x00, .awake_vlevel = 0xF2, .retention_vlevel = 0xE0, .collapse_vlevel = 0x72, .retention_mid_vlevel = 0xE0, .collapse_mid_vlevel = 0xE0, .vctl_timeout_us = 50, }; //Div2-SW2-BSP,JOE HSU,+++ //#ifdef CONFIG_FIH_CONFIG_GROUP extern void fxx_info_init(void); //#endif //Div2-SW2-BSP,JOE HSU,--- #if defined(CONFIG_TOUCHSCREEN_TSC2007) || \ defined(CONFIG_TOUCHSCREEN_TSC2007_MODULE) #define TSC2007_TS_PEN_INT 20 static struct msm_gpio tsc2007_config_data[] = { { GPIO_CFG(TSC2007_TS_PEN_INT, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), "tsc2007_irq" }, }; static struct vreg *vreg_tsc_s3; static struct vreg *vreg_tsc_s2; static int tsc2007_init(void) { int rc; vreg_tsc_s3 = vreg_get(NULL, "s3"); if (IS_ERR(vreg_tsc_s3)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_tsc_s3)); return -ENODEV; } rc = vreg_set_level(vreg_tsc_s3, 1800); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_set_level; } rc = vreg_enable(vreg_tsc_s3); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_set_level; } vreg_tsc_s2 = vreg_get(NULL, "s2"); if (IS_ERR(vreg_tsc_s2)) { printk(KERN_ERR "%s: vreg get failed (%ld)\n", __func__, PTR_ERR(vreg_tsc_s2)); goto fail_vreg_get; } rc = vreg_set_level(vreg_tsc_s2, 1300); if (rc) { pr_err("%s: vreg_set_level failed \n", __func__); goto fail_vreg_s2_level; } rc = vreg_enable(vreg_tsc_s2); if (rc) { pr_err("%s: vreg_enable failed \n", __func__); goto fail_vreg_s2_level; } rc = msm_gpios_request_enable(tsc2007_config_data, ARRAY_SIZE(tsc2007_config_data)); if (rc) { pr_err("%s: Unable to request gpios\n", __func__); goto fail_gpio_req; } return 0; fail_gpio_req: vreg_disable(vreg_tsc_s2); fail_vreg_s2_level: vreg_put(vreg_tsc_s2); fail_vreg_get: vreg_disable(vreg_tsc_s3); fail_vreg_set_level: vreg_put(vreg_tsc_s3); return rc; } static int tsc2007_get_pendown_state(void) { int rc; rc = gpio_get_value(TSC2007_TS_PEN_INT); if (rc < 0) { pr_err("%s: MSM GPIO %d read failed\n", __func__, TSC2007_TS_PEN_INT); return rc; } return (rc == 0 ? 1 : 0); } static void tsc2007_exit(void) { vreg_disable(vreg_tsc_s3); vreg_put(vreg_tsc_s3); vreg_disable(vreg_tsc_s2); vreg_put(vreg_tsc_s2); msm_gpios_disable_free(tsc2007_config_data, ARRAY_SIZE(tsc2007_config_data)); } static int tsc2007_power_shutdown(bool enable) { int rc; if (enable == false) { rc = vreg_enable(vreg_tsc_s2); if (rc) { pr_err("%s: vreg_enable failed\n", __func__); return rc; } rc = vreg_enable(vreg_tsc_s3); if (rc) { pr_err("%s: vreg_enable failed\n", __func__); vreg_disable(vreg_tsc_s2); return rc; } /* Voltage settling delay */ msleep(20); } else { rc = vreg_disable(vreg_tsc_s2); if (rc) { pr_err("%s: vreg_disable failed\n", __func__); return rc; } rc = vreg_disable(vreg_tsc_s3); if (rc) { pr_err("%s: vreg_disable failed\n", __func__); vreg_enable(vreg_tsc_s2); return rc; } } return rc; } static struct tsc2007_platform_data tsc2007_ts_data = { .model = 2007, .x_plate_ohms = 300, .irq_flags = IRQF_TRIGGER_LOW, .init_platform_hw = tsc2007_init, .exit_platform_hw = tsc2007_exit, .power_shutdown = tsc2007_power_shutdown, .invert_x = true, .invert_y = true, /* REVISIT: Temporary fix for reversed pressure */ .invert_z1 = true, .invert_z2 = true, .get_pendown_state = tsc2007_get_pendown_state, }; static struct i2c_board_info tsc_i2c_board_info[] = { { I2C_BOARD_INFO("tsc2007", 0x48), .irq = MSM_GPIO_TO_INT(TSC2007_TS_PEN_INT), .platform_data = &tsc2007_ts_data, }, }; #endif static const char *vregs_isa1200_name[] = { "gp7", "gp10", }; static const int vregs_isa1200_val[] = { 1800, 2600, }; static struct vreg *vregs_isa1200[ARRAY_SIZE(vregs_isa1200_name)]; static int isa1200_power(int vreg_on) { int i, rc = 0; for (i = 0; i < ARRAY_SIZE(vregs_isa1200_name); i++) { if (!vregs_isa1200[i]) { pr_err("%s: vreg_get %s failed (%d)\n", __func__, vregs_isa1200_name[i], rc); goto vreg_fail; } rc = vreg_on ? vreg_enable(vregs_isa1200[i]) : vreg_disable(vregs_isa1200[i]); if (rc < 0) { pr_err("%s: vreg %s %s failed (%d)\n", __func__, vregs_isa1200_name[i], vreg_on ? "enable" : "disable", rc); goto vreg_fail; } } return 0; vreg_fail: while (i) vreg_disable(vregs_isa1200[--i]); return rc; } static int isa1200_dev_setup(bool enable) { int i, rc; if (enable == true) { for (i = 0; i < ARRAY_SIZE(vregs_isa1200_name); i++) { vregs_isa1200[i] = vreg_get(NULL, vregs_isa1200_name[i]); if (IS_ERR(vregs_isa1200[i])) { pr_err("%s: vreg get %s failed (%ld)\n", __func__, vregs_isa1200_name[i], PTR_ERR(vregs_isa1200[i])); rc = PTR_ERR(vregs_isa1200[i]); goto vreg_get_fail; } rc = vreg_set_level(vregs_isa1200[i], vregs_isa1200_val[i]); if (rc) { pr_err("%s: vreg_set_level() = %d\n", __func__, rc); goto vreg_get_fail; } } rc = gpio_tlmm_config(GPIO_CFG(HAP_LVL_SHFT_MSM_GPIO, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE); if (rc) { pr_err("%s: Could not configure gpio %d\n", __func__, HAP_LVL_SHFT_MSM_GPIO); goto vreg_get_fail; } rc = gpio_request(HAP_LVL_SHFT_MSM_GPIO, "haptics_shft_lvl_oe"); if (rc) { pr_err("%s: unable to request gpio %d (%d)\n", __func__, HAP_LVL_SHFT_MSM_GPIO, rc); goto vreg_get_fail; } gpio_set_value(HAP_LVL_SHFT_MSM_GPIO, 1); } else { for (i = 0; i < ARRAY_SIZE(vregs_isa1200_name); i++) vreg_put(vregs_isa1200[i]); gpio_free(HAP_LVL_SHFT_MSM_GPIO); } return 0; vreg_get_fail: while (i) vreg_put(vregs_isa1200[--i]); return rc; } static struct isa1200_platform_data isa1200_1_pdata = { .name = "vibrator", .power_on = isa1200_power, .dev_setup = isa1200_dev_setup, .pwm_ch_id = 1, /*channel id*/ /*gpio to enable haptic*/ .hap_en_gpio = PM8058_GPIO_PM_TO_SYS(PMIC_GPIO_HAP_ENABLE), .max_timeout = 15000, .mode_ctrl = PWM_GEN_MODE, .pwm_fd = { .pwm_div = 256, }, .is_erm = false, .smart_en = true, .ext_clk_en = true, .chip_en = 1, }; static struct i2c_board_info msm_isa1200_board_info[] = { { I2C_BOARD_INFO("isa1200_1", 0x90>>1), .platform_data = &isa1200_1_pdata, }, }; static int kp_flip_mpp_config(void) { return pm8058_mpp_config_digital_in(PM_FLIP_MPP, PM8058_MPP_DIG_LEVEL_S3, PM_MPP_DIN_TO_INT); } static struct flip_switch_pdata flip_switch_data = { .name = "kp_flip_switch", .flip_gpio = PM8058_GPIO_PM_TO_SYS(PM8058_GPIOS) + PM_FLIP_MPP, .left_key = KEY_OPEN, .right_key = KEY_CLOSE, .active_low = 0, .wakeup = 1, .flip_mpp_config = kp_flip_mpp_config, }; static struct platform_device flip_switch_device = { .name = "kp_flip_switch", .id = -1, .dev = { .platform_data = &flip_switch_data, } }; static const char *vregs_tma300_name[] = { "gp6", "gp7", }; static const int vregs_tma300_val[] = { 3050, 1800, }; static struct vreg *vregs_tma300[ARRAY_SIZE(vregs_tma300_name)]; static int tma300_power(int vreg_on) { int i, rc = -EINVAL; for (i = 0; i < ARRAY_SIZE(vregs_tma300_name); i++) { /* Never disable gp6 for fluid as lcd has a problem with it */ if (!i && !vreg_on) continue; if (!vregs_tma300[i]) { printk(KERN_ERR "%s: vreg_get %s failed (%d)\n", __func__, vregs_tma300_name[i], rc); return rc; } rc = vreg_on ? vreg_enable(vregs_tma300[i]) : vreg_disable(vregs_tma300[i]); if (rc < 0) { printk(KERN_ERR "%s: vreg %s %s failed (%d)\n", __func__, vregs_tma300_name[i], vreg_on ? "enable" : "disable", rc); return rc; } } return 0; } #define TS_GPIO_IRQ 150 static int tma300_dev_setup(bool enable) { int i, rc; if (enable) { /* get voltage sources */ for (i = 0; i < ARRAY_SIZE(vregs_tma300_name); i++) { vregs_tma300[i] = vreg_get(NULL, vregs_tma300_name[i]); if (IS_ERR(vregs_tma300[i])) { pr_err("%s: vreg get %s failed (%ld)\n", __func__, vregs_tma300_name[i], PTR_ERR(vregs_tma300[i])); rc = PTR_ERR(vregs_tma300[i]); goto vreg_get_fail; } rc = vreg_set_level(vregs_tma300[i], vregs_tma300_val[i]); if (rc) { pr_err("%s: vreg_set_level() = %d\n", __func__, rc); i++; goto vreg_get_fail; } } /* enable interrupt gpio */ rc = gpio_tlmm_config(GPIO_CFG(TS_GPIO_IRQ, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_6MA), GPIO_CFG_ENABLE); if (rc) { pr_err("%s: Could not configure gpio %d\n", __func__, TS_GPIO_IRQ); goto vreg_get_fail; } /* virtual keys */ tma300_vkeys_attr.attr.name = "virtualkeys.msm_tma300_ts"; properties_kobj = kobject_create_and_add("board_properties", NULL); if (!properties_kobj) { pr_err("%s: failed to create a kobject" "for board_properites\n", __func__); rc = -ENOMEM; goto vreg_get_fail; } rc = sysfs_create_group(properties_kobj, &tma300_properties_attr_group); if (rc) { pr_err("%s: failed to create a sysfs entry %s\n", __func__, tma300_vkeys_attr.attr.name); kobject_put(properties_kobj); goto vreg_get_fail; } } else { /* put voltage sources */ for (i = 0; i < ARRAY_SIZE(vregs_tma300_name); i++) vreg_put(vregs_tma300[i]); /* destroy virtual keys */ if (properties_kobj) { sysfs_remove_group(properties_kobj, &tma300_properties_attr_group); kobject_put(properties_kobj); } } return 0; vreg_get_fail: while (i) vreg_put(vregs_tma300[--i]); return rc; } static struct cy8c_ts_platform_data cy8ctma300_pdata = { .power_on = tma300_power, .dev_setup = tma300_dev_setup, .ts_name = "msm_tma300_ts", .dis_min_x = 0, .dis_max_x = 479, .dis_min_y = 0, .dis_max_y = 799, .res_x = 479, .res_y = 1009, .min_tid = 1, .max_tid = 255, .min_touch = 0, .max_touch = 255, .min_width = 0, .max_width = 255, .invert_y = 1, .nfingers = 4, .irq_gpio = TS_GPIO_IRQ, .resout_gpio = -1, }; static struct i2c_board_info cy8ctma300_board_info[] = { { I2C_BOARD_INFO("cy8ctma300", 0x2), .platform_data = &cy8ctma300_pdata, } }; static void __init msm7x30_init(void) { int rc; //SW5-Multimedia-TH-MT9P111forV6-00+{ int pid = Product_FB0; int cnt = 0; int camera_num = 0; //SW5-Multimedia-TH-MT9P111forV6-00+} unsigned smem_size; uint32_t usb_hub_gpio_cfg_value = GPIO_CFG(56, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA); uint32_t soc_version = 0; if (socinfo_init() < 0) printk(KERN_ERR "%s: socinfo_init() failed!\n", __func__); soc_version = socinfo_get_version(); //Div2-SW2-BSP,JOE HSU fih_get_oem_info(); fih_get_host_oem_info(); // SW2-5-1-MP-HostOemInfo-00+ msm_clock_init(msm_clocks_7x30, msm_num_clocks_7x30); #ifdef CONFIG_SERIAL_MSM_CONSOLE msm7x30_init_uart2(); #endif msm_spm_init(&msm_spm_data, 1); msm_acpu_clock_init(&msm7x30_clock_data); /* Div2-SW2-BSP-FBX-OW { */ #ifdef CONFIG_SMSC911X if (machine_is_msm7x30_surf() || machine_is_msm7x30_fluid()) msm7x30_cfg_smsc911x(); #endif /* } Div2-SW2-BSP-FBX-OW */ #ifdef CONFIG_USB_FUNCTION msm_hsusb_pdata.swfi_latency = msm_pm_data [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].latency; msm_device_hsusb_peripheral.dev.platform_data = &msm_hsusb_pdata; #endif #ifdef CONFIG_USB_MSM_OTG_72K if (SOCINFO_VERSION_MAJOR(soc_version) >= 2 && SOCINFO_VERSION_MINOR(soc_version) >= 1) { pr_debug("%s: SOC Version:2.(1 or more)\n", __func__); msm_otg_pdata.ldo_set_voltage = 0; } msm_device_otg.dev.platform_data = &msm_otg_pdata; #ifdef CONFIG_USB_GADGET msm_otg_pdata.swfi_latency = msm_pm_data [MSM_PM_SLEEP_MODE_RAMP_DOWN_AND_WAIT_FOR_INTERRUPT].latency; msm_device_gadget_peripheral.dev.platform_data = &msm_gadget_pdata; #endif #endif msm_uart_dm1_pdata.wakeup_irq = gpio_to_irq(136); msm_device_uart_dm1.dev.platform_data = &msm_uart_dm1_pdata; camera_sensor_hwpin_init(); #if defined(CONFIG_TSIF) || defined(CONFIG_TSIF_MODULE) msm_device_tsif.dev.platform_data = &tsif_platform_data; #endif if (machine_is_msm7x30_fluid()) { msm_adc_pdata.dev_names = msm_adc_fluid_device_names; msm_adc_pdata.num_adc = ARRAY_SIZE(msm_adc_fluid_device_names); } else { msm_adc_pdata.dev_names = msm_adc_surf_device_names; msm_adc_pdata.num_adc = ARRAY_SIZE(msm_adc_surf_device_names); } #ifdef CONFIG_USB_ANDROID if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { android_usb_pdata.product_id = 0x9028; android_usb_pdata.num_products = ARRAY_SIZE(fusion_usb_products); android_usb_pdata.products = fusion_usb_products; } #endif platform_add_devices(devices, ARRAY_SIZE(devices)); #ifdef CONFIG_USB_EHCI_MSM msm_add_host(0, &msm_usb_host_pdata); #endif /* FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized { */ #ifdef CONFIG_FIH_FXX sync_from_custom_nv(); //Div2-5-3-Peripheral-LL-UsbPorting-00+ #endif // CONFIG_FIH_FXX /* } FIHTDC, Div2-SW2-BSP, Penho, UsbCustomized */ msm7x30_init_mmc(); msm7x30_init_nand(); msm_qsd_spi_init(); #ifdef CONFIG_SPI_QSD if (machine_is_msm7x30_fluid()) spi_register_board_info(lcdc_sharp_spi_board_info, ARRAY_SIZE(lcdc_sharp_spi_board_info)); else spi_register_board_info(lcdc_toshiba_spi_board_info, ARRAY_SIZE(lcdc_toshiba_spi_board_info)); #endif msm_fb_add_devices(); msm_pm_set_platform_data(msm_pm_data, ARRAY_SIZE(msm_pm_data)); /* FIHTDC, Div2-SW2-BSP SungSCLee, HDMI { */ msm_device_i2c_power_domain(); /* } FIHTDC, Div2-SW2-BSP SungSCLee, HDMI */ msm_device_i2c_init(); msm_device_i2c_2_init(); qup_device_i2c_init(); buses_init(); msm7x30_init_marimba(); #ifdef CONFIG_MSM7KV2_AUDIO snddev_poweramp_gpio_init(); aux_pcm_gpio_init(); #endif #ifdef CONFIG_BATTERY_FIH_MSM fih_battery_driver_init(); // DIV2-SW2-BSP-FBx-BATT #endif i2c_register_board_info(0, msm_i2c_board_info, ARRAY_SIZE(msm_i2c_board_info)); if (!machine_is_msm8x55_svlte_ffa()) marimba_pdata.tsadc = &marimba_tsadc_pdata; if (machine_is_msm7x30_fluid()) i2c_register_board_info(0, cy8info, ARRAY_SIZE(cy8info)); #ifdef CONFIG_BOSCH_BMA150 if (machine_is_msm7x30_fluid()) i2c_register_board_info(0, bma150_board_info, ARRAY_SIZE(bma150_board_info)); #endif i2c_register_board_info(2, msm_marimba_board_info, ARRAY_SIZE(msm_marimba_board_info)); //SW5-Multimedia-TH-MT9P111forV6-00+{ pid = fih_get_product_id(); camera_num = ARRAY_SIZE(msm_camera_boardinfo); if (pid == Product_SF6 || IS_SF8_SERIES_PRJ())//Div2-SW6-MM-MC-ImplementCameraFTMforSF8Serials-00* { for (cnt = 0; cnt < camera_num; cnt++) { if(strncasecmp(msm_camera_boardinfo[cnt].type, "mt9p111", 7) == 0) { printk(KERN_INFO "%s: Old camera slave address = %x .\n", __func__, msm_camera_boardinfo[cnt].addr); msm_camera_boardinfo[cnt].addr = (0x7A >> 1); printk(KERN_INFO "%s: New camera slave address = %x .\n", __func__, msm_camera_boardinfo[cnt].addr); } } if (IS_SF8_SERIES_PRJ()) printk(KERN_INFO "%s: This is SF8 series project.....\n", __func__); } //SW5-Multimedia-TH-MT9P111forV6-00+} i2c_register_board_info(2, msm_i2c_gsbi7_timpani_info, ARRAY_SIZE(msm_i2c_gsbi7_timpani_info)); i2c_register_board_info(4 /* QUP ID */, msm_camera_boardinfo, ARRAY_SIZE(msm_camera_boardinfo)); bt_power_init(); // FihtdcCode@20110908 WeiChu add for WiFi porting begin // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_WLAN_POWER bcm4329_wifi_power_init(); #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 WLAN driver For SF8 +] // FIHTDC-SW2-Div6-CW-Project BCM4329 BLUETOOTH driver For SF8 +[ #ifdef CONFIG_BROADCOM_BCM4329_BLUETOOTH_POWER bcm4329_bt_power_init(); bcm4329_fm_power_init(); #endif // FIHTDC-SW2-Div6-CW-Project BCM4329 BLUETOOTH driver For SF8 +] // FihtdcCode@20110908 WeiChu add for WiFi porting end #ifdef CONFIG_I2C_SSBI msm_device_ssbi6.dev.platform_data = &msm_i2c_ssbi6_pdata; msm_device_ssbi7.dev.platform_data = &msm_i2c_ssbi7_pdata; #endif if (machine_is_msm7x30_fluid()) i2c_register_board_info(0, msm_isa1200_board_info, ARRAY_SIZE(msm_isa1200_board_info)); #if defined(CONFIG_TOUCHSCREEN_TSC2007) || \ defined(CONFIG_TOUCHSCREEN_TSC2007_MODULE) if (machine_is_msm8x55_svlte_ffa()) i2c_register_board_info(2, tsc_i2c_board_info, ARRAY_SIZE(tsc_i2c_board_info)); #endif if (machine_is_msm7x30_surf()) platform_device_register(&flip_switch_device); #ifdef CONFIG_LEDS_PM8058 pmic8058_leds_init(); #endif if (machine_is_msm7x30_fluid()) { /* Initialize platform data for fluid v2 hardware */ if (SOCINFO_VERSION_MAJOR( socinfo_get_platform_version()) == 2) { cy8ctma300_pdata.res_y = 920; cy8ctma300_pdata.invert_y = 0; } i2c_register_board_info(0, cy8ctma300_board_info, ARRAY_SIZE(cy8ctma300_board_info)); } if (machine_is_msm8x55_svlte_surf() || machine_is_msm8x55_svlte_ffa()) { rc = gpio_tlmm_config(usb_hub_gpio_cfg_value, GPIO_CFG_ENABLE); if (rc) pr_err("%s: gpio_tlmm_config(%#x)=%d\n", __func__, usb_hub_gpio_cfg_value, rc); } boot_reason = *(unsigned int *) (smem_get_entry(SMEM_POWER_ON_STATUS_INFO, &smem_size)); printk(KERN_NOTICE "Boot Reason = 0x%02x\n", boot_reason); //Div2-SW2-BSP,JOE HSU,+++ //#ifdef CONFIG_FIH_CONFIG_GROUP /*call product id functions for init verification*/ fih_get_product_id(); fih_get_product_phase(); fih_get_band_id(); fxx_info_init(); //#endif //Div2-SW2-BSP,JOE HSU,--- } static unsigned pmem_sf_size = MSM_PMEM_SF_SIZE; static int __init pmem_sf_size_setup(char *p) { pmem_sf_size = memparse(p, NULL); return 0; } early_param("pmem_sf_size", pmem_sf_size_setup); static unsigned fb_size = MSM_FB_SIZE; static int __init fb_size_setup(char *p) { fb_size = memparse(p, NULL); return 0; } early_param("fb_size", fb_size_setup); static unsigned pmem_adsp_size = MSM_PMEM_ADSP_SIZE; static int __init pmem_adsp_size_setup(char *p) { pmem_adsp_size = memparse(p, NULL); return 0; } early_param("pmem_adsp_size", pmem_adsp_size_setup); static unsigned fluid_pmem_adsp_size = MSM_FLUID_PMEM_ADSP_SIZE; static int __init fluid_pmem_adsp_size_setup(char *p) { fluid_pmem_adsp_size = memparse(p, NULL); return 0; } early_param("fluid_pmem_adsp_size", fluid_pmem_adsp_size_setup); static unsigned pmem_audio_size = MSM_PMEM_AUDIO_SIZE; static int __init pmem_audio_size_setup(char *p) { pmem_audio_size = memparse(p, NULL); return 0; } early_param("pmem_audio_size", pmem_audio_size_setup); static unsigned pmem_kernel_ebi1_size = PMEM_KERNEL_EBI1_SIZE; static int __init pmem_kernel_ebi1_size_setup(char *p) { pmem_kernel_ebi1_size = memparse(p, NULL); return 0; } early_param("pmem_kernel_ebi1_size", pmem_kernel_ebi1_size_setup); static void __init msm7x30_allocate_memory_regions(void) { void *addr; unsigned long size; /* Request allocation of Hardware accessible PMEM regions at the beginning to make sure they are allocated in EBI-0. This will allow 7x30 with two mem banks enter the second mem bank into Self-Refresh State during Idle Power Collapse. The current HW accessible PMEM regions are 1. Frame Buffer. LCDC HW can access msm_fb_resources during Idle-PC. 2. Audio LPA HW can access android_pmem_audio_pdata during Idle-PC. */ size = fb_size ? : MSM_FB_SIZE; addr = alloc_bootmem(size); msm_fb_resources[0].start = __pa(addr); msm_fb_resources[0].end = msm_fb_resources[0].start + size - 1; pr_info("allocating %lu bytes at %p (%lx physical) for fb\n", size, addr, __pa(addr)); size = pmem_audio_size; if (size) { addr = alloc_bootmem(size); android_pmem_audio_pdata.start = __pa(addr); android_pmem_audio_pdata.size = size; pr_info("allocating %lu bytes at %p (%lx physical) for audio " "pmem arena\n", size, addr, __pa(addr)); } size = pmem_kernel_ebi1_size; if (size) { addr = alloc_bootmem_aligned(size, 0x100000); android_pmem_kernel_ebi1_pdata.start = __pa(addr); android_pmem_kernel_ebi1_pdata.size = size; pr_info("allocating %lu bytes at %p (%lx physical) for kernel" " ebi1 pmem arena\n", size, addr, __pa(addr)); } size = pmem_sf_size; if (size) { addr = alloc_bootmem(size); android_pmem_pdata.start = __pa(addr); android_pmem_pdata.size = size; pr_info("allocating %lu bytes at %p (%lx physical) for sf " "pmem arena\n", size, addr, __pa(addr)); } if machine_is_msm7x30_fluid() size = fluid_pmem_adsp_size; else size = pmem_adsp_size; if (size) { addr = alloc_bootmem(size); android_pmem_adsp_pdata.start = __pa(addr); android_pmem_adsp_pdata.size = size; pr_info("allocating %lu bytes at %p (%lx physical) for adsp " "pmem arena\n", size, addr, __pa(addr)); } } static void __init msm7x30_map_io(void) { msm_shared_ram_phys = 0x00100000; msm_map_msm7x30_io(); msm7x30_allocate_memory_regions(); } MACHINE_START(MSM7X30_SURF, "QCT MSM7X30 SURF") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM7X30_FFA, "QCT MSM7X30 FFA") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM7X30_FLUID, "QCT MSM7X30 FLUID") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM8X55_SURF, "QCT MSM8X55 SURF") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM8X55_FFA, "FB0") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM8X55_SVLTE_SURF, "QCT MSM8X55 SVLTE SURF") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END MACHINE_START(MSM8X55_SVLTE_FFA, "QCT MSM8X55 SVLTE FFA") #ifdef CONFIG_MSM_DEBUG_UART .phys_io = MSM_DEBUG_UART_PHYS, .io_pg_offst = ((MSM_DEBUG_UART_BASE) >> 18) & 0xfffc, #endif .boot_params = PHYS_OFFSET + 0x100, .map_io = msm7x30_map_io, .init_irq = msm7x30_init_irq, .init_machine = msm7x30_init, .timer = &msm_timer, MACHINE_END
Java
import MySQLdb class DatabaseHandler: def __init__(self): pass def is_delete(self, tableName): reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"] isDeleteFlag = 1 for name in reservedTableNameList: isIdentical = cmp(tableName, name) if isIdentical == 0: isDeleteFlag = 0 break return isDeleteFlag def Clean_Database(self, hostUrl, account, password, databaseName): print 'clean database1' db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName) cursor = db.cursor() cursor.execute("Show Tables from " + databaseName) result = cursor.fetchall() for record in result: tableName = record[0] isDelete = self.is_delete(tableName) if isDelete == 0: print "Reserve " + tableName else : print "TRUNCATE TABLE `" + tableName + "`" cursor.execute("TRUNCATE TABLE `" + tableName + "`") print 'Add admin' cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', 'example@ezScrum.tw', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)") cursor.execute("INSERT INTO `system` VALUES (1, 1)") db.commit() #if __name__ == '__main__': # databaseHandler = DatabaseHandler() # databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
Java
#!/usr/bin/ruby require File.expand_path(ENV['MOSYNCDIR']+'/rules/mosync_exe.rb') work = PipeExeWork.new work.instance_eval do @SOURCES = ["."] @LIBRARIES = ["mautil"] @NAME = "Stylus" end work.invoke
Java
/*********************************************************************************** * * * Voreen - The Volume Rendering Engine * * * * Copyright (C) 2005-2013 University of Muenster, Germany. * * Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> * * For a list of authors please refer to the file "CREDITS.txt". * * * * This file is part of the Voreen software package. Voreen is free software: * * you can redistribute it and/or modify it under the terms of the GNU General * * Public License version 2 as published by the Free Software Foundation. * * * * Voreen 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 in the file * * "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. * * * * For non-commercial academic use see the license exception specified in the file * * "LICENSE-academic.txt". To get information about commercial licensing please * * contact the authors. * * * ***********************************************************************************/ #include "isolatedconnectedimagefilter.h" #include "voreen/core/datastructures/volume/volumeram.h" #include "voreen/core/datastructures/volume/volume.h" #include "voreen/core/datastructures/volume/volumeatomic.h" #include "voreen/core/ports/conditions/portconditionvolumetype.h" #include "modules/itk/utils/itkwrapper.h" #include "voreen/core/datastructures/volume/operators/volumeoperatorconvert.h" #include "itkImage.h" #include "itkIsolatedConnectedImageFilter.h" #include <iostream> namespace voreen { const std::string IsolatedConnectedImageFilterITK::loggerCat_("voreen.IsolatedConnectedImageFilterITK"); IsolatedConnectedImageFilterITK::IsolatedConnectedImageFilterITK() : ITKProcessor(), inport1_(Port::INPORT, "InputImage"), outport1_(Port::OUTPORT, "OutputImage"), seedPointPort1_(Port::INPORT, "seedPointInput1"), seedPointPort2_(Port::INPORT, "seedPointInput2"), enableProcessing_("enabled", "Enable", false), replaceValue_("replaceValue", "ReplaceValue"), isolatedValueTolerance_("isolatedValueTolerance", "IsolatedValueTolerance"), upper_("upper", "Upper"), lower_("lower", "Lower"), findUpperThreshold_("findUpperThreshold", "FindUpperThreshold", false) { addPort(inport1_); PortConditionLogicalOr* orCondition1 = new PortConditionLogicalOr(); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt8()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt8()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt16()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt16()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt32()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt32()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeFloat()); orCondition1->addLinkedCondition(new PortConditionVolumeTypeDouble()); inport1_.addCondition(orCondition1); addPort(outport1_); addPort(seedPointPort1_); addPort(seedPointPort2_); addProperty(enableProcessing_); addProperty(replaceValue_); addProperty(isolatedValueTolerance_); addProperty(upper_); addProperty(lower_); addProperty(findUpperThreshold_); } Processor* IsolatedConnectedImageFilterITK::create() const { return new IsolatedConnectedImageFilterITK(); } template<class T> void IsolatedConnectedImageFilterITK::isolatedConnectedImageFilterITK() { replaceValue_.setVolume(inport1_.getData()); isolatedValueTolerance_.setVolume(inport1_.getData()); upper_.setVolume(inport1_.getData()); lower_.setVolume(inport1_.getData()); if (!enableProcessing_.get()) { outport1_.setData(inport1_.getData(), false); return; } typedef itk::Image<T, 3> InputImageType1; typedef itk::Image<T, 3> OutputImageType1; typename InputImageType1::Pointer p1 = voreenToITK<T>(inport1_.getData()); //Filter define typedef itk::IsolatedConnectedImageFilter<InputImageType1, OutputImageType1> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); if (seedPointPort1_.hasChanged()) { const PointListGeometry<tgt::vec3>* pointList1 = dynamic_cast< const PointListGeometry<tgt::vec3>* >(seedPointPort1_.getData()); if (pointList1) { seedPoints1 = pointList1->getData(); } } filter->ClearSeeds1(); typename InputImageType1::IndexType seed1; for (size_t i = 0; i < seedPoints1.size(); i++) { seed1[0] = seedPoints1[i].x; seed1[1] = seedPoints1[i].y; seed1[2] = seedPoints1[i].z; filter->AddSeed1(seed1); } if (seedPointPort2_.hasChanged()) { const PointListGeometry<tgt::vec3>* pointList2 = dynamic_cast< const PointListGeometry<tgt::vec3>* >(seedPointPort2_.getData()); if (pointList2) { seedPoints2 = pointList2->getData(); } } filter->ClearSeeds2(); typename InputImageType1::IndexType seed2; for (size_t i = 0; i < seedPoints2.size(); i++) { seed2[0] = seedPoints2[i].x; seed2[1] = seedPoints2[i].y; seed2[2] = seedPoints2[i].z; filter->AddSeed2(seed2); } filter->SetReplaceValue(replaceValue_.getValue<T>()); filter->SetIsolatedValueTolerance(isolatedValueTolerance_.getValue<T>()); filter->SetUpper(upper_.getValue<T>()); filter->SetLower(lower_.getValue<T>()); filter->SetFindUpperThreshold(findUpperThreshold_.get()); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } void IsolatedConnectedImageFilterITK::process() { const VolumeBase* inputHandle1 = inport1_.getData(); const VolumeRAM* inputVolume1 = inputHandle1->getRepresentation<VolumeRAM>(); if (dynamic_cast<const VolumeRAM_UInt8*>(inputVolume1)) { isolatedConnectedImageFilterITK<uint8_t>(); } else if (dynamic_cast<const VolumeRAM_Int8*>(inputVolume1)) { isolatedConnectedImageFilterITK<int8_t>(); } else if (dynamic_cast<const VolumeRAM_UInt16*>(inputVolume1)) { isolatedConnectedImageFilterITK<uint16_t>(); } else if (dynamic_cast<const VolumeRAM_Int16*>(inputVolume1)) { isolatedConnectedImageFilterITK<int16_t>(); } else if (dynamic_cast<const VolumeRAM_UInt32*>(inputVolume1)) { isolatedConnectedImageFilterITK<uint32_t>(); } else if (dynamic_cast<const VolumeRAM_Int32*>(inputVolume1)) { isolatedConnectedImageFilterITK<int32_t>(); } else if (dynamic_cast<const VolumeRAM_Float*>(inputVolume1)) { isolatedConnectedImageFilterITK<float>(); } else if (dynamic_cast<const VolumeRAM_Double*>(inputVolume1)) { isolatedConnectedImageFilterITK<double>(); } else { LERROR("Inputformat of Volume 1 is not supported!"); } } } // namespace
Java
<!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_06) on Wed Dec 28 15:03:50 CET 2005 --> <TITLE> SimpleTextGUI01 </TITLE> <META NAME="keywords" CONTENT="jmatlink.ui.SimpleTextGUI01 class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="SimpleTextGUI01"; } </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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SimpleTextGUI01.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../jmatlink/ui/SimpleTestGui02.html" title="class in jmatlink.ui"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../jmatlink/ui/SimpleTextGUI02.html" title="class in jmatlink.ui"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SimpleTextGUI01.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> jmatlink.ui</FONT> <BR> Class SimpleTextGUI01</H2> <PRE> java.lang.Object <IMG SRC="../../resources/inherit.gif" ALT="extended by"><B>jmatlink.ui.SimpleTextGUI01</B> </PRE> <HR> <DL> <DT>public class <B>SimpleTextGUI01</B><DT>extends java.lang.Object</DL> <P> <HR> <P> <!-- ======== NESTED CLASS SUMMARY ======== --> <!-- =========== FIELD SUMMARY =========== --> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../jmatlink/ui/SimpleTextGUI01.html#SimpleTextGUI01()">SimpleTextGUI01</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Method Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../jmatlink/ui/SimpleTextGUI01.html#main(java.lang.String[])">main</A></B>(java.lang.String[]&nbsp;args)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class java.lang.Object</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TD> </TR> </TABLE> <A NAME="SimpleTextGUI01()"><!-- --></A><H3> SimpleTextGUI01</H3> <PRE> public <B>SimpleTextGUI01</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Method Detail</B></FONT></TD> </TR> </TABLE> <A NAME="main(java.lang.String[])"><!-- --></A><H3> main</H3> <PRE> public static void <B>main</B>(java.lang.String[]&nbsp;args)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SimpleTextGUI01.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../jmatlink/ui/SimpleTestGui02.html" title="class in jmatlink.ui"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../jmatlink/ui/SimpleTextGUI02.html" title="class in jmatlink.ui"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SimpleTextGUI01.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Java
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ /*** This file is part of systemd. Copyright 2010 Lennart Poettering systemd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. systemd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with systemd; If not, see <http://www.gnu.org/licenses/>. ***/ #include <errno.h> #include <sys/mount.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sched.h> #include <sys/syscall.h> #include <limits.h> #include <linux/fs.h> #include "strv.h" #include "util.h" #include "path-util.h" #include "namespace.h" #include "missing.h" #include "execute.h" typedef enum MountMode { /* This is ordered by priority! */ INACCESSIBLE, READONLY, PRIVATE_TMP, PRIVATE_VAR_TMP, READWRITE } MountMode; typedef struct BindMount { const char *path; MountMode mode; bool done; bool ignore; } BindMount; static int append_mounts(BindMount **p, char **strv, MountMode mode) { char **i; STRV_FOREACH(i, strv) { (*p)->ignore = false; if ((mode == INACCESSIBLE || mode == READONLY) && (*i)[0] == '-') { (*p)->ignore = true; (*i)++; } if (!path_is_absolute(*i)) return -EINVAL; (*p)->path = *i; (*p)->mode = mode; (*p)++; } return 0; } static int mount_path_compare(const void *a, const void *b) { const BindMount *p = a, *q = b; if (path_equal(p->path, q->path)) { /* If the paths are equal, check the mode */ if (p->mode < q->mode) return -1; if (p->mode > q->mode) return 1; return 0; } /* If the paths are not equal, then order prefixes first */ if (path_startswith(p->path, q->path)) return 1; if (path_startswith(q->path, p->path)) return -1; return 0; } static void drop_duplicates(BindMount *m, unsigned *n) { BindMount *f, *t, *previous; assert(m); assert(n); for (f = m, t = m, previous = NULL; f < m+*n; f++) { /* The first one wins */ if (previous && path_equal(f->path, previous->path)) continue; t->path = f->path; t->mode = f->mode; previous = t; t++; } *n = t - m; } static int apply_mount( BindMount *m, const char *tmp_dir, const char *var_tmp_dir) { const char *what; int r; assert(m); switch (m->mode) { case INACCESSIBLE: what = "/run/systemd/inaccessible"; break; case READONLY: case READWRITE: what = m->path; break; case PRIVATE_TMP: what = tmp_dir; break; case PRIVATE_VAR_TMP: what = var_tmp_dir; break; default: assert_not_reached("Unknown mode"); } assert(what); r = mount(what, m->path, NULL, MS_BIND|MS_REC, NULL); if (r >= 0) log_debug("Successfully mounted %s to %s", what, m->path); else if (m->ignore && errno == ENOENT) r = 0; return r; } static int make_read_only(BindMount *m) { int r; assert(m); if (m->mode != INACCESSIBLE && m->mode != READONLY) return 0; r = mount(NULL, m->path, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_REC, NULL); if (r < 0 && !(m->ignore && errno == ENOENT)) return -errno; return 0; } int setup_tmpdirs(const char *unit_id, char **tmp_dir, char **var_tmp_dir) { int r = 0; _cleanup_free_ char *tmp = NULL, *var = NULL; assert(tmp_dir); assert(var_tmp_dir); tmp = strjoin("/tmp/systemd-", unit_id, "-XXXXXXX", NULL); var = strjoin("/var/tmp/systemd-", unit_id, "-XXXXXXX", NULL); r = create_tmp_dir(tmp, tmp_dir); if (r < 0) return r; r = create_tmp_dir(var, var_tmp_dir); if (r == 0) return 0; /* failure */ rmdir(*tmp_dir); rmdir(tmp); free(*tmp_dir); *tmp_dir = NULL; return r; } int setup_namespace(char** read_write_dirs, char** read_only_dirs, char** inaccessible_dirs, char* tmp_dir, char* var_tmp_dir, bool private_tmp, unsigned mount_flags) { unsigned n = strv_length(read_write_dirs) + strv_length(read_only_dirs) + strv_length(inaccessible_dirs) + (private_tmp ? 2 : 0); BindMount *m, *mounts = NULL; int r = 0; if (!mount_flags) mount_flags = MS_SHARED; if (unshare(CLONE_NEWNS) < 0) return -errno; if (n) { m = mounts = (BindMount *) alloca(n * sizeof(BindMount)); if ((r = append_mounts(&m, read_write_dirs, READWRITE)) < 0 || (r = append_mounts(&m, read_only_dirs, READONLY)) < 0 || (r = append_mounts(&m, inaccessible_dirs, INACCESSIBLE)) < 0) return r; if (private_tmp) { m->path = "/tmp"; m->mode = PRIVATE_TMP; m++; m->path = "/var/tmp"; m->mode = PRIVATE_VAR_TMP; m++; } assert(mounts + n == m); qsort(mounts, n, sizeof(BindMount), mount_path_compare); drop_duplicates(mounts, &n); } /* Remount / as SLAVE so that nothing now mounted in the namespace shows up in the parent */ if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) return -errno; for (m = mounts; m < mounts + n; ++m) { r = apply_mount(m, tmp_dir, var_tmp_dir); if (r < 0) goto undo_mounts; } for (m = mounts; m < mounts + n; ++m) { r = make_read_only(m); if (r < 0) goto undo_mounts; } /* Remount / as the desired mode */ if (mount(NULL, "/", NULL, mount_flags | MS_REC, NULL) < 0) { r = -errno; goto undo_mounts; } return 0; undo_mounts: for (m = mounts; m < mounts + n; ++m) { if (m->done) umount2(m->path, MNT_DETACH); } return r; }
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Function template operator++</title> <link rel="stylesheet" href="boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="index.html" title="ODTONE 0.6"> <link rel="up" href="odtone_base_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.types.base_hpp" title="Header &lt;/home/carlos/Projectos/odtone/inc/odtone/mih/types/base.hpp&gt;"> <link rel="prev" href="odtone/mih/operator_idp11211072.html" title="Function operator&lt;&lt;"> <link rel="next" href="odtone/bind_rv_.html" title="Struct template bind_rv_"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="'ODTONE - Open Dot Twenty One'" width="100" height="100" src="./images/logo.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="odtone/mih/operator_idp11211072.html"><img src="images/prev.png" alt="Prev"></a><a accesskey="u" href="odtone_base_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.types.base_hpp"><img src="images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="images/home.png" alt="Home"></a><a accesskey="n" href="odtone/bind_rv_.html"><img src="images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="operator++"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Function template operator++</span></h2> <p>operator++</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="odtone_base_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.types.base_hpp" title="Header &lt;/home/carlos/Projectos/odtone/inc/odtone/mih/types/base.hpp&gt;">/home/carlos/Projectos/odtone/inc/odtone/mih/types/base.hpp</a>&gt; </span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> EnumT<span class="special">&gt;</span> <span class="identifier">EnumT</span> <span class="keyword">operator</span><span class="special">++</span><span class="special">(</span><span class="identifier">EnumT</span> <span class="special">&amp;</span> rs<span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp65712112"></a><h2>Description</h2> <p>Define a postfix increment operator for enumeration types. </p> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2009-2013 Universidade Aveiro<br>Copyright &#169; 2009-2013 Instituto de Telecomunica&#231;&#245;es - P&#243;lo Aveiro<p> This software is distributed under a license. The full license agreement can be found in the LICENSE in this distribution. This software may not be copied, modified, sold or distributed other than expressed in the named license agreement. This software is distributed without any warranty. </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="odtone/mih/operator_idp11211072.html"><img src="images/prev.png" alt="Prev"></a><a accesskey="u" href="odtone_base_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.types.base_hpp"><img src="images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="images/home.png" alt="Home"></a><a accesskey="n" href="odtone/bind_rv_.html"><img src="images/next.png" alt="Next"></a> </div> </body> </html>
Java
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import com.oracle.java.testlibrary.Asserts; import java.lang.management.MemoryType; import sun.hotspot.code.BlobType; /** * @test BeanTypeTest * @library /testlibrary /../../test/lib * @modules java.management * @build BeanTypeTest * @run main ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+WhiteBoxAPI -XX:+SegmentedCodeCache BeanTypeTest * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+WhiteBoxAPI -XX:-SegmentedCodeCache BeanTypeTest * @summary verify types of code cache memory pool bean */ public class BeanTypeTest { public static void main(String args[]) { for (BlobType bt : BlobType.getAvailable()) { Asserts.assertEQ(MemoryType.NON_HEAP, bt.getMemoryPool().getType()); } } }
Java
#include "EOSProjectData.h" EOSProjectData::EOSProjectData() { } EOSProjectData::~EOSProjectData() { }
Java
/** * TODO: legal stuff * * purple * * Purple is the legal property of its developers, whose names are too numerous * to list here. Please refer to the COPYRIGHT file distributed with this * source distribution. * * 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 02111-1301 USA */ #include <glib/gstdio.h> #include "prpltwtr.h" typedef struct { PurpleAccount *account; gchar *username; } TwitterAccountUserNameChange; static GHashTable *oauth_result_to_hashtable(const gchar * txt); static void account_mismatch_screenname_change_cancel_cb(TwitterAccountUserNameChange * change, gint action_id); static void account_mismatch_screenname_change_ok_cb(TwitterAccountUserNameChange * change, gint action_id); static void account_username_change_verify(PurpleAccount * account, const gchar * username); static void verify_credentials_success_cb(TwitterRequestor * r, xmlnode * node, gpointer user_data); static void verify_credentials_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data); static void oauth_request_token_success_cb(TwitterRequestor * r, const gchar * response, gpointer user_data); static void oauth_request_token_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data); static const gchar *account_get_oauth_access_token(PurpleAccount * account); static void account_set_oauth_access_token(PurpleAccount * account, const gchar * oauth_token); static const gchar *account_get_oauth_access_token_secret(PurpleAccount * account); static void account_set_oauth_access_token_secret(PurpleAccount * account, const gchar * oauth_token); static void oauth_request_pin_ok(PurpleAccount * account, const gchar * pin); static void oauth_request_pin_cancel(PurpleAccount * account, const gchar * pin); static void oauth_access_token_success_cb(TwitterRequestor * r, const gchar * response, gpointer user_data); static void oauth_access_token_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data); static const gchar *twitter_option_url_oauth_authorize(PurpleAccount * account); static const gchar *twitter_option_url_oauth_access_token(PurpleAccount * account); static const gchar *twitter_option_url_oauth_request_token(PurpleAccount * account); static const gchar *twitter_oauth_create_url(PurpleAccount * account, const gchar * endpoint); void prpltwtr_auth_invalidate_token(PurpleAccount * account) { account_set_oauth_access_token(account, NULL); account_set_oauth_access_token_secret(account, NULL); } void prpltwtr_auth_pre_send_auth_basic(TwitterRequestor * r, gboolean * post, const char **url, TwitterRequestParams ** params, gchar *** header_fields, gpointer * requestor_data) { const char *pass = purple_connection_get_password(purple_account_get_connection(r->account)); char **userparts = g_strsplit(purple_account_get_username(r->account), "@", 2); const char *sn = userparts[0]; char *auth_text = g_strdup_printf("%s:%s", sn, pass); char *auth_text_b64 = purple_base64_encode((guchar *) auth_text, strlen(auth_text)); *header_fields = g_new(gchar *, 2); (*header_fields)[0] = g_strdup_printf("Authorization: Basic %s", auth_text_b64); (*header_fields)[1] = NULL; g_strfreev(userparts); g_free(auth_text); g_free(auth_text_b64); } void prpltwtr_auth_post_send_auth_basic(TwitterRequestor * r, gboolean * post, const char **url, TwitterRequestParams ** params, gchar *** header_fields, gpointer * requestor_data) { g_strfreev(*header_fields); } const gchar *prpltwtr_auth_get_oauth_key(PurpleAccount * account) { if (!strcmp(purple_account_get_protocol_id(account), TWITTER_PROTOCOL_ID)) { return TWITTER_OAUTH_KEY; } else { const gchar *key = purple_account_get_string(account, TWITTER_PREF_CONSUMER_KEY, ""); if (!strcmp(key, "")) { purple_debug_error(purple_account_get_protocol_id(account), "No Consumer key specified!\n"); } return key; } } const gchar *prpltwtr_auth_get_oauth_secret(PurpleAccount * account) { if (!strcmp(purple_account_get_protocol_id(account), TWITTER_PROTOCOL_ID)) { return TWITTER_OAUTH_SECRET; } else { const gchar *secret = purple_account_get_string(account, TWITTER_PREF_CONSUMER_SECRET, ""); if (!strcmp(secret, "")) { purple_debug_error(purple_account_get_protocol_id(account), "No Consumer secret specified!\n"); } return secret; } } void prpltwtr_auth_pre_send_oauth(TwitterRequestor * r, gboolean * post, const char **url, TwitterRequestParams ** params, gchar *** header_fields, gpointer * requestor_data) { PurpleAccount *account = r->account; PurpleConnection *gc = purple_account_get_connection(account); TwitterConnectionData *twitter = gc->proto_data; gchar *signing_key = g_strdup_printf("%s&%s", prpltwtr_auth_get_oauth_secret(account), twitter->oauth_token_secret ? twitter->oauth_token_secret : ""); TwitterRequestParams *oauth_params = twitter_request_params_add_oauth_params(account, *post, *url, *params, twitter->oauth_token, signing_key); if (oauth_params == NULL) { TwitterRequestErrorData *error = g_new0(TwitterRequestErrorData, 1); gchar *error_msg = g_strdup(_("Could not sign request")); error->type = TWITTER_REQUEST_ERROR_NO_OAUTH; error->message = error_msg; g_free(error_msg); g_free(error); g_free(signing_key); //TODO: error if couldn't sign return; } g_free(signing_key); *requestor_data = *params; *params = oauth_params; } void prpltwtr_auth_oauth_login(PurpleAccount * account, TwitterConnectionData * twitter) { const gchar *oauth_token; const gchar *oauth_token_secret; oauth_token = account_get_oauth_access_token(account); oauth_token_secret = account_get_oauth_access_token_secret(account); if (oauth_token && oauth_token_secret) { twitter->oauth_token = g_strdup(oauth_token); twitter->oauth_token_secret = g_strdup(oauth_token_secret); twitter_api_verify_credentials(purple_account_get_requestor(account), verify_credentials_success_cb, verify_credentials_error_cb, NULL); } else { twitter_send_request(purple_account_get_requestor(account), FALSE, twitter_option_url_oauth_request_token(account), NULL, oauth_request_token_success_cb, oauth_request_token_error_cb, NULL); } } void prpltwtr_auth_post_send_oauth(TwitterRequestor * r, gboolean * post, const char **url, TwitterRequestParams ** params, gchar *** header_fields, gpointer * requestor_data) { twitter_request_params_free(*params); *params = (TwitterRequestParams *) * requestor_data; } static void oauth_access_token_success_cb(TwitterRequestor * r, const gchar * response, gpointer user_data) { PurpleAccount *account = r->account; PurpleConnection *gc = purple_account_get_connection(account); TwitterConnectionData *twitter = gc->proto_data; GHashTable *results = oauth_result_to_hashtable(response); const gchar *oauth_token = g_hash_table_lookup(results, "oauth_token"); const gchar *oauth_token_secret = g_hash_table_lookup(results, "oauth_token_secret"); const gchar *response_screen_name = g_hash_table_lookup(results, "screen_name"); if (oauth_token && oauth_token_secret) { if (twitter->oauth_token) g_free(twitter->oauth_token); if (twitter->oauth_token_secret) g_free(twitter->oauth_token_secret); twitter->oauth_token = g_strdup(oauth_token); twitter->oauth_token_secret = g_strdup(oauth_token_secret); account_set_oauth_access_token(account, oauth_token); account_set_oauth_access_token_secret(account, oauth_token_secret); //FIXME: set this to be case insensitive { char **userparts = g_strsplit(purple_account_get_username(r->account), "@", 2); const char *username = userparts[0]; if (response_screen_name && !twitter_usernames_match(account, response_screen_name, username)) { account_username_change_verify(account, response_screen_name); } else { prpltwtr_verify_connection(account); } g_strfreev(userparts); } } else { purple_debug_error(purple_account_get_protocol_id(account), "Unknown error receiving access token: %s\n", response); prpltwtr_disconnect(account, _("Unknown response getting access token")); } } static void oauth_access_token_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data) { gchar *error = g_strdup_printf(_("Error verifying PIN: %s"), error_data->message ? error_data->message : _("unknown error")); prpltwtr_disconnect(r->account, error); g_free(error); } static GHashTable *oauth_result_to_hashtable(const gchar * txt) { gchar **pieces = g_strsplit(txt, "&", 0); GHashTable *results = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free); gchar **p; for (p = pieces; *p; p++) { gchar *equalpos = strchr(*p, '='); if (equalpos) { equalpos[0] = '\0'; g_hash_table_replace(results, g_strdup(*p), g_strdup(equalpos + 1)); } } g_strfreev(pieces); return results; } static void account_mismatch_screenname_change_cancel_cb(TwitterAccountUserNameChange * change, gint action_id) { PurpleAccount *account = change->account; prpltwtr_auth_invalidate_token(account); g_free(change->username); g_free(change); prpltwtr_disconnect(account, _("Username mismatch")); } static void account_mismatch_screenname_change_ok_cb(TwitterAccountUserNameChange * change, gint action_id) { PurpleAccount *account = change->account; purple_account_set_username(account, change->username); g_free(change->username); g_free(change); prpltwtr_verify_connection(account); } static void account_username_change_verify(PurpleAccount * account, const gchar * username) { PurpleConnection *gc = purple_account_get_connection(account); gchar *secondary = g_strdup_printf(_("Do you wish to change the name on this account to %s?"), username); TwitterAccountUserNameChange *change_data = (TwitterAccountUserNameChange *) g_new0(TwitterAccountUserNameChange *, 1); change_data->account = account; change_data->username = g_strdup(username); purple_request_action(gc, _("Mismatched Screen Names"), _("Authorized screen name does not match with account screen name"), secondary, 0, account, NULL, NULL, change_data, 2, _("Cancel"), account_mismatch_screenname_change_cancel_cb, _("Yes"), account_mismatch_screenname_change_ok_cb, NULL); g_free(secondary); } static void verify_credentials_success_cb(TwitterRequestor * r, xmlnode * node, gpointer user_data) { PurpleAccount *account = r->account; TwitterUserTweet *user_tweet = twitter_verify_credentials_parse(node); char **userparts = g_strsplit(purple_account_get_username(r->account), "@", 2); const char *username = userparts[0]; if (!user_tweet || !user_tweet->screen_name) { prpltwtr_disconnect(account, _("Could not verify credentials")); } else if (!twitter_usernames_match(account, user_tweet->screen_name, username)) { account_username_change_verify(account, user_tweet->screen_name); } else { prpltwtr_verify_connection(account); } g_strfreev(userparts); twitter_user_tweet_free(user_tweet); } static void verify_credentials_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data) { gchar *error = g_strdup_printf(_("Error verifying credentials: %s"), error_data->message ? error_data->message : _("unknown error")); switch (error_data->type) { case TWITTER_REQUEST_ERROR_SERVER: case TWITTER_REQUEST_ERROR_CANCELED: prpltwtr_recoverable_disconnect(r->account, error); break; case TWITTER_REQUEST_ERROR_NONE: case TWITTER_REQUEST_ERROR_TWITTER_GENERAL: case TWITTER_REQUEST_ERROR_INVALID_XML: case TWITTER_REQUEST_ERROR_NO_OAUTH: case TWITTER_REQUEST_ERROR_UNAUTHORIZED: default: prpltwtr_disconnect(r->account, error); break; } g_free(error); } static void oauth_request_token_success_cb(TwitterRequestor * r, const gchar * response, gpointer user_data) { PurpleAccount *account = r->account; PurpleConnection *gc = purple_account_get_connection(account); TwitterConnectionData *twitter = gc->proto_data; GHashTable *results = oauth_result_to_hashtable(response); const gchar *oauth_token = g_hash_table_lookup(results, "oauth_token"); const gchar *oauth_token_secret = g_hash_table_lookup(results, "oauth_token_secret"); if (oauth_token && oauth_token_secret) { /* http://api.twitter.com/oauth/authorize */ gchar *msg = g_strdup_printf("http://%s?oauth_token=%s", twitter_option_url_oauth_authorize(account), purple_url_encode(oauth_token)); gchar *prompt = g_strdup_printf("%s %s", _("Please enter PIN for"), purple_account_get_username(account)); twitter->oauth_token = g_strdup(oauth_token); twitter->oauth_token_secret = g_strdup(oauth_token_secret); purple_notify_uri(twitter, msg); purple_request_input(twitter, _("OAuth Authentication"), //title prompt, //primary msg, //secondary NULL, //default FALSE, //multiline, FALSE, //password NULL, //hint _("Submit"), //ok text G_CALLBACK(oauth_request_pin_ok), _("Cancel"), G_CALLBACK(oauth_request_pin_cancel), account, NULL, NULL, account); g_free(msg); g_free(prompt); } else { purple_debug_error(purple_account_get_protocol_id(account), "Unknown error receiving request token: %s\n", response); prpltwtr_disconnect(account, _("Invalid response receiving request token")); } g_hash_table_destroy(results); } static void oauth_request_token_error_cb(TwitterRequestor * r, const TwitterRequestErrorData * error_data, gpointer user_data) { gchar *error = g_strdup_printf(_("Error receiving request token: %s"), error_data->message ? error_data->message : _("unknown error")); prpltwtr_disconnect(r->account, error); g_free(error); } static const gchar *account_get_oauth_access_token(PurpleAccount * account) { return purple_account_get_string(account, "oauth_token", NULL); } static void account_set_oauth_access_token(PurpleAccount * account, const gchar * oauth_token) { purple_account_set_string(account, "oauth_token", oauth_token); } static const gchar *account_get_oauth_access_token_secret(PurpleAccount * account) { return purple_account_get_string(account, "oauth_token_secret", NULL); } static void account_set_oauth_access_token_secret(PurpleAccount * account, const gchar * oauth_token) { purple_account_set_string(account, "oauth_token_secret", oauth_token); } static void oauth_request_pin_ok(PurpleAccount * account, const gchar * pin) { TwitterRequestParams *params = twitter_request_params_new(); twitter_request_params_add(params, twitter_request_param_new("oauth_verifier", pin)); twitter_send_request(purple_account_get_requestor(account), FALSE, twitter_option_url_oauth_access_token(account), params, oauth_access_token_success_cb, oauth_access_token_error_cb, NULL); twitter_request_params_free(params); } static void oauth_request_pin_cancel(PurpleAccount * account, const gchar * pin) { prpltwtr_disconnect(account, _("Canceled PIN entry")); } static const gchar *twitter_option_url_oauth_authorize(PurpleAccount * account) { return twitter_oauth_create_url(account, "/authorize"); } static const gchar *twitter_option_url_oauth_request_token(PurpleAccount * account) { return twitter_oauth_create_url(account, "/request_token"); } static const gchar *twitter_option_url_oauth_access_token(PurpleAccount * account) { return twitter_oauth_create_url(account, "/access_token"); } static const gchar *twitter_oauth_create_url(PurpleAccount * account, const gchar * endpoint) { static char url[1024]; char host[256]; g_return_val_if_fail(endpoint != NULL && endpoint[0] != '\0', NULL); if (!strcmp(purple_account_get_protocol_id(account), TWITTER_PROTOCOL_ID)) { snprintf(host, 255, "api.twitter.com/oauth"); } else { snprintf(host, 255, "%s/oauth", purple_account_get_string(account, TWITTER_PREF_API_BASE, STATUSNET_PREF_API_BASE_DEFAULT)); } snprintf(url, 1023, "%s%s%s", host, host[strlen(host) - 1] == '/' || endpoint[0] == '/' ? "" : "/", host[strlen(host) - 1] == '/' && endpoint[0] == '/' ? endpoint + 1 : endpoint); return url; }
Java
/* * Definitions for akm8975 compass chip. */ #ifndef AKM8975_H #define AKM8975_H #include <linux/ioctl.h> #define AKM8975_I2C_NAME "akm8975" /*! \name AK8975 operation mode \anchor AK8975_Mode Defines an operation mode of the AK8975.*/ /*! @{*/ #define AK8975_MODE_SNG_MEASURE 0x01 #define AK8975_MODE_SELF_TEST 0x08 #define AK8975_MODE_FUSE_ACCESS 0x0F #define AK8975_MODE_POWERDOWN 0x00 /*! @}*/ #define SENSOR_DATA_SIZE 8 #define RWBUF_SIZE 16 /*! \name AK8975 register address \anchor AK8975_REG Defines a register address of the AK8975.*/ /*! @{*/ #define AK8975_REG_WIA 0x00 #define AK8975_REG_INFO 0x01 #define AK8975_REG_ST1 0x02 #define AK8975_REG_HXL 0x03 #define AK8975_REG_HXH 0x04 #define AK8975_REG_HYL 0x05 #define AK8975_REG_HYH 0x06 #define AK8975_REG_HZL 0x07 #define AK8975_REG_HZH 0x08 #define AK8975_REG_ST2 0x09 #define AK8975_REG_CNTL 0x0A #define AK8975_REG_RSV 0x0B #define AK8975_REG_ASTC 0x0C #define AK8975_REG_TS1 0x0D #define AK8975_REG_TS2 0x0E #define AK8975_REG_I2CDIS 0x0F /*! @}*/ /*! \name AK8975 fuse-rom address \anchor AK8975_FUSE Defines a read-only address of the fuse ROM of the AK8975.*/ /*! @{*/ #define AK8975_FUSE_ASAX 0x10 #define AK8975_FUSE_ASAY 0x11 #define AK8975_FUSE_ASAZ 0x12 /*! @}*/ #define AKMIO 0xA1 /* IOCTLs for AKM library */ #define ECS_IOCTL_WRITE _IOW(AKMIO, 0x01, char*) #define ECS_IOCTL_READ _IOWR(AKMIO, 0x02, char*) #define ECS_IOCTL_RESET _IO(AKMIO, 0x03) #define ECS_IOCTL_SET_MODE _IOW(AKMIO, 0x04, short) #define ECS_IOCTL_GETDATA _IOR(AKMIO, 0x05, char[SENSOR_DATA_SIZE]) #define ECS_IOCTL_SET_YPR _IOW(AKMIO, 0x06, short[12]) #define ECS_IOCTL_GET_OPEN_STATUS _IOR(AKMIO, 0x07, int) #define ECS_IOCTL_GET_CLOSE_STATUS _IOR(AKMIO, 0x08, int) #define ECS_IOCTL_GET_DELAY _IOR(AKMIO, 0x30, short) #define ECS_IOCTL_GET_PROJECT_NAME _IOR(AKMIO, 0x0D, char[64]) #define ECS_IOCTL_GET_MATRIX _IOR(AKMIO, 0x0E, short [4][3][3]) /* IOCTLs for APPs */ #define ECS_IOCTL_APP_SET_MODE _IOW(AKMIO, 0x10, short)/* NOT use */ #define ECS_IOCTL_APP_SET_MFLAG _IOW(AKMIO, 0x11, short) #define ECS_IOCTL_APP_GET_MFLAG _IOW(AKMIO, 0x12, short) #define ECS_IOCTL_APP_SET_AFLAG _IOW(AKMIO, 0x13, short) #define ECS_IOCTL_APP_GET_AFLAG _IOR(AKMIO, 0x14, short) #define ECS_IOCTL_APP_SET_TFLAG _IOR(AKMIO, 0x15, short)/* NOT use */ #define ECS_IOCTL_APP_GET_TFLAG _IOR(AKMIO, 0x16, short)/* NOT use */ #define ECS_IOCTL_APP_RESET_PEDOMETER _IO(AKMIO, 0x17) /* NOT use */ #define ECS_IOCTL_APP_SET_DELAY _IOW(AKMIO, 0x18, short) #define ECS_IOCTL_APP_GET_DELAY ECS_IOCTL_GET_DELAY #define ECS_IOCTL_APP_SET_MVFLAG _IOW(AKMIO, 0x19, short) #define ECS_IOCTL_APP_GET_MVFLAG _IOR(AKMIO, 0x1A, short) /* */ #define ECS_IOCTL_APP_SET_PFLAG _IOR(AKMIO, 0x1B, short) /* Get proximity flag */ #define ECS_IOCTL_APP_GET_PFLAG _IOR(AKMIO, 0x1C, short) /* Set proximity flag */ /* */ #define ECS_IOCTL_GET_ACCEL_PATH _IOR(AKMIO, 0x20, char[30]) #define ECS_IOCTL_ACCEL_INIT _IOR(AKMIO, 0x21, int[7]) #define ECS_IOCTL_GET_ALAYOUT_INIO _IOR(AKMIO, 0x22, signed short[18]) #define ECS_IOCTL_GET_HLAYOUT_INIO _IOR(AKMIO, 0x23, signed short[18]) #define AKMD2_TO_ACCEL_IOCTL_READ_XYZ _IOWR(AKMIO, 0x31, int) #define AKMD2_TO_ACCEL_IOCTL_ACCEL_INIT _IOWR(AKMIO, 0x32, int) /* original source struct akm8975_platform_data { char layouts[3][3]; char project_name[64]; int gpio_DRDY; }; */ #endif
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Swift Kanban Webinar Series</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <meta name="robots" content="noindex,nofollow"/> </head> <body> <table align="center" style="float:none;width:500px; background-color:#FFFFFF; border: none; border-width: 0px; font-family: Arial;"> <tbody> <!--<tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px; text-align:center;"> <span style='font-size:9px;'>If you are not able to view the email properly click <a href='http://www.Swift-Kanban.com/emailer/masa_kanban_beyond_IT_ and_software/invitation_email.html'>Here</a></span> </td> <td style="width:5px;"></td> </tr> --> <tr style="vertical-align: middle;"> <td style="width:5px;"></td> <td style="width:120px; text-align: left;"> <a href="http://www.swift-kanban.com"> <img src="http://app.streamsend.com/public_images/266321/images/kanban.JPG" border="0" alt="Swift kanban Logo"/> </a> </td> <td style="width:370px; text-align: right;font-family: Arial; font-size: 13px; font-weight: bold; vertical-align: bottom;"> Dr. Masa Maeda Webinar </td> <td style="width:5px;"></td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px; text-align: left;font-size: 8px;"> <hr style="border: none;background-color:#d3d3d3;height: 3px;"/> </td> <td style="width:5px;"></td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px; text-align: left;font-family: Arial;font-weight: bold;line-height: 24px;"> <span style="font-size: 13px; color: #000000;">Webinar: Jun 06, 2012; 10 AM - 11 AM Pacific</span><br/> </td> <td style="width:5px;"></td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:500px; text-align: center;"> <center><a href="http://www.swift-kanban.com/masa_webinar"> <img src="http://www.swift-kanban.com/emailer/masa_kanban_beyond_IT_ and_software/webinar-header.jpg" style="width: 500px;height:101px;"/> </a></center> </td> <td style="width:5px;"></td> </tr> <tr style="height: 0px; font-size: 5px;"> <td colspan="3" style="height: 0px">&nbsp;</td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px; text-align: justify;font-family: Arial; font-size: 13px; line-height: 20px;"> <b style="line-height: 30px;">Kanban - Beyond IT and Software!</b><br/> One of the important contributors to the success of several organizations is alignment of IT strategy with Business for achieving Corporate Goals. If <strong><em>Reduced Waste</em></strong> and <strong><em>Smooth Flow</em></strong> (or streamlined processes) throughout the enterprise are part of your corporate strategy, then you should look at Kanban. While Kanban is making waves in IT operations and Software development, it is also proving invaluable for a number of forward-thinking business functions such as HR, sales, marketing, insurance claims and more! <br/> <br/> Come hear Dr. Masa K Maeda, renowned thought leader, consultant and coach for Lean Value Innovation, discuss the tremendous benefits of Kanban not only in IT but also for other divisions or BUs of your organization like Sales. <u>Invite your business colleagues</u> to collaboratively use Kanban for improving throughput, quality and other business benefits throughout the enterprise. <br/> <br/> <b style="font-size: 15px;">Click <a href="http://www.swift-kanban.com/masa_webinar"> here</a> to Register for the webinar</b><br/> Date: Jun 06, 2012; 10 AM - 11 AM Pacific <br/> <br/> Thank you and we hope that you will join us! <br/> <br/> Swift-Kanban Team <br/> <a href="http://www.swift-kanban.com">http://www.swift-kanban.com</a> </td> <td style="width:5px;"></td> </tr> <tr> <td style="width:5px;"></td> <td colspan="2" style="width:540px;height:5px;"> </td> <td style="width:5px;"></td> </tr> <!-- Social Media starts here--> <tr style="background-color: #99FFFF;"> <td colspan="3" style="width:540px;height:20px;"> <table> <tr> <td style="text-align: left;"> <table style="float: left;"> <tr> <td align="right" valign="middle" style='color: #000000; font-family: "Arial"; font-size:14px;'> Follow us: </td> <td align="center" valign="middle" style='color: #000000; font-family: "Arial";font-size:14px;'> <a style="text-decoration: none; border: medium none;" target="_blank" href="http://www.facebook.com/digite"><img src="http://cache.addthis.com/icons/v1/thumbs/facebook.gif" width="16px" border="0" alt=" f" title="Facebook"/></a> </td> <td align="center" valign="middle" style='color: #000000; font-family: "Arial";font-size:14px;'> <a style="text-decoration: none;" target="_blank" href="http://twitter.com/swiftkanban"><img src="http://cache.addthis.com/icons/v1/thumbs/twitter.gif" width="16px" hspace="0" border="0" alt=" t" title="Twitter"></a> </td> <td align="center" valign="middle" style='color: #000000; font-family: "Arial";font-size:14px;'> <a target="_blank" href="http://www.swift-kanban.com/community/blog"><img src="http://cache.addthiscdn.com/icons/v1/thumbs/blogger.gif" width="16px" border="0" alt=" B" title="Blog"></a> </td> <td align="center" valign="middle" style='color:#000000; font-family: "Arial";font-size:14px;'></a> </td> </tr> </table> </td> </tr> </table> </td> </tr> <!-- Social Media ends here --> <tr> <td colspan="3" style="width:540px; text-align: justify;font-family: Arial; font-size: 11px;"> Digite, Inc. is a leading provider of Lean/ Agile ALM and PPM products and solutions, based out of Mountain View, CA. Digite products and solutions have helped thousands of users around the world manage and deliver large and complex projects and applications executed by distributed teams, both in-house and outsourced. To learn more, please visit <a href="http://www.swift-kanban.com" target="_blank" style="text-decoration: none;">www.swift-kanban.com</a> or <a href="http://www.digite.com" target="_blank" style="text-decoration: none;">www.digite.com<br/> <br/> </a><em>Copyright &copy; 2012 Digite, Inc. All rights reserved.</em> <br/> You are receiving this email as you signed up with Digite or one of our media partners. If you have any questions, please contact us at <a href="mailto:marketing@digite.com" style="text-decoration: none;">marketing@digite.com </a> <br/> <br/> Our mailing address is: Digite, Inc., 82 Pioneer Way, Suite 102, Mountain View, CA 94041 <br/><br/> <!-- To manage your communication preferences/subscription with us <a href="{{{unsubscribe}}}">click here</a> --> </td> </tr> </tbody> </table> </body> </html>
Java
/* * Copyright 2002-2011 the original author or authors. * * 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 org.springframework.cache.interceptor; import java.io.Serializable; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; /** * AOP Alliance MethodInterceptor for declarative cache * management using the common Spring caching infrastructure * ({@link org.springframework.cache.Cache}). * * <p>Derives from the {@link CacheAspectSupport} class which * contains the integration with Spring's underlying caching API. * CacheInterceptor simply calls the relevant superclass methods * in the correct order. * * <p>CacheInterceptors are thread-safe. * * @author Costin Leau * @author Juergen Hoeller * @since 3.1 */ @SuppressWarnings("serial") public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable { private static class ThrowableWrapper extends RuntimeException { private final Throwable original; ThrowableWrapper(Throwable original) { this.original = original; } } public Object invoke(final MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); Invoker aopAllianceInvoker = new Invoker() { public Object invoke() { try { return invocation.proceed(); } catch (Throwable ex) { throw new ThrowableWrapper(ex); } } }; try { return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments()); } catch (ThrowableWrapper th) { throw th.original; } } }
Java
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.protocols.jmx.connectors; import javax.management.MBeanServerConnection; /* * This interface defines the ability to handle a live connection and the ability to * close it. * * @author <A HREF="mailto:mike@opennms.org">Mike Jamison </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> */ /** * <p>ConnectionWrapper interface.</p> * * @author ranger * @version $Id: $ */ public interface ConnectionWrapper { /** * <p>getMBeanServer</p> * * @return a {@link javax.management.MBeanServerConnection} object. */ public MBeanServerConnection getMBeanServer(); /** * <p>close</p> */ public void close(); }
Java