code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; namespace Microsoft.ProcessDomain { [Serializable] internal class CrossDomainInvokeRequest { public Guid MessageId { get; set; } public MethodInfo Method { get; set; } public object[] Arguments { get; set; } public byte[] ToByteArray() { MemoryStream memStream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memStream, this); return memStream.ToArray(); } public static CrossDomainInvokeRequest FromByteArray(byte[] bytes) { MemoryStream memStream = new MemoryStream(bytes); BinaryFormatter formatter = new BinaryFormatter(); return (CrossDomainInvokeRequest)formatter.Deserialize(memStream); } } }
mmitche/xunit-performance
src/procdomain/CrossDomainInvokeRequest.cs
C#
mit
1,087
class Author < ActiveRecord::Base has_many :posts has_many :posts_with_comments, :include => :comments, :class_name => "Post" has_many :popular_grouped_posts, :include => :comments, :class_name => "Post", :group => "type", :having => "SUM(comments_count) > 1", :select => "type" has_many :posts_with_comments_sorted_by_comment_id, :include => :comments, :class_name => "Post", :order => 'comments.id' has_many :posts_sorted_by_id_limited, :class_name => "Post", :order => 'posts.id', :limit => 1 has_many :posts_with_categories, :include => :categories, :class_name => "Post" has_many :posts_with_comments_and_categories, :include => [ :comments, :categories ], :order => "posts.id", :class_name => "Post" has_many :posts_containing_the_letter_a, :class_name => "Post" has_many :posts_with_extension, :class_name => "Post" do #, :extend => ProxyTestExtension def testing_proxy_owner proxy_owner end def testing_proxy_reflection proxy_reflection end def testing_proxy_target proxy_target end end has_one :post_about_thinking, :class_name => 'Post', :conditions => "posts.title like '%thinking%'" has_one :post_about_thinking_with_last_comment, :class_name => 'Post', :conditions => "posts.title like '%thinking%'", :include => :last_comment has_many :comments, :through => :posts has_many :comments_containing_the_letter_e, :through => :posts, :source => :comments has_many :comments_with_order_and_conditions, :through => :posts, :source => :comments, :order => 'comments.body', :conditions => "comments.body like 'Thank%'" has_many :comments_with_include, :through => :posts, :source => :comments, :include => :post has_many :thinking_posts, :class_name => 'Post', :conditions => { :title => 'So I was thinking' }, :dependent => :delete_all has_many :welcome_posts, :class_name => 'Post', :conditions => { :title => 'Welcome to the weblog' } has_many :comments_desc, :through => :posts, :source => :comments, :order => 'comments.id DESC' has_many :limited_comments, :through => :posts, :source => :comments, :limit => 1 has_many :funky_comments, :through => :posts, :source => :comments has_many :ordered_uniq_comments, :through => :posts, :source => :comments, :uniq => true, :order => 'comments.id' has_many :ordered_uniq_comments_desc, :through => :posts, :source => :comments, :uniq => true, :order => 'comments.id DESC' has_many :readonly_comments, :through => :posts, :source => :comments, :readonly => true has_many :special_posts has_many :special_post_comments, :through => :special_posts, :source => :comments has_many :sti_posts, :class_name => 'StiPost' has_many :sti_post_comments, :through => :sti_posts, :source => :comments has_many :special_nonexistant_posts, :class_name => "SpecialPost", :conditions => "posts.body = 'nonexistant'" has_many :special_nonexistant_post_comments, :through => :special_nonexistant_posts, :source => :comments, :conditions => "comments.post_id = 0" has_many :nonexistant_comments, :through => :posts has_many :hello_posts, :class_name => "Post", :conditions => "posts.body = 'hello'" has_many :hello_post_comments, :through => :hello_posts, :source => :comments has_many :posts_with_no_comments, :class_name => 'Post', :conditions => 'comments.id is null', :include => :comments has_many :hello_posts_with_hash_conditions, :class_name => "Post", :conditions => {:body => 'hello'} has_many :hello_post_comments_with_hash_conditions, :through => :hello_posts_with_hash_conditions, :source => :comments has_many :other_posts, :class_name => "Post" has_many :posts_with_callbacks, :class_name => "Post", :before_add => :log_before_adding, :after_add => :log_after_adding, :before_remove => :log_before_removing, :after_remove => :log_after_removing has_many :posts_with_proc_callbacks, :class_name => "Post", :before_add => Proc.new {|o, r| o.post_log << "before_adding#{r.id || '<new>'}"}, :after_add => Proc.new {|o, r| o.post_log << "after_adding#{r.id || '<new>'}"}, :before_remove => Proc.new {|o, r| o.post_log << "before_removing#{r.id}"}, :after_remove => Proc.new {|o, r| o.post_log << "after_removing#{r.id}"} has_many :posts_with_multiple_callbacks, :class_name => "Post", :before_add => [:log_before_adding, Proc.new {|o, r| o.post_log << "before_adding_proc#{r.id || '<new>'}"}], :after_add => [:log_after_adding, Proc.new {|o, r| o.post_log << "after_adding_proc#{r.id || '<new>'}"}] has_many :unchangable_posts, :class_name => "Post", :before_add => :raise_exception, :after_add => :log_after_adding has_many :categorizations has_many :categories, :through => :categorizations has_many :categories_like_general, :through => :categorizations, :source => :category, :class_name => 'Category', :conditions => { :name => 'General' } has_many :categorized_posts, :through => :categorizations, :source => :post has_many :unique_categorized_posts, :through => :categorizations, :source => :post, :uniq => true has_many :nothings, :through => :kateggorisatons, :class_name => 'Category' has_many :author_favorites has_many :favorite_authors, :through => :author_favorites, :order => 'name' has_many :tagging, :through => :posts # through polymorphic has_one has_many :taggings, :through => :posts, :source => :taggings # through polymorphic has_many has_many :tags, :through => :posts # through has_many :through has_many :post_categories, :through => :posts, :source => :categories has_one :essay, :primary_key => :name, :as => :writer belongs_to :author_address, :dependent => :destroy belongs_to :author_address_extra, :dependent => :delete, :class_name => "AuthorAddress" attr_accessor :post_log def after_initialize @post_log = [] end def label "#{id}-#{name}" end private def log_before_adding(object) @post_log << "before_adding#{object.id || '<new>'}" end def log_after_adding(object) @post_log << "after_adding#{object.id}" end def log_before_removing(object) @post_log << "before_removing#{object.id}" end def log_after_removing(object) @post_log << "after_removing#{object.id}" end def raise_exception(object) raise Exception.new("You can't add a post") end end class AuthorAddress < ActiveRecord::Base has_one :author def self.destroyed_author_address_ids @destroyed_author_address_ids ||= Hash.new { |h,k| h[k] = [] } end before_destroy do |author_address| if author_address.author AuthorAddress.destroyed_author_address_ids[author_address.author.id] << author_address.id end true end end class AuthorFavorite < ActiveRecord::Base belongs_to :author belongs_to :favorite_author, :class_name => "Author" end
unilogic/zackup
vendor/rails/activerecord/test/models/author.rb
Ruby
mit
6,912
// Copyright 2012-present Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import ( "context" "encoding/json" "fmt" "net/http" "net/url" "strings" "github.com/olivere/elastic/v7/uritemplates" ) // NodesStatsService returns node statistics. // See http://www.elastic.co/guide/en/elasticsearch/reference/7.0/cluster-nodes-stats.html // for details. type NodesStatsService struct { client *Client pretty *bool // pretty format the returned JSON response human *bool // return human readable values for statistics errorTrace *bool // include the stack trace of returned errors filterPath []string // list of filters used to reduce the response headers http.Header // custom request-level HTTP headers metric []string indexMetric []string nodeId []string completionFields []string fielddataFields []string fields []string groups *bool level string timeout string types []string } // NewNodesStatsService creates a new NodesStatsService. func NewNodesStatsService(client *Client) *NodesStatsService { return &NodesStatsService{ client: client, } } // Pretty tells Elasticsearch whether to return a formatted JSON response. func (s *NodesStatsService) Pretty(pretty bool) *NodesStatsService { s.pretty = &pretty return s } // Human specifies whether human readable values should be returned in // the JSON response, e.g. "7.5mb". func (s *NodesStatsService) Human(human bool) *NodesStatsService { s.human = &human return s } // ErrorTrace specifies whether to include the stack trace of returned errors. func (s *NodesStatsService) ErrorTrace(errorTrace bool) *NodesStatsService { s.errorTrace = &errorTrace return s } // FilterPath specifies a list of filters used to reduce the response. func (s *NodesStatsService) FilterPath(filterPath ...string) *NodesStatsService { s.filterPath = filterPath return s } // Header adds a header to the request. func (s *NodesStatsService) Header(name string, value string) *NodesStatsService { if s.headers == nil { s.headers = http.Header{} } s.headers.Add(name, value) return s } // Headers specifies the headers of the request. func (s *NodesStatsService) Headers(headers http.Header) *NodesStatsService { s.headers = headers return s } // Metric limits the information returned to the specified metrics. func (s *NodesStatsService) Metric(metric ...string) *NodesStatsService { s.metric = append(s.metric, metric...) return s } // IndexMetric limits the information returned for `indices` metric // to the specific index metrics. Isn't used if `indices` (or `all`) // metric isn't specified.. func (s *NodesStatsService) IndexMetric(indexMetric ...string) *NodesStatsService { s.indexMetric = append(s.indexMetric, indexMetric...) return s } // NodeId is a list of node IDs or names to limit the returned information; // use `_local` to return information from the node you're connecting to, // leave empty to get information from all nodes. func (s *NodesStatsService) NodeId(nodeId ...string) *NodesStatsService { s.nodeId = append(s.nodeId, nodeId...) return s } // CompletionFields is a list of fields for `fielddata` and `suggest` // index metric (supports wildcards). func (s *NodesStatsService) CompletionFields(completionFields ...string) *NodesStatsService { s.completionFields = append(s.completionFields, completionFields...) return s } // FielddataFields is a list of fields for `fielddata` index metric (supports wildcards). func (s *NodesStatsService) FielddataFields(fielddataFields ...string) *NodesStatsService { s.fielddataFields = append(s.fielddataFields, fielddataFields...) return s } // Fields is a list of fields for `fielddata` and `completion` index metric (supports wildcards). func (s *NodesStatsService) Fields(fields ...string) *NodesStatsService { s.fields = append(s.fields, fields...) return s } // Groups is a list of search groups for `search` index metric. func (s *NodesStatsService) Groups(groups bool) *NodesStatsService { s.groups = &groups return s } // Level specifies whether to return indices stats aggregated at node, index or shard level. func (s *NodesStatsService) Level(level string) *NodesStatsService { s.level = level return s } // Timeout specifies an explicit operation timeout. func (s *NodesStatsService) Timeout(timeout string) *NodesStatsService { s.timeout = timeout return s } // Types a list of document types for the `indexing` index metric. func (s *NodesStatsService) Types(types ...string) *NodesStatsService { s.types = append(s.types, types...) return s } // buildURL builds the URL for the operation. func (s *NodesStatsService) buildURL() (string, url.Values, error) { var err error var path string if len(s.nodeId) > 0 && len(s.metric) > 0 && len(s.indexMetric) > 0 { path, err = uritemplates.Expand("/_nodes/{node_id}/stats/{metric}/{index_metric}", map[string]string{ "index_metric": strings.Join(s.indexMetric, ","), "node_id": strings.Join(s.nodeId, ","), "metric": strings.Join(s.metric, ","), }) } else if len(s.nodeId) > 0 && len(s.metric) > 0 && len(s.indexMetric) == 0 { path, err = uritemplates.Expand("/_nodes/{node_id}/stats/{metric}", map[string]string{ "node_id": strings.Join(s.nodeId, ","), "metric": strings.Join(s.metric, ","), }) } else if len(s.nodeId) > 0 && len(s.metric) == 0 && len(s.indexMetric) > 0 { path, err = uritemplates.Expand("/_nodes/{node_id}/stats/_all/{index_metric}", map[string]string{ "index_metric": strings.Join(s.indexMetric, ","), "node_id": strings.Join(s.nodeId, ","), }) } else if len(s.nodeId) > 0 && len(s.metric) == 0 && len(s.indexMetric) == 0 { path, err = uritemplates.Expand("/_nodes/{node_id}/stats", map[string]string{ "node_id": strings.Join(s.nodeId, ","), }) } else if len(s.nodeId) == 0 && len(s.metric) > 0 && len(s.indexMetric) > 0 { path, err = uritemplates.Expand("/_nodes/stats/{metric}/{index_metric}", map[string]string{ "index_metric": strings.Join(s.indexMetric, ","), "metric": strings.Join(s.metric, ","), }) } else if len(s.nodeId) == 0 && len(s.metric) > 0 && len(s.indexMetric) == 0 { path, err = uritemplates.Expand("/_nodes/stats/{metric}", map[string]string{ "metric": strings.Join(s.metric, ","), }) } else if len(s.nodeId) == 0 && len(s.metric) == 0 && len(s.indexMetric) > 0 { path, err = uritemplates.Expand("/_nodes/stats/_all/{index_metric}", map[string]string{ "index_metric": strings.Join(s.indexMetric, ","), }) } else { // if len(s.nodeId) == 0 && len(s.metric) == 0 && len(s.indexMetric) == 0 { path = "/_nodes/stats" } if err != nil { return "", url.Values{}, err } // Add query string parameters params := url.Values{} if v := s.pretty; v != nil { params.Set("pretty", fmt.Sprint(*v)) } if v := s.human; v != nil { params.Set("human", fmt.Sprint(*v)) } if v := s.errorTrace; v != nil { params.Set("error_trace", fmt.Sprint(*v)) } if len(s.filterPath) > 0 { params.Set("filter_path", strings.Join(s.filterPath, ",")) } if len(s.completionFields) > 0 { params.Set("completion_fields", strings.Join(s.completionFields, ",")) } if len(s.fielddataFields) > 0 { params.Set("fielddata_fields", strings.Join(s.fielddataFields, ",")) } if len(s.fields) > 0 { params.Set("fields", strings.Join(s.fields, ",")) } if s.groups != nil { params.Set("groups", fmt.Sprintf("%v", *s.groups)) } if s.level != "" { params.Set("level", s.level) } if s.timeout != "" { params.Set("timeout", s.timeout) } if len(s.types) > 0 { params.Set("types", strings.Join(s.types, ",")) } return path, params, nil } // Validate checks if the operation is valid. func (s *NodesStatsService) Validate() error { return nil } // Do executes the operation. func (s *NodesStatsService) Do(ctx context.Context) (*NodesStatsResponse, error) { // Check pre-conditions if err := s.Validate(); err != nil { return nil, err } // Get URL for request path, params, err := s.buildURL() if err != nil { return nil, err } // Get HTTP response res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ Method: "GET", Path: path, Params: params, Headers: s.headers, }) if err != nil { return nil, err } // Return operation response ret := new(NodesStatsResponse) if err := json.Unmarshal(res.Body, ret); err != nil { return nil, err } return ret, nil } // NodesStatsResponse is the response of NodesStatsService.Do. type NodesStatsResponse struct { ClusterName string `json:"cluster_name"` Nodes map[string]*NodesStatsNode `json:"nodes"` } type NodesStatsNode struct { // Timestamp when these stats we're gathered. Timestamp int64 `json:"timestamp"` // Name of the node, e.g. "Mister Fear" Name string `json:"name"` // TransportAddress, e.g. "127.0.0.1:9300" TransportAddress string `json:"transport_address"` // Host is the host name, e.g. "macbookair" Host string `json:"host"` // IP is an IP address, e.g. "192.168.1.2" IP string `json:"ip"` // Roles is a list of the roles of the node, e.g. master, data, ingest. Roles []string `json:"roles"` // Attributes of the node. Attributes map[string]interface{} `json:"attributes"` // Indices returns index information. Indices *NodesStatsIndex `json:"indices"` // OS information, e.g. CPU and memory. OS *NodesStatsNodeOS `json:"os"` // Process information, e.g. max file descriptors. Process *NodesStatsNodeProcess `json:"process"` // JVM information, e.g. VM version. JVM *NodesStatsNodeJVM `json:"jvm"` // ThreadPool information. ThreadPool map[string]*NodesStatsNodeThreadPool `json:"thread_pool"` // FS returns information about the filesystem. FS *NodesStatsNodeFS `json:"fs"` // Network information. Transport *NodesStatsNodeTransport `json:"transport"` // HTTP information. HTTP *NodesStatsNodeHTTP `json:"http"` // Breaker contains information about circuit breakers. Breaker map[string]*NodesStatsBreaker `json:"breakers"` // ScriptStats information. ScriptStats *NodesStatsScriptStats `json:"script"` // Discovery information. Discovery *NodesStatsDiscovery `json:"discovery"` // Ingest information Ingest *NodesStatsIngest `json:"ingest"` } type NodesStatsIndex struct { Docs *NodesStatsDocsStats `json:"docs"` Store *NodesStatsStoreStats `json:"store"` Indexing *NodesStatsIndexingStats `json:"indexing"` Get *NodesStatsGetStats `json:"get"` Search *NodesStatsSearchStats `json:"search"` Merges *NodesStatsMergeStats `json:"merges"` Refresh *NodesStatsRefreshStats `json:"refresh"` Flush *NodesStatsFlushStats `json:"flush"` Warmer *NodesStatsWarmerStats `json:"warmer"` QueryCache *NodesStatsQueryCacheStats `json:"query_cache"` Fielddata *NodesStatsFielddataStats `json:"fielddata"` Percolate *NodesStatsPercolateStats `json:"percolate"` Completion *NodesStatsCompletionStats `json:"completion"` Segments *NodesStatsSegmentsStats `json:"segments"` Translog *NodesStatsTranslogStats `json:"translog"` Suggest *NodesStatsSuggestStats `json:"suggest"` RequestCache *NodesStatsRequestCacheStats `json:"request_cache"` Recovery NodesStatsRecoveryStats `json:"recovery"` Indices map[string]*NodesStatsIndex `json:"indices"` // for level=indices Shards map[string]*NodesStatsIndex `json:"shards"` // for level=shards } type NodesStatsDocsStats struct { Count int64 `json:"count"` Deleted int64 `json:"deleted"` } type NodesStatsStoreStats struct { Size string `json:"size"` SizeInBytes int64 `json:"size_in_bytes"` } type NodesStatsIndexingStats struct { IndexTotal int64 `json:"index_total"` IndexTime string `json:"index_time"` IndexTimeInMillis int64 `json:"index_time_in_millis"` IndexCurrent int64 `json:"index_current"` IndexFailed int64 `json:"index_failed"` DeleteTotal int64 `json:"delete_total"` DeleteTime string `json:"delete_time"` DeleteTimeInMillis int64 `json:"delete_time_in_millis"` DeleteCurrent int64 `json:"delete_current"` NoopUpdateTotal int64 `json:"noop_update_total"` IsThrottled bool `json:"is_throttled"` ThrottledTime string `json:"throttle_time"` // no typo, see https://github.com/elastic/elasticsearch/blob/ff99bc1d3f8a7ea72718872d214ec2097dfca276/server/src/main/java/org/elasticsearch/index/shard/IndexingStats.java#L244 ThrottledTimeInMillis int64 `json:"throttle_time_in_millis"` Types map[string]*NodesStatsIndexingStats `json:"types"` // stats for individual types } type NodesStatsGetStats struct { Total int64 `json:"total"` Time string `json:"get_time"` TimeInMillis int64 `json:"time_in_millis"` Exists int64 `json:"exists"` ExistsTime string `json:"exists_time"` ExistsTimeInMillis int64 `json:"exists_in_millis"` Missing int64 `json:"missing"` MissingTime string `json:"missing_time"` MissingTimeInMillis int64 `json:"missing_in_millis"` Current int64 `json:"current"` } type NodesStatsSearchStats struct { OpenContexts int64 `json:"open_contexts"` QueryTotal int64 `json:"query_total"` QueryTime string `json:"query_time"` QueryTimeInMillis int64 `json:"query_time_in_millis"` QueryCurrent int64 `json:"query_current"` FetchTotal int64 `json:"fetch_total"` FetchTime string `json:"fetch_time"` FetchTimeInMillis int64 `json:"fetch_time_in_millis"` FetchCurrent int64 `json:"fetch_current"` ScrollTotal int64 `json:"scroll_total"` ScrollTime string `json:"scroll_time"` ScrollTimeInMillis int64 `json:"scroll_time_in_millis"` ScrollCurrent int64 `json:"scroll_current"` Groups map[string]*NodesStatsSearchStats `json:"groups"` // stats for individual groups } type NodesStatsMergeStats struct { Current int64 `json:"current"` CurrentDocs int64 `json:"current_docs"` CurrentSize string `json:"current_size"` CurrentSizeInBytes int64 `json:"current_size_in_bytes"` Total int64 `json:"total"` TotalTime string `json:"total_time"` TotalTimeInMillis int64 `json:"total_time_in_millis"` TotalDocs int64 `json:"total_docs"` TotalSize string `json:"total_size"` TotalSizeInBytes int64 `json:"total_size_in_bytes"` TotalStoppedTime string `json:"total_stopped_time"` TotalStoppedTimeInMillis int64 `json:"total_stopped_time_in_millis"` TotalThrottledTime string `json:"total_throttled_time"` TotalThrottledTimeInMillis int64 `json:"total_throttled_time_in_millis"` TotalThrottleBytes string `json:"total_auto_throttle"` TotalThrottleBytesInBytes int64 `json:"total_auto_throttle_in_bytes"` } type NodesStatsRefreshStats struct { Total int64 `json:"total"` TotalTime string `json:"total_time"` TotalTimeInMillis int64 `json:"total_time_in_millis"` } type NodesStatsFlushStats struct { Total int64 `json:"total"` TotalTime string `json:"total_time"` TotalTimeInMillis int64 `json:"total_time_in_millis"` } type NodesStatsWarmerStats struct { Current int64 `json:"current"` Total int64 `json:"total"` TotalTime string `json:"total_time"` TotalTimeInMillis int64 `json:"total_time_in_millis"` } type NodesStatsQueryCacheStats struct { MemorySize string `json:"memory_size"` MemorySizeInBytes int64 `json:"memory_size_in_bytes"` TotalCount int64 `json:"total_count"` HitCount int64 `json:"hit_count"` MissCount int64 `json:"miss_count"` CacheSize int64 `json:"cache_size"` CacheCount int64 `json:"cache_count"` Evictions int64 `json:"evictions"` } type NodesStatsFielddataStats struct { MemorySize string `json:"memory_size"` MemorySizeInBytes int64 `json:"memory_size_in_bytes"` Evictions int64 `json:"evictions"` Fields map[string]struct { MemorySize string `json:"memory_size"` MemorySizeInBytes int64 `json:"memory_size_in_bytes"` } `json:"fields"` } type NodesStatsPercolateStats struct { Total int64 `json:"total"` Time string `json:"time"` TimeInMillis int64 `json:"time_in_millis"` Current int64 `json:"current"` MemorySize string `json:"memory_size"` MemorySizeInBytes int64 `json:"memory_size_in_bytes"` Queries int64 `json:"queries"` } type NodesStatsCompletionStats struct { Size string `json:"size"` SizeInBytes int64 `json:"size_in_bytes"` Fields map[string]struct { Size string `json:"size"` SizeInBytes int64 `json:"size_in_bytes"` } `json:"fields"` } type NodesStatsSegmentsStats struct { Count int64 `json:"count"` Memory string `json:"memory"` MemoryInBytes int64 `json:"memory_in_bytes"` TermsMemory string `json:"terms_memory"` TermsMemoryInBytes int64 `json:"terms_memory_in_bytes"` StoredFieldsMemory string `json:"stored_fields_memory"` StoredFieldsMemoryInBytes int64 `json:"stored_fields_memory_in_bytes"` TermVectorsMemory string `json:"term_vectors_memory"` TermVectorsMemoryInBytes int64 `json:"term_vectors_memory_in_bytes"` NormsMemory string `json:"norms_memory"` NormsMemoryInBytes int64 `json:"norms_memory_in_bytes"` DocValuesMemory string `json:"doc_values_memory"` DocValuesMemoryInBytes int64 `json:"doc_values_memory_in_bytes"` IndexWriterMemory string `json:"index_writer_memory"` IndexWriterMemoryInBytes int64 `json:"index_writer_memory_in_bytes"` IndexWriterMaxMemory string `json:"index_writer_max_memory"` IndexWriterMaxMemoryInBytes int64 `json:"index_writer_max_memory_in_bytes"` VersionMapMemory string `json:"version_map_memory"` VersionMapMemoryInBytes int64 `json:"version_map_memory_in_bytes"` FixedBitSetMemory string `json:"fixed_bit_set"` // not a typo FixedBitSetMemoryInBytes int64 `json:"fixed_bit_set_memory_in_bytes"` } type NodesStatsTranslogStats struct { Operations int64 `json:"operations"` Size string `json:"size"` SizeInBytes int64 `json:"size_in_bytes"` } type NodesStatsSuggestStats struct { Total int64 `json:"total"` TotalTime string `json:"total_time"` TotalTimeInMillis int64 `json:"total_time_in_millis"` Current int64 `json:"current"` } type NodesStatsRequestCacheStats struct { MemorySize string `json:"memory_size"` MemorySizeInBytes int64 `json:"memory_size_in_bytes"` Evictions int64 `json:"evictions"` HitCount int64 `json:"hit_count"` MissCount int64 `json:"miss_count"` } type NodesStatsRecoveryStats struct { CurrentAsSource int `json:"current_as_source"` CurrentAsTarget int `json:"current_as_target"` } type NodesStatsNodeOS struct { Timestamp int64 `json:"timestamp"` CPU *NodesStatsNodeOSCPU `json:"cpu"` Mem *NodesStatsNodeOSMem `json:"mem"` Swap *NodesStatsNodeOSSwap `json:"swap"` } type NodesStatsNodeOSCPU struct { Percent int `json:"percent"` LoadAverage map[string]float64 `json:"load_average"` // keys are: 1m, 5m, and 15m } type NodesStatsNodeOSMem struct { Total string `json:"total"` TotalInBytes int64 `json:"total_in_bytes"` Free string `json:"free"` FreeInBytes int64 `json:"free_in_bytes"` Used string `json:"used"` UsedInBytes int64 `json:"used_in_bytes"` FreePercent int `json:"free_percent"` UsedPercent int `json:"used_percent"` } type NodesStatsNodeOSSwap struct { Total string `json:"total"` TotalInBytes int64 `json:"total_in_bytes"` Free string `json:"free"` FreeInBytes int64 `json:"free_in_bytes"` Used string `json:"used"` UsedInBytes int64 `json:"used_in_bytes"` } type NodesStatsNodeProcess struct { Timestamp int64 `json:"timestamp"` OpenFileDescriptors int64 `json:"open_file_descriptors"` MaxFileDescriptors int64 `json:"max_file_descriptors"` CPU struct { Percent int `json:"percent"` Total string `json:"total"` TotalInMillis int64 `json:"total_in_millis"` } `json:"cpu"` Mem struct { TotalVirtual string `json:"total_virtual"` TotalVirtualInBytes int64 `json:"total_virtual_in_bytes"` } `json:"mem"` } type NodesStatsNodeJVM struct { Timestamp int64 `json:"timestamp"` Uptime string `json:"uptime"` UptimeInMillis int64 `json:"uptime_in_millis"` Mem *NodesStatsNodeJVMMem `json:"mem"` Threads *NodesStatsNodeJVMThreads `json:"threads"` GC *NodesStatsNodeJVMGC `json:"gc"` BufferPools map[string]*NodesStatsNodeJVMBufferPool `json:"buffer_pools"` Classes *NodesStatsNodeJVMClasses `json:"classes"` } type NodesStatsNodeJVMMem struct { HeapUsed string `json:"heap_used"` HeapUsedInBytes int64 `json:"heap_used_in_bytes"` HeapUsedPercent int `json:"heap_used_percent"` HeapCommitted string `json:"heap_committed"` HeapCommittedInBytes int64 `json:"heap_committed_in_bytes"` HeapMax string `json:"heap_max"` HeapMaxInBytes int64 `json:"heap_max_in_bytes"` NonHeapUsed string `json:"non_heap_used"` NonHeapUsedInBytes int64 `json:"non_heap_used_in_bytes"` NonHeapCommitted string `json:"non_heap_committed"` NonHeapCommittedInBytes int64 `json:"non_heap_committed_in_bytes"` Pools map[string]struct { Used string `json:"used"` UsedInBytes int64 `json:"used_in_bytes"` Max string `json:"max"` MaxInBytes int64 `json:"max_in_bytes"` PeakUsed string `json:"peak_used"` PeakUsedInBytes int64 `json:"peak_used_in_bytes"` PeakMax string `json:"peak_max"` PeakMaxInBytes int64 `json:"peak_max_in_bytes"` } `json:"pools"` } type NodesStatsNodeJVMThreads struct { Count int64 `json:"count"` PeakCount int64 `json:"peak_count"` } type NodesStatsNodeJVMGC struct { Collectors map[string]*NodesStatsNodeJVMGCCollector `json:"collectors"` } type NodesStatsNodeJVMGCCollector struct { CollectionCount int64 `json:"collection_count"` CollectionTime string `json:"collection_time"` CollectionTimeInMillis int64 `json:"collection_time_in_millis"` } type NodesStatsNodeJVMBufferPool struct { Count int64 `json:"count"` TotalCapacity string `json:"total_capacity"` TotalCapacityInBytes int64 `json:"total_capacity_in_bytes"` } type NodesStatsNodeJVMClasses struct { CurrentLoadedCount int64 `json:"current_loaded_count"` TotalLoadedCount int64 `json:"total_loaded_count"` TotalUnloadedCount int64 `json:"total_unloaded_count"` } type NodesStatsNodeThreadPool struct { Threads int `json:"threads"` Queue int `json:"queue"` Active int `json:"active"` Rejected int64 `json:"rejected"` Largest int `json:"largest"` Completed int64 `json:"completed"` } type NodesStatsNodeFS struct { Timestamp int64 `json:"timestamp"` Total *NodesStatsNodeFSEntry `json:"total"` Data []*NodesStatsNodeFSEntry `json:"data"` IOStats *NodesStatsNodeFSIOStats `json:"io_stats"` } type NodesStatsNodeFSEntry struct { Path string `json:"path"` Mount string `json:"mount"` Type string `json:"type"` Total string `json:"total"` TotalInBytes int64 `json:"total_in_bytes"` Free string `json:"free"` FreeInBytes int64 `json:"free_in_bytes"` Available string `json:"available"` AvailableInBytes int64 `json:"available_in_bytes"` Spins string `json:"spins"` } type NodesStatsNodeFSIOStats struct { Devices []*NodesStatsNodeFSIOStatsEntry `json:"devices"` Total *NodesStatsNodeFSIOStatsEntry `json:"total"` } type NodesStatsNodeFSIOStatsEntry struct { DeviceName string `json:"device_name"` Operations int64 `json:"operations"` ReadOperations int64 `json:"read_operations"` WriteOperations int64 `json:"write_operations"` ReadKilobytes int64 `json:"read_kilobytes"` WriteKilobytes int64 `json:"write_kilobytes"` } type NodesStatsNodeTransport struct { ServerOpen int `json:"server_open"` RxCount int64 `json:"rx_count"` RxSize string `json:"rx_size"` RxSizeInBytes int64 `json:"rx_size_in_bytes"` TxCount int64 `json:"tx_count"` TxSize string `json:"tx_size"` TxSizeInBytes int64 `json:"tx_size_in_bytes"` } type NodesStatsNodeHTTP struct { CurrentOpen int `json:"current_open"` TotalOpened int `json:"total_opened"` } type NodesStatsBreaker struct { LimitSize string `json:"limit_size"` LimitSizeInBytes int64 `json:"limit_size_in_bytes"` EstimatedSize string `json:"estimated_size"` EstimatedSizeInBytes int64 `json:"estimated_size_in_bytes"` Overhead float64 `json:"overhead"` Tripped int64 `json:"tripped"` } type NodesStatsScriptStats struct { Compilations int64 `json:"compilations"` CacheEvictions int64 `json:"cache_evictions"` } type NodesStatsDiscovery struct { ClusterStateQueue *NodesStatsDiscoveryStats `json:"cluster_state_queue"` } type NodesStatsDiscoveryStats struct { Total int64 `json:"total"` Pending int64 `json:"pending"` Committed int64 `json:"committed"` } type NodesStatsIngest struct { Total *NodesStatsIngestStats `json:"total"` Pipelines interface{} `json:"pipelines"` } type NodesStatsIngestStats struct { Count int64 `json:"count"` Time string `json:"time"` TimeInMillis int64 `json:"time_in_millis"` Current int64 `json:"current"` Failed int64 `json:"failed"` }
cez81/gitea
vendor/github.com/olivere/elastic/v7/nodes_stats.go
GO
mit
26,654
require 'celluloid' class Eye::ChildProcess include Celluloid # needs: kill_process include Eye::Process::Commands # easy config + defaults: prepare_config, c, [] include Eye::Process::Config # conditional watchers: start_checkers include Eye::Process::Watchers # system methods: send_signal include Eye::Process::System # self_status_data include Eye::Process::Data # manage notify methods include Eye::Process::Notify # scheduler include Eye::Process::Scheduler attr_reader :pid, :name, :full_name, :config, :watchers, :parent def initialize(pid, config = {}, logger_prefix = nil, parent = nil) raise 'Empty pid' unless pid @pid = pid @parent = parent @config = prepare_config(config) @name = "child-#{pid}" @full_name = [logger_prefix, @name] * ':' @watchers = {} debug { "start monitoring CHILD config: #{@config.inspect}" } start_checkers end def logger_tag full_name end def state :up end def up? state == :up end def send_command(command, *args) schedule command, *args, Eye::Reason::User.new(command) end def start end def stop kill_process end def restart if self[:restart_command] execute_restart_command else stop end end def monitor end def unmonitor end def delete end def destroy remove_watchers terminate end def signal(sig) send_signal(sig) if self.pid end def status_data(debug = false) self_status_data(debug) end def prepare_command(command) # override super.gsub('{PARENT_PID}', @parent.pid.to_s) end end
marshall-lee/eye
lib/eye/child_process.rb
Ruby
mit
1,645
from setuptools import setup import re import sys # workaround: nosetests don't exit cleanly with older # python version (<=2.6 and even <2.7.4) try: import multiprocessing except ImportError: pass INSTALL_REQUIRES = [] # extract html5validator version from __init__.py with open('html5validator/__init__.py', 'r') as f: INIT = f.read() VERSION = next(re.finditer('__version__ = \"(.*?)\"', INIT)).group(1) # add argparse dependency for python < 2.7 major, minor1, minor2, release, serial = sys.version_info if major <= 2 and minor1 < 7: INSTALL_REQUIRES.append('argparse==1.2.1') setup( name='html5validator', version=VERSION, packages=['html5validator', 'vnujar'], license='MIT', description='Validate HTML5 files.', long_description=open('README.rst').read(), author='Sven Kreiss', author_email='[email protected]', url='https://github.com/svenkreiss/html5validator', include_package_data=True, install_requires=INSTALL_REQUIRES, entry_points={ 'console_scripts': [ 'html5validator = html5validator.cli:main', ] }, tests_require=[ 'nose', ], test_suite='nose.collector', classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", ] )
afulsom/afulsom.github.io
setup.py
Python
mit
1,507
require File.dirname(__FILE__) + '/../../spec_helper' class DescriptionGenerationSpecController < ActionController::Base def render_action end def redirect_action redirect_to :action => :render_action end end describe "Description generation", :behaviour_type => :controller do controller_name :description_generation_spec before(:each) do @desc = nil @callback = lambda { |desc| @desc = desc } Spec::Matchers.description_generated(@callback) end after(:each) do Spec::Matchers.unregister_description_generated(@callback) end it "should generate description for render_template" do get 'render_action' response.should render_template("render_action") @desc.should == "should render template \"render_action\"" end it "should generate description for render_template with full path" do get 'render_action' response.should render_template("description_generation_spec/render_action") @desc.should == "should render template \"description_generation_spec/render_action\"" end it "should generate description for redirect_to" do get 'redirect_action' response.should redirect_to("http://test.host/description_generation_spec/render_action") @desc.should == "should redirect to \"http://test.host/description_generation_spec/render_action\"" end end
mikeymckay/formtastic.us
vendor/plugins/rspec_on_rails/spec/rails/matchers/description_generation_spec.rb
Ruby
mit
1,351
module CDQ describe "CDQ Magic Method" do before do class << Author include CDQ end class << self include CDQ end end it "wraps an NSManagedObject class in a CDQTargetedQuery" do cdq(Author).class.should == CDQTargetedQuery end it "treats a string as an entity name and returns a CDQTargetedQuery" do cdq('Author').class.should == CDQTargetedQuery end it "treats a symbol as an attribute key and returns a CDQPartialPredicate" do cdq(:name).class.should == CDQPartialPredicate end it "passes through existing CDQObjects unchanged" do query = CDQQuery.new cdq(query).should == query end it "uses 'self' if no object passed in" do Author.cdq.class.should == CDQTargetedQuery end it "works with entities that do not have a specific implementation class" do cdq('Publisher').class.should == CDQTargetedQuery end end end
Watson1978/cdq
spec/cdq/module_spec.rb
Ruby
mit
971
namespace DataStructuresEfficiency { using System; using System.Collections.Generic; using System.Linq; using Wintellect.PowerCollections; public class Store { private OrderedMultiDictionary<decimal, Product> products = new OrderedMultiDictionary<decimal, Product>(true); public OrderedMultiDictionary<decimal, Product> Products { get { return this.products; } set { this.products = value; } } public void AddProduct(Product product) { this.products[product.Price].Add(product); } public ICollection<Product> SearchInPriceRange(decimal from, decimal to) { return this.products.Range(from, true, to, true).Values; } } }
TelerikAcademy/flextry-Telerik-Academy
Programming with C#/5. C# Data Structures and Algorithms/06. Data Structures Efficiency/02. Trade company/Store.cs
C#
mit
873
<div class="search-box"> <div class="input-group input-group-sm"> <div class="input-group-btn"> <button type="button" class="btn btn-default" ><span class="caret"></span></button> </div> <input class="form-control ng-pristine ng-valid" ng-model="config.$" placeholder="Search..."> <!-- /btn-group --> </div> </div>
ksmyth/isis-ui-components
src/library/searchBox/templates/searchBox.html
HTML
mit
371
from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError as DjangoValidationError from django.core.validators import RegexValidator from django.forms import ImageField as DjangoImageField from django.utils import six, timezone from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.encoding import is_protected_type, smart_text from django.utils.translation import ugettext_lazy as _ from rest_framework import ISO_8601 from rest_framework.compat import ( EmailValidator, MinValueValidator, MaxValueValidator, MinLengthValidator, MaxLengthValidator, URLValidator, OrderedDict, unicode_repr, unicode_to_repr ) from rest_framework.exceptions import ValidationError from rest_framework.settings import api_settings from rest_framework.utils import html, representation, humanize_datetime import collections import copy import datetime import decimal import inspect import re import uuid class empty: """ This class is used to represent no data being provided for a given input or output value. It is required because `None` may be a valid input or output value. """ pass def is_simple_callable(obj): """ True if the object is a callable that takes no arguments. """ function = inspect.isfunction(obj) method = inspect.ismethod(obj) if not (function or method): return False args, _, _, defaults = inspect.getargspec(obj) len_args = len(args) if function else len(args) - 1 len_defaults = len(defaults) if defaults else 0 return len_args <= len_defaults def get_attribute(instance, attrs): """ Similar to Python's built in `getattr(instance, attr)`, but takes a list of nested attributes, instead of a single attribute. Also accepts either attribute lookup on objects or dictionary lookups. """ for attr in attrs: if instance is None: # Break out early if we get `None` at any point in a nested lookup. return None try: if isinstance(instance, collections.Mapping): instance = instance[attr] else: instance = getattr(instance, attr) except ObjectDoesNotExist: return None if is_simple_callable(instance): instance = instance() return instance def set_value(dictionary, keys, value): """ Similar to Python's built in `dictionary[key] = value`, but takes a list of nested keys instead of a single key. set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2} set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2} set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}} """ if not keys: dictionary.update(value) return for key in keys[:-1]: if key not in dictionary: dictionary[key] = {} dictionary = dictionary[key] dictionary[keys[-1]] = value class CreateOnlyDefault: """ This class may be used to provide default values that are only used for create operations, but that do not return any value for update operations. """ def __init__(self, default): self.default = default def set_context(self, serializer_field): self.is_update = serializer_field.parent.instance is not None def __call__(self): if self.is_update: raise SkipField() if callable(self.default): return self.default() return self.default def __repr__(self): return unicode_to_repr( '%s(%s)' % (self.__class__.__name__, unicode_repr(self.default)) ) class CurrentUserDefault: def set_context(self, serializer_field): self.user = serializer_field.context['request'].user def __call__(self): return self.user def __repr__(self): return unicode_to_repr('%s()' % self.__class__.__name__) class SkipField(Exception): pass NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`' NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`' NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField' MISSING_ERROR_MESSAGE = ( 'ValidationError raised by `{class_name}`, but error key `{key}` does ' 'not exist in the `error_messages` dictionary.' ) class Field(object): _creation_counter = 0 default_error_messages = { 'required': _('This field is required.'), 'null': _('This field may not be null.') } default_validators = [] default_empty_html = empty initial = None def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=empty, source=None, label=None, help_text=None, style=None, error_messages=None, validators=None, allow_null=False): self._creation_counter = Field._creation_counter Field._creation_counter += 1 # If `required` is unset, then use `True` unless a default is provided. if required is None: required = default is empty and not read_only # Some combinations of keyword arguments do not make sense. assert not (read_only and write_only), NOT_READ_ONLY_WRITE_ONLY assert not (read_only and required), NOT_READ_ONLY_REQUIRED assert not (required and default is not empty), NOT_REQUIRED_DEFAULT assert not (read_only and self.__class__ == Field), USE_READONLYFIELD self.read_only = read_only self.write_only = write_only self.required = required self.default = default self.source = source self.initial = self.initial if (initial is empty) else initial self.label = label self.help_text = help_text self.style = {} if style is None else style self.allow_null = allow_null if self.default_empty_html is not empty: if not required: self.default_empty_html = empty elif default is not empty: self.default_empty_html = default if validators is not None: self.validators = validators[:] # These are set up by `.bind()` when the field is added to a serializer. self.field_name = None self.parent = None # Collect default error message from self and parent classes messages = {} for cls in reversed(self.__class__.__mro__): messages.update(getattr(cls, 'default_error_messages', {})) messages.update(error_messages or {}) self.error_messages = messages def bind(self, field_name, parent): """ Initializes the field name and parent for the field instance. Called when a field is added to the parent serializer instance. """ # In order to enforce a consistent style, we error if a redundant # 'source' argument has been used. For example: # my_field = serializer.CharField(source='my_field') assert self.source != field_name, ( "It is redundant to specify `source='%s'` on field '%s' in " "serializer '%s', because it is the same as the field name. " "Remove the `source` keyword argument." % (field_name, self.__class__.__name__, parent.__class__.__name__) ) self.field_name = field_name self.parent = parent # `self.label` should default to being based on the field name. if self.label is None: self.label = field_name.replace('_', ' ').capitalize() # self.source should default to being the same as the field name. if self.source is None: self.source = field_name # self.source_attrs is a list of attributes that need to be looked up # when serializing the instance, or populating the validated data. if self.source == '*': self.source_attrs = [] else: self.source_attrs = self.source.split('.') # .validators is a lazily loaded property, that gets its default # value from `get_validators`. @property def validators(self): if not hasattr(self, '_validators'): self._validators = self.get_validators() return self._validators @validators.setter def validators(self, validators): self._validators = validators def get_validators(self): return self.default_validators[:] def get_initial(self): """ Return a value to use when the field is being returned as a primitive value, without any object instance. """ return self.initial def get_value(self, dictionary): """ Given the *incoming* primitive data, return the value for this field that should be validated and transformed to a native value. """ if html.is_html_input(dictionary): # HTML forms will represent empty fields as '', and cannot # represent None or False values directly. if self.field_name not in dictionary: if getattr(self.root, 'partial', False): return empty return self.default_empty_html ret = dictionary[self.field_name] if ret == '' and self.allow_null: # If the field is blank, and null is a valid value then # determine if we should use null instead. return '' if getattr(self, 'allow_blank', False) else None return ret return dictionary.get(self.field_name, empty) def get_attribute(self, instance): """ Given the *outgoing* object instance, return the primitive value that should be used for this field. """ try: return get_attribute(instance, self.source_attrs) except (KeyError, AttributeError) as exc: if not self.required and self.default is empty: raise SkipField() msg = ( 'Got {exc_type} when attempting to get a value for field ' '`{field}` on serializer `{serializer}`.\nThe serializer ' 'field might be named incorrectly and not match ' 'any attribute or key on the `{instance}` instance.\n' 'Original exception text was: {exc}.'.format( exc_type=type(exc).__name__, field=self.field_name, serializer=self.parent.__class__.__name__, instance=instance.__class__.__name__, exc=exc ) ) raise type(exc)(msg) def get_default(self): """ Return the default value to use when validating data if no input is provided for this field. If a default has not been set for this field then this will simply return `empty`, indicating that no value should be set in the validated data for this field. """ if self.default is empty: raise SkipField() if callable(self.default): if hasattr(self.default, 'set_context'): self.default.set_context(self) return self.default() return self.default def validate_empty_values(self, data): """ Validate empty values, and either: * Raise `ValidationError`, indicating invalid data. * Raise `SkipField`, indicating that the field should be ignored. * Return (True, data), indicating an empty value that should be returned without any furhter validation being applied. * Return (False, data), indicating a non-empty value, that should have validation applied as normal. """ if self.read_only: return (True, self.get_default()) if data is empty: if getattr(self.root, 'partial', False): raise SkipField() if self.required: self.fail('required') return (True, self.get_default()) if data is None: if not self.allow_null: self.fail('null') return (True, None) return (False, data) def run_validation(self, data=empty): """ Validate a simple representation and return the internal value. The provided data may be `empty` if no representation was included in the input. May raise `SkipField` if the field should not be included in the validated data. """ (is_empty_value, data) = self.validate_empty_values(data) if is_empty_value: return data value = self.to_internal_value(data) self.run_validators(value) return value def run_validators(self, value): """ Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return. """ errors = [] for validator in self.validators: if hasattr(validator, 'set_context'): validator.set_context(self) try: validator(value) except ValidationError as exc: # If the validation error contains a mapping of fields to # errors then simply raise it immediately rather than # attempting to accumulate a list of errors. if isinstance(exc.detail, dict): raise errors.extend(exc.detail) except DjangoValidationError as exc: errors.extend(exc.messages) if errors: raise ValidationError(errors) def to_internal_value(self, data): """ Transform the *incoming* primitive data into a native value. """ raise NotImplementedError( '{cls}.to_internal_value() must be implemented.'.format( cls=self.__class__.__name__ ) ) def to_representation(self, value): """ Transform the *outgoing* native value into primitive data. """ raise NotImplementedError( '{cls}.to_representation() must be implemented.\n' 'If you are upgrading from REST framework version 2 ' 'you might want `ReadOnlyField`.'.format( cls=self.__class__.__name__ ) ) def fail(self, key, **kwargs): """ A helper method that simply raises a validation error. """ try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) message_string = msg.format(**kwargs) raise ValidationError(message_string) @property def root(self): """ Returns the top-level serializer for this field. """ root = self while root.parent is not None: root = root.parent return root @property def context(self): """ Returns the context as passed to the root serializer on initialization. """ return getattr(self.root, '_context', {}) def __new__(cls, *args, **kwargs): """ When a field is instantiated, we store the arguments that were used, so that we can present a helpful representation of the object. """ instance = super(Field, cls).__new__(cls) instance._args = args instance._kwargs = kwargs return instance def __deepcopy__(self, memo): """ When cloning fields we instantiate using the arguments it was originally created with, rather than copying the complete state. """ args = copy.deepcopy(self._args) kwargs = dict(self._kwargs) # Bit ugly, but we need to special case 'validators' as Django's # RegexValidator does not support deepcopy. # We treat validator callables as immutable objects. # See https://github.com/tomchristie/django-rest-framework/issues/1954 validators = kwargs.pop('validators', None) kwargs = copy.deepcopy(kwargs) if validators is not None: kwargs['validators'] = validators return self.__class__(*args, **kwargs) def __repr__(self): """ Fields are represented using their initial calling arguments. This allows us to create descriptive representations for serializer instances that show all the declared fields on the serializer. """ return unicode_to_repr(representation.field_repr(self)) # Boolean types... class BooleanField(Field): default_error_messages = { 'invalid': _('`{input}` is not a valid boolean.') } default_empty_html = False initial = False TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) def __init__(self, **kwargs): assert 'allow_null' not in kwargs, '`allow_null` is not a valid option. Use `NullBooleanField` instead.' super(BooleanField, self).__init__(**kwargs) def to_internal_value(self, data): if data in self.TRUE_VALUES: return True elif data in self.FALSE_VALUES: return False self.fail('invalid', input=data) def to_representation(self, value): if value in self.TRUE_VALUES: return True elif value in self.FALSE_VALUES: return False return bool(value) class NullBooleanField(Field): default_error_messages = { 'invalid': _('`{input}` is not a valid boolean.') } initial = None TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True)) FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False)) NULL_VALUES = set(('n', 'N', 'null', 'Null', 'NULL', '', None)) def __init__(self, **kwargs): assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.' kwargs['allow_null'] = True super(NullBooleanField, self).__init__(**kwargs) def to_internal_value(self, data): if data in self.TRUE_VALUES: return True elif data in self.FALSE_VALUES: return False elif data in self.NULL_VALUES: return None self.fail('invalid', input=data) def to_representation(self, value): if value in self.NULL_VALUES: return None if value in self.TRUE_VALUES: return True elif value in self.FALSE_VALUES: return False return bool(value) # String types... class CharField(Field): default_error_messages = { 'blank': _('This field may not be blank.'), 'max_length': _('Ensure this field has no more than {max_length} characters.'), 'min_length': _('Ensure this field has at least {min_length} characters.') } initial = '' def __init__(self, **kwargs): self.allow_blank = kwargs.pop('allow_blank', False) max_length = kwargs.pop('max_length', None) min_length = kwargs.pop('min_length', None) super(CharField, self).__init__(**kwargs) if max_length is not None: message = self.error_messages['max_length'].format(max_length=max_length) self.validators.append(MaxLengthValidator(max_length, message=message)) if min_length is not None: message = self.error_messages['min_length'].format(min_length=min_length) self.validators.append(MinLengthValidator(min_length, message=message)) def run_validation(self, data=empty): # Test for the empty string here so that it does not get validated, # and so that subclasses do not need to handle it explicitly # inside the `to_internal_value()` method. if data == '': if not self.allow_blank: self.fail('blank') return '' return super(CharField, self).run_validation(data) def to_internal_value(self, data): return six.text_type(data) def to_representation(self, value): return six.text_type(value) class EmailField(CharField): default_error_messages = { 'invalid': _('Enter a valid email address.') } def __init__(self, **kwargs): super(EmailField, self).__init__(**kwargs) validator = EmailValidator(message=self.error_messages['invalid']) self.validators.append(validator) def to_internal_value(self, data): return six.text_type(data).strip() def to_representation(self, value): return six.text_type(value).strip() class RegexField(CharField): default_error_messages = { 'invalid': _('This value does not match the required pattern.') } def __init__(self, regex, **kwargs): super(RegexField, self).__init__(**kwargs) validator = RegexValidator(regex, message=self.error_messages['invalid']) self.validators.append(validator) class SlugField(CharField): default_error_messages = { 'invalid': _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.") } def __init__(self, **kwargs): super(SlugField, self).__init__(**kwargs) slug_regex = re.compile(r'^[-a-zA-Z0-9_]+$') validator = RegexValidator(slug_regex, message=self.error_messages['invalid']) self.validators.append(validator) class URLField(CharField): default_error_messages = { 'invalid': _("Enter a valid URL.") } def __init__(self, **kwargs): super(URLField, self).__init__(**kwargs) validator = URLValidator(message=self.error_messages['invalid']) self.validators.append(validator) class UUIDField(Field): default_error_messages = { 'invalid': _('"{value}" is not a valid UUID.'), } def to_internal_value(self, data): if not isinstance(data, uuid.UUID): try: return uuid.UUID(data) except (ValueError, TypeError): self.fail('invalid', value=data) return data def to_representation(self, value): return str(value) # Number types... class IntegerField(Field): default_error_messages = { 'invalid': _('A valid integer is required.'), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), 'max_string_length': _('String value too large') } MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. def __init__(self, **kwargs): max_value = kwargs.pop('max_value', None) min_value = kwargs.pop('min_value', None) super(IntegerField, self).__init__(**kwargs) if max_value is not None: message = self.error_messages['max_value'].format(max_value=max_value) self.validators.append(MaxValueValidator(max_value, message=message)) if min_value is not None: message = self.error_messages['min_value'].format(min_value=min_value) self.validators.append(MinValueValidator(min_value, message=message)) def to_internal_value(self, data): if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: data = int(data) except (ValueError, TypeError): self.fail('invalid') return data def to_representation(self, value): return int(value) class FloatField(Field): default_error_messages = { 'invalid': _("A valid number is required."), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), 'max_string_length': _('String value too large') } MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. def __init__(self, **kwargs): max_value = kwargs.pop('max_value', None) min_value = kwargs.pop('min_value', None) super(FloatField, self).__init__(**kwargs) if max_value is not None: message = self.error_messages['max_value'].format(max_value=max_value) self.validators.append(MaxValueValidator(max_value, message=message)) if min_value is not None: message = self.error_messages['min_value'].format(min_value=min_value) self.validators.append(MinValueValidator(min_value, message=message)) def to_internal_value(self, data): if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: return float(data) except (TypeError, ValueError): self.fail('invalid') def to_representation(self, value): return float(value) class DecimalField(Field): default_error_messages = { 'invalid': _('A valid number is required.'), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), 'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'), 'max_decimal_places': _('Ensure that there are no more than {max_decimal_places} decimal places.'), 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.'), 'max_string_length': _('String value too large') } MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. coerce_to_string = api_settings.COERCE_DECIMAL_TO_STRING def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None, **kwargs): self.max_digits = max_digits self.decimal_places = decimal_places self.coerce_to_string = coerce_to_string if (coerce_to_string is not None) else self.coerce_to_string super(DecimalField, self).__init__(**kwargs) if max_value is not None: message = self.error_messages['max_value'].format(max_value=max_value) self.validators.append(MaxValueValidator(max_value, message=message)) if min_value is not None: message = self.error_messages['min_value'].format(min_value=min_value) self.validators.append(MinValueValidator(min_value, message=message)) def to_internal_value(self, data): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ data = smart_text(data).strip() if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') # Check for NaN. It is the only value that isn't equal to itself, # so we can use this to identify NaN values. if value != value: self.fail('invalid') # Check for infinity and negative infinity. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): self.fail('invalid') sign, digittuple, exponent = value.as_tuple() decimals = abs(exponent) # digittuple doesn't include any leading zeros. digits = len(digittuple) if decimals > digits: # We have leading zeros up to or past the decimal point. Count # everything past the decimal point as a digit. We do not count # 0 before the decimal point as a digit since that would mean # we would not allow max_digits = decimal_places. digits = decimals whole_digits = digits - decimals if self.max_digits is not None and digits > self.max_digits: self.fail('max_digits', max_digits=self.max_digits) if self.decimal_places is not None and decimals > self.decimal_places: self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places): self.fail('max_whole_digits', max_whole_digits=self.max_digits - self.decimal_places) return value def to_representation(self, value): if not isinstance(value, decimal.Decimal): value = decimal.Decimal(six.text_type(value).strip()) context = decimal.getcontext().copy() context.prec = self.max_digits quantized = value.quantize( decimal.Decimal('.1') ** self.decimal_places, context=context ) if not self.coerce_to_string: return quantized return '{0:f}'.format(quantized) # Date & time fields... class DateTimeField(Field): default_error_messages = { 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}'), 'date': _('Expected a datetime but got a date.'), } format = api_settings.DATETIME_FORMAT input_formats = api_settings.DATETIME_INPUT_FORMATS default_timezone = timezone.get_default_timezone() if settings.USE_TZ else None def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs): self.format = format if format is not empty else self.format self.input_formats = input_formats if input_formats is not None else self.input_formats self.default_timezone = default_timezone if default_timezone is not None else self.default_timezone super(DateTimeField, self).__init__(*args, **kwargs) def enforce_timezone(self, value): """ When `self.default_timezone` is `None`, always return naive datetimes. When `self.default_timezone` is not `None`, always return aware datetimes. """ if (self.default_timezone is not None) and not timezone.is_aware(value): return timezone.make_aware(value, self.default_timezone) elif (self.default_timezone is None) and timezone.is_aware(value): return timezone.make_naive(value, timezone.UTC()) return value def to_internal_value(self, value): if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): self.fail('date') if isinstance(value, datetime.datetime): return self.enforce_timezone(value) for format in self.input_formats: if format.lower() == ISO_8601: try: parsed = parse_datetime(value) except (ValueError, TypeError): pass else: if parsed is not None: return self.enforce_timezone(parsed) else: try: parsed = datetime.datetime.strptime(value, format) except (ValueError, TypeError): pass else: return self.enforce_timezone(parsed) humanized_format = humanize_datetime.datetime_formats(self.input_formats) self.fail('invalid', format=humanized_format) def to_representation(self, value): if self.format is None: return value if self.format.lower() == ISO_8601: value = value.isoformat() if value.endswith('+00:00'): value = value[:-6] + 'Z' return value return value.strftime(self.format) class DateField(Field): default_error_messages = { 'invalid': _('Date has wrong format. Use one of these formats instead: {format}'), 'datetime': _('Expected a date but got a datetime.'), } format = api_settings.DATE_FORMAT input_formats = api_settings.DATE_INPUT_FORMATS def __init__(self, format=empty, input_formats=None, *args, **kwargs): self.format = format if format is not empty else self.format self.input_formats = input_formats if input_formats is not None else self.input_formats super(DateField, self).__init__(*args, **kwargs) def to_internal_value(self, value): if isinstance(value, datetime.datetime): self.fail('datetime') if isinstance(value, datetime.date): return value for format in self.input_formats: if format.lower() == ISO_8601: try: parsed = parse_date(value) except (ValueError, TypeError): pass else: if parsed is not None: return parsed else: try: parsed = datetime.datetime.strptime(value, format) except (ValueError, TypeError): pass else: return parsed.date() humanized_format = humanize_datetime.date_formats(self.input_formats) self.fail('invalid', format=humanized_format) def to_representation(self, value): if self.format is None: return value # Applying a `DateField` to a datetime value is almost always # not a sensible thing to do, as it means naively dropping # any explicit or implicit timezone info. assert not isinstance(value, datetime.datetime), ( 'Expected a `date`, but got a `datetime`. Refusing to coerce, ' 'as this may mean losing timezone information. Use a custom ' 'read-only field and deal with timezone issues explicitly.' ) if self.format.lower() == ISO_8601: return value.isoformat() return value.strftime(self.format) class TimeField(Field): default_error_messages = { 'invalid': _('Time has wrong format. Use one of these formats instead: {format}'), } format = api_settings.TIME_FORMAT input_formats = api_settings.TIME_INPUT_FORMATS def __init__(self, format=empty, input_formats=None, *args, **kwargs): self.format = format if format is not empty else self.format self.input_formats = input_formats if input_formats is not None else self.input_formats super(TimeField, self).__init__(*args, **kwargs) def to_internal_value(self, value): if isinstance(value, datetime.time): return value for format in self.input_formats: if format.lower() == ISO_8601: try: parsed = parse_time(value) except (ValueError, TypeError): pass else: if parsed is not None: return parsed else: try: parsed = datetime.datetime.strptime(value, format) except (ValueError, TypeError): pass else: return parsed.time() humanized_format = humanize_datetime.time_formats(self.input_formats) self.fail('invalid', format=humanized_format) def to_representation(self, value): if self.format is None: return value # Applying a `TimeField` to a datetime value is almost always # not a sensible thing to do, as it means naively dropping # any explicit or implicit timezone info. assert not isinstance(value, datetime.datetime), ( 'Expected a `time`, but got a `datetime`. Refusing to coerce, ' 'as this may mean losing timezone information. Use a custom ' 'read-only field and deal with timezone issues explicitly.' ) if self.format.lower() == ISO_8601: return value.isoformat() return value.strftime(self.format) # Choice types... class ChoiceField(Field): default_error_messages = { 'invalid_choice': _('`{input}` is not a valid choice.') } def __init__(self, choices, **kwargs): # Allow either single or paired choices style: # choices = [1, 2, 3] # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] pairs = [ isinstance(item, (list, tuple)) and len(item) == 2 for item in choices ] if all(pairs): self.choices = OrderedDict([(key, display_value) for key, display_value in choices]) else: self.choices = OrderedDict([(item, item) for item in choices]) # Map the string representation of choices to the underlying value. # Allows us to deal with eg. integer choices while supporting either # integer or string input, but still get the correct datatype out. self.choice_strings_to_values = dict([ (six.text_type(key), key) for key in self.choices.keys() ]) self.allow_blank = kwargs.pop('allow_blank', False) super(ChoiceField, self).__init__(**kwargs) def to_internal_value(self, data): if data == '' and self.allow_blank: return '' try: return self.choice_strings_to_values[six.text_type(data)] except KeyError: self.fail('invalid_choice', input=data) def to_representation(self, value): if value in ('', None): return value return self.choice_strings_to_values[six.text_type(value)] class MultipleChoiceField(ChoiceField): default_error_messages = { 'invalid_choice': _('`{input}` is not a valid choice.'), 'not_a_list': _('Expected a list of items but got type `{input_type}`.') } default_empty_html = [] def get_value(self, dictionary): # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): return dictionary.getlist(self.field_name) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): if isinstance(data, type('')) or not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) return set([ super(MultipleChoiceField, self).to_internal_value(item) for item in data ]) def to_representation(self, value): return set([ self.choice_strings_to_values[six.text_type(item)] for item in value ]) # File types... class FileField(Field): default_error_messages = { 'required': _("No file was submitted."), 'invalid': _("The submitted data was not a file. Check the encoding type on the form."), 'no_name': _("No filename could be determined."), 'empty': _("The submitted file is empty."), 'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'), } use_url = api_settings.UPLOADED_FILES_USE_URL def __init__(self, *args, **kwargs): self.max_length = kwargs.pop('max_length', None) self.allow_empty_file = kwargs.pop('allow_empty_file', False) self.use_url = kwargs.pop('use_url', self.use_url) super(FileField, self).__init__(*args, **kwargs) def to_internal_value(self, data): try: # `UploadedFile` objects should have name and size attributes. file_name = data.name file_size = data.size except AttributeError: self.fail('invalid') if not file_name: self.fail('no_name') if not self.allow_empty_file and not file_size: self.fail('empty') if self.max_length and len(file_name) > self.max_length: self.fail('max_length', max_length=self.max_length, length=len(file_name)) return data def to_representation(self, value): if self.use_url: if not value: return None url = value.url request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(url) return url return value.name class ImageField(FileField): default_error_messages = { 'invalid_image': _( 'Upload a valid image. The file you uploaded was either not an ' 'image or a corrupted image.' ), } def __init__(self, *args, **kwargs): self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField) super(ImageField, self).__init__(*args, **kwargs) def to_internal_value(self, data): # Image validation is a bit grungy, so we'll just outright # defer to Django's implementation so we don't need to # consider it, or treat PIL as a test dependency. file_object = super(ImageField, self).to_internal_value(data) django_field = self._DjangoImageField() django_field.error_messages = self.error_messages django_field.to_python(file_object) return file_object # Composite field types... class _UnvalidatedField(Field): def __init__(self, *args, **kwargs): super(_UnvalidatedField, self).__init__(*args, **kwargs) self.allow_blank = True self.allow_null = True def to_internal_value(self, data): return data def to_representation(self, value): return value class ListField(Field): child = _UnvalidatedField() initial = [] default_error_messages = { 'not_a_list': _('Expected a list of items but got type `{input_type}`') } def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) assert not inspect.isclass(self.child), '`child` has not been instantiated.' super(ListField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) def get_value(self, dictionary): # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): return html.parse_html_list(dictionary, prefix=self.field_name) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): """ List of dicts of native values <- List of dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_list(data) if isinstance(data, type('')) or not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) return [self.child.run_validation(item) for item in data] def to_representation(self, data): """ List of object instances -> List of dicts of primitive datatypes. """ return [self.child.to_representation(item) for item in data] class DictField(Field): child = _UnvalidatedField() initial = [] default_error_messages = { 'not_a_dict': _('Expected a dictionary of items but got type `{input_type}`') } def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) assert not inspect.isclass(self.child), '`child` has not been instantiated.' super(DictField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) def get_value(self, dictionary): # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): return html.parse_html_list(dictionary, prefix=self.field_name) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): """ Dicts of native values <- Dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_dict(data) if not isinstance(data, dict): self.fail('not_a_dict', input_type=type(data).__name__) return dict([ (six.text_type(key), self.child.run_validation(value)) for key, value in data.items() ]) def to_representation(self, value): """ List of object instances -> List of dicts of primitive datatypes. """ return dict([ (six.text_type(key), self.child.to_representation(val)) for key, val in value.items() ]) # Miscellaneous field types... class ReadOnlyField(Field): """ A read-only field that simply returns the field value. If the field is a method with no parameters, the method will be called and it's return value used as the representation. For example, the following would call `get_expiry_date()` on the object: class ExampleSerializer(self): expiry_date = ReadOnlyField(source='get_expiry_date') """ def __init__(self, **kwargs): kwargs['read_only'] = True super(ReadOnlyField, self).__init__(**kwargs) def to_representation(self, value): return value class HiddenField(Field): """ A hidden field does not take input from the user, or present any output, but it does populate a field in `validated_data`, based on its default value. This is particularly useful when we have a `unique_for_date` constraint on a pair of fields, as we need some way to include the date in the validated data. """ def __init__(self, **kwargs): assert 'default' in kwargs, 'default is a required argument.' kwargs['write_only'] = True super(HiddenField, self).__init__(**kwargs) def get_value(self, dictionary): # We always use the default value for `HiddenField`. # User input is never provided or accepted. return empty def to_internal_value(self, data): return data class SerializerMethodField(Field): """ A read-only field that get its representation from calling a method on the parent serializer class. The method called will be of the form "get_{field_name}", and should take a single argument, which is the object being serialized. For example: class ExampleSerializer(self): extra_info = SerializerMethodField() def get_extra_info(self, obj): return ... # Calculate some data to return. """ def __init__(self, method_name=None, **kwargs): self.method_name = method_name kwargs['source'] = '*' kwargs['read_only'] = True super(SerializerMethodField, self).__init__(**kwargs) def bind(self, field_name, parent): # In order to enforce a consistent style, we error if a redundant # 'method_name' argument has been used. For example: # my_field = serializer.CharField(source='my_field') default_method_name = 'get_{field_name}'.format(field_name=field_name) assert self.method_name != default_method_name, ( "It is redundant to specify `%s` on SerializerMethodField '%s' in " "serializer '%s', because it is the same as the default method name. " "Remove the `method_name` argument." % (self.method_name, field_name, parent.__class__.__name__) ) # The method name should default to `get_{field_name}`. if self.method_name is None: self.method_name = default_method_name super(SerializerMethodField, self).bind(field_name, parent) def to_representation(self, value): method = getattr(self.parent, self.method_name) return method(value) class ModelField(Field): """ A generic field that can be used against an arbitrary model field. This is used by `ModelSerializer` when dealing with custom model fields, that do not have a serializer field to be mapped to. """ default_error_messages = { 'max_length': _('Ensure this field has no more than {max_length} characters.'), } def __init__(self, model_field, **kwargs): self.model_field = model_field # The `max_length` option is supported by Django's base `Field` class, # so we'd better support it here. max_length = kwargs.pop('max_length', None) super(ModelField, self).__init__(**kwargs) if max_length is not None: message = self.error_messages['max_length'].format(max_length=max_length) self.validators.append(MaxLengthValidator(max_length, message=message)) def to_internal_value(self, data): rel = getattr(self.model_field, 'rel', None) if rel is not None: return rel.to._meta.get_field(rel.field_name).to_python(data) return self.model_field.to_python(data) def get_attribute(self, obj): # We pass the object instance onto `to_representation`, # not just the field attribute. return obj def to_representation(self, obj): value = self.model_field._get_val_from_obj(obj) if is_protected_type(value): return value return self.model_field.value_to_string(obj)
ojengwa/talk
venv/lib/python2.7/site-packages/rest_framework/fields.py
Python
mit
49,597
# FDWaveformView [![CI Status](http://img.shields.io/travis/William Entriken/FDWaveformView.svg?style=flat)](https://travis-ci.org/fulldecent/FDWaveformView) [![Version](https://img.shields.io/cocoapods/v/FDWaveformView.svg?style=flat)](http://cocoadocs.org/docsets/FDWaveformView) [![License](https://img.shields.io/cocoapods/l/FDWaveformView.svg?style=flat)](http://cocoadocs.org/docsets/FDWaveformView) [![Platform](https://img.shields.io/cocoapods/p/FDWaveformView.svg?style=flat)](http://cocoadocs.org/docsets/FDWaveformView) FDWaveformView is an easy way to display an audio waveform in your app. It is a nice visualization to show a playing audio file or to select a position in a file. Usage ----- To use it, add an `FDWaveformView` using Interface Builder or programmatically and then just load your audio as per this example. Note: if your audio file does not have file extension, see <a href="https://stackoverflow.com/questions/9290972/is-it-possible-to-make-avurlasset-work-without-a-file-extension">this SO question</a>. NSBundle *thisBundle = [NSBundle bundleForClass:[self class]]; NSString *filePath = [thisBundle pathForResource:@"Submarine" ofType:@"aiff"]; NSURL *url = [NSURL fileURLWithPath:filePath]; self.waveform.audioURL = url; <p align="center"> <img src="https://i.imgur.com/5N7ozog.png" width=250> </p> Features -------- **Set play progress** to highlight part of the waveform: self.waveform.progressSamples = self.waveform.totalSamples / 2; <p align="center"> <img src="https://i.imgur.com/fRrHiRP.png" width=250> </p> **Zoom in** to show only part of the waveform, of course, zooming in will smoothly rerender to show progressively more detail: self.waveform.zoomStartSamples = 0; self.waveform.zoomEndSamples = self.waveform.totalSamples / 4; <p align="center"> <img src="https://i.imgur.com/JQOKQ3o.png" width=250> </p> **Enable gestures** for zooming in, panning around or scrubbing: self.waveform.doesAllowScrubbing = YES; self.waveform.doesAllowStretch = YES; self.waveform.doesAllowScroll = YES; <p align="center"> <img src="https://i.imgur.com/8oR7cpq.gif" width=250 loop=infinite> </p> **Supports animation** for changing properties: [UIView animateWithDuration:0.3 animations:^{ NSInteger randomNumber = arc4random() % self.waveform.totalSamples; self.waveform.progressSamples = randomNumber; }]; <p align="center"> <img src="https://i.imgur.com/EgxXaCY.gif" width=250 loop=infinite> </p> Creates **antialiased waveforms** by drawing more pixels than are seen on screen. Also, if you resize me (autolayout) I will render more detail if necessary to avoid pixelation. **Supports ARC** and **iOS7+**. **Includes unit tests** which run successfully using Travis CI. Installation ------------ 1. Add `pod 'FDWaveformView'` to your <a href="https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking">Podfile</a> 2. The the API documentation under "Class Reference" at http://cocoadocs.org/docsets/FDWaveformView/ 3. Please add your project to "I USE THIS" at https://www.cocoacontrols.com/controls/fdwaveformview
johnryan/FDWaveformView
README.md
Markdown
mit
3,112
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: The class denotes how to specify the usage of an attribute ** ** ===========================================================*/ using System.Reflection; namespace System { /* By default, attributes are inherited and multiple attributes are not allowed */ [Serializable] [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute { internal AttributeTargets m_attributeTarget = AttributeTargets.All; // Defaults to all internal bool m_allowMultiple = false; // Defaults to false internal bool m_inherited = true; // Defaults to true internal static AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All); //Constructors public AttributeUsageAttribute(AttributeTargets validOn) { m_attributeTarget = validOn; } internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited) { m_attributeTarget = validOn; m_allowMultiple = allowMultiple; m_inherited = inherited; } //Properties public AttributeTargets ValidOn { get { return m_attributeTarget; } } public bool AllowMultiple { get { return m_allowMultiple; } set { m_allowMultiple = value; } } public bool Inherited { get { return m_inherited; } set { m_inherited = value; } } } }
sjsinju/coreclr
src/mscorlib/shared/System/AttributeUsageAttribute.cs
C#
mit
1,852
<?php namespace Kunstmaan\VotingBundle\Tests\Event\UpDown; use Kunstmaan\VotingBundle\Event\UpDown\UpVoteEvent; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class UpVoteEventTest extends TestCase { public function testGetSet() { $request = new Request(); $response = new Response(); $event = new UpVoteEvent($request, $response, 100); $this->assertInstanceOf(Request::class, $event->getRequest()); $this->assertInstanceOf(Response::class, $event->getReference()); $this->assertEquals(100, $event->getValue()); } }
Kunstmaan/KunstmaanBundlesCMS
src/Kunstmaan/VotingBundle/Tests/Event/UpDown/UpVoteEventTest.php
PHP
mit
659
//----------------------------------------------------------------------------- // File: D3DFont.h // // Desc: Texture-based font class // // Copyright (c) 1999-2001 Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #ifndef D3DFONT_H #define D3DFONT_H #include <tchar.h> #include <D3D9.h> // Font creation flags #define D3DFONT_BOLD 0x0001 #define D3DFONT_ITALIC 0x0002 #define D3DFONT_ZENABLE 0x0004 // Font rendering flags #define D3DFONT_CENTERED 0x0001 #define D3DFONT_TWOSIDED 0x0002 #define D3DFONT_FILTERED 0x0004 //----------------------------------------------------------------------------- // Name: class CD3DFont // Desc: Texture-based font class for doing text in a 3D scene. //----------------------------------------------------------------------------- class CD3DFont { TCHAR m_strFontName[80]; // Font properties DWORD m_dwFontHeight; DWORD m_dwFontFlags; LPDIRECT3DDEVICE9 m_pd3dDevice; // A D3DDevice used for rendering LPDIRECT3DTEXTURE9 m_pTexture; // The d3d texture for this font LPDIRECT3DVERTEXBUFFER9 m_pVB; // VertexBuffer for rendering text DWORD m_dwTexWidth; // Texture dimensions DWORD m_dwTexHeight; FLOAT m_fTextScale; FLOAT m_fTexCoords[128-32][4]; // Stateblocks for setting and restoring render states LPDIRECT3DSTATEBLOCK9 m_pStateBlockSaved; LPDIRECT3DSTATEBLOCK9 m_pStateBlockDrawText; public: // 2D and 3D text drawing functions HRESULT DrawText( FLOAT x, FLOAT y, DWORD dwColor, const TCHAR* strText, DWORD dwFlags=0L ); HRESULT DrawTextScaled( FLOAT x, FLOAT y, FLOAT z, FLOAT fXScale, FLOAT fYScale, DWORD dwColor, const TCHAR* strText, DWORD dwFlags=0L ); HRESULT Render3DText( const TCHAR* strText, DWORD dwFlags=0L ); // Function to get extent of text HRESULT GetTextExtent( const TCHAR* strText, SIZE* pSize ); // Initializing and destroying device-dependent objects HRESULT InitDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice ); HRESULT RestoreDeviceObjects(); HRESULT InvalidateDeviceObjects(); HRESULT DeleteDeviceObjects(); // Constructor / destructor CD3DFont( const TCHAR* strFontName, DWORD dwHeight, DWORD dwFlags=0L ); ~CD3DFont(); }; #endif
arkiny/Direct3D
DirectX9/DX3D9HomeAssignment2015/021015 Particle/d3dfont.h
C
mit
2,466
<?php // fail soderzhit zagruzochnuju infu karty // VESHI $items = array ( ); // NPC POKA NET $npc = array ( ); ?>
nadvamir/forgotten-story-mmorpg
game/modules/mapinfo/load_epf4.php
PHP
mit
141
# frozen_string_literal: true module StubMetrics def authentication_metrics Gitlab::Auth::Activity end def stub_authentication_activity_metrics(debug: false) authentication_metrics.each_counter do |name, metric, description| allow(authentication_metrics).to receive(name) .and_return(double("#{metric} - #{description}")) end debug_authentication_activity_metrics if debug end def debug_authentication_activity_metrics authentication_metrics.tap do |metrics| metrics.each_counter do |name, metric| "#{name}_increment!".tap do |incrementer| allow(metrics).to receive(incrementer).and_wrap_original do |method| puts "Authentication activity metric incremented: #{name}" method.call end end end end end end
stoplightio/gitlabhq
spec/support/helpers/stub_metrics.rb
Ruby
mit
830
$(document).ready(function() { $(window).scroll(function() { var widy = window.top.scrollY; if (widy > 80) { $('#top-nav').addClass('nav-scrolled'); } else { if ($('#top-nav').hasClass('showing-sub')) { // Do nothing $('#top-nav'); } else { $('#top-nav').removeClass('nav-scrolled'); } } }); $('.show-submenu-mobile').on('click', function() { //-- Add a menu to the top of the nav if ($('#top-nav').hasClass('showing-sub')) { //-- Remove $('#top-nav').removeClass('showing-sub'); $('body').removeClass('allow-for-submenu'); $('.resp-nav').remove(); } else { //-- Add $('#top-nav').addClass('nav-scrolled showing-sub'); $('body').addClass('allow-for-submenu'); $('#top-nav').prepend('<ul class=\'resp-nav\'>' + $('.tnav').html() + '</ul>'); } return false; }); $('[data-toggle="popover"]').popover(); $('#package-details').on('show.bs.modal', function(event) { var selectedDetails = $(event.relatedTarget); var title = selectedDetails.parent().text(); var data = selectedDetails.data('content'); console.log(data); console.log(marked(data)); // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) modal.find('.modal-title').text(title); modal.find('.modal-body').html(marked(data)); }); });
Manoj-nathwani/hackference-2015
assets/js/pages.js
JavaScript
mit
1,614
module SwitchUser module Provider class Clearance < Base def initialize(controller) @controller = controller end def login(user, scope = nil) @controller.sign_in(user) end def logout(scope = nil) @controller.sign_out end def current_user(scope = nil) @controller.current_user end end end end
MustWin/switch_user
lib/switch_user/provider/clearance.rb
Ruby
mit
387
import {ImageDemo} from './index_common'; import {bootstrapApp} from '../../../../@angular/platform-browser/src/worker_app'; export function main() { bootstrapApp(ImageDemo); }
shuhei/angular
modules/playground/src/web_workers/images/background_index.ts
TypeScript
mit
180
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <TITLE> org.apache.poi.ss.formula.ptg (POI API Documentation) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.poi.ss.formula.ptg (POI API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= 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=2 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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.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-all.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="../../../../../../org/apache/poi/ss/formula/functions/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/poi/ss/formula/udf/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/poi/ss/formula/ptg/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.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> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package org.apache.poi.ss.formula.ptg </H2> formula package contains binary PTG structures used in Formulas <P> <B>See:</B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="#package_description"><B>Description</B></A> <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AreaI.html" title="interface in org.apache.poi.ss.formula.ptg">AreaI</A></B></TD> <TD>Common interface for AreaPtg and Area3DPtg, and their child classes.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Pxg.html" title="interface in org.apache.poi.ss.formula.ptg">Pxg</A></B></TD> <TD>An XSSF only special kind of Ptg, which stores the sheet / book reference in string form.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Pxg3D.html" title="interface in org.apache.poi.ss.formula.ptg">Pxg3D</A></B></TD> <TD>An XSSF only special kind of Ptg, which stores a range of sheet / book references in string form.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AbstractFunctionPtg.html" title="class in org.apache.poi.ss.formula.ptg">AbstractFunctionPtg</A></B></TD> <TD>This class provides the base functionality for Excel sheet functions There are two kinds of function Ptgs - tFunc and tFuncVar Therefore, this class will have ONLY two subclasses</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AddPtg.html" title="class in org.apache.poi.ss.formula.ptg">AddPtg</A></B></TD> <TD>Addition operator PTG the "+" binomial operator.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Area2DPtgBase.html" title="class in org.apache.poi.ss.formula.ptg">Area2DPtgBase</A></B></TD> <TD>Common superclass of 2-D area refs</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Area3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">Area3DPtg</A></B></TD> <TD>Title: Area 3D Ptg - 3D reference (Sheet + Area)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Area3DPxg.html" title="class in org.apache.poi.ss.formula.ptg">Area3DPxg</A></B></TD> <TD>Title: XSSF Area 3D Reference (Sheet + Area)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AreaErrPtg.html" title="class in org.apache.poi.ss.formula.ptg">AreaErrPtg</A></B></TD> <TD>AreaErr - handles deleted cell area references.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AreaI.OffsetArea.html" title="class in org.apache.poi.ss.formula.ptg">AreaI.OffsetArea</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AreaNPtg.html" title="class in org.apache.poi.ss.formula.ptg">AreaNPtg</A></B></TD> <TD>Specifies a rectangular area of cells A1:A4 for instance.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AreaPtg.html" title="class in org.apache.poi.ss.formula.ptg">AreaPtg</A></B></TD> <TD>Specifies a rectangular area of cells A1:A4 for instance.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AreaPtgBase.html" title="class in org.apache.poi.ss.formula.ptg">AreaPtgBase</A></B></TD> <TD>Specifies a rectangular area of cells A1:A4 for instance.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/ArrayPtg.html" title="class in org.apache.poi.ss.formula.ptg">ArrayPtg</A></B></TD> <TD>ArrayPtg - handles arrays The ArrayPtg is a little weird, the size of the Ptg when parsing initially only includes the Ptg sid and the reserved bytes.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AttrPtg.html" title="class in org.apache.poi.ss.formula.ptg">AttrPtg</A></B></TD> <TD>"Special Attributes" This seems to be a Misc Stuff and Junk record.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/AttrPtg.SpaceType.html" title="class in org.apache.poi.ss.formula.ptg">AttrPtg.SpaceType</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/BoolPtg.html" title="class in org.apache.poi.ss.formula.ptg">BoolPtg</A></B></TD> <TD>Boolean (boolean) Stores a (java) boolean value in a formula.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/ConcatPtg.html" title="class in org.apache.poi.ss.formula.ptg">ConcatPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/ControlPtg.html" title="class in org.apache.poi.ss.formula.ptg">ControlPtg</A></B></TD> <TD>Common superclass for tExp tTbl tParen tNlr tAttr tSheet tEndSheet</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Deleted3DPxg.html" title="class in org.apache.poi.ss.formula.ptg">Deleted3DPxg</A></B></TD> <TD>An XSSF only representation of a reference to a deleted area</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/DeletedArea3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">DeletedArea3DPtg</A></B></TD> <TD>Title: Deleted Area 3D Ptg - 3D referecnce (Sheet + Area)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/DeletedRef3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">DeletedRef3DPtg</A></B></TD> <TD>Title: Deleted Reference 3D Ptg</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/DividePtg.html" title="class in org.apache.poi.ss.formula.ptg">DividePtg</A></B></TD> <TD>This PTG implements the standard binomial divide "/"</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/EqualPtg.html" title="class in org.apache.poi.ss.formula.ptg">EqualPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/ErrPtg.html" title="class in org.apache.poi.ss.formula.ptg">ErrPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/ExpPtg.html" title="class in org.apache.poi.ss.formula.ptg">ExpPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/FuncPtg.html" title="class in org.apache.poi.ss.formula.ptg">FuncPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/FuncVarPtg.html" title="class in org.apache.poi.ss.formula.ptg">FuncVarPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/GreaterEqualPtg.html" title="class in org.apache.poi.ss.formula.ptg">GreaterEqualPtg</A></B></TD> <TD>PTG class to implement greater or equal to</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/GreaterThanPtg.html" title="class in org.apache.poi.ss.formula.ptg">GreaterThanPtg</A></B></TD> <TD>Greater than operator PTG ">"</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/IntersectionPtg.html" title="class in org.apache.poi.ss.formula.ptg">IntersectionPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/IntPtg.html" title="class in org.apache.poi.ss.formula.ptg">IntPtg</A></B></TD> <TD>Integer (unsigned short integer) Stores an unsigned short value (java int) in a formula</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/LessEqualPtg.html" title="class in org.apache.poi.ss.formula.ptg">LessEqualPtg</A></B></TD> <TD>Ptg class to implement less than or equal</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/LessThanPtg.html" title="class in org.apache.poi.ss.formula.ptg">LessThanPtg</A></B></TD> <TD>Less than operator PTG "<".</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/MemAreaPtg.html" title="class in org.apache.poi.ss.formula.ptg">MemAreaPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/MemErrPtg.html" title="class in org.apache.poi.ss.formula.ptg">MemErrPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/MemFuncPtg.html" title="class in org.apache.poi.ss.formula.ptg">MemFuncPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/MissingArgPtg.html" title="class in org.apache.poi.ss.formula.ptg">MissingArgPtg</A></B></TD> <TD>Missing Function Arguments Avik Sengupta &lt;avik at apache.org&gt;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/MultiplyPtg.html" title="class in org.apache.poi.ss.formula.ptg">MultiplyPtg</A></B></TD> <TD>Implements the standard mathmatical multiplication - *</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/NamePtg.html" title="class in org.apache.poi.ss.formula.ptg">NamePtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/NameXPtg.html" title="class in org.apache.poi.ss.formula.ptg">NameXPtg</A></B></TD> <TD>A Name, be that a Named Range or a Function / User Defined Function, addressed in the HSSF External Sheet style.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/NameXPxg.html" title="class in org.apache.poi.ss.formula.ptg">NameXPxg</A></B></TD> <TD>A Name, be that a Named Range or a Function / User Defined Function, addressed in the HSSF External Sheet style.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/NotEqualPtg.html" title="class in org.apache.poi.ss.formula.ptg">NotEqualPtg</A></B></TD> <TD>Ptg class to implement not equal</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/NumberPtg.html" title="class in org.apache.poi.ss.formula.ptg">NumberPtg</A></B></TD> <TD>Number Stores a floating point value in a formula value stored in a 8 byte field using IEEE notation</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/OperandPtg.html" title="class in org.apache.poi.ss.formula.ptg">OperandPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/OperationPtg.html" title="class in org.apache.poi.ss.formula.ptg">OperationPtg</A></B></TD> <TD>defines a Ptg that is an operation instead of an operand</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/ParenthesisPtg.html" title="class in org.apache.poi.ss.formula.ptg">ParenthesisPtg</A></B></TD> <TD>While formula tokens are stored in RPN order and thus do not need parenthesis for precedence reasons, Parenthesis tokens ARE written to ensure that user entered parenthesis are displayed as-is on reading back Avik Sengupta &lt;[email protected]&gt; Andrew C.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/PercentPtg.html" title="class in org.apache.poi.ss.formula.ptg">PercentPtg</A></B></TD> <TD>Percent PTG.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/PowerPtg.html" title="class in org.apache.poi.ss.formula.ptg">PowerPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Ptg.html" title="class in org.apache.poi.ss.formula.ptg">Ptg</A></B></TD> <TD><tt>Ptg</tt> represents a syntactic token in a formula.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/RangePtg.html" title="class in org.apache.poi.ss.formula.ptg">RangePtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Ref3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">Ref3DPtg</A></B></TD> <TD>Title: Reference 3D Ptg</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Ref3DPxg.html" title="class in org.apache.poi.ss.formula.ptg">Ref3DPxg</A></B></TD> <TD>Title: XSSF 3D Reference</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/RefErrorPtg.html" title="class in org.apache.poi.ss.formula.ptg">RefErrorPtg</A></B></TD> <TD>RefError - handles deleted cell reference</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/RefNPtg.html" title="class in org.apache.poi.ss.formula.ptg">RefNPtg</A></B></TD> <TD>RefNPtg</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/RefPtg.html" title="class in org.apache.poi.ss.formula.ptg">RefPtg</A></B></TD> <TD>ReferencePtg - handles references (such as A1, A2, IA4)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/RefPtgBase.html" title="class in org.apache.poi.ss.formula.ptg">RefPtgBase</A></B></TD> <TD>ReferencePtgBase - handles references (such as A1, A2, IA4)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/ScalarConstantPtg.html" title="class in org.apache.poi.ss.formula.ptg">ScalarConstantPtg</A></B></TD> <TD>Common superclass of all <A HREF="../../../../../../org/apache/poi/ss/formula/ptg/Ptg.html" title="class in org.apache.poi.ss.formula.ptg"><CODE>Ptg</CODE></A>s that represent simple constant values.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/StringPtg.html" title="class in org.apache.poi.ss.formula.ptg">StringPtg</A></B></TD> <TD>String Stores a String value in a formula value stored in the format &lt;length 2 bytes&gt;char[]</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/SubtractPtg.html" title="class in org.apache.poi.ss.formula.ptg">SubtractPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/TblPtg.html" title="class in org.apache.poi.ss.formula.ptg">TblPtg</A></B></TD> <TD>This ptg indicates a data table.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/UnaryMinusPtg.html" title="class in org.apache.poi.ss.formula.ptg">UnaryMinusPtg</A></B></TD> <TD>Unary Plus operator does not have any effect on the operand</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/UnaryPlusPtg.html" title="class in org.apache.poi.ss.formula.ptg">UnaryPlusPtg</A></B></TD> <TD>Unary Plus operator does not have any effect on the operand</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/UnionPtg.html" title="class in org.apache.poi.ss.formula.ptg">UnionPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/UnknownPtg.html" title="class in org.apache.poi.ss.formula.ptg">UnknownPtg</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/apache/poi/ss/formula/ptg/ValueOperatorPtg.html" title="class in org.apache.poi.ss.formula.ptg">ValueOperatorPtg</A></B></TD> <TD>Common superclass of all value operators.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="package_description"><!-- --></A><H2> Package org.apache.poi.ss.formula.ptg Description </H2> <P> formula package contains binary PTG structures used in Formulas <h2>Related Documentation</h2> For overviews, tutorials, examples, guides, and tool documentation, please see: <ul> <li><a href="http://poi.apache.org">Apache POI Project</a> </ul> <!-- Put @see and @since tags down here. --> <P> <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../../org/apache/poi/hssf/record/package-summary.html"><CODE>org.apache.poi.hssf.record</CODE></A>, <A HREF="../../../../../../org/apache/poi/hssf/record/FormulaRecord.html" title="class in org.apache.poi.hssf.record"><CODE>FormulaRecord</CODE></A></DL> <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=2 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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.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-all.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="../../../../../../org/apache/poi/ss/formula/functions/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/poi/ss/formula/udf/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/poi/ss/formula/ptg/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.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> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2016 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
Sebaxtian/KDD
poi-3.14/docs/apidocs/org/apache/poi/ss/formula/ptg/package-summary.html
HTML
mit
25,894
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var _ = require('underscore'); var EventEmitter = require('events').EventEmitter; var util = require('util'); var MAX_NUM_UPDATES = 250; function numOrDefault(value, defaultValue) { return typeof value === 'number' ? value : defaultValue; } function MembershipUpdateRollup(options) { this.ringpop = options.ringpop; this.flushInterval = options.flushInterval; this.maxNumUpdates = numOrDefault(options.maxNumUpdates, MAX_NUM_UPDATES); this.buffer = {}; this.firstUpdateTime = null; this.lastFlushTime = null; this.lastUpdateTime = null; this.flushTimer = null; } util.inherits(MembershipUpdateRollup, EventEmitter); MembershipUpdateRollup.prototype.addUpdates = function addUpdates(updates) { var ts = Date.now(); for (var i = 0; i < updates.length; i++) { var update = updates[i]; if (!this.buffer[update.address]) { this.buffer[update.address] = []; } // TODO Replace _.extend with extend module var updateWithTimestamp = _.extend({ ts: ts }, update); this.buffer[update.address].push(updateWithTimestamp); } }; MembershipUpdateRollup.prototype.destroy = function destroy() { clearTimeout(this.flushTimer); }; MembershipUpdateRollup.prototype.flushBuffer = function flushBuffer() { // Nothing to flush if no updates are present in buffer if (Object.keys(this.buffer).length === 0) { return; } var now = Date.now(); var numUpdates = this.getNumUpdates(); this.ringpop.logger.debug('ringpop flushed membership update buffer', { local: this.ringpop.whoami(), checksum: this.ringpop.membership.checksum, sinceFirstUpdate: this.lastUpdateTime && (this.lastUpdateTime - this.firstUpdateTime), sinceLastFlush: this.lastFlushTime && (now - this.lastFlushTime), numUpdates: numUpdates, updates: numUpdates < this.maxNumUpdates ? this.buffer : null }); this.buffer = {}; this.firstUpdateTime = null; this.lastUpdateTime = null; this.lastFlushTime = now; this.emit('flushed'); }; MembershipUpdateRollup.prototype.getNumUpdates = function getNumUpdates() { var self = this; return Object.keys(this.buffer).reduce(function eachKey(total, key) { return total + self.buffer[key].length; }, 0); }; MembershipUpdateRollup.prototype.renewFlushTimer = function renewFlushTimer() { clearTimeout(this.flushTimer); this.flushTimer = setTimeout( this.flushBuffer.bind(this), this.flushInterval); }; MembershipUpdateRollup.prototype.trackUpdates = function trackUpdates(updates) { if (!Array.isArray(updates) || updates.length === 0) { return; } var sinceLastUpdate = Date.now() - this.lastUpdateTime; if (sinceLastUpdate >= this.flushInterval) { this.flushBuffer(); } if (!this.firstUpdateTime) { this.firstUpdateTime = Date.now(); } this.renewFlushTimer(); this.addUpdates(updates); this.lastUpdateTime = Date.now(); }; module.exports = MembershipUpdateRollup;
hj3938/ringpop
lib/membership/rollup.js
JavaScript
mit
4,215
FROM debian:wheezy RUN apt-get update # For installing hhvm RUN apt-get install -y apt-transport-https software-properties-common RUN apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xB4112585D386EB94 RUN echo deb https://dl.hhvm.com/debian wheezy main > /etc/apt/sources.list.d/hhvm.list RUN apt-get update RUN apt-get -y install curl rake php5 php5-cli php5-curl php-pear hhvm phpunit WORKDIR /braintree-php
besongsamuel/eapp
vendor/braintree/braintree_php/Dockerfile
Dockerfile
mit
432
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2018 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #pragma once // appleseed.renderer headers. #include "renderer/modeling/bssrdf/dipolebssrdffactory.h" // appleseed.foundation headers. #include "foundation/memory/autoreleaseptr.h" // appleseed.main headers. #include "main/dllsymbol.h" // Forward declarations. namespace foundation { class Dictionary; } namespace renderer { class BSSRDF; } namespace renderer { class ParamArray; } namespace renderer { // // Standard dipole BSSRDF factory. // class APPLESEED_DLLSYMBOL StandardDipoleBSSRDFFactory : public DipoleBSSRDFFactory { public: // Delete this instance. void release() override; // Return a string identifying this BSSRDF model. const char* get_model() const override; // Return metadata for this BSSRDF model. foundation::Dictionary get_model_metadata() const override; // Create a new BSSRDF instance. foundation::auto_release_ptr<BSSRDF> create( const char* name, const ParamArray& params) const override; }; } // namespace renderer
est77/appleseed
src/appleseed/renderer/modeling/bssrdf/standarddipolebssrdf.h
C
mit
2,365
package hudson.plugins.git.extensions.impl; import hudson.Extension; import hudson.Util; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitSCM; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; import hudson.plugins.git.util.BuildData; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.gitclient.GitClient; import org.kohsuke.stapler.DataBoundConstructor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; /** * {@link GitSCMExtension} that ignores commits that only affects specific paths. * * @author Juerg Haefliger * @author Andrew Bayer * @author Kohsuke Kawaguchi */ public class PathRestriction extends GitSCMExtension { private final String includedRegions; private final String excludedRegions; // compiled cache private transient volatile List<Pattern> includedPatterns,excludedPatterns; @Override public boolean requiresWorkspaceForPolling() { return true; } @DataBoundConstructor public PathRestriction(String includedRegions, String excludedRegions) { this.includedRegions = includedRegions; this.excludedRegions = excludedRegions; } public String getIncludedRegions() { return includedRegions; } public String getExcludedRegions() { return excludedRegions; } public String[] getExcludedRegionsNormalized() { return normalize(excludedRegions); } public String[] getIncludedRegionsNormalized() { return normalize(includedRegions); } private String[] normalize(String s) { return StringUtils.isBlank(s) ? null : s.split("[\\r\\n]+"); } private List<Pattern> getIncludedPatterns() { if (includedPatterns==null) includedPatterns = getRegionsPatterns(getIncludedRegionsNormalized()); return includedPatterns; } private List<Pattern> getExcludedPatterns() { if (excludedPatterns==null) excludedPatterns = getRegionsPatterns(getExcludedRegionsNormalized()); return excludedPatterns; } private List<Pattern> getRegionsPatterns(String[] regions) { if (regions != null) { List<Pattern> patterns = new ArrayList<Pattern>(regions.length); for (String region : regions) { patterns.add(Pattern.compile(region)); } return patterns; } return Collections.emptyList(); } @Override public Boolean isRevExcluded(GitSCM scm, GitClient git, GitChangeSet commit, TaskListener listener, BuildData buildData) { Collection<String> paths = commit.getAffectedPaths(); if (paths.isEmpty()) {// nothing modified, so no need to compute any of this return null; } List<Pattern> included = getIncludedPatterns(); List<Pattern> excluded = getExcludedPatterns(); // Assemble the list of included paths List<String> includedPaths = new ArrayList<String>(paths.size()); if (!included.isEmpty()) { for (String path : paths) { for (Pattern pattern : included) { if (pattern.matcher(path).matches()) { includedPaths.add(path); break; } } } } else { includedPaths.addAll(paths); } // Assemble the list of excluded paths List<String> excludedPaths = new ArrayList<String>(); if (!excluded.isEmpty()) { for (String path : includedPaths) { for (Pattern pattern : excluded) { if (pattern.matcher(path).matches()) { excludedPaths.add(path); break; } } } } // If every affected path is excluded, return true. if (includedPaths.size() == excludedPaths.size()) { listener.getLogger().println("Ignored commit " + commit.getCommitId() + ": Found only excluded paths: " + Util.join(excludedPaths, ", ")); return true; } return null; } @Extension public static class DescriptorImpl extends GitSCMExtensionDescriptor { @Override public String getDisplayName() { return "Polling ignores commits in certain paths"; } } }
ialbors/git-plugin
src/main/java/hudson/plugins/git/extensions/impl/PathRestriction.java
Java
mit
4,636
'use strict'; const CommandLineInterface = require('cmnd').CommandLineInterface; const CLI = new CommandLineInterface(); CLI.load(__dirname, './commands'); module.exports = CLI;
servicefull/cloudcompose
src/cli.js
JavaScript
mit
181
import TextNode from 'weex/runtime/text-node' // this will be preserved during build const VueFactory = require('./factory') const instances = {} const modules = {} const components = {} const renderer = { TextNode, instances, modules, components } /** * Prepare framework config, basically about the virtual-DOM and JS bridge. * @param {object} cfg */ export function init (cfg) { renderer.Document = cfg.Document renderer.Element = cfg.Element renderer.Comment = cfg.Comment renderer.sendTasks = cfg.sendTasks } /** * Reset framework config and clear all registrations. */ export function reset () { clear(instances) clear(modules) clear(components) delete renderer.Document delete renderer.Element delete renderer.Comment delete renderer.sendTasks } /** * Delete all keys of an object. * @param {object} obj */ function clear (obj) { for (const key in obj) { delete obj[key] } } /** * Create an instance with id, code, config and external data. * @param {string} instanceId * @param {string} appCode * @param {object} config * @param {object} data * @param {object} env { info, config, services } */ export function createInstance ( instanceId, appCode = '', config = {}, data, env = {} ) { // Virtual-DOM object. const document = new renderer.Document(instanceId, config.bundleUrl) // All function/callback of parameters before sent to native // will be converted as an id. So `callbacks` is used to store // these real functions. When a callback invoked and won't be // called again, it should be removed from here automatically. const callbacks = [] // The latest callback id, incremental. const callbackId = 1 const instance = instances[instanceId] = { instanceId, config, data, document, callbacks, callbackId } // Prepare native module getter and HTML5 Timer APIs. const moduleGetter = genModuleGetter(instanceId) const timerAPIs = getInstanceTimer(instanceId, moduleGetter) // Prepare `weex` instance variable. const weexInstanceVar = { config, document, requireModule: moduleGetter } Object.freeze(weexInstanceVar) // Each instance has a independent `Vue` mdoule instance const Vue = instance.Vue = createVueModuleInstance(instanceId, moduleGetter) // The function which create a closure the JS Bundle will run in. // It will declare some instance variables like `Vue`, HTML5 Timer APIs etc. const instanceVars = Object.assign({ Vue, weex: weexInstanceVar, // deprecated __weex_require_module__: weexInstanceVar.requireModule // eslint-disable-line }, timerAPIs) callFunction(instanceVars, appCode) // Send `createFinish` signal to native. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'createFinish', args: [] }], -1) } /** * Destroy an instance with id. It will make sure all memory of * this instance released and no more leaks. * @param {string} instanceId */ export function destroyInstance (instanceId) { const instance = instances[instanceId] if (instance && instance.app instanceof instance.Vue) { instance.app.$destroy() } delete instances[instanceId] } /** * Refresh an instance with id and new top-level component data. * It will use `Vue.set` on all keys of the new data. So it's better * define all possible meaningful keys when instance created. * @param {string} instanceId * @param {object} data */ export function refreshInstance (instanceId, data) { const instance = instances[instanceId] if (!instance || !(instance.app instanceof instance.Vue)) { return new Error(`refreshInstance: instance ${instanceId} not found!`) } for (const key in data) { instance.Vue.set(instance.app, key, data[key]) } // Finally `refreshFinish` signal needed. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'refreshFinish', args: [] }], -1) } /** * Get the JSON object of the root element. * @param {string} instanceId */ export function getRoot (instanceId) { const instance = instances[instanceId] if (!instance || !(instance.app instanceof instance.Vue)) { return new Error(`getRoot: instance ${instanceId} not found!`) } return instance.app.$el.toJSON() } /** * Receive tasks from native. Generally there are two types of tasks: * 1. `fireEvent`: an device actions or user actions from native. * 2. `callback`: invoke function which sent to native as a parameter before. * @param {string} instanceId * @param {array} tasks */ export function receiveTasks (instanceId, tasks) { const instance = instances[instanceId] if (!instance || !(instance.app instanceof instance.Vue)) { return new Error(`receiveTasks: instance ${instanceId} not found!`) } const { callbacks, document } = instance tasks.forEach(task => { // `fireEvent` case: find the event target and fire. if (task.method === 'fireEvent') { const [nodeId, type, e, domChanges] = task.args const el = document.getRef(nodeId) document.fireEvent(el, type, e, domChanges) } // `callback` case: find the callback by id and call it. if (task.method === 'callback') { const [callbackId, data, ifKeepAlive] = task.args const callback = callbacks[callbackId] if (typeof callback === 'function') { callback(data) // Remove the callback from `callbacks` if it won't called again. if (typeof ifKeepAlive === 'undefined' || ifKeepAlive === false) { callbacks[callbackId] = undefined } } } }) // Finally `updateFinish` signal needed. renderer.sendTasks(instanceId + '', [{ module: 'dom', method: 'updateFinish', args: [] }], -1) } /** * Register native modules information. * @param {object} newModules */ export function registerModules (newModules) { for (const name in newModules) { if (!modules[name]) { modules[name] = {} } newModules[name].forEach(method => { if (typeof method === 'string') { modules[name][method] = true } else { modules[name][method.name] = method.args } }) } } /** * Register native components information. * @param {array} newComponents */ export function registerComponents (newComponents) { if (Array.isArray(newComponents)) { newComponents.forEach(component => { if (!component) { return } if (typeof component === 'string') { components[component] = true } else if (typeof component === 'object' && typeof component.type === 'string') { components[component.type] = component } }) } } /** * Create a fresh instance of Vue for each Weex instance. */ function createVueModuleInstance (instanceId, moduleGetter) { const exports = {} VueFactory(exports, renderer) const Vue = exports.Vue const instance = instances[instanceId] // patch reserved tag detection to account for dynamically registered // components const isReservedTag = Vue.config.isReservedTag || (() => false) Vue.config.isReservedTag = name => { return components[name] || isReservedTag(name) } // expose weex-specific info Vue.prototype.$instanceId = instanceId Vue.prototype.$document = instance.document // expose weex native module getter on subVue prototype so that // vdom runtime modules can access native modules via vnode.context Vue.prototype.$requireWeexModule = moduleGetter // Hack `Vue` behavior to handle instance information and data // before root component created. Vue.mixin({ beforeCreate () { const options = this.$options // root component (vm) if (options.el) { // set external data of instance const dataOption = options.data const internalData = (typeof dataOption === 'function' ? dataOption() : dataOption) || {} options.data = Object.assign(internalData, instance.data) // record instance by id instance.app = this } } }) /** * @deprecated Just instance variable `weex.config` * Get instance config. * @return {object} */ Vue.prototype.$getConfig = function () { if (instance.app instanceof Vue) { return instance.config } } return Vue } /** * Generate native module getter. Each native module has several * methods to call. And all the hebaviors is instance-related. So * this getter will return a set of methods which additionally * send current instance id to native when called. Also the args * will be normalized into "safe" value. For example function arg * will be converted into a callback id. * @param {string} instanceId * @return {function} */ function genModuleGetter (instanceId) { const instance = instances[instanceId] return function (name) { const nativeModule = modules[name] || [] const output = {} for (const methodName in nativeModule) { output[methodName] = (...args) => { const finalArgs = args.map(value => { return normalize(value, instance) }) renderer.sendTasks(instanceId + '', [{ module: name, method: methodName, args: finalArgs }], -1) } } return output } } /** * Generate HTML5 Timer APIs. An important point is that the callback * will be converted into callback id when sent to native. So the * framework can make sure no side effect of the callabck happened after * an instance destroyed. * @param {[type]} instanceId [description] * @param {[type]} moduleGetter [description] * @return {[type]} [description] */ function getInstanceTimer (instanceId, moduleGetter) { const instance = instances[instanceId] const timer = moduleGetter('timer') const timerAPIs = { setTimeout: (...args) => { const handler = function () { args[0](...args.slice(2)) } timer.setTimeout(handler, args[1]) return instance.callbackId.toString() }, setInterval: (...args) => { const handler = function () { args[0](...args.slice(2)) } timer.setInterval(handler, args[1]) return instance.callbackId.toString() }, clearTimeout: (n) => { timer.clearTimeout(n) }, clearInterval: (n) => { timer.clearInterval(n) } } return timerAPIs } /** * Call a new function body with some global objects. * @param {object} globalObjects * @param {string} code * @return {any} */ function callFunction (globalObjects, body) { const globalKeys = [] const globalValues = [] for (const key in globalObjects) { globalKeys.push(key) globalValues.push(globalObjects[key]) } globalKeys.push(body) const result = new Function(...globalKeys) return result(...globalValues) } /** * Convert all type of values into "safe" format to send to native. * 1. A `function` will be converted into callback id. * 2. An `Element` object will be converted into `ref`. * The `instance` param is used to generate callback id and store * function if necessary. * @param {any} v * @param {object} instance * @return {any} */ function normalize (v, instance) { const type = typof(v) switch (type) { case 'undefined': case 'null': return '' case 'regexp': return v.toString() case 'date': return v.toISOString() case 'number': case 'string': case 'boolean': case 'array': case 'object': if (v instanceof renderer.Element) { return v.ref } return v case 'function': instance.callbacks[++instance.callbackId] = v return instance.callbackId.toString() default: return JSON.stringify(v) } } /** * Get the exact type of an object by `toString()`. For example call * `toString()` on an array will be returned `[object Array]`. * @param {any} v * @return {string} */ function typof (v) { const s = Object.prototype.toString.call(v) return s.substring(8, s.length - 1).toLowerCase() }
masterfish2015/my_project
半导体物理/js/vue/src/platforms/weex/framework.js
JavaScript
mit
12,333
<?php namespace flo\Command\Deployments; use Acquia\Cloud\Api\CloudApiClient; use flo\Command\Command; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class TagDeploy extends Command { /** * {@inheritdoc} */ protected function configure() { $this->setName('tag-deploy') ->setDescription('Deploy a Tag on Acquia.') ->addOption('pre-release', null, InputOption::VALUE_NONE, 'Allow deployment of pre-release tag.') ->addArgument('env', InputArgument::REQUIRED, 'The environment on Acquia to deploy this tag.') ->addArgument('tag', InputArgument::REQUIRED, 'The tag on GitHub to be marked as a "pre-release" tag.'); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $tag = $input->getArgument('tag'); $GitHub = $this->getGithub(FALSE); $is_environment_available = FALSE; if (!$input->getOption('pre-release')) { try { $release = $GitHub->api('repo')->releases()->showTag( $this->getConfigParameter('organization'), $this->getConfigParameter('repository'), $tag ); } catch (\Exception $e) { $output->writeln("<error>Tag: {$tag} does not exists.</error>"); return 1; } // If the release is already marked "prerelease" fail. if (!empty($release['prerelease']) && $release['prerelease'] == 1) { $output->writeln("<error>Tag: {$tag} is marked as pre-release. Please certify before deploying</error>"); return 1; } } $env = $input->getArgument('env'); $tag = 'tags/' . $input->getArgument('tag'); $acquia = $this->getConfigParameter('acquia'); $subscription = $this->getConfigParameter('subscription'); if (empty($acquia['username']) || empty($acquia['username']) || empty($subscription)) { $output->writeln("<error>You must have your acquia username/password/subscription configured in your flo config to run deploys.</error>"); return 1; } $cloud_api = CloudApiClient::factory(array( 'username' => $acquia['username'], 'password' => $acquia['password'] )); $acquia_environments = $cloud_api->environments($subscription); foreach ($acquia_environments as $acquia_env) { if ($acquia_env->name() == $env) { $is_environment_available = TRUE; break; } } if (!$is_environment_available) { $output->writeln("<error>Environment: {$env} does not exists on Acquia Cloud.</error>"); return 1; } $task = $cloud_api->pushCode($subscription, $env, $tag); $progress = new ProgressBar($output, 100); $progress->start(); while (!$task->completed()) { $progress->advance(); // Lets not kill their api. sleep(2); $task = $cloud_api->task($subscription, $task); } $progress->finish(); if ($task->state() == 'failed') { $output->writeln("\n<error>Task: {$task->id()} failed.</error>"); $output->writeln($task->logs()); return 1; } $output->writeln("\n<info>Tag: {$tag} deployed.</info>"); $output->writeln($task->logs()); } }
sergesemashko/flo
src/flo/Command/Deployments/TagDeploy.php
PHP
mit
3,367
# Introduction These are recommended actions to take for APIs that are not supported on a .NET platform. The [.NET Portability Analyzer](docs/HowTo/Introduction.md#usage) consumes these as they are updated, so the latest recommendations are used. ## Adding Recommendations 1. Copy the template: [! Template.md](!%20Template.md) 2. Fill in a Twitter-sized Recommended Action 3. Fill in "Affected APIs" 1. Find the highest level that your recommended action affects and use that [docId](#document-comment-identifiers-docid) 2. Find [docIds](#document-comment-identifiers-docid) using: * http://dotnetstatus.azurewebsites.net or * Using the console tool and running: `ApiPort.exe docidsearch` 4. Place the file in the following folder structure: __namespace__ => __recommended_action.md__ 5. Create a pull request! ### Example I have a recommended change for the class `System.Threading.Thread`. My change could look like this: __Full Path:__ `docs/RecommendedChanges/System.Threading/Use Task library.md` __Content__: ```markdown ### Recommended Action Use Task library instead. ### Affected APIs * `T:System.Threading.Thread` ``` ## Updating Recommendations 1. Find the `namespace` of the recommendation you want to update 2. Locate the folder with that `namespace` under `docs/RecommendedChanges` 3. Find the .md file with the recommendation 4. Update the contents 5. Create a pull request! ## Note The .NET Portability Service is aware of the hierarchy of APIs. First, it looks for a recommended change containing that exact docId, then it searches the ancestors of that docId until it reaches the first recommended change or the namespace level. ## Document Comment Identifiers (docId) Each API is represented as an ID string that is constructed using the guidelines specified in [Processing the XML File](https://msdn.microsoft.com/en-us/library/fsbx0t7x.aspx). Microsoft.Fx.Portability.MetadataReader decodes docIds using this specification (ie. [DependencyFinderEngineHelper.cs](../../src/Microsoft.Fx.Portability.MetadataReader/DependencyFinderEngineHelper.cs#L160))
JJVertical/dotnet-apiport
docs/RecommendedChanges/README.md
Markdown
mit
2,109
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Thelia\Core\Template\Loop\Accessory | </title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css"> </head> <body id="class"> <div class="header"> <ul> <li><a href="../../../../classes.html">Classes</a></li> <li><a href="../../../../namespaces.html">Namespaces</a></li> <li><a href="../../../../interfaces.html">Interfaces</a></li> <li><a href="../../../../traits.html">Traits</a></li> <li><a href="../../../../doc-index.html">Index</a></li> </ul> <div id="title"></div> <div class="type">Class</div> <h1><a href="../../../../Thelia/Core/Template/Loop.html">Thelia\Core\Template\Loop</a>\Accessory</h1> </div> <div class="content"> <p> class <strong>Accessory</strong> extends <a href="../../../../Thelia/Core/Template/Loop/Product.html"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a></p> <div class="description"> <p>Accessory loop</p> <p>Class Accessory</p> </div> <h2>Methods</h2> <table> <tr> <td class="type"> array </td> <td class="last"> <a href="#method_getSearchIn">getSearchIn</a>() <p> </p> </td> <td><small>from&nbsp;<a href="../../../../Thelia/Core/Template/Loop/Product.html#method_getSearchIn"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a></small></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_doSearch">doSearch</a>(<a href="../../../../Thelia/Model/ProductQuery.html"><abbr title="Thelia\Model\ProductQuery">ProductQuery</abbr></a> $search, <abbr title="Thelia\Core\Template\Loop\$searchTerm">$searchTerm</abbr> $searchTerm, <abbr title="Thelia\Core\Template\Loop\$searchIn">$searchIn</abbr> $searchIn, <abbr title="Thelia\Core\Template\Loop\$searchCriteria">$searchCriteria</abbr> $searchCriteria) <p> </p> </td> <td><small>from&nbsp;<a href="../../../../Thelia/Core/Template/Loop/Product.html#method_doSearch"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a></small></td> </tr> <tr> <td class="type"> <abbr title="Propel\Runtime\ActiveQuery\ModelCriteria">ModelCriteria</abbr> </td> <td class="last"> <a href="#method_buildModelCriteria">buildModelCriteria</a>() <p>this method returns a Propel ModelCriteria</p> </td> <td></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_parseResults">parseResults</a>(<a href="../../../../Thelia/Core/Template/Element/LoopResult.html"><abbr title="Thelia\Core\Template\Element\LoopResult">LoopResult</abbr></a> $results) <p> </p> </td> <td></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_buildComplex">buildComplex</a>() <p> </p> </td> <td><small>from&nbsp;<a href="../../../../Thelia/Core/Template/Loop/Product.html#method_buildComplex"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a></small></td> </tr> <tr> <td class="type"> </td> <td class="last"> <a href="#method_parseComplex">parseComplex</a>(<a href="../../../../Thelia/Core/Template/Element/LoopResult.html"><abbr title="Thelia\Core\Template\Element\LoopResult">LoopResult</abbr></a> $results) <p> </p> </td> <td><small>from&nbsp;<a href="../../../../Thelia/Core/Template/Loop/Product.html#method_parseComplex"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a></small></td> </tr> </table> <h2>Details</h2> <h3 id="method_getSearchIn"> <div class="location">in <a href="../../../../Thelia/Core/Template/Loop/Product.html#method_getSearchIn"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a> at line 134</div> <code> public array <strong>getSearchIn</strong>()</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> <h4>Return Value</h4> <table> <tr> <td>array</td> <td>of available field to search in</td> </tr> </table> </div> </div> <h3 id="method_doSearch"> <div class="location">in <a href="../../../../Thelia/Core/Template/Loop/Product.html#method_doSearch"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a> at line 148</div> <code> public <strong>doSearch</strong>(<a href="../../../../Thelia/Model/ProductQuery.html"><abbr title="Thelia\Model\ProductQuery">ProductQuery</abbr></a> $search, <abbr title="Thelia\Core\Template\Loop\$searchTerm">$searchTerm</abbr> $searchTerm, <abbr title="Thelia\Core\Template\Loop\$searchIn">$searchIn</abbr> $searchIn, <abbr title="Thelia\Core\Template\Loop\$searchCriteria">$searchCriteria</abbr> $searchCriteria)</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../../../Thelia/Model/ProductQuery.html"><abbr title="Thelia\Model\ProductQuery">ProductQuery</abbr></a></td> <td>$search</td> <td> </td> </tr> <tr> <td><abbr title="Thelia\Core\Template\Loop\$searchTerm">$searchTerm</abbr></td> <td>$searchTerm</td> <td> </td> </tr> <tr> <td><abbr title="Thelia\Core\Template\Loop\$searchIn">$searchIn</abbr></td> <td>$searchIn</td> <td> </td> </tr> <tr> <td><abbr title="Thelia\Core\Template\Loop\$searchCriteria">$searchCriteria</abbr></td> <td>$searchCriteria</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_buildModelCriteria"> <div class="location">at line 68</div> <code> public <abbr title="Propel\Runtime\ActiveQuery\ModelCriteria">ModelCriteria</abbr> <strong>buildModelCriteria</strong>()</code> </h3> <div class="details"> <p>this method returns a Propel ModelCriteria</p> <p> </p> <div class="tags"> <h4>Return Value</h4> <table> <tr> <td><abbr title="Propel\Runtime\ActiveQuery\ModelCriteria">ModelCriteria</abbr></td> <td> </td> </tr> </table> </div> </div> <h3 id="method_parseResults"> <div class="location">at line 117</div> <code> public <strong>parseResults</strong>(<a href="../../../../Thelia/Core/Template/Element/LoopResult.html"><abbr title="Thelia\Core\Template\Element\LoopResult">LoopResult</abbr></a> $results)</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../../../Thelia/Core/Template/Element/LoopResult.html"><abbr title="Thelia\Core\Template\Element\LoopResult">LoopResult</abbr></a></td> <td>$results</td> <td> </td> </tr> </table> </div> </div> <h3 id="method_buildComplex"> <div class="location">in <a href="../../../../Thelia/Core/Template/Loop/Product.html#method_buildComplex"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a> at line 559</div> <code> public <strong>buildComplex</strong>()</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> </div> </div> <h3 id="method_parseComplex"> <div class="location">in <a href="../../../../Thelia/Core/Template/Loop/Product.html#method_parseComplex"><abbr title="Thelia\Core\Template\Loop\Product">Product</abbr></a> at line 983</div> <code> public <strong>parseComplex</strong>(<a href="../../../../Thelia/Core/Template/Element/LoopResult.html"><abbr title="Thelia\Core\Template\Element\LoopResult">LoopResult</abbr></a> $results)</code> </h3> <div class="details"> <p> </p> <p> </p> <div class="tags"> <h4>Parameters</h4> <table> <tr> <td><a href="../../../../Thelia/Core/Template/Element/LoopResult.html"><abbr title="Thelia\Core\Template\Element\LoopResult">LoopResult</abbr></a></td> <td>$results</td> <td> </td> </tr> </table> </div> </div> </div> <div id="footer"> Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>. </div> </body> </html>
InformatiqueProg/thelia.github.io
api/2.0.0-RC1/Thelia/Core/Template/Loop/Accessory.html
HTML
mit
10,665
/*========================================================================= Program: OsiriX Copyright (c) OsiriX Team All rights reserved. Distributed under GNU - LGPL See http://www.osirix-viewer.com/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #import <Foundation/Foundation.h> #import <Cocoa/Cocoa.h> #include <OpenGL/gl.h> #include <OpenGL/glext.h> #include <OpenGL/glu.h> #include <OpenGL/CGLMacro.h> #include <OpenGL/CGLCurrent.h> #include <OpenGL/CGLContext.h> #import "N3Geometry.h" #define STAT_UPDATE 0.6f #define IMAGE_COUNT 1 #define IMAGE_DEPTH 32 // Tools. // WARNING: If you add or modify this list, check ViewerController.m, DCMView.h and HotKey Pref Pane enum { tWL = 0, tTranslate, // 1 tZoom, // 2 tRotate, // 3 tNext, // 4 tMesure, // 5 tROI, // 6 t3DRotate, // 7 tCross, // 8 tOval, // 9 tOPolygon, // 10 tCPolygon, // 11 tAngle , // 12 tText, // 13 tArrow, // 14 tPencil, // 15 t3Dpoint, // 16 t3DCut, // 17 tCamera3D, // 18 t2DPoint, // 19 tPlain, // 20 tBonesRemoval, // 21 tWLBlended, // 22 tRepulsor, // 23 tLayerROI, // 24 tROISelector, // 25 tAxis, // 26 tDynAngle, // 27 tCurvedROI // 28 }; extern NSString *pasteBoardOsiriX; extern NSString *pasteBoardOsiriXPlugin; extern int CLUTBARS, ANNOTATIONS, SOFTWAREINTERPOLATION_MAX, DISPLAYCROSSREFERENCELINES; enum { annotNone = 0, annotGraphics, annotBase, annotFull }; enum { barHide = 0, barOrigin, barFused, barBoth }; enum { syncroOFF = 0, syncroABS = 1, syncroREL = 2, syncroLOC = 3, syncroRatio = 4}; typedef enum {DCMViewTextAlignLeft, DCMViewTextAlignCenter, DCMViewTextAlignRight} DCMViewTextAlign; @class GLString; @class DCMPix; @class DCMView; @class ROI; @class OrthogonalMPRController; @class DICOMExport; @class DicomImage, DicomSeries, DicomStudy; @class DCMObject; @interface DCMExportPlugin: NSObject - (void) finalize:(DCMObject*) dcmDst withSourceObject:(DCMObject*) dcmObject; - (NSString*) seriesName; @end /** \brief Image/Frame View for ViewerController */ @interface DCMView: NSOpenGLView { NSInteger _imageRows; NSInteger _imageColumns; NSInteger _tag; BOOL flippedData; BOOL whiteBackground; NSString *yearOld; ROI *curROI; int volumicData; BOOL drawingROI, noScale, volumicSeries, mouseDraggedForROIUndo; DCMView *blendingView; float blendingFactor, blendingFactorStart; BOOL eraserFlag; // use by the PaletteController to switch between the Brush and the Eraser BOOL colorTransfer; unsigned char *colorBuf, *blendingColorBuf; unsigned char alphaTable[256], opaqueTable[256], redTable[256], greenTable[256], blueTable[256]; float redFactor, greenFactor, blueFactor; long blendingMode; float sliceFromTo[ 2][ 3], sliceFromToS[ 2][ 3], sliceFromToE[ 2][ 3], sliceFromTo2[ 2][ 3], sliceFromToThickness; float sliceVector[ 3]; float slicePoint3D[ 3]; float syncRelativeDiff; long syncSeriesIndex; float mprVector[ 3], mprPoint[ 3]; NSTimeInterval timeIntervalForDrag; short thickSlabMode, thickSlabStacks; NSMutableArray *rectArray; NSMutableArray *dcmPixList; NSArray *dcmFilesList; NSMutableArray *dcmRoiList, *curRoiList; DCMPix *curDCM; DCMExportPlugin *dcmExportPlugin; char listType; short curImage, startImage; short currentTool, currentToolRight, currentMouseEventTool; BOOL mouseDragging; BOOL suppress_labels; // keep from drawing the labels when command+shift is pressed NSPoint start, originStart, previous; float startWW, curWW, startMin, startMax; float startWL, curWL; float bdstartWW, bdcurWW, bdstartMin, bdstartMax; float bdstartWL, bdcurWL; BOOL curWLWWSUVConverted; float curWLWWSUVFactor; NSSize scaleStart, scaleInit; double resizeTotal; float scaleValue, startScaleValue; float rotation, rotationStart; NSPoint origin; short crossMove; NSMatrix *matrix; long count; BOOL xFlipped, yFlipped; long fontListGLSize[256]; long labelFontListGLSize[ 256]; NSSize stringSize; NSFont *labelFont; NSFont *fontGL; NSColor *fontColor; GLuint fontListGL; GLuint labelFontListGL; float fontRasterY; NSPoint mesureA, mesureB; NSRect roiRect; NSString *stringID; NSSize previousViewSize; float contextualMenuInWindowPosX; float contextualMenuInWindowPosY; float mouseXPos, mouseYPos; float pixelMouseValue; long pixelMouseValueR, pixelMouseValueG, pixelMouseValueB; float blendingMouseXPos, blendingMouseYPos; float blendingPixelMouseValue; long blendingPixelMouseValueR, blendingPixelMouseValueG, blendingPixelMouseValueB; long textureX, blendingTextureX; long textureY, blendingTextureY; GLuint * pTextureName; GLuint * blendingTextureName; long textureWidth, blendingTextureWidth; long textureHeight, blendingTextureHeight; BOOL f_ext_texture_rectangle; // is texture rectangle extension supported BOOL f_arb_texture_rectangle; // is texture rectangle extension supported BOOL f_ext_client_storage; // is client storage extension supported BOOL f_ext_packed_pixel; // is packed pixel extension supported BOOL f_ext_texture_edge_clamp; // is SGI texture edge clamp extension supported BOOL f_gl_texture_edge_clamp; // is OpenGL texture edge clamp support (1.2+) unsigned long edgeClampParam; // the param that is passed to the texturing parmeteres long maxTextureSize; // the minimum max texture size across all GPUs long maxNOPTDTextureSize; // the minimum max texture size across all GPUs that support non-power of two texture dimensions long TEXTRECTMODE; BOOL isKeyView; //needed for Image View subclass NSCursor *cursor; BOOL cursorSet; NSTrackingArea *cursorTracking; NSPoint display2DPoint; int display2DPointIndex; NSMutableDictionary *stringTextureCache; BOOL _dragInProgress; // Are we drag and dropping NSTimer *_mouseDownTimer; //Timer to check if mouseDown is Persisiting; NSTimer *_rightMouseDownTimer; //Checking For Right hold NSImage *destinationImage; //image will be dropping BOOL _hasChanged, needToLoadTexture, dontEnterReshape, showDescriptionInLarge; BOOL scaleToFitNoReentry; GLString *showDescriptionInLargeText, *warningNotice; float previousScalingFactor; //Context for rendering to iChat // NSOpenGLContext *_alternateContext; BOOL drawing; int repulsorRadius; NSPoint repulsorPosition; NSTimer *repulsorColorTimer; float repulsorAlpha, repulsorAlphaSign; BOOL repulsorROIEdition; long scrollMode; NSPoint ROISelectorStartPoint, ROISelectorEndPoint; BOOL selectorROIEdition; NSMutableArray *ROISelectorSelectedROIList; BOOL syncOnLocationImpossible, updateNotificationRunning; char *resampledBaseAddr, *blendingResampledBaseAddr; BOOL zoomIsSoftwareInterpolated, firstTimeDisplay; int resampledBaseAddrSize, blendingResampledBaseAddrSize; // iChat // float iChatWidth, iChatHeight; // unsigned char* iChatCursorTextureBuffer; // GLuint iChatCursorTextureName; // NSSize iChatCursorImageSize; // NSPoint iChatCursorHotSpot; // BOOL iChatDrawing; // GLuint iChatFontListGL; // NSFont *iChatFontGL; // long iChatFontListGLSize[ 256]; // NSMutableDictionary *iChatStringTextureCache; // NSSize iChatStringSize; NSRect drawingFrameRect; BOOL exceptionDisplayed; BOOL COPYSETTINGSINSERIES; BOOL is2DViewerCached, is2DViewerValue; char* lensTexture; int LENSSIZE; float LENSRATIO; BOOL cursorhidden; int avoidRecursiveSync; BOOL avoidMouseMovedRecursive; BOOL avoidChangeWLWWRecursive; BOOL TextureComputed32bitPipeline; // BOOL iChatRunning; NSImage *loupeImage, *loupeMaskImage; GLuint loupeTextureID, loupeTextureWidth, loupeTextureHeight; GLubyte *loupeTextureBuffer; GLuint loupeMaskTextureID, loupeMaskTextureWidth, loupeMaskTextureHeight; GLubyte *loupeMaskTextureBuffer; float studyColorR, studyColorG, studyColorB; NSUInteger studyDateIndex; // LoupeController *loupeController; GLString *studyDateBox; int annotationType; } @property NSRect drawingFrameRect; @property(readonly) NSMutableArray *rectArray, *curRoiList; @property BOOL COPYSETTINGSINSERIES, flippedData, dontEnterReshape, showDescriptionInLarge; @property(nonatomic) BOOL whiteBackground; @property(readonly) NSMutableArray *dcmPixList, *dcmRoiList; @property(readonly) NSArray *dcmFilesList; @property long syncSeriesIndex; @property(nonatomic)float syncRelativeDiff, studyColorR, studyColorG, studyColorB; @property(nonatomic) long blendingMode; @property(nonatomic) NSUInteger studyDateIndex; @property(retain,setter=setBlending:) DCMView *blendingView; @property(readonly) float blendingFactor; @property(nonatomic) BOOL xFlipped, yFlipped; @property(retain) NSString *stringID; @property(nonatomic) short currentTool; @property(setter=setRightTool:) short currentToolRight; @property(readonly) short curImage; @property(retain) NSMatrix *theMatrix; @property(readonly) BOOL suppressLabels; @property(nonatomic) float scaleValue, rotation; @property(nonatomic) NSPoint origin; @property(readonly) double pixelSpacing, pixelSpacingX, pixelSpacingY; @property(readonly) DCMPix *curDCM; @property(retain) DCMExportPlugin *dcmExportPlugin; @property(readonly) float mouseXPos, mouseYPos; @property(readonly) float contextualMenuInWindowPosX, contextualMenuInWindowPosY; @property(readonly) GLuint fontListGL; @property(readonly) NSFont *fontGL; @property NSInteger tag; @property(readonly) float curWW, curWL; @property NSInteger rows, columns; @property(readonly) NSCursor *cursor; @property BOOL eraserFlag; @property BOOL drawing; @property BOOL volumicSeries; @property (nonatomic) NSTimeInterval timeIntervalForDrag; @property(readonly) BOOL isKeyView, mouseDragging; @property int annotationType; + (void) setDontListenToSyncMessage: (BOOL) v; + (BOOL) noPropagateSettingsInSeriesForModality: (NSString*) m; + (void) purgeStringTextureCache; + (void) setDefaults; + (void) setCLUTBARS:(int) c ANNOTATIONS:(int) a; + (void)setPluginOverridesMouse: (BOOL)override DEPRECATED_ATTRIBUTE; + (void) computePETBlendingCLUT; + (NSString*) findWLWWPreset: (float) wl :(float) ww :(DCMPix*) pix; + (NSSize)sizeOfString:(NSString *)string forFont:(NSFont *)font; + (long) lengthOfString:( char *) cstr forFont:(long *)fontSizeArray; + (BOOL) intersectionBetweenTwoLinesA1:(NSPoint) a1 A2:(NSPoint) a2 B1:(NSPoint) b1 B2:(NSPoint) b2 result:(NSPoint*) r; + (float) Magnitude:( NSPoint) Point1 :(NSPoint) Point2; + (float) angleBetweenVector: (float*) v1 andVector: (float*) v2; + (int) DistancePointLine: (NSPoint) Point :(NSPoint) startPoint :(NSPoint) endPoint :(float*) Distance; + (float) pbase_Plane: (float*) point :(float*) planeOrigin :(float*) planeVector :(float*) pointProjection; + (short)syncro; + (void)setSyncro:(short) s; - (BOOL) softwareInterpolation; - (void) applyImageTransformation; - (void) gClickCountSetReset; - (int) findPlaneAndPoint:(float*) pt :(float*) location; - (int) findPlaneForPoint:(float*) pt localPoint:(float*) location distanceWithPlane: (float*) distanceResult; - (int) findPlaneForPoint:(float*) pt preferParallelTo:(float*)parto localPoint:(float*) location distanceWithPlane: (float*) distanceResult; - (unsigned char*) getRawPixels:(long*) width :(long*) height :(long*) spp :(long*) bpp :(BOOL) screenCapture :(BOOL) force8bits; - (unsigned char*) getRawPixelsWidth:(long*) width height:(long*) height spp:(long*) spp bpp:(long*) bpp screenCapture:(BOOL) screenCapture force8bits:(BOOL) force8bits removeGraphical:(BOOL) removeGraphical squarePixels:(BOOL) squarePixels allTiles:(BOOL) allTiles allowSmartCropping:(BOOL) allowSmartCropping origin:(float*) imOrigin spacing:(float*) imSpacing; - (unsigned char*) getRawPixelsWidth:(long*) width height:(long*) height spp:(long*) spp bpp:(long*) bpp screenCapture:(BOOL) screenCapture force8bits:(BOOL) force8bits removeGraphical:(BOOL) removeGraphical squarePixels:(BOOL) squarePixels allTiles:(BOOL) allTiles allowSmartCropping:(BOOL) allowSmartCropping origin:(float*) imOrigin spacing:(float*) imSpacing offset:(int*) offset isSigned:(BOOL*) isSigned; - (unsigned char*) getRawPixelsWidth:(long*) width height:(long*) height spp:(long*) spp bpp:(long*) bpp screenCapture:(BOOL) screenCapture force8bits:(BOOL) force8bits removeGraphical:(BOOL) removeGraphical squarePixels:(BOOL) squarePixels allTiles:(BOOL) allTiles allowSmartCropping:(BOOL) allowSmartCropping origin:(float*) imOrigin spacing:(float*) imSpacing offset:(int*) offset isSigned:(BOOL*) isSigned views: (NSArray*) views viewsRect: (NSArray*) rects; - (unsigned char*) getRawPixelsViewWidth:(long*) width height:(long*) height spp:(long*) spp bpp:(long*) bpp screenCapture:(BOOL) screenCapture force8bits:(BOOL) force8bits removeGraphical:(BOOL) removeGraphical squarePixels:(BOOL) squarePixels allowSmartCropping:(BOOL) allowSmartCropping origin:(float*) imOrigin spacing:(float*) imSpacing; - (unsigned char*) getRawPixelsViewWidth:(long*) width height:(long*) height spp:(long*) spp bpp:(long*) bpp screenCapture:(BOOL) screenCapture force8bits:(BOOL) force8bits removeGraphical:(BOOL) removeGraphical squarePixels:(BOOL) squarePixels allowSmartCropping:(BOOL) allowSmartCropping origin:(float*) imOrigin spacing:(float*) imSpacing offset:(int*) offset isSigned:(BOOL*) isSigned; - (void) blendingPropagate; - (void) subtract:(DCMView*) bV; - (void) subtract:(DCMView*) bV absolute:(BOOL) abs; - (void) multiply:(DCMView*) bV; - (GLuint *) loadTextureIn:(GLuint *) texture blending:(BOOL) blending colorBuf: (unsigned char**) colorBufPtr textureX:(long*) tX textureY:(long*) tY redTable:(unsigned char*) rT greenTable:(unsigned char*) gT blueTable:(unsigned char*) bT textureWidth: (long*) tW textureHeight:(long*) tH resampledBaseAddr:(char**) rAddr resampledBaseAddrSize:(int*) rBAddrSize; - (short)syncro; - (void)setSyncro:(short) s; // checks to see if tool is for ROIs. maybe better name - (BOOL)isToolforROIs:(long)tool - (BOOL) roiTool:(long) tool; - (void) prepareToRelease; - (void) orientationCorrectedToView:(float*) correctedOrientation; #ifndef OSIRIX_LIGHT - (N3AffineTransform)pixToSubDrawRectTransform; // converst points in DCMPix "Slice Coordinates" to coordinates that need to be passed to GL in subDrawRect #endif - (NSPoint) ConvertFromNSView2GL:(NSPoint) a; - (NSPoint) ConvertFromView2GL:(NSPoint) a; - (NSPoint) ConvertFromUpLeftView2GL:(NSPoint) a; - (NSPoint) ConvertFromGL2View:(NSPoint) a; - (NSPoint) ConvertFromGL2NSView:(NSPoint) a; - (NSPoint) ConvertFromGL2Screen:(NSPoint) a; - (NSPoint) ConvertFromGL2GL:(NSPoint) a toView:(DCMView*) otherView; - (NSRect) smartCrop; - (void) setWLWW:(float) wl :(float) ww; - (void)discretelySetWLWW:(float)wl :(float)ww; - (void) getWLWW:(float*) wl :(float*) ww; - (void) getThickSlabThickness:(float*) thickness location:(float*) location; - (void) setCLUT:( unsigned char*) r :(unsigned char*) g :(unsigned char*) b; - (NSImage*) nsimage; - (NSImage*) nsimage:(BOOL) originalSize; - (NSImage*) nsimage:(BOOL) originalSize allViewers:(BOOL) allViewers; - (NSDictionary*) exportDCMCurrentImage: (DICOMExport*) exportDCM size:(int) size; - (NSDictionary*) exportDCMCurrentImage: (DICOMExport*) exportDCM size:(int) size views: (NSArray*) views viewsRect: (NSArray*) viewsRect; - (NSDictionary*) exportDCMCurrentImage: (DICOMExport*) exportDCM size:(int) size views: (NSArray*) views viewsRect: (NSArray*) viewsRect exportSpacingAndOrigin: (BOOL) exportSpacingAndOrigin; - (NSImage*) exportNSImageCurrentImageWithSize:(int) size; - (void) setIndex:(short) index; - (void) setIndexWithReset:(short) index :(BOOL)sizeToFit; - (void) setDCM:(NSMutableArray*) c :(NSArray*)d :(NSMutableArray*)e :(short) firstImage :(char) type :(BOOL) reset; - (void) setPixels: (NSMutableArray*) pixels files: (NSArray*) files rois: (NSMutableArray*) rois firstImage: (short) firstImage level: (char) level reset: (BOOL) reset; - (void) sendSyncMessage:(short) inc; - (void) loadTextures; - (void)loadTexturesCompute; - (IBAction) flipVertical:(id) sender; - (IBAction) flipHorizontal:(id) sender; - (void) setFusion:(short) mode :(short) stacks; - (void) FindMinimumOpenGLCapabilities; - (NSPoint) rotatePoint:(NSPoint) a; - (void) setOrigin:(NSPoint) x; - (void) setOriginX:(float) x Y:(float) y; - (void) scaleToFit; - (float) scaleToFitForDCMPix: (DCMPix*) d; - (void) setBlendingFactor:(float) f; - (void) sliderAction:(id) sender; - (void) roiSet; - (void) sync3DPosition; - (void) roiSet:(ROI*) aRoi; - (void) colorTables:(unsigned char **) a :(unsigned char **) r :(unsigned char **)g :(unsigned char **) b; - (void) blendingColorTables:(unsigned char **) a :(unsigned char **) r :(unsigned char **)g :(unsigned char **) b; - (void )changeFont:(id)sender; - (IBAction) sliderRGBFactor:(id) sender; - (IBAction) alwaysSyncMenu:(id) sender; - (void) getCLUT:( unsigned char**) r : (unsigned char**) g : (unsigned char**) b; - (void) sync:(NSNotification*)note; - (id)initWithFrame:(NSRect)frame imageRows:(int)rows imageColumns:(int)columns; - (float)getSUV; - (IBAction) roiLoadFromXMLFiles: (NSArray*) filenames; - (BOOL)checkHasChanged; - (void) drawRectIn:(NSRect) size :(GLuint *) texture :(NSPoint) offset :(long) tX :(long) tY :(long) tW :(long) tH; - (void) DrawNSStringGL: (NSString*) cstrOut :(GLuint) fontL :(long) x :(long) y; - (void) DrawNSStringGL: (NSString*) str :(GLuint) fontL :(long) x :(long) y rightAlignment: (BOOL) right useStringTexture: (BOOL) stringTex; - (void)DrawNSStringGL:(NSString*)str :(GLuint)fontL :(long)x :(long)y align:(DCMViewTextAlign)align useStringTexture:(BOOL)stringTex; - (void) DrawCStringGL: ( char *) cstrOut :(GLuint) fontL :(long) x :(long) y; - (void) DrawCStringGL: ( char *) cstrOut :(GLuint) fontL :(long) x :(long) y rightAlignment: (BOOL) right useStringTexture: (BOOL) stringTex; - (void)DrawCStringGL:(char*)cstrOut :(GLuint)fontL :(long)x :(long)y align:(DCMViewTextAlign)align useStringTexture:(BOOL)stringTex; - (void) drawTextualData:(NSRect) size :(long) annotations; - (void) drawTextualData:(NSRect) size annotationsLevel:(long) annotations fullText: (BOOL) fullText onlyOrientation: (BOOL) onlyOrientation; - (void) draw2DPointMarker; - (void) drawImage:(NSImage *)image inBounds:(NSRect)rect; - (void) setScaleValueCentered:(float) x; - (void) updateCurrentImage: (NSNotification*) note; - (void) setImageParamatersFromView:(DCMView *)aView; - (void) setRows:(int)rows columns:(int)columns; - (void) updateTilingViews; - (void) becomeMainWindow; - (void) checkCursor; - (DicomImage *)imageObj; - (DicomSeries *)seriesObj; - (DicomStudy *)studyObj; - (void) updatePresentationStateFromSeries; - (void) updatePresentationStateFromSeriesOnlyImageLevel: (BOOL) onlyImage; - (void) setCursorForView: (long) tool; - (long) getTool: (NSEvent*) event; - (void)resizeWindowToScale:(float)resizeScale; - (float) getBlendedSUV; - (OrthogonalMPRController*) controller; - (void) roiChange:(NSNotification*)note; - (void) roiSelected:(NSNotification*) note; - (void) magnifyWithEvent:(NSEvent *)anEvent; - (void) rotateWithEvent:(NSEvent *)anEvent; - (void) setStartWLWW; - (void) stopROIEditing; - (void) computeMagnifyLens:(NSPoint) p; - (void) makeTextureFromImage:(NSImage*)image forTexture:(GLuint*)texName buffer:(GLubyte*)buffer textureUnit:(GLuint)textureUnit; - (void) stopROIEditingForce:(BOOL) force; - (void) subDrawRect: (NSRect)aRect; // Subclassable, default does nothing. - (void) drawRectAnyway:(NSRect)aRect; // Subclassable, default does nothing. - (void) updateImage; - (BOOL) shouldPropagate; //- (NSPoint) convertFromView2iChat: (NSPoint) a; //- (NSPoint) convertFromNSView2iChat: (NSPoint) a; - (void) annotMenu:(id) sender; - (ROI*) clickInROI: (NSPoint) tempPt; - (void) switchShowDescriptionInLarge; - (void) deleteLens; - (void)getOrientationText:(char *) orientation : (float *) vector :(BOOL) inv; - (NSMutableArray*) selectedROIs; - (void) computeSliceIntersection: (DCMPix*) oPix sliceFromTo: (float[2][3]) sft vector: (float*) vectorB origin: (float*) originB; - (void) drawCrossLines:(float[2][3]) sft ctx: (CGLContextObj) cgl_ctx; - (void) drawCrossLines:(float[2][3]) sft ctx: (CGLContextObj) cgl_ctx withShift: (double) shift; - (void) drawCrossLines:(float[2][3]) sft ctx: (CGLContextObj) cgl_ctx withShift: (double) shift showPoint: (BOOL) showPoint; - (void) drawCrossLines:(float[2][3]) sft ctx: (CGLContextObj) cgl_ctx perpendicular:(BOOL) perpendicular; - (void) drawCrossLines:(float[2][3]) sft ctx: (CGLContextObj) cgl_ctx perpendicular:(BOOL) perpendicular withShift:(double) shift; - (void) drawCrossLines:(float[2][3]) sft ctx: (CGLContextObj) cgl_ctx perpendicular:(BOOL) perpendicular withShift:(double) shift half:(BOOL) half; - (void) drawCrossLines:(float[2][3]) sft ctx: (CGLContextObj) cgl_ctx perpendicular:(BOOL) perpendicular withShift:(double) shift half:(BOOL) half showPoint: (BOOL) showPoint; + (unsigned char*) PETredTable; + (unsigned char*) PETgreenTable; + (unsigned char*) PETblueTable; - (void) startDrag:(NSTimer*)theTimer; - (void)deleteMouseDownTimer; - (id)dicomImage; - (void) roiLoadFromFilesArray: (NSArray*) filenames; - (id)windowController; - (BOOL)is2DViewer; - (IBAction)realSize:(id)sender; - (IBAction)scaleToFit:(id)sender; - (IBAction)actualSize:(id)sender; - (void) drawOrientation:(NSRect) size; - (void) setCOPYSETTINGSINSERIESdirectly: (BOOL) b; -(BOOL)actionForHotKey:(NSString *)hotKey; +(NSDictionary*) hotKeyDictionary; +(NSDictionary*) hotKeyModifiersDictionary; //iChat // New Draw method to allow for IChat Theater - (void) drawRect:(NSRect)aRect withContext:(NSOpenGLContext *)ctx; - (BOOL)_checkHasChanged:(BOOL)flag; // Methods for mouse drag response Can be modified for subclassing // This allow the various tools to have different responses indifferent subclasses. // Making it easie to modify mouseDragged: - (NSPoint)currentPointInView:(NSEvent *)event; - (BOOL)checkROIsForHitAtPoint:(NSPoint)point forEvent:(NSEvent *)event; - (BOOL)mouseDraggedForROIs:(NSEvent *)event; - (void)mouseDraggedCrosshair:(NSEvent *)event; - (void)mouseDragged3DRotate:(NSEvent *)event; - (void)mouseDraggedZoom:(NSEvent *)event; - (void)mouseDraggedTranslate:(NSEvent *)event; - (void)mouseDraggedRotate:(NSEvent *)event; - (void)mouseDraggedImageScroll:(NSEvent *)event; - (void)mouseDraggedBlending:(NSEvent *)event; - (void)mouseDraggedWindowLevel:(NSEvent *)event; - (void)mouseDraggedRepulsor:(NSEvent *)event; - (void)mouseDraggedROISelector:(NSEvent *)event; - (void)deleteROIGroupID:(NSTimeInterval)groupID; - (void) computeColor; - (void)setIsLUT12Bit:(BOOL)boo; - (BOOL)isLUT12Bit; //- (void)displayLoupe; //- (void)displayLoupeWithCenter:(NSPoint)center; //- (void)hideLoupe; + (NSArray*)cleanedOutDcmPixArray:(NSArray*)input; // filters the input array of DCMPix by returning only the pix with the most common ImageType in the input array @end
byvernault/xnat_osirix_plugin
src/OsiriXAPI.framework/Versions/Current/Headers/DCMView.h
C
mit
23,655
require "spec_helper" describe Rbish do before do end describe "#initialize" do before do end end end
suu-g/rbish
spec/shell_spec.rb
Ruby
mit
121
window.baseButton = { 'border-radius': '5px', 'text-align': 'center', 'line-height': '40px' }
mpal9000/jss
examples/famous/styles/base-button.js
JavaScript
mit
106
node.default["freeruler_download_uri"] = "http://www.pascal.com/software/freeruler/FreeRuler1.7b5.zip" node.default["freeruler_app_path"] = "/Applications/Free Ruler 1.7b5.app"
WideEyeLabs/wel-station
wel_station/attributes/freeruler.rb
Ruby
mit
177
import { NDArray } from './'; /** * @static * @memberof module:Globals * @function array * @description `array(...args)` is an alias for `new v(...args)` * @param {} ...args * @returns {NDArray} * @example * import { array } from 'vectorious/core/array'; * * array([1, 2, 3]); // => array([1, 2, 3]) */ export declare const array: (...args: any[]) => NDArray;
cdnjs/cdnjs
ajax/libs/vectorious/6.1.1/core/array.d.ts
TypeScript
mit
371
package fitnesse.wikitext.parser; import fitnesse.html.HtmlElement; import org.junit.Test; public class TableTest { @Test public void scansTables() { ParserTestHelper.assertScansTokenType("|a|\n", "Table", true); ParserTestHelper.assertScansTokenType("!|a|\n", "Table", true); ParserTestHelper.assertScansTokenType("-|a|\n", "Table", true); ParserTestHelper.assertScansTokenType("-!|a|\n", "Table", true); ParserTestHelper.assertScansTokenType("!| a |\n", "Table", true); } @Test public void parsesTables() { ParserTestHelper.assertParses("|a|\n", "SymbolList[Table[TableRow[TableCell[Text]]]]"); ParserTestHelper.assertParses("!|a|\n", "SymbolList[Table[TableRow[TableCell[Text]]]]"); ParserTestHelper.assertParses("| a |\n", "SymbolList[Table[TableRow[TableCell[Whitespace, Text, Whitespace]]]]"); ParserTestHelper.assertParses("!| a |\n", "SymbolList[Table[TableRow[TableCell[Whitespace, Text, Whitespace]]]]"); ParserTestHelper.assertParses("!|a:b|\n", "SymbolList[Table[TableRow[TableCell[Text, Colon, Text]]]]"); } @Test public void translatesTables() { ParserTestHelper.assertTranslatesTo("|a|\n", tableWithCell("a")); ParserTestHelper.assertTranslatesTo("|a| \n", tableWithCell("a")); ParserTestHelper.assertTranslatesTo("|a|", tableWithCell("a")); ParserTestHelper.assertTranslatesTo("||\n", tableWithCell("", false)); ParserTestHelper.assertTranslatesTo("| a |\n", tableWithCell("a")); ParserTestHelper.assertTranslatesTo("|!- a -!|\n", tableWithCell(" a ")); ParserTestHelper.assertTranslatesTo("|''a''|\n", tableWithCell("<i>a</i>")); ParserTestHelper.assertTranslatesTo("|!c a|\n", tableWithCell("<center>a</center>")); ParserTestHelper.assertTranslatesTo("|http://mysite.org|\n", tableWithCell("<a href=\"http://mysite.org\">http://mysite.org</a>")); ParserTestHelper.assertTranslatesTo("|!-line\nbreaks\n-!|\n", tableWithCell("line\nbreaks\n")); ParserTestHelper.assertTranslatesTo("|a|b|c|\n|d|e|f|\n", "<table>" + HtmlElement.endl + "\t<tr>" + HtmlElement.endl + "\t\t<td>a</td>" + HtmlElement.endl + "\t\t<td>b</td>" + HtmlElement.endl + "\t\t<td>c</td>" + HtmlElement.endl + "\t</tr>" + HtmlElement.endl + "\t<tr>" + HtmlElement.endl + "\t\t<td>d</td>" + HtmlElement.endl + "\t\t<td>e</td>" + HtmlElement.endl + "\t\t<td>f</td>" + HtmlElement.endl + "\t</tr>" + HtmlElement.endl + "</table>" + HtmlElement.endl); } @Test public void ignoresMalformedTables() { ParserTestHelper.assertTranslatesTo("!|\n\n|a|\n", "!|" + ParserTestHelper.newLineRendered + ParserTestHelper.newLineRendered + tableWithCell("a")); } @Test public void ignoreMostMarkupInLiteralTable() { ParserTestHelper.assertTranslatesTo("!|''<a''|\n", tableWithCell("''&lt;a''")); ParserTestHelper.assertTranslatesTo("!|[email protected]|\n", tableWithCell("[email protected]")); } @Test public void evaluatesExpressionsInLiteralTable() { ParserTestHelper.assertTranslatesTo("!|${=3+4=}|\n", tableWithCell("7")); } @Test public void normalizesRowLength() { ParserTestHelper.assertTranslatesTo("|a|\n|b|c|\n|d|e|f|\n", "<table>" + HtmlElement.endl + "\t<tr>" + HtmlElement.endl + "\t\t<td colspan=\"3\">a</td>" + HtmlElement.endl + "\t</tr>" + HtmlElement.endl + "\t<tr>" + HtmlElement.endl + "\t\t<td>b</td>" + HtmlElement.endl + "\t\t<td colspan=\"2\">c</td>" + HtmlElement.endl + "\t</tr>" + HtmlElement.endl + "\t<tr>" + HtmlElement.endl + "\t\t<td>d</td>" + HtmlElement.endl + "\t\t<td>e</td>" + HtmlElement.endl + "\t\t<td>f</td>" + HtmlElement.endl + "\t</tr>" + HtmlElement.endl + "</table>" + HtmlElement.endl); } @Test public void hidesFirstRowInCommentTable() { ParserTestHelper.assertTranslatesTo("-|a|\n", tableWithCellAndRow("a", "<tr class=\"hidden\">")); } @Test public void combinesLiteralAndCommentOptions() { ParserTestHelper.assertTranslatesTo("-!|''<a''|\n", tableWithCellAndRow("''&lt;a''", "<tr class=\"hidden\">")); } @Test public void overridesNestedRule() { ParserTestHelper.assertTranslatesTo("|''|\n", tableWithCell("''", false)); ParserTestHelper.assertTranslatesTo("|''a|\n''", tableWithCell("''a") + "''"); } @Test public void translatesNestedLiteralTable() { ParserTestHelper.assertTranslatesTo("|${x}|\n", new TestVariableSource("x", "!|y|\n"), tableWithCell(ParserTestHelper.nestedTableWithCellAndRow("y", "<tr>"))); } @Test public void translatesLiteralNestedTable() { ParserTestHelper.assertTranslatesTo("!|${x}|\n", new TestVariableSource("x", "|y|\n"), tableWithCell("|y|")); } @Test public void translatesVariableWithWhitespace() { ParserTestHelper.assertTranslatesTo("!|${x}|\n", new TestVariableSource("x", " a "), tableWithCell("a")); ParserTestHelper.assertTranslatesTo("!|${x}|\n", new TestVariableSource("x", "!- a -!"), tableWithCell(" a ")); ParserTestHelper.assertTranslatesTo("!|${x}|\n${x}", new TestVariableSource("x", "!- a -!"), tableWithCell(" a ") + " a "); } private String tableWithCell(String cellContent, boolean hasRowTitle) { return ParserTestHelper.tableWithCell(cellContent, hasRowTitle); } private String tableWithCell(String cellContent) { return ParserTestHelper.tableWithCell(cellContent); } private String tableWithCellAndRow(String cellContent, String firstRow) { return ParserTestHelper.tableWithCellAndRow(cellContent, firstRow); } }
amolenaar/fitnesse
test/fitnesse/wikitext/parser/TableTest.java
Java
epl-1.0
5,961
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.network.service; import static org.openhab.binding.network.NetworkBindingConstants.CHANNEL_ONLINE; import java.io.IOException; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Queue; import java.util.TreeSet; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.SystemUtils; import org.apache.commons.net.util.SubnetUtils; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.io.net.actions.Ping; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link NetworkService} handles the connection to the Device * * @author Marc Mettke */ public class NetworkService { private final static Object lockObject = new Object(); private static ScheduledFuture<?> discoveryJob; private static Logger logger = LoggerFactory.getLogger(NetworkService.class); private ScheduledFuture<?> refreshJob; private String hostname; private int port; private int retry; private long refreshInterval; private int timeout; private boolean useSystemPing; public NetworkService() { this("", 0, 1, 60000, 5000, false); } public NetworkService(String hostname, int port, int retry, long refreshInterval, int timeout, boolean useSystemPing) { super(); this.hostname = hostname; this.port = port; this.retry = retry; this.refreshInterval = refreshInterval; this.timeout = timeout; this.useSystemPing = useSystemPing; } public String getHostname() { return hostname; } public int getPort() { return port; } public int getRetry() { return retry; } public long getRefreshInterval() { return refreshInterval; } public int getTimeout() { return timeout; } public boolean isUseSystemPing() { return useSystemPing; } public void setHostname(String hostname) { this.hostname = hostname; } public void setPort(int port) { this.port = port; } public void setRetry(int retry) { this.retry = retry; } public void setRefreshInterval(long refreshInterval) { this.refreshInterval = refreshInterval; } public void setTimeout(int timeout) { this.timeout = timeout; } public void setUseSystemPing(boolean useSystemPing) { this.useSystemPing = useSystemPing; } public void startAutomaticRefresh(ScheduledExecutorService scheduledExecutorService, final StateUpdate stateUpdate) { Runnable runnable = new Runnable() { public void run() { try { stateUpdate.newState(updateDeviceState()); } catch (InvalidConfigurationException e) { stateUpdate.invalidConfig(); } } }; refreshJob = scheduledExecutorService.scheduleAtFixedRate(runnable, 0, refreshInterval, TimeUnit.MILLISECONDS); } public void stopAutomaticRefresh() { refreshJob.cancel(true); } /** * Updates one device to a new status */ public boolean updateDeviceState() throws InvalidConfigurationException { int currentTry = 0; boolean result; do { result = updateDeviceState(getHostname(), getPort(), getTimeout(), isUseSystemPing()); currentTry++; } while( !result && currentTry < this.retry); return result; } /** * Try's to reach the Device by Ping */ private static boolean updateDeviceState(String hostname, int port, int timeout, boolean useSystemPing) throws InvalidConfigurationException { boolean success = false; try { if( !useSystemPing ) { success = Ping.checkVitality(hostname, port, timeout); } else { Process proc; if( SystemUtils.IS_OS_UNIX ) { proc = new ProcessBuilder("ping", "-t", String.valueOf((int)(timeout / 1000)), "-c", "1", hostname).start(); } else if( SystemUtils.IS_OS_WINDOWS) { proc = new ProcessBuilder("ping", "-w", String.valueOf(timeout), "-n", "1", hostname).start(); } else { logger.error("The System Ping is not supported on this Operating System"); throw new InvalidConfigurationException("System Ping not supported"); } int exitValue = proc.waitFor(); success = exitValue == 0; if( !success ) { logger.debug("Ping stopped with Error Number: " + exitValue + " on Command :" + "ping" + (SystemUtils.IS_OS_UNIX ? " -t " : " -w ") + (SystemUtils.IS_OS_UNIX ? String.valueOf((int)(timeout / 1000)) : String.valueOf(timeout)) + (SystemUtils.IS_OS_UNIX ? " -c" : " -n") + " 1 " + hostname); } } logger.debug("established connection [host '{}' port '{}' timeout '{}']", new Object[] {hostname, port, timeout}); } catch (SocketTimeoutException se) { logger.debug("timed out while connecting to host '{}' port '{}' timeout '{}'", new Object[] {hostname, port, timeout}); } catch (IOException ioe) { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] {hostname, port, timeout}); } catch (InterruptedException e) { logger.debug("ping program was interrupted"); } return success; } /** * Handles the whole Discovery */ public static void discoverNetwork(DiscoveryCallback discoveryCallback, ScheduledExecutorService scheduledExecutorService) { TreeSet<String> interfaceIPs; LinkedHashSet<String> networkIPs; logger.debug("Starting Device Discovery"); interfaceIPs = getInterfaceIPs(); networkIPs = getNetworkIPs(interfaceIPs); startDiscovery(networkIPs, discoveryCallback, scheduledExecutorService); } /** * Gets every IPv4 Address on each Interface except the loopback * The Address format is ip/subnet * @return The collected IPv4 Addresses */ private static TreeSet<String> getInterfaceIPs() { TreeSet<String> interfaceIPs = new TreeSet<String>(); try { // For each interface ... for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface networkInterface = en.nextElement(); if (!networkInterface.isLoopback()) { // .. and for each address ... for (Iterator<InterfaceAddress> it = networkInterface .getInterfaceAddresses().iterator(); it.hasNext();) { // ... get IP and Subnet InterfaceAddress interfaceAddress = it.next(); interfaceIPs.add(interfaceAddress.getAddress() .getHostAddress() + "/" + interfaceAddress.getNetworkPrefixLength()); } } } } catch (SocketException e) { } return interfaceIPs; } /** * Takes the interfaceIPs and fetches every IP which can be assigned on their network * @param networkIPs The IPs which are assigned to the Network Interfaces * @return Every single IP which can be assigned on the Networks the computer is connected to */ private static LinkedHashSet<String> getNetworkIPs(TreeSet<String> interfaceIPs) { LinkedHashSet<String> networkIPs = new LinkedHashSet<String>(); for (Iterator<String> it = interfaceIPs.iterator(); it.hasNext();) { try { // gets every ip which can be assigned on the given network SubnetUtils utils = new SubnetUtils(it.next()); String[] addresses = utils.getInfo().getAllAddresses(); for (int i = 0; i < addresses.length; i++) { networkIPs.add(addresses[i]); } } catch (Exception ex) { } } return networkIPs; } /** * Starts the DiscoveryThread for each IP on the Networks * @param allNetworkIPs */ private static void startDiscovery(final LinkedHashSet<String> networkIPs, final DiscoveryCallback discoveryCallback, ScheduledExecutorService scheduledExecutorService) { final int PING_TIMEOUT_IN_MS = 500; ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 10); for( Iterator<String> it = networkIPs.iterator() ; it.hasNext() ; ) { final String ip = it.next(); executorService.execute(new Runnable() { @Override public void run() { if( ip != null ) { try { if( Ping.checkVitality(ip, 0, PING_TIMEOUT_IN_MS) ) { discoveryCallback.newDevice(ip); } } catch (IOException e) {} } } }); } try { executorService.awaitTermination(PING_TIMEOUT_IN_MS * networkIPs.size(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) {} executorService.shutdown(); } @Override public String toString() { return this.hostname + ";" + this.port + ";" + this.retry + ";" + this.refreshInterval + ";" + this.timeout + ";" + this.useSystemPing; } }
EricQ47/openhab2
addons/binding/org.openhab.binding.network/src/main/java/org/openhab/binding/network/service/NetworkService.java
Java
epl-1.0
9,482
package org.python.pydev.ui.dialogs; /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * * copied from org.eclipse.ui.internal.ide.misc.ContainerSelectionGroup * so that we can just get the current project! * *******************************************************************************/ import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.ui.part.DrillDownComposite; /** * Workbench-level composite for choosing a container. */ public class ProjectFolderSelectionGroup extends Composite { /** * Provides content for a tree viewer that shows only containers. */ public static class CopiedContainerContentProvider implements ITreeContentProvider { private boolean showClosedProjects = true; /** * Creates a new ContainerContentProvider. */ public CopiedContainerContentProvider() { } /** * The visual part that is using this content provider is about * to be disposed. Deallocate all allocated SWT resources. */ public void dispose() { } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) */ public Object[] getChildren(Object element) { if (element instanceof IWorkspace) { // check if closed projects should be shown IProject[] allProjects = ((IWorkspace) element).getRoot().getProjects(); if (showClosedProjects) return allProjects; ArrayList<IProject> accessibleProjects = new ArrayList<IProject>(); for (int i = 0; i < allProjects.length; i++) { if (allProjects[i].isOpen()) { accessibleProjects.add(allProjects[i]); } } return accessibleProjects.toArray(); } else if (element instanceof IContainer) { IContainer container = (IContainer) element; if (container.isAccessible()) { try { List<IResource> children = new ArrayList<IResource>(); IResource[] members = container.members(); for (int i = 0; i < members.length; i++) { if (members[i].getType() != IResource.FILE) { children.add(members[i]); } } return children.toArray(); } catch (CoreException e) { // this should never happen because we call #isAccessible before invoking #members } } } return new Object[0]; } /* * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) */ public Object[] getElements(Object element) { return getChildren(element); } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) */ public Object getParent(Object element) { if (element instanceof IResource) return ((IResource) element).getParent(); return null; } /* * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) */ public boolean hasChildren(Object element) { return getChildren(element).length > 0; } /* * @see org.eclipse.jface.viewers.IContentProvider#inputChanged */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } /** * Specify whether or not to show closed projects in the tree * viewer. Default is to show closed projects. * * @param show boolean if false, do not show closed projects in the tree */ public void showClosedProjects(boolean show) { showClosedProjects = show; } } // The listener to notify of events private Listener listener; // Enable user to type in new container name private boolean allowNewContainerName = true; // show all projects by default private boolean showClosedProjects = true; // Last selection made by user private IContainer selectedContainer; // handle on parts private Text containerNameField; TreeViewer treeViewer; // sizing constants private static final int SIZING_SELECTION_PANE_WIDTH = 320; private static final int SIZING_SELECTION_PANE_HEIGHT = 300; private IProject project; /** * Creates a new instance of the widget. * * @param parent The parent widget of the group. * @param listener A listener to forward events to. Can be null if no listener is required. * @param allowNewContainerName Enable the user to type in a new container name instead of just selecting from the existing ones. * @param message The text to present to the user. * @param showClosedProjects Whether or not to show closed projects. */ public ProjectFolderSelectionGroup(Composite parent, Listener listener, boolean allowNewContainerName, String message, boolean showClosedProjects, IProject project) { this(parent, listener, allowNewContainerName, message, showClosedProjects, SIZING_SELECTION_PANE_HEIGHT, project); } /** * Creates a new instance of the widget. * * @param parent The parent widget of the group. * @param listener A listener to forward events to. Can be null if no listener is required. * @param allowNewContainerName Enable the user to type in a new container name instead of just selecting from the existing ones. * @param message The text to present to the user. * @param showClosedProjects Whether or not to show closed projects. * @param heightHint height hint for the drill down composite */ private ProjectFolderSelectionGroup(Composite parent, Listener listener, boolean allowNewContainerName, String message, boolean showClosedProjects, int heightHint, IProject project) { super(parent, SWT.NONE); this.project = project; this.listener = listener; this.allowNewContainerName = allowNewContainerName; this.showClosedProjects = showClosedProjects; createContents(message, heightHint); } /** * The container selection has changed in the tree view. Update the container name field value and notify all listeners. */ public void containerSelectionChanged(IContainer container) { selectedContainer = container; if (allowNewContainerName) { if (container == null) containerNameField.setText("");//$NON-NLS-1$ else containerNameField.setText(container.getFullPath().makeRelative().toString()); } // fire an event so the parent can update its controls if (listener != null) { Event changeEvent = new Event(); changeEvent.type = SWT.Selection; changeEvent.widget = this; listener.handleEvent(changeEvent); } } /** * Creates the contents of the composite. */ public void createContents(String message) { createContents(message, SIZING_SELECTION_PANE_HEIGHT); } /** * Creates the contents of the composite. * * @param heightHint height hint for the drill down composite */ public void createContents(String message, int heightHint) { GridLayout layout = new GridLayout(); layout.marginWidth = 0; setLayout(layout); setLayoutData(new GridData(GridData.FILL_BOTH)); Label label = new Label(this, SWT.WRAP); label.setText(message); label.setFont(this.getFont()); if (allowNewContainerName) { containerNameField = new Text(this, SWT.SINGLE | SWT.BORDER); containerNameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); containerNameField.addListener(SWT.Modify, listener); containerNameField.setFont(this.getFont()); } else { // filler... new Label(this, SWT.NONE); } createTreeViewer(heightHint); Dialog.applyDialogFont(this); } /** * Returns a new drill down viewer for this dialog. * * @param heightHint height hint for the drill down composite * @return a new drill down viewer */ protected void createTreeViewer(int heightHint) { // Create drill down. DrillDownComposite drillDown = new DrillDownComposite(this, SWT.BORDER); GridData spec = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL); spec.widthHint = SIZING_SELECTION_PANE_WIDTH; spec.heightHint = heightHint; drillDown.setLayoutData(spec); // Create tree viewer inside drill down. treeViewer = new TreeViewer(drillDown, SWT.NONE); drillDown.setChildTree(treeViewer); // // //ALL THAT JUST SO THAT WE CAN SET THAT WE JUST WANT THE SPECIFIED PROJECT!!!!!! // // CopiedContainerContentProvider cp = new CopiedContainerContentProvider() { public Object[] getChildren(Object element) { if (element instanceof IWorkspace) { return new Object[] { project }; } else if (element instanceof IContainer) { IContainer container = (IContainer) element; if (container.isAccessible()) { try { List<IResource> children = new ArrayList<IResource>(); IResource[] members = container.members(); for (int i = 0; i < members.length; i++) { if (members[i].getType() != IResource.FILE) { children.add(members[i]); } } return children.toArray(); } catch (CoreException e) { // this should never happen because we call #isAccessible before invoking #members } } } return new Object[0]; } }; cp.showClosedProjects(showClosedProjects); treeViewer.setContentProvider(cp); treeViewer.setLabelProvider(WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider()); treeViewer.setSorter(new ViewerSorter()); treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); containerSelectionChanged((IContainer) selection.getFirstElement()); // allow null } }); treeViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { Object item = ((IStructuredSelection) selection).getFirstElement(); if (treeViewer.getExpandedState(item)) treeViewer.collapseToLevel(item, 1); else treeViewer.expandToLevel(item, 1); } } }); // This has to be done after the viewer has been laid out treeViewer.setInput(ResourcesPlugin.getWorkspace()); } /** * Returns the currently entered container name. Null if the field is empty. Note that the container may not exist yet if the user * entered a new container name in the field. */ public IPath getContainerFullPath() { if (allowNewContainerName) { String pathName = containerNameField.getText(); if (pathName == null || pathName.length() < 1) return null; else //The user may not have made this absolute so do it for them return (new Path(pathName)).makeAbsolute(); } else { if (selectedContainer == null) return null; else return selectedContainer.getFullPath(); } } /** * Gives focus to one of the widgets in the group, as determined by the group. */ public void setInitialFocus() { if (allowNewContainerName) containerNameField.setFocus(); else treeViewer.getTree().setFocus(); } /** * Sets the selected existing container. */ public void setSelectedContainer(IContainer container) { selectedContainer = container; //expand to and select the specified container List<IContainer> itemsToExpand = new ArrayList<IContainer>(); IContainer parent = container.getParent(); while (parent != null) { itemsToExpand.add(0, parent); parent = parent.getParent(); } treeViewer.setExpandedElements(itemsToExpand.toArray()); treeViewer.setSelection(new StructuredSelection(container), true); } }
siddhika1889/Pydev-Editor
src/org/python/pydev/ui/dialogs/ProjectFolderSelectionGroup.java
Java
epl-1.0
15,375
/* Copyright (C) NAVER corp. 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ //{ /** * @fileOverview This file contains Husky plugin that takes care of changing the background color * @name hp_SE2M_BGColor.js */ nhn.husky.SE2M_BGColor = jindo.$Class({ name : "SE2M_BGColor", rxColorPattern : /^#?[0-9a-fA-F]{6}$|^rgb\(\d+, ?\d+, ?\d+\)$/i, $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.elLastUsed = jindo.$$.getSingle("SPAN.husky_se2m_BGColor_lastUsed", elAppContainer); this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_BGColor_layer", elAppContainer); this.elBGColorList = jindo.$$.getSingle("UL.husky_se2m_bgcolor_list", elAppContainer); this.elPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_BGColor_paletteHolder", this.elDropdownLayer); //@ec] this._setLastUsedBGColor("#777777"); }, $BEFORE_MSG_APP_READY : function() { this.oApp.exec("ADD_APP_PROPERTY", ["getLastUsedBackgroundColor", jindo.$Fn(this.getLastUsedBGColor, this).bind()]); }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["BGColorA", "click", "APPLY_LAST_USED_BGCOLOR"]); this.oApp.exec("REGISTER_UI_EVENT", ["BGColorB", "click", "TOGGLE_BGCOLOR_LAYER"]); this.oApp.registerBrowserEvent(this.elBGColorList, "click", "EVENT_APPLY_BGCOLOR", []); this.oApp.registerLazyMessage(["APPLY_LAST_USED_BGCOLOR", "TOGGLE_BGCOLOR_LAYER"], ["hp_SE2M_BGColor$Lazy.js"]); }, _setLastUsedBGColor : function(sBGColor){ this.sLastUsedColor = sBGColor; this.elLastUsed.style.backgroundColor = this.sLastUsedColor; }, getLastUsedBGColor : function(){ return (!!this.sLastUsedColor) ? this.sLastUsedColor : '#777777'; } }); //}
braverokmc79/macaronics-spring-one
web04/src/main/webapp/resources/smarteditor2.0/js_src/fundamental/base/hp_SE2M_BGColor.js
JavaScript
epl-1.0
2,454
<?php require('password.php3'); if ($action == 'checkpass'){ $ds=@ldap_connect("$config[ldap_server]"); // must be a valid ldap server! if ($ds){ if ($dn != ''){ if ($passwd == '') $passwd = 'not_exist'; $r = @ldap_bind($ds,$dn,$passwd); if ($r) $msg = '<font color=blue><b>YES It is that</b></font>'; else $msg = '<font color=red><b>NO It is wrong</b></font>'; } else $msg = 'User DN is not available. Check your configuration'; @ldap_close($ds); } else $msg = '<font color=red><b>Could not connect to LDAP server</b></font>'; echo "<tr><td colspan=3 align=center>$msg</td></tr>\n"; } ?> </form>
ZHAW-INES/rioxo-uClinux-dist
user/freeradius/dialup_admin/lib/ldap/password_check.php3
PHP
gpl-2.0
641
/* * OSPF Neighbor functions. * Copyright (C) 1999, 2000 Toshiaki Takada * * This file is part of GNU Zebra. * * GNU Zebra 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. * * GNU Zebra 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 Zebra; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include <zebra.h> #include "linklist.h" #include "prefix.h" #include "memory.h" #include "command.h" #include "thread.h" #include "stream.h" #include "table.h" #include "log.h" #include "json.h" #include "ospfd/ospfd.h" #include "ospfd/ospf_interface.h" #include "ospfd/ospf_asbr.h" #include "ospfd/ospf_lsa.h" #include "ospfd/ospf_lsdb.h" #include "ospfd/ospf_neighbor.h" #include "ospfd/ospf_nsm.h" #include "ospfd/ospf_packet.h" #include "ospfd/ospf_network.h" #include "ospfd/ospf_flood.h" #include "ospfd/ospf_dump.h" #include "ospfd/ospf_bfd.h" /* Fill in the the 'key' as appropriate to retrieve the entry for nbr * from the ospf_interface's nbrs table. Indexed by interface address * for all cases except Virtual-link and PointToPoint interfaces, where * neighbours are indexed by router-ID instead. */ static void ospf_nbr_key (struct ospf_interface *oi, struct ospf_neighbor *nbr, struct prefix *key) { key->family = AF_INET; key->prefixlen = IPV4_MAX_BITLEN; /* vlinks are indexed by router-id */ if (oi->type == OSPF_IFTYPE_VIRTUALLINK || oi->type == OSPF_IFTYPE_POINTOPOINT) key->u.prefix4 = nbr->router_id; else key->u.prefix4 = nbr->src; return; } struct ospf_neighbor * ospf_nbr_new (struct ospf_interface *oi) { struct ospf_neighbor *nbr; /* Allcate new neighbor. */ nbr = XCALLOC (MTYPE_OSPF_NEIGHBOR, sizeof (struct ospf_neighbor)); /* Relate neighbor to the interface. */ nbr->oi = oi; /* Set default values. */ nbr->state = NSM_Down; /* Set inheritance values. */ nbr->v_inactivity = OSPF_IF_PARAM (oi, v_wait); nbr->v_db_desc = OSPF_IF_PARAM (oi, retransmit_interval); nbr->v_ls_req = OSPF_IF_PARAM (oi, retransmit_interval); nbr->v_ls_upd = OSPF_IF_PARAM (oi, retransmit_interval); nbr->priority = -1; /* DD flags. */ nbr->dd_flags = OSPF_DD_FLAG_MS|OSPF_DD_FLAG_M|OSPF_DD_FLAG_I; /* Last received and sent DD. */ nbr->last_send = NULL; nbr->nbr_nbma = NULL; ospf_lsdb_init (&nbr->db_sum); ospf_lsdb_init (&nbr->ls_rxmt); ospf_lsdb_init (&nbr->ls_req); nbr->crypt_seqnum = 0; ospf_bfd_info_nbr_create(oi, nbr); return nbr; } void ospf_nbr_free (struct ospf_neighbor *nbr) { /* Free DB summary list. */ if (ospf_db_summary_count (nbr)) ospf_db_summary_clear (nbr); /* ospf_db_summary_delete_all (nbr); */ /* Free ls request list. */ if (ospf_ls_request_count (nbr)) ospf_ls_request_delete_all (nbr); /* Free retransmit list. */ if (ospf_ls_retransmit_count (nbr)) ospf_ls_retransmit_clear (nbr); /* Cleanup LSDBs. */ ospf_lsdb_cleanup (&nbr->db_sum); ospf_lsdb_cleanup (&nbr->ls_req); ospf_lsdb_cleanup (&nbr->ls_rxmt); /* Clear last send packet. */ if (nbr->last_send) ospf_packet_free (nbr->last_send); if (nbr->nbr_nbma) { nbr->nbr_nbma->nbr = NULL; nbr->nbr_nbma = NULL; } /* Cancel all timers. */ OSPF_NSM_TIMER_OFF (nbr->t_inactivity); OSPF_NSM_TIMER_OFF (nbr->t_db_desc); OSPF_NSM_TIMER_OFF (nbr->t_ls_req); OSPF_NSM_TIMER_OFF (nbr->t_ls_upd); /* Cancel all events. *//* Thread lookup cost would be negligible. */ thread_cancel_event (master, nbr); ospf_bfd_info_free(&nbr->bfd_info); XFREE (MTYPE_OSPF_NEIGHBOR, nbr); } /* Delete specified OSPF neighbor from interface. */ void ospf_nbr_delete (struct ospf_neighbor *nbr) { struct ospf_interface *oi; struct route_node *rn; struct prefix p; oi = nbr->oi; /* get appropriate prefix 'key' */ ospf_nbr_key (oi, nbr, &p); rn = route_node_lookup (oi->nbrs, &p); if (rn) { /* If lookup for a NBR succeeds, the leaf route_node could * only exist because there is (or was) a nbr there. * If the nbr was deleted, the leaf route_node should have * lost its last refcount too, and be deleted. * Therefore a looked-up leaf route_node in nbrs table * should never have NULL info. */ assert (rn->info); if (rn->info) { rn->info = NULL; route_unlock_node (rn); } else zlog_info ("Can't find neighbor %s in the interface %s", inet_ntoa (nbr->src), IF_NAME (oi)); route_unlock_node (rn); } else { /* * This neighbor was not found, but before we move on and * free the neighbor structre, make sure that it was not * indexed incorrectly and ended up in the "worng" place */ /* Reverse the lookup rules */ if (oi->type == OSPF_IFTYPE_VIRTUALLINK || oi->type == OSPF_IFTYPE_POINTOPOINT) p.u.prefix4 = nbr->src; else p.u.prefix4 = nbr->router_id; rn = route_node_lookup (oi->nbrs, &p); if (rn){ /* We found the neighbor! * Now make sure it is not the exact same neighbor * structure that we are about to free */ if (nbr == rn->info){ /* Same neighbor, drop the reference to it */ rn->info = NULL; route_unlock_node (rn); } route_unlock_node (rn); } } /* Free ospf_neighbor structure. */ ospf_nbr_free (nbr); } /* Check myself is in the neighbor list. */ int ospf_nbr_bidirectional (struct in_addr *router_id, struct in_addr *neighbors, int size) { int i; int max; max = size / sizeof (struct in_addr); for (i = 0; i < max; i ++) if (IPV4_ADDR_SAME (router_id, &neighbors[i])) return 1; return 0; } /* reset nbr_self */ void ospf_nbr_self_reset (struct ospf_interface *oi, struct in_addr router_id) { if (oi->nbr_self) ospf_nbr_delete (oi->nbr_self); oi->nbr_self = ospf_nbr_new (oi); ospf_nbr_add_self (oi, router_id); } /* Add self to nbr list. */ void ospf_nbr_add_self (struct ospf_interface *oi, struct in_addr router_id) { struct prefix p; struct route_node *rn; if (!oi->nbr_self) oi->nbr_self = ospf_nbr_new (oi); /* Initial state */ oi->nbr_self->address = *oi->address; oi->nbr_self->priority = OSPF_IF_PARAM (oi, priority); oi->nbr_self->router_id = router_id; oi->nbr_self->src = oi->address->u.prefix4; oi->nbr_self->state = NSM_TwoWay; switch (oi->area->external_routing) { case OSPF_AREA_DEFAULT: SET_FLAG (oi->nbr_self->options, OSPF_OPTION_E); break; case OSPF_AREA_STUB: UNSET_FLAG (oi->nbr_self->options, OSPF_OPTION_E); break; case OSPF_AREA_NSSA: UNSET_FLAG (oi->nbr_self->options, OSPF_OPTION_E); SET_FLAG (oi->nbr_self->options, OSPF_OPTION_NP); break; } /* Add nbr_self to nbrs table */ ospf_nbr_key (oi, oi->nbr_self, &p); rn = route_node_get (oi->nbrs, &p); if (rn->info) { /* There is already pseudo neighbor. */ assert (oi->nbr_self == rn->info); route_unlock_node (rn); } else rn->info = oi->nbr_self; } /* Get neighbor count by status. Specify status = 0, get all neighbor other than myself. */ int ospf_nbr_count (struct ospf_interface *oi, int state) { struct ospf_neighbor *nbr; struct route_node *rn; int count = 0; for (rn = route_top (oi->nbrs); rn; rn = route_next (rn)) if ((nbr = rn->info)) if (!IPV4_ADDR_SAME (&nbr->router_id, &oi->ospf->router_id)) if (state == 0 || nbr->state == state) count++; return count; } int ospf_nbr_count_opaque_capable (struct ospf_interface *oi) { struct ospf_neighbor *nbr; struct route_node *rn; int count = 0; for (rn = route_top (oi->nbrs); rn; rn = route_next (rn)) if ((nbr = rn->info)) if (!IPV4_ADDR_SAME (&nbr->router_id, &oi->ospf->router_id)) if (nbr->state == NSM_Full) if (CHECK_FLAG (nbr->options, OSPF_OPTION_O)) count++; return count; } /* lookup nbr by address - use this only if you know you must * otherwise use the ospf_nbr_lookup() wrapper, which deals * with virtual link and PointToPoint neighbours */ struct ospf_neighbor * ospf_nbr_lookup_by_addr (struct route_table *nbrs, struct in_addr *addr) { struct prefix p; struct route_node *rn; struct ospf_neighbor *nbr; p.family = AF_INET; p.prefixlen = IPV4_MAX_BITLEN; p.u.prefix4 = *addr; rn = route_node_lookup (nbrs, &p); if (! rn) return NULL; /* See comment in ospf_nbr_delete */ assert (rn->info); if (rn->info == NULL) { route_unlock_node (rn); return NULL; } nbr = (struct ospf_neighbor *) rn->info; route_unlock_node (rn); return nbr; } struct ospf_neighbor * ospf_nbr_lookup_by_routerid (struct route_table *nbrs, struct in_addr *id) { struct route_node *rn; struct ospf_neighbor *nbr; for (rn = route_top (nbrs); rn; rn = route_next (rn)) if ((nbr = rn->info) != NULL) if (IPV4_ADDR_SAME (&nbr->router_id, id)) { route_unlock_node(rn); return nbr; } return NULL; } void ospf_renegotiate_optional_capabilities (struct ospf *top) { struct listnode *node; struct ospf_interface *oi; struct route_table *nbrs; struct route_node *rn; struct ospf_neighbor *nbr; /* At first, flush self-originated LSAs from routing domain. */ ospf_flush_self_originated_lsas_now (top); /* Revert all neighbor status to ExStart. */ for (ALL_LIST_ELEMENTS_RO (top->oiflist, node, oi)) { if ((nbrs = oi->nbrs) == NULL) continue; for (rn = route_top (nbrs); rn; rn = route_next (rn)) { if ((nbr = rn->info) == NULL || nbr == oi->nbr_self) continue; if (nbr->state < NSM_ExStart) continue; if (IS_DEBUG_OSPF_EVENT) zlog_debug ("Renegotiate optional capabilities with neighbor(%s)", inet_ntoa (nbr->router_id)); OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch); } } return; } struct ospf_neighbor * ospf_nbr_lookup (struct ospf_interface *oi, struct ip *iph, struct ospf_header *ospfh) { if (oi->type == OSPF_IFTYPE_VIRTUALLINK || oi->type == OSPF_IFTYPE_POINTOPOINT) return (ospf_nbr_lookup_by_routerid (oi->nbrs, &ospfh->router_id)); else return (ospf_nbr_lookup_by_addr (oi->nbrs, &iph->ip_src)); } static struct ospf_neighbor * ospf_nbr_add (struct ospf_interface *oi, struct ospf_header *ospfh, struct prefix *p) { struct ospf_neighbor *nbr; nbr = ospf_nbr_new (oi); nbr->state = NSM_Down; nbr->src = p->u.prefix4; memcpy (&nbr->address, p, sizeof (struct prefix)); nbr->nbr_nbma = NULL; if (oi->type == OSPF_IFTYPE_NBMA) { struct ospf_nbr_nbma *nbr_nbma; struct listnode *node; for (ALL_LIST_ELEMENTS_RO (oi->nbr_nbma, node, nbr_nbma)) { if (IPV4_ADDR_SAME(&nbr_nbma->addr, &nbr->src)) { nbr_nbma->nbr = nbr; nbr->nbr_nbma = nbr_nbma; if (nbr_nbma->t_poll) OSPF_POLL_TIMER_OFF (nbr_nbma->t_poll); nbr->state_change = nbr_nbma->state_change + 1; } } } /* New nbr, save the crypto sequence number if necessary */ if (ntohs (ospfh->auth_type) == OSPF_AUTH_CRYPTOGRAPHIC) nbr->crypt_seqnum = ospfh->u.crypt.crypt_seqnum; if (IS_DEBUG_OSPF_EVENT) zlog_debug ("NSM[%s:%s]: start", IF_NAME (nbr->oi), inet_ntoa (nbr->router_id)); return nbr; } struct ospf_neighbor * ospf_nbr_get (struct ospf_interface *oi, struct ospf_header *ospfh, struct ip *iph, struct prefix *p) { struct route_node *rn; struct prefix key; struct ospf_neighbor *nbr; key.family = AF_INET; key.prefixlen = IPV4_MAX_BITLEN; if (oi->type == OSPF_IFTYPE_VIRTUALLINK || oi->type == OSPF_IFTYPE_POINTOPOINT) key.u.prefix4 = ospfh->router_id;/* index vlink and ptp nbrs by router-id */ else key.u.prefix4 = iph->ip_src; rn = route_node_get (oi->nbrs, &key); if (rn->info) { route_unlock_node (rn); nbr = rn->info; if (oi->type == OSPF_IFTYPE_NBMA && nbr->state == NSM_Attempt) { nbr->src = iph->ip_src; memcpy (&nbr->address, p, sizeof (struct prefix)); } } else { rn->info = nbr = ospf_nbr_add (oi, ospfh, p); } nbr->router_id = ospfh->router_id; return nbr; }
mwinter-osr/frr
ospfd/ospf_neighbor.c
C
gpl-2.0
12,911
/* * SoC specific setup code for the AT91SAM9N12 * * Copyright (C) 2012 Atmel Corporation. * * Licensed under GPLv2 or later. */ #include <asm/system_misc.h> #include <mach/hardware.h> #include "soc.h" #include "generic.h" /* -------------------------------------------------------------------- * AT91SAM9N12 processor initialization * -------------------------------------------------------------------- */ static void __init at91sam9n12_initialize(void) { at91_sysirq_mask_rtc(AT91SAM9N12_BASE_RTC); } AT91_SOC_START(at91sam9n12) .init = at91sam9n12_initialize, AT91_SOC_END
JoshWu/linux-at91
arch/arm/mach-at91/at91sam9n12.c
C
gpl-2.0
593
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2013-2014 Intel Corporation. All rights reserved. * * */ bool bt_hid_register(struct ipc *ipc, const bdaddr_t *addr, uint8_t mode); void bt_hid_unregister(void);
cktakahasi/bluez
android/hidhost.h
C
gpl-2.0
290
/* Copyright (c) 2008-2010, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/mm.h> #include <linux/fb.h> #include <linux/init.h> #include <linux/ioport.h> #include <linux/device.h> #include <linux/dma-mapping.h> #include "msm_fb_panel.h" #include "mddihost.h" #include "mddihosti.h" #define FEATURE_MDDI_UNDERRUN_RECOVERY #ifndef FEATURE_MDDI_DISABLE_REVERSE static void mddi_read_rev_packet(byte *data_ptr); #endif struct timer_list mddi_host_timer; #define MDDI_DEFAULT_TIMER_LENGTH 5000 /* 5 seconds */ uint32 mddi_rtd_frequency = 60000; /* send RTD every 60 seconds */ uint32 mddi_client_status_frequency = 60000; /* get status pkt every 60 secs */ boolean mddi_vsync_detect_enabled = FALSE; mddi_gpio_info_type mddi_gpio; uint32 mddi_host_core_version; boolean mddi_debug_log_statistics = FALSE; /* #define FEATURE_MDDI_HOST_ENABLE_EARLY_HIBERNATION */ /* default to TRUE in case MDP does not vote */ static boolean mddi_host_mdp_active_flag = TRUE; static uint32 mddi_log_stats_counter; uint32 mddi_log_stats_frequency = 4000; int32 mddi_client_type; #define MDDI_DEFAULT_REV_PKT_SIZE 0x20 #ifndef FEATURE_MDDI_DISABLE_REVERSE static boolean mddi_rev_ptr_workaround = TRUE; static uint32 mddi_reg_read_retry; static uint32 mddi_reg_read_retry_max = 20; static boolean mddi_enable_reg_read_retry = TRUE; static boolean mddi_enable_reg_read_retry_once = FALSE; #define MDDI_MAX_REV_PKT_SIZE 0x60 #define MDDI_CLIENT_CAPABILITY_REV_PKT_SIZE 0x60 #define MDDI_VIDEO_REV_PKT_SIZE 0x40 #define MDDI_REV_BUFFER_SIZE MDDI_MAX_REV_PKT_SIZE static byte rev_packet_data[MDDI_MAX_REV_PKT_SIZE]; #endif /* FEATURE_MDDI_DISABLE_REVERSE */ /* leave these variables so graphics will compile */ #define MDDI_MAX_REV_DATA_SIZE 128 /*lint -d__align(x) */ boolean mddi_debug_clear_rev_data = TRUE; uint32 *mddi_reg_read_value_ptr; mddi_client_capability_type mddi_client_capability_pkt; static boolean mddi_client_capability_request = FALSE; #ifndef FEATURE_MDDI_DISABLE_REVERSE #define MAX_MDDI_REV_HANDLERS 2 #define INVALID_PKT_TYPE 0xFFFF typedef struct { mddi_rev_handler_type handler; /* ISR to be executed */ uint16 pkt_type; } mddi_rev_pkt_handler_type; static mddi_rev_pkt_handler_type mddi_rev_pkt_handler[MAX_MDDI_REV_HANDLERS] = { {NULL, INVALID_PKT_TYPE}, {NULL, INVALID_PKT_TYPE} }; static boolean mddi_rev_encap_user_request = FALSE; static mddi_linked_list_notify_type mddi_rev_user; spinlock_t mddi_host_spin_lock; extern uint32 mdp_in_processing; #endif typedef enum { MDDI_REV_IDLE #ifndef FEATURE_MDDI_DISABLE_REVERSE , MDDI_REV_REG_READ_ISSUED, MDDI_REV_REG_READ_SENT, MDDI_REV_ENCAP_ISSUED, MDDI_REV_STATUS_REQ_ISSUED, MDDI_REV_CLIENT_CAP_ISSUED #endif } mddi_rev_link_state_type; typedef enum { MDDI_LINK_DISABLED, MDDI_LINK_HIBERNATING, MDDI_LINK_ACTIVATING, MDDI_LINK_ACTIVE } mddi_host_link_state_type; typedef struct { uint32 count; uint32 in_count; uint32 disp_req_count; uint32 state_change_count; uint32 ll_done_count; uint32 rev_avail_count; uint32 error_count; uint32 rev_encap_count; uint32 llist_ptr_write_1; uint32 llist_ptr_write_2; } mddi_host_int_type; typedef struct { uint32 fwd_crc_count; uint32 rev_crc_count; uint32 pri_underflow; uint32 sec_underflow; uint32 rev_overflow; uint32 pri_overwrite; uint32 sec_overwrite; uint32 rev_overwrite; uint32 dma_failure; uint32 rtd_failure; uint32 reg_read_failure; #ifdef FEATURE_MDDI_UNDERRUN_RECOVERY uint32 pri_underrun_detected; #endif } mddi_host_stat_type; typedef struct { uint32 rtd_cnt; uint32 rev_enc_cnt; uint32 vid_cnt; uint32 reg_acc_cnt; uint32 cli_stat_cnt; uint32 cli_cap_cnt; uint32 reg_read_cnt; uint32 link_active_cnt; uint32 link_hibernate_cnt; uint32 vsync_response_cnt; uint32 fwd_crc_cnt; uint32 rev_crc_cnt; } mddi_log_params_struct_type; typedef struct { uint32 rtd_value; uint32 rtd_counter; uint32 client_status_cnt; boolean rev_ptr_written; uint8 *rev_ptr_start; uint8 *rev_ptr_curr; uint32 mddi_rev_ptr_write_val; dma_addr_t rev_data_dma_addr; uint16 rev_pkt_size; mddi_rev_link_state_type rev_state; mddi_host_link_state_type link_state; mddi_host_driver_state_type driver_state; boolean disable_hibernation; uint32 saved_int_reg; uint32 saved_int_en; mddi_linked_list_type *llist_ptr; dma_addr_t llist_dma_addr; mddi_linked_list_type *llist_dma_ptr; uint32 *rev_data_buf; struct completion mddi_llist_avail_comp; boolean mddi_waiting_for_llist_avail; mddi_host_int_type int_type; mddi_host_stat_type stats; mddi_log_params_struct_type log_parms; mddi_llist_info_type llist_info; mddi_linked_list_notify_type llist_notify[MDDI_MAX_NUM_LLIST_ITEMS]; } mddi_host_cntl_type; static mddi_host_type mddi_curr_host = MDDI_HOST_PRIM; static mddi_host_cntl_type mhctl[MDDI_NUM_HOST_CORES]; mddi_linked_list_type *llist_extern[MDDI_NUM_HOST_CORES]; mddi_linked_list_type *llist_dma_extern[MDDI_NUM_HOST_CORES]; mddi_linked_list_notify_type *llist_extern_notify[MDDI_NUM_HOST_CORES]; static mddi_log_params_struct_type prev_parms[MDDI_NUM_HOST_CORES]; extern uint32 mdp_total_vdopkts; static boolean mddi_host_io_clock_on = FALSE; static boolean mddi_host_hclk_on = FALSE; int int_mddi_pri_flag = FALSE; int int_mddi_ext_flag = FALSE; static void mddi_report_errors(uint32 int_reg) { mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); if (int_reg & MDDI_INT_PRI_UNDERFLOW) { pmhctl->stats.pri_underflow++; MDDI_MSG_ERR("!!! MDDI Primary Underflow !!!\n"); } if (int_reg & MDDI_INT_SEC_UNDERFLOW) { pmhctl->stats.sec_underflow++; MDDI_MSG_ERR("!!! MDDI Secondary Underflow !!!\n"); } #ifndef FEATURE_MDDI_DISABLE_REVERSE if (int_reg & MDDI_INT_REV_OVERFLOW) { pmhctl->stats.rev_overflow++; MDDI_MSG_ERR("!!! MDDI Reverse Overflow !!!\n"); pmhctl->rev_ptr_curr = pmhctl->rev_ptr_start; mddi_host_reg_out(REV_PTR, pmhctl->mddi_rev_ptr_write_val); } if (int_reg & MDDI_INT_CRC_ERROR) MDDI_MSG_ERR("!!! MDDI Reverse CRC Error !!!\n"); #endif if (int_reg & MDDI_INT_PRI_OVERWRITE) { pmhctl->stats.pri_overwrite++; MDDI_MSG_ERR("!!! MDDI Primary Overwrite !!!\n"); } if (int_reg & MDDI_INT_SEC_OVERWRITE) { pmhctl->stats.sec_overwrite++; MDDI_MSG_ERR("!!! MDDI Secondary Overwrite !!!\n"); } #ifndef FEATURE_MDDI_DISABLE_REVERSE if (int_reg & MDDI_INT_REV_OVERWRITE) { pmhctl->stats.rev_overwrite++; /* This will show up normally and is not a problem */ MDDI_MSG_DEBUG("MDDI Reverse Overwrite!\n"); } if (int_reg & MDDI_INT_RTD_FAILURE) { mddi_host_reg_outm(INTEN, MDDI_INT_RTD_FAILURE, 0); pmhctl->stats.rtd_failure++; MDDI_MSG_ERR("!!! MDDI RTD Failure !!!\n"); } #endif if (int_reg & MDDI_INT_DMA_FAILURE) { pmhctl->stats.dma_failure++; MDDI_MSG_ERR("!!! MDDI DMA Abort !!!\n"); } } static void mddi_host_enable_io_clock(void) { if (!MDDI_HOST_IS_IO_CLOCK_ON) MDDI_HOST_ENABLE_IO_CLOCK; } static void mddi_host_enable_hclk(void) { if (!MDDI_HOST_IS_HCLK_ON) MDDI_HOST_ENABLE_HCLK; } static void mddi_host_disable_io_clock(void) { #ifndef FEATURE_MDDI_HOST_IO_CLOCK_CONTROL_DISABLE if (MDDI_HOST_IS_IO_CLOCK_ON) MDDI_HOST_DISABLE_IO_CLOCK; #endif } static void mddi_host_disable_hclk(void) { #ifndef FEATURE_MDDI_HOST_HCLK_CONTROL_DISABLE if (MDDI_HOST_IS_HCLK_ON) MDDI_HOST_DISABLE_HCLK; #endif } static void mddi_vote_to_sleep(mddi_host_type host_idx, boolean sleep) { uint16 vote_mask; if (host_idx == MDDI_HOST_PRIM) vote_mask = 0x01; else vote_mask = 0x02; } static void mddi_report_state_change(uint32 int_reg) { mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); if ((pmhctl->saved_int_reg & MDDI_INT_IN_HIBERNATION) && (pmhctl->saved_int_reg & MDDI_INT_LINK_ACTIVE)) { /* recover from condition where the io_clock was turned off by the clock driver during a transition to hibernation. The io_clock disable is to prevent MDP/MDDI underruns when changing ARM clock speeds. In the process of halting the ARM, the hclk divider needs to be set to 1. When it is set to 1, there is a small time (usecs) when hclk is off or slow, and this can cause an underrun. To prevent the underrun, clock driver turns off the MDDI io_clock before making the change. */ mddi_host_reg_out(CMD, MDDI_CMD_POWERUP); } if (int_reg & MDDI_INT_LINK_ACTIVE) { pmhctl->link_state = MDDI_LINK_ACTIVE; pmhctl->log_parms.link_active_cnt++; pmhctl->rtd_value = mddi_host_reg_in(RTD_VAL); MDDI_MSG_DEBUG("!!! MDDI Active RTD:0x%x!!!\n", pmhctl->rtd_value); /* now interrupt on hibernation */ mddi_host_reg_outm(INTEN, (MDDI_INT_IN_HIBERNATION | MDDI_INT_LINK_ACTIVE), MDDI_INT_IN_HIBERNATION); #ifdef DEBUG_MDDIHOSTI /* if gpio interrupt is enabled, start polling at fastest * registered rate */ if (mddi_gpio.polling_enabled) { timer_reg(&mddi_gpio_poll_timer, mddi_gpio_poll_timer_cb, 0, mddi_gpio.polling_interval, 0); } #endif #ifndef FEATURE_MDDI_DISABLE_REVERSE if (mddi_rev_ptr_workaround) { /* HW CR: need to reset reverse register stuff */ pmhctl->rev_ptr_written = FALSE; pmhctl->rev_ptr_curr = pmhctl->rev_ptr_start; } #endif /* vote on sleep */ mddi_vote_to_sleep(host_idx, FALSE); if (host_idx == MDDI_HOST_PRIM) { if (mddi_vsync_detect_enabled) { /* * Indicate to client specific code that vsync * was enabled, but we did not detect a client * intiated wakeup. The client specific * handler can either reassert vsync detection, * or treat this as a valid vsync. */ mddi_client_lcd_vsync_detected(FALSE); pmhctl->log_parms.vsync_response_cnt++; } } } if (int_reg & MDDI_INT_IN_HIBERNATION) { pmhctl->link_state = MDDI_LINK_HIBERNATING; pmhctl->log_parms.link_hibernate_cnt++; MDDI_MSG_DEBUG("!!! MDDI Hibernating !!!\n"); if (mddi_client_type == 2) { mddi_host_reg_out(PAD_CTL, 0x402a850f); mddi_host_reg_out(PAD_CAL, 0x10220020); mddi_host_reg_out(TA1_LEN, 0x0010); mddi_host_reg_out(TA2_LEN, 0x0040); } /* now interrupt on link_active */ #ifdef FEATURE_MDDI_DISABLE_REVERSE mddi_host_reg_outm(INTEN, (MDDI_INT_MDDI_IN | MDDI_INT_IN_HIBERNATION | MDDI_INT_LINK_ACTIVE), MDDI_INT_LINK_ACTIVE); #else mddi_host_reg_outm(INTEN, (MDDI_INT_MDDI_IN | MDDI_INT_IN_HIBERNATION | MDDI_INT_LINK_ACTIVE), (MDDI_INT_MDDI_IN | MDDI_INT_LINK_ACTIVE)); pmhctl->rtd_counter = mddi_rtd_frequency; if (pmhctl->rev_state != MDDI_REV_IDLE) { /* a rev_encap will not wake up the link, so we do that here */ pmhctl->link_state = MDDI_LINK_ACTIVATING; mddi_host_reg_out(CMD, MDDI_CMD_LINK_ACTIVE); } #endif if (pmhctl->disable_hibernation) { mddi_host_reg_out(CMD, MDDI_CMD_HIBERNATE); mddi_host_reg_out(CMD, MDDI_CMD_LINK_ACTIVE); pmhctl->link_state = MDDI_LINK_ACTIVATING; } #ifdef FEATURE_MDDI_UNDERRUN_RECOVERY if ((pmhctl->llist_info.transmitting_start_idx != UNASSIGNED_INDEX) && ((pmhctl-> saved_int_reg & (MDDI_INT_PRI_LINK_LIST_DONE | MDDI_INT_PRI_PTR_READ)) == MDDI_INT_PRI_PTR_READ)) { mddi_linked_list_type *llist_dma; llist_dma = pmhctl->llist_dma_ptr; /* * All indications are that we have not received a * linked list done interrupt, due to an underrun * condition. Recovery attempt is to send again. */ dma_coherent_pre_ops(); /* Write to primary pointer register again */ mddi_host_reg_out(PRI_PTR, &llist_dma[pmhctl->llist_info. transmitting_start_idx]); pmhctl->stats.pri_underrun_detected++; } #endif /* vote on sleep */ if (pmhctl->link_state == MDDI_LINK_HIBERNATING) { mddi_vote_to_sleep(host_idx, TRUE); } #ifdef DEBUG_MDDIHOSTI /* need to stop polling timer */ if (mddi_gpio.polling_enabled) { (void) timer_clr(&mddi_gpio_poll_timer, T_NONE); } #endif } } void mddi_host_timer_service(unsigned long data) { #ifndef FEATURE_MDDI_DISABLE_REVERSE unsigned long flags; #endif mddi_host_type host_idx; mddi_host_cntl_type *pmhctl; unsigned long time_ms = MDDI_DEFAULT_TIMER_LENGTH; init_timer(&mddi_host_timer); for (host_idx = MDDI_HOST_PRIM; host_idx < MDDI_NUM_HOST_CORES; host_idx++) { pmhctl = &(mhctl[host_idx]); mddi_log_stats_counter += (uint32) time_ms; #ifndef FEATURE_MDDI_DISABLE_REVERSE pmhctl->rtd_counter += (uint32) time_ms; pmhctl->client_status_cnt += (uint32) time_ms; if (host_idx == MDDI_HOST_PRIM) { if (pmhctl->client_status_cnt >= mddi_client_status_frequency) { if ((pmhctl->link_state == MDDI_LINK_HIBERNATING) && (pmhctl->client_status_cnt > mddi_client_status_frequency)) { /* * special case where we are hibernating * and mddi_host_isr is not firing, so * kick the link so that the status can * be retrieved */ /* need to wake up link before issuing * rev encap command */ MDDI_MSG_INFO("wake up link!\n"); spin_lock_irqsave(&mddi_host_spin_lock, flags); mddi_host_enable_hclk(); mddi_host_enable_io_clock(); pmhctl->link_state = MDDI_LINK_ACTIVATING; mddi_host_reg_out(CMD, MDDI_CMD_LINK_ACTIVE); spin_unlock_irqrestore (&mddi_host_spin_lock, flags); } else if ((pmhctl->link_state == MDDI_LINK_ACTIVE) && pmhctl->disable_hibernation) { /* * special case where we have disabled * hibernation and mddi_host_isr * is not firing, so enable interrupt * for no pkts pending, which will * generate an interrupt */ MDDI_MSG_INFO("kick isr!\n"); spin_lock_irqsave(&mddi_host_spin_lock, flags); mddi_host_enable_hclk(); mddi_host_reg_outm(INTEN, MDDI_INT_NO_CMD_PKTS_PEND, MDDI_INT_NO_CMD_PKTS_PEND); spin_unlock_irqrestore (&mddi_host_spin_lock, flags); } } } #endif /* #ifndef FEATURE_MDDI_DISABLE_REVERSE */ } /* Check if logging is turned on */ for (host_idx = MDDI_HOST_PRIM; host_idx < MDDI_NUM_HOST_CORES; host_idx++) { mddi_log_params_struct_type *prev_ptr = &(prev_parms[host_idx]); pmhctl = &(mhctl[host_idx]); if (mddi_debug_log_statistics) { /* get video pkt count from MDP, since MDDI sw cannot know this */ pmhctl->log_parms.vid_cnt = mdp_total_vdopkts; if (mddi_log_stats_counter >= mddi_log_stats_frequency) { /* mddi_log_stats_counter = 0; */ if (mddi_debug_log_statistics) { MDDI_MSG_NOTICE ("MDDI Statistics since last report:\n"); MDDI_MSG_NOTICE(" Packets sent:\n"); MDDI_MSG_NOTICE (" %d RTD packet(s)\n", pmhctl->log_parms.rtd_cnt - prev_ptr->rtd_cnt); if (prev_ptr->rtd_cnt != pmhctl->log_parms.rtd_cnt) { unsigned long flags; spin_lock_irqsave (&mddi_host_spin_lock, flags); mddi_host_enable_hclk(); pmhctl->rtd_value = mddi_host_reg_in(RTD_VAL); spin_unlock_irqrestore (&mddi_host_spin_lock, flags); MDDI_MSG_NOTICE (" RTD value=%d\n", pmhctl->rtd_value); } MDDI_MSG_NOTICE (" %d VIDEO packets\n", pmhctl->log_parms.vid_cnt - prev_ptr->vid_cnt); MDDI_MSG_NOTICE (" %d Register Access packets\n", pmhctl->log_parms.reg_acc_cnt - prev_ptr->reg_acc_cnt); MDDI_MSG_NOTICE (" %d Reverse Encapsulation packet(s)\n", pmhctl->log_parms.rev_enc_cnt - prev_ptr->rev_enc_cnt); if (prev_ptr->rev_enc_cnt != pmhctl->log_parms.rev_enc_cnt) { /* report # of reverse CRC errors */ MDDI_MSG_NOTICE (" %d reverse CRC errors detected\n", pmhctl->log_parms. rev_crc_cnt - prev_ptr->rev_crc_cnt); } MDDI_MSG_NOTICE (" Packets received:\n"); MDDI_MSG_NOTICE (" %d Client Status packets", pmhctl->log_parms.cli_stat_cnt - prev_ptr->cli_stat_cnt); if (prev_ptr->cli_stat_cnt != pmhctl->log_parms.cli_stat_cnt) { MDDI_MSG_NOTICE (" %d forward CRC errors reported\n", pmhctl->log_parms. fwd_crc_cnt - prev_ptr->fwd_crc_cnt); } MDDI_MSG_NOTICE (" %d Register Access Read packets\n", pmhctl->log_parms.reg_read_cnt - prev_ptr->reg_read_cnt); if (pmhctl->link_state == MDDI_LINK_ACTIVE) { MDDI_MSG_NOTICE (" Current Link Status: Active\n"); } else if ((pmhctl->link_state == MDDI_LINK_HIBERNATING) || (pmhctl->link_state == MDDI_LINK_ACTIVATING)) { MDDI_MSG_NOTICE (" Current Link Status: Hibernation\n"); } else { MDDI_MSG_NOTICE (" Current Link Status: Inactive\n"); } MDDI_MSG_NOTICE (" Active state entered %d times\n", pmhctl->log_parms.link_active_cnt - prev_ptr->link_active_cnt); MDDI_MSG_NOTICE (" Hibernation state entered %d times\n", pmhctl->log_parms. link_hibernate_cnt - prev_ptr->link_hibernate_cnt); } } prev_parms[host_idx] = pmhctl->log_parms; } } if (mddi_log_stats_counter >= mddi_log_stats_frequency) mddi_log_stats_counter = 0; mutex_lock(&mddi_timer_lock); if (!mddi_timer_shutdown_flag) { mddi_host_timer.function = mddi_host_timer_service; mddi_host_timer.data = 0; mddi_host_timer.expires = jiffies + ((time_ms * HZ) / 1000); add_timer(&mddi_host_timer); } mutex_unlock(&mddi_timer_lock); return; } /* mddi_host_timer_cb */ static void mddi_process_link_list_done(void) { mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); /* normal forward linked list packet(s) were sent */ if (pmhctl->llist_info.transmitting_start_idx == UNASSIGNED_INDEX) { MDDI_MSG_ERR("**** getting LL done, but no list ****\n"); } else { uint16 idx; #ifndef FEATURE_MDDI_DISABLE_REVERSE if (pmhctl->rev_state == MDDI_REV_REG_READ_ISSUED) { /* special case where a register read packet was sent */ pmhctl->rev_state = MDDI_REV_REG_READ_SENT; if (pmhctl->llist_info.reg_read_idx == UNASSIGNED_INDEX) { MDDI_MSG_ERR ("**** getting LL done, but no list ****\n"); } } #endif for (idx = pmhctl->llist_info.transmitting_start_idx;;) { uint16 next_idx = pmhctl->llist_notify[idx].next_idx; /* with reg read we don't release the waiting tcb until after * the reverse encapsulation has completed. */ if (idx != pmhctl->llist_info.reg_read_idx) { /* notify task that may be waiting on this completion */ if (pmhctl->llist_notify[idx].waiting) { complete(& (pmhctl->llist_notify[idx]. done_comp)); } if (pmhctl->llist_notify[idx].done_cb != NULL) { (*(pmhctl->llist_notify[idx].done_cb)) (); } pmhctl->llist_notify[idx].in_use = FALSE; pmhctl->llist_notify[idx].waiting = FALSE; pmhctl->llist_notify[idx].done_cb = NULL; if (idx < MDDI_NUM_DYNAMIC_LLIST_ITEMS) { /* static LLIST items are configured only once */ pmhctl->llist_notify[idx].next_idx = UNASSIGNED_INDEX; } /* * currently, all linked list packets are * register access, so we can increment the * counter for that packet type here. */ pmhctl->log_parms.reg_acc_cnt++; } if (idx == pmhctl->llist_info.transmitting_end_idx) break; idx = next_idx; if (idx == UNASSIGNED_INDEX) MDDI_MSG_CRIT("MDDI linked list corruption!\n"); } pmhctl->llist_info.transmitting_start_idx = UNASSIGNED_INDEX; pmhctl->llist_info.transmitting_end_idx = UNASSIGNED_INDEX; if (pmhctl->mddi_waiting_for_llist_avail) { if (! (pmhctl-> llist_notify[pmhctl->llist_info.next_free_idx]. in_use)) { pmhctl->mddi_waiting_for_llist_avail = FALSE; complete(&(pmhctl->mddi_llist_avail_comp)); } } } /* Turn off MDDI_INT_PRI_LINK_LIST_DONE interrupt */ mddi_host_reg_outm(INTEN, MDDI_INT_PRI_LINK_LIST_DONE, 0); } static void mddi_queue_forward_linked_list(void) { uint16 first_pkt_index; mddi_linked_list_type *llist_dma; mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); llist_dma = pmhctl->llist_dma_ptr; first_pkt_index = UNASSIGNED_INDEX; if (pmhctl->llist_info.transmitting_start_idx == UNASSIGNED_INDEX) { #ifndef FEATURE_MDDI_DISABLE_REVERSE if (pmhctl->llist_info.reg_read_waiting) { if (pmhctl->rev_state == MDDI_REV_IDLE) { /* * we have a register read to send and * can send it now */ pmhctl->rev_state = MDDI_REV_REG_READ_ISSUED; mddi_reg_read_retry = 0; first_pkt_index = pmhctl->llist_info.waiting_start_idx; pmhctl->llist_info.reg_read_waiting = FALSE; } } else #endif { /* * not register read to worry about, go ahead and write * anything that may be on the waiting list. */ first_pkt_index = pmhctl->llist_info.waiting_start_idx; } } if (first_pkt_index != UNASSIGNED_INDEX) { pmhctl->llist_info.transmitting_start_idx = pmhctl->llist_info.waiting_start_idx; pmhctl->llist_info.transmitting_end_idx = pmhctl->llist_info.waiting_end_idx; pmhctl->llist_info.waiting_start_idx = UNASSIGNED_INDEX; pmhctl->llist_info.waiting_end_idx = UNASSIGNED_INDEX; /* write to the primary pointer register */ MDDI_MSG_DEBUG("MDDI writing primary ptr with idx=%d\n", first_pkt_index); pmhctl->int_type.llist_ptr_write_2++; dma_coherent_pre_ops(); mddi_host_reg_out(PRI_PTR, &llist_dma[first_pkt_index]); /* enable interrupt when complete */ mddi_host_reg_outm(INTEN, MDDI_INT_PRI_LINK_LIST_DONE, MDDI_INT_PRI_LINK_LIST_DONE); } } #ifndef FEATURE_MDDI_DISABLE_REVERSE static void mddi_read_rev_packet(byte *data_ptr) { uint16 i, length; mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); uint8 *rev_ptr_overflow = (pmhctl->rev_ptr_start + MDDI_REV_BUFFER_SIZE); /* first determine the length and handle invalid lengths */ length = *pmhctl->rev_ptr_curr++; if (pmhctl->rev_ptr_curr >= rev_ptr_overflow) pmhctl->rev_ptr_curr = pmhctl->rev_ptr_start; length |= ((*pmhctl->rev_ptr_curr++) << 8); if (pmhctl->rev_ptr_curr >= rev_ptr_overflow) pmhctl->rev_ptr_curr = pmhctl->rev_ptr_start; if (length > (pmhctl->rev_pkt_size - 2)) { MDDI_MSG_ERR("Invalid rev pkt length %d\n", length); /* rev_pkt_size should always be <= rev_ptr_size so limit to packet size */ length = pmhctl->rev_pkt_size - 2; } /* If the data pointer is NULL, just increment the pmhctl->rev_ptr_curr. * Loop around if necessary. Don't bother reading the data. */ if (data_ptr == NULL) { pmhctl->rev_ptr_curr += length; if (pmhctl->rev_ptr_curr >= rev_ptr_overflow) pmhctl->rev_ptr_curr -= MDDI_REV_BUFFER_SIZE; return; } data_ptr[0] = length & 0x0ff; data_ptr[1] = length >> 8; data_ptr += 2; /* copy the data to data_ptr byte-at-a-time */ for (i = 0; (i < length) && (pmhctl->rev_ptr_curr < rev_ptr_overflow); i++) *data_ptr++ = *pmhctl->rev_ptr_curr++; if (pmhctl->rev_ptr_curr >= rev_ptr_overflow) pmhctl->rev_ptr_curr = pmhctl->rev_ptr_start; for (; (i < length) && (pmhctl->rev_ptr_curr < rev_ptr_overflow); i++) *data_ptr++ = *pmhctl->rev_ptr_curr++; } static void mddi_process_rev_packets(void) { uint32 rev_packet_count; word i; uint32 crc_errors; boolean mddi_reg_read_successful = FALSE; mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); pmhctl->log_parms.rev_enc_cnt++; if ((pmhctl->rev_state != MDDI_REV_ENCAP_ISSUED) && (pmhctl->rev_state != MDDI_REV_STATUS_REQ_ISSUED) && (pmhctl->rev_state != MDDI_REV_CLIENT_CAP_ISSUED)) { MDDI_MSG_ERR("Wrong state %d for reverse int\n", pmhctl->rev_state); } /* Turn off MDDI_INT_REV_AVAIL interrupt */ mddi_host_reg_outm(INTEN, MDDI_INT_REV_DATA_AVAIL, 0); /* Clear rev data avail int */ mddi_host_reg_out(INT, MDDI_INT_REV_DATA_AVAIL); /* Get Number of packets */ rev_packet_count = mddi_host_reg_in(REV_PKT_CNT); #ifndef T_MSM7500 /* Clear out rev packet counter */ mddi_host_reg_out(REV_PKT_CNT, 0x0000); #endif #if defined(CONFIG_FB_MSM_MDP31) || defined(CONFIG_FB_MSM_MDP40) if ((pmhctl->rev_state == MDDI_REV_CLIENT_CAP_ISSUED) && (rev_packet_count > 0) && (mddi_host_core_version == 0x28 || mddi_host_core_version == 0x30)) { uint32 int_reg; uint32 max_count = 0; mddi_host_reg_out(REV_PTR, pmhctl->mddi_rev_ptr_write_val); int_reg = mddi_host_reg_in(INT); while ((int_reg & 0x100000) == 0) { udelay(3); int_reg = mddi_host_reg_in(INT); if (++max_count > 100) break; } } #endif /* Get CRC error count */ crc_errors = mddi_host_reg_in(REV_CRC_ERR); if (crc_errors != 0) { pmhctl->log_parms.rev_crc_cnt += crc_errors; pmhctl->stats.rev_crc_count += crc_errors; MDDI_MSG_ERR("!!! MDDI %d Reverse CRC Error(s) !!!\n", crc_errors); #ifndef T_MSM7500 /* Clear CRC error count */ mddi_host_reg_out(REV_CRC_ERR, 0x0000); #endif /* also issue an RTD to attempt recovery */ pmhctl->rtd_counter = mddi_rtd_frequency; } pmhctl->rtd_value = mddi_host_reg_in(RTD_VAL); MDDI_MSG_DEBUG("MDDI rev pkt cnt=%d, ptr=0x%x, RTD:0x%x\n", rev_packet_count, pmhctl->rev_ptr_curr - pmhctl->rev_ptr_start, pmhctl->rtd_value); if (rev_packet_count >= 1) { mddi_invalidate_cache_lines((uint32 *) pmhctl->rev_ptr_start, MDDI_REV_BUFFER_SIZE); } else { MDDI_MSG_ERR("Reverse pkt sent, no data rxd\n"); if (mddi_reg_read_value_ptr) *mddi_reg_read_value_ptr = -EBUSY; } /* order the reads */ dma_coherent_post_ops(); for (i = 0; i < rev_packet_count; i++) { mddi_rev_packet_type *rev_pkt_ptr; mddi_read_rev_packet(rev_packet_data); rev_pkt_ptr = (mddi_rev_packet_type *) rev_packet_data; if (rev_pkt_ptr->packet_length > pmhctl->rev_pkt_size) { MDDI_MSG_ERR("!!!invalid packet size: %d\n", rev_pkt_ptr->packet_length); } MDDI_MSG_DEBUG("MDDI rev pkt 0x%x size 0x%x\n", rev_pkt_ptr->packet_type, rev_pkt_ptr->packet_length); /* Do whatever you want to do with the data based on the packet type */ switch (rev_pkt_ptr->packet_type) { case 66: /* Client Capability */ { mddi_client_capability_type *client_capability_pkt_ptr; client_capability_pkt_ptr = (mddi_client_capability_type *) rev_packet_data; MDDI_MSG_NOTICE ("Client Capability: Week=%d, Year=%d\n", client_capability_pkt_ptr-> Week_of_Manufacture, client_capability_pkt_ptr-> Year_of_Manufacture); memcpy((void *)&mddi_client_capability_pkt, (void *)rev_packet_data, sizeof(mddi_client_capability_type)); pmhctl->log_parms.cli_cap_cnt++; } break; case 70: /* Display Status */ { mddi_client_status_type *client_status_pkt_ptr; client_status_pkt_ptr = (mddi_client_status_type *) rev_packet_data; if ((client_status_pkt_ptr->crc_error_count != 0) || (client_status_pkt_ptr-> reverse_link_request != 0)) { MDDI_MSG_ERR ("Client Status: RevReq=%d, CrcErr=%d\n", client_status_pkt_ptr-> reverse_link_request, client_status_pkt_ptr-> crc_error_count); } else { MDDI_MSG_DEBUG ("Client Status: RevReq=%d, CrcErr=%d\n", client_status_pkt_ptr-> reverse_link_request, client_status_pkt_ptr-> crc_error_count); } pmhctl->log_parms.fwd_crc_cnt += client_status_pkt_ptr->crc_error_count; pmhctl->stats.fwd_crc_count += client_status_pkt_ptr->crc_error_count; pmhctl->log_parms.cli_stat_cnt++; } break; case 146: /* register access packet */ { mddi_register_access_packet_type * regacc_pkt_ptr; uint32 data_count; regacc_pkt_ptr = (mddi_register_access_packet_type *) rev_packet_data; /* Bits[0:13] - read data count */ data_count = regacc_pkt_ptr->read_write_info & 0x3FFF; MDDI_MSG_DEBUG("\n MDDI rev read: 0x%x", regacc_pkt_ptr->read_write_info); MDDI_MSG_DEBUG("Reg Acc parse reg=0x%x," "value=0x%x\n", regacc_pkt_ptr-> register_address, regacc_pkt_ptr-> register_data_list[0]); /* Copy register value to location passed in */ if (mddi_reg_read_value_ptr) { #if defined(T_MSM6280) && !defined(T_MSM7200) /* only least significant 16 bits are valid with 6280 */ *mddi_reg_read_value_ptr = regacc_pkt_ptr-> register_data_list[0] & 0x0000ffff; mddi_reg_read_successful = TRUE; mddi_reg_read_value_ptr = NULL; #else if (data_count && data_count <= MDDI_HOST_MAX_CLIENT_REG_IN_SAME_ADDR) { memcpy(mddi_reg_read_value_ptr, (void *)&regacc_pkt_ptr-> register_data_list[0], data_count * 4); mddi_reg_read_successful = TRUE; mddi_reg_read_value_ptr = NULL; } #endif } #ifdef DEBUG_MDDIHOSTI if ((mddi_gpio.polling_enabled) && (regacc_pkt_ptr->register_address == mddi_gpio.polling_reg)) { /* * ToDo: need to call Linux GPIO call * here... */ mddi_client_lcd_gpio_poll( regacc_pkt_ptr->register_data_list[0]); } #endif pmhctl->log_parms.reg_read_cnt++; } break; case INVALID_PKT_TYPE: /* 0xFFFF */ MDDI_MSG_ERR("!!!INVALID_PKT_TYPE rcvd\n"); break; default: /* any other packet */ { uint16 hdlr; for (hdlr = 0; hdlr < MAX_MDDI_REV_HANDLERS; hdlr++) { if (mddi_rev_pkt_handler[hdlr]. handler == NULL) continue; if (mddi_rev_pkt_handler[hdlr]. pkt_type == rev_pkt_ptr->packet_type) { (*(mddi_rev_pkt_handler[hdlr]. handler)) (rev_pkt_ptr); /* pmhctl->rev_state = MDDI_REV_IDLE; */ break; } } if (hdlr >= MAX_MDDI_REV_HANDLERS) MDDI_MSG_ERR("MDDI unknown rev pkt\n"); } break; } } if ((pmhctl->rev_ptr_curr + pmhctl->rev_pkt_size) >= (pmhctl->rev_ptr_start + MDDI_REV_BUFFER_SIZE)) { pmhctl->rev_ptr_written = FALSE; } if (pmhctl->rev_state == MDDI_REV_ENCAP_ISSUED) { pmhctl->rev_state = MDDI_REV_IDLE; if (mddi_rev_user.waiting) { mddi_rev_user.waiting = FALSE; complete(&(mddi_rev_user.done_comp)); } else if (pmhctl->llist_info.reg_read_idx == UNASSIGNED_INDEX) { MDDI_MSG_ERR ("Reverse Encap state, but no reg read in progress\n"); } else { if ((!mddi_reg_read_successful) && (mddi_reg_read_retry < mddi_reg_read_retry_max) && (mddi_enable_reg_read_retry)) { /* * There is a race condition that can happen * where the reverse encapsulation message is * sent out by the MDDI host before the register * read packet is sent. As a work-around for * that problem we issue the reverse * encapsulation one more time before giving up. */ if (mddi_enable_reg_read_retry_once) mddi_reg_read_retry = mddi_reg_read_retry_max; else mddi_reg_read_retry++; pmhctl->rev_state = MDDI_REV_REG_READ_SENT; pmhctl->stats.reg_read_failure++; } else { uint16 reg_read_idx = pmhctl->llist_info.reg_read_idx; mddi_reg_read_retry = 0; if (pmhctl->llist_notify[reg_read_idx].waiting) { complete(& (pmhctl-> llist_notify[reg_read_idx]. done_comp)); } pmhctl->llist_info.reg_read_idx = UNASSIGNED_INDEX; if (pmhctl->llist_notify[reg_read_idx]. done_cb != NULL) { (* (pmhctl->llist_notify[reg_read_idx]. done_cb)) (); } pmhctl->llist_notify[reg_read_idx].next_idx = UNASSIGNED_INDEX; pmhctl->llist_notify[reg_read_idx].in_use = FALSE; pmhctl->llist_notify[reg_read_idx].waiting = FALSE; pmhctl->llist_notify[reg_read_idx].done_cb = NULL; if (!mddi_reg_read_successful) pmhctl->stats.reg_read_failure++; } } } else if (pmhctl->rev_state == MDDI_REV_CLIENT_CAP_ISSUED) { #if defined(CONFIG_FB_MSM_MDP31) || defined(CONFIG_FB_MSM_MDP40) if (mddi_host_core_version == 0x28 || mddi_host_core_version == 0x30) { mddi_host_reg_out(FIFO_ALLOC, 0x00); pmhctl->rev_ptr_written = TRUE; mddi_host_reg_out(REV_PTR, pmhctl->mddi_rev_ptr_write_val); pmhctl->rev_ptr_curr = pmhctl->rev_ptr_start; mddi_host_reg_out(CMD, 0xC00); } #endif if (mddi_rev_user.waiting) { mddi_rev_user.waiting = FALSE; complete(&(mddi_rev_user.done_comp)); } pmhctl->rev_state = MDDI_REV_IDLE; } else { pmhctl->rev_state = MDDI_REV_IDLE; } /* pmhctl->rev_state = MDDI_REV_IDLE; */ /* Re-enable interrupt */ mddi_host_reg_outm(INTEN, MDDI_INT_REV_DATA_AVAIL, MDDI_INT_REV_DATA_AVAIL); } static void mddi_issue_reverse_encapsulation(void) { mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); /* Only issue a reverse encapsulation packet if: * 1) another reverse is not in progress (MDDI_REV_IDLE). * 2) a register read has been sent (MDDI_REV_REG_READ_SENT). * 3) forward is not in progress, because of a hw bug in client that * causes forward crc errors on packet immediately after rev encap. */ if (((pmhctl->rev_state == MDDI_REV_IDLE) || (pmhctl->rev_state == MDDI_REV_REG_READ_SENT)) && (pmhctl->llist_info.transmitting_start_idx == UNASSIGNED_INDEX) && (!mdp_in_processing)) { uint32 mddi_command = MDDI_CMD_SEND_REV_ENCAP; if ((pmhctl->rev_state == MDDI_REV_REG_READ_SENT) || (mddi_rev_encap_user_request == TRUE)) { mddi_host_enable_io_clock(); if (pmhctl->link_state == MDDI_LINK_HIBERNATING) { /* need to wake up link before issuing rev encap command */ MDDI_MSG_DEBUG("wake up link!\n"); pmhctl->link_state = MDDI_LINK_ACTIVATING; mddi_host_reg_out(CMD, MDDI_CMD_LINK_ACTIVE); } else { if (pmhctl->rtd_counter >= mddi_rtd_frequency) { MDDI_MSG_DEBUG ("mddi sending RTD command!\n"); mddi_host_reg_out(CMD, MDDI_CMD_SEND_RTD); pmhctl->rtd_counter = 0; pmhctl->log_parms.rtd_cnt++; } if (pmhctl->rev_state != MDDI_REV_REG_READ_SENT) { /* this is generic reverse request by user, so * reset the waiting flag. */ mddi_rev_encap_user_request = FALSE; } /* link is active so send reverse encap to get register read results */ pmhctl->rev_state = MDDI_REV_ENCAP_ISSUED; mddi_command = MDDI_CMD_SEND_REV_ENCAP; MDDI_MSG_DEBUG("sending rev encap!\n"); } } else if ((pmhctl->client_status_cnt >= mddi_client_status_frequency) || mddi_client_capability_request) { mddi_host_enable_io_clock(); if (pmhctl->link_state == MDDI_LINK_HIBERNATING) { /* only wake up the link if it client status is overdue */ if ((pmhctl->client_status_cnt >= (mddi_client_status_frequency * 2)) || mddi_client_capability_request) { /* need to wake up link before issuing rev encap command */ MDDI_MSG_DEBUG("wake up link!\n"); pmhctl->link_state = MDDI_LINK_ACTIVATING; mddi_host_reg_out(CMD, MDDI_CMD_LINK_ACTIVE); } } else { if (pmhctl->rtd_counter >= mddi_rtd_frequency) { MDDI_MSG_DEBUG ("mddi sending RTD command!\n"); mddi_host_reg_out(CMD, MDDI_CMD_SEND_RTD); pmhctl->rtd_counter = 0; pmhctl->log_parms.rtd_cnt++; } /* periodically get client status */ MDDI_MSG_DEBUG ("mddi sending rev enc! (get status)\n"); if (mddi_client_capability_request) { pmhctl->rev_state = MDDI_REV_CLIENT_CAP_ISSUED; mddi_command = MDDI_CMD_GET_CLIENT_CAP; mddi_client_capability_request = FALSE; } else { pmhctl->rev_state = MDDI_REV_STATUS_REQ_ISSUED; pmhctl->client_status_cnt = 0; mddi_command = MDDI_CMD_GET_CLIENT_STATUS; } } } if ((pmhctl->rev_state == MDDI_REV_ENCAP_ISSUED) || (pmhctl->rev_state == MDDI_REV_STATUS_REQ_ISSUED) || (pmhctl->rev_state == MDDI_REV_CLIENT_CAP_ISSUED)) { pmhctl->int_type.rev_encap_count++; #if defined(T_MSM6280) && !defined(T_MSM7200) mddi_rev_pointer_written = TRUE; mddi_host_reg_out(REV_PTR, mddi_rev_ptr_write_val); mddi_rev_ptr_curr = mddi_rev_ptr_start; /* force new rev ptr command */ mddi_host_reg_out(CMD, 0xC00); #else if (!pmhctl->rev_ptr_written) { MDDI_MSG_DEBUG("writing reverse pointer!\n"); pmhctl->rev_ptr_written = TRUE; #if defined(CONFIG_FB_MSM_MDP31) || defined(CONFIG_FB_MSM_MDP40) if ((pmhctl->rev_state == MDDI_REV_CLIENT_CAP_ISSUED) && (mddi_host_core_version == 0x28 || mddi_host_core_version == 0x30)) { pmhctl->rev_ptr_written = FALSE; mddi_host_reg_out(FIFO_ALLOC, 0x02); } else mddi_host_reg_out(REV_PTR, pmhctl-> mddi_rev_ptr_write_val); #else mddi_host_reg_out(REV_PTR, pmhctl-> mddi_rev_ptr_write_val); #endif } #endif if (mddi_debug_clear_rev_data) { uint16 i; for (i = 0; i < MDDI_MAX_REV_DATA_SIZE / 4; i++) pmhctl->rev_data_buf[i] = 0xdddddddd; /* clean cache */ mddi_flush_cache_lines(pmhctl->rev_data_buf, MDDI_MAX_REV_DATA_SIZE); } /* send reverse encapsulation to get needed data */ mddi_host_reg_out(CMD, mddi_command); } } } static void mddi_process_client_initiated_wakeup(void) { mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); /* Disable MDDI_INT Interrupt, we detect client initiated wakeup one * time for each entry into hibernation */ mddi_host_reg_outm(INTEN, MDDI_INT_MDDI_IN, 0); if (host_idx == MDDI_HOST_PRIM) { if (mddi_vsync_detect_enabled) { mddi_host_enable_io_clock(); #ifndef MDDI_HOST_DISP_LISTEN /* issue command to bring up link */ /* need to do this to clear the vsync condition */ if (pmhctl->link_state == MDDI_LINK_HIBERNATING) { pmhctl->link_state = MDDI_LINK_ACTIVATING; mddi_host_reg_out(CMD, MDDI_CMD_LINK_ACTIVE); } #endif /* * Indicate to client specific code that vsync was * enabled, and we did not detect a client initiated * wakeup. The client specific handler can clear the * condition if necessary to prevent subsequent * client initiated wakeups. */ mddi_client_lcd_vsync_detected(TRUE); pmhctl->log_parms.vsync_response_cnt++; MDDI_MSG_NOTICE("MDDI_INT_IN condition\n"); } } if (mddi_gpio.polling_enabled) { mddi_host_enable_io_clock(); /* check interrupt status now */ (void)mddi_queue_register_read_int(mddi_gpio.polling_reg, &mddi_gpio.polling_val); } } #endif /* FEATURE_MDDI_DISABLE_REVERSE */ static void mddi_host_isr(void) { uint32 int_reg, int_en; #ifndef FEATURE_MDDI_DISABLE_REVERSE uint32 status_reg; #endif mddi_host_type host_idx = mddi_curr_host; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); if (!MDDI_HOST_IS_HCLK_ON) { MDDI_HOST_ENABLE_HCLK; } int_reg = mddi_host_reg_in(INT); int_en = mddi_host_reg_in(INTEN); pmhctl->saved_int_reg = int_reg; pmhctl->saved_int_en = int_en; int_reg = int_reg & int_en; pmhctl->int_type.count++; #ifndef FEATURE_MDDI_DISABLE_REVERSE status_reg = mddi_host_reg_in(STAT); if ((int_reg & MDDI_INT_MDDI_IN) || ((int_en & MDDI_INT_MDDI_IN) && ((int_reg == 0) || (status_reg & MDDI_STAT_CLIENT_WAKEUP_REQ)))) { /* * The MDDI_IN condition will clear itself, and so it is * possible that MDDI_IN was the reason for the isr firing, * even though the interrupt register does not have the * MDDI_IN bit set. To check if this was the case we need to * look at the status register bit that signifies a client * initiated wakeup. If the status register bit is set, as well * as the MDDI_IN interrupt enabled, then we treat this as a * client initiated wakeup. */ if (int_reg & MDDI_INT_MDDI_IN) pmhctl->int_type.in_count++; mddi_process_client_initiated_wakeup(); } #endif if (int_reg & MDDI_INT_LINK_STATE_CHANGES) { pmhctl->int_type.state_change_count++; mddi_report_state_change(int_reg); } if (int_reg & MDDI_INT_PRI_LINK_LIST_DONE) { pmhctl->int_type.ll_done_count++; mddi_process_link_list_done(); } #ifndef FEATURE_MDDI_DISABLE_REVERSE if (int_reg & MDDI_INT_REV_DATA_AVAIL) { pmhctl->int_type.rev_avail_count++; mddi_process_rev_packets(); } #endif if (int_reg & MDDI_INT_ERROR_CONDITIONS) { pmhctl->int_type.error_count++; mddi_report_errors(int_reg); mddi_host_reg_out(INT, int_reg & MDDI_INT_ERROR_CONDITIONS); } #ifndef FEATURE_MDDI_DISABLE_REVERSE mddi_issue_reverse_encapsulation(); if ((pmhctl->rev_state != MDDI_REV_ENCAP_ISSUED) && (pmhctl->rev_state != MDDI_REV_STATUS_REQ_ISSUED)) #endif /* don't want simultaneous reverse and forward with Eagle */ mddi_queue_forward_linked_list(); if (int_reg & MDDI_INT_NO_CMD_PKTS_PEND) { /* this interrupt is used to kick the isr when hibernation is disabled */ mddi_host_reg_outm(INTEN, MDDI_INT_NO_CMD_PKTS_PEND, 0); } if ((!mddi_host_mdp_active_flag) && (!mddi_vsync_detect_enabled) && (pmhctl->llist_info.transmitting_start_idx == UNASSIGNED_INDEX) && (pmhctl->llist_info.waiting_start_idx == UNASSIGNED_INDEX) && (pmhctl->rev_state == MDDI_REV_IDLE)) { if (pmhctl->link_state == MDDI_LINK_HIBERNATING) { mddi_host_disable_io_clock(); mddi_host_disable_hclk(); } #ifdef FEATURE_MDDI_HOST_ENABLE_EARLY_HIBERNATION else if ((pmhctl->link_state == MDDI_LINK_ACTIVE) && (!pmhctl->disable_hibernation)) { mddi_host_reg_out(CMD, MDDI_CMD_POWERDOWN); } #endif } } static void mddi_host_isr_primary(void) { mddi_curr_host = MDDI_HOST_PRIM; mddi_host_isr(); } irqreturn_t mddi_pmdh_isr_proxy(int irq, void *ptr) { mddi_host_isr_primary(); return IRQ_HANDLED; } static void mddi_host_isr_external(void) { mddi_curr_host = MDDI_HOST_EXT; mddi_host_isr(); mddi_curr_host = MDDI_HOST_PRIM; } irqreturn_t mddi_emdh_isr_proxy(int irq, void *ptr) { mddi_host_isr_external(); return IRQ_HANDLED; } static void mddi_host_initialize_registers(mddi_host_type host_idx) { uint32 pad_reg_val; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); if (pmhctl->driver_state == MDDI_DRIVER_ENABLED) return; /* turn on HCLK to MDDI host core */ mddi_host_enable_hclk(); /* MDDI Reset command */ mddi_host_reg_out(CMD, MDDI_CMD_RESET); /* Version register (= 0x01) */ mddi_host_reg_out(VERSION, 0x0001); /* Bytes per subframe register */ mddi_host_reg_out(BPS, MDDI_HOST_BYTES_PER_SUBFRAME); /* Subframes per media frames register (= 0x03) */ mddi_host_reg_out(SPM, 0x0003); /* Turn Around 1 register (= 0x05) */ mddi_host_reg_out(TA1_LEN, 0x0005); /* Turn Around 2 register (= 0x0C) */ mddi_host_reg_out(TA2_LEN, MDDI_HOST_TA2_LEN); /* Drive hi register (= 0x96) */ mddi_host_reg_out(DRIVE_HI, 0x0096); /* Drive lo register (= 0x32) */ mddi_host_reg_out(DRIVE_LO, 0x0032); /* Display wakeup count register (= 0x3c) */ mddi_host_reg_out(DISP_WAKE, 0x003c); /* Reverse Rate Divisor register (= 0x2) */ mddi_host_reg_out(REV_RATE_DIV, MDDI_HOST_REV_RATE_DIV); #ifndef FEATURE_MDDI_DISABLE_REVERSE /* Reverse Pointer Size */ mddi_host_reg_out(REV_SIZE, MDDI_REV_BUFFER_SIZE); /* Rev Encap Size */ mddi_host_reg_out(REV_ENCAP_SZ, pmhctl->rev_pkt_size); #endif /* Periodic Rev Encap */ /* don't send periodically */ mddi_host_reg_out(CMD, MDDI_CMD_PERIODIC_REV_ENCAP); pad_reg_val = mddi_host_reg_in(PAD_CTL); if (pad_reg_val == 0) { /* If we are turning on band gap, need to wait 5us before turning * on the rest of the PAD */ mddi_host_reg_out(PAD_CTL, 0x08000); udelay(5); } #ifdef T_MSM7200 /* Recommendation from PAD hw team */ mddi_host_reg_out(PAD_CTL, 0xa850a); #else /* Recommendation from PAD hw team */ mddi_host_reg_out(PAD_CTL, 0xa850f); #endif pad_reg_val = 0x00220020; #if defined(CONFIG_FB_MSM_MDP31) || defined(CONFIG_FB_MSM_MDP40) mddi_host_reg_out(PAD_IO_CTL, 0x00320000); mddi_host_reg_out(PAD_CAL, pad_reg_val); #endif mddi_host_core_version = mddi_host_reg_inm(CORE_VER, 0xffff); #ifndef FEATURE_MDDI_DISABLE_REVERSE if (mddi_host_core_version >= 8) mddi_rev_ptr_workaround = FALSE; pmhctl->rev_ptr_curr = pmhctl->rev_ptr_start; #endif if ((mddi_host_core_version > 8) && (mddi_host_core_version < 0x19)) mddi_host_reg_out(TEST, 0x2); /* Need an even number for counts */ mddi_host_reg_out(DRIVER_START_CNT, 0x60006); #ifndef T_MSM7500 /* Setup defaults for MDP related register */ mddi_host_reg_out(MDP_VID_FMT_DES, 0x5666); mddi_host_reg_out(MDP_VID_PIX_ATTR, 0x00C3); mddi_host_reg_out(MDP_VID_CLIENTID, 0); #endif /* automatically hibernate after 1 empty subframe */ if (pmhctl->disable_hibernation) mddi_host_reg_out(CMD, MDDI_CMD_HIBERNATE); else mddi_host_reg_out(CMD, MDDI_CMD_HIBERNATE | 1); /* Bring up link if display (client) requests it */ #ifdef MDDI_HOST_DISP_LISTEN mddi_host_reg_out(CMD, MDDI_CMD_DISP_LISTEN); #else mddi_host_reg_out(CMD, MDDI_CMD_DISP_IGNORE); #endif } void mddi_host_configure_interrupts(mddi_host_type host_idx, boolean enable) { unsigned long flags; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); spin_lock_irqsave(&mddi_host_spin_lock, flags); /* turn on HCLK to MDDI host core if it has been disabled */ mddi_host_enable_hclk(); /* Clear MDDI Interrupt enable reg */ mddi_host_reg_out(INTEN, 0); spin_unlock_irqrestore(&mddi_host_spin_lock, flags); if (enable) { pmhctl->driver_state = MDDI_DRIVER_ENABLED; if (host_idx == MDDI_HOST_PRIM) { if (request_irq (INT_MDDI_PRI, mddi_pmdh_isr_proxy, IRQF_DISABLED, "PMDH", 0) != 0) printk(KERN_ERR "a mddi: unable to request_irq\n"); else { int_mddi_pri_flag = TRUE; irq_enabled = 1; } } else { if (request_irq (INT_MDDI_EXT, mddi_emdh_isr_proxy, IRQF_DISABLED, "EMDH", 0) != 0) printk(KERN_ERR "b mddi: unable to request_irq\n"); else int_mddi_ext_flag = TRUE; } /* Set MDDI Interrupt enable reg -- Enable Reverse data avail */ #ifdef FEATURE_MDDI_DISABLE_REVERSE mddi_host_reg_out(INTEN, MDDI_INT_ERROR_CONDITIONS | MDDI_INT_LINK_STATE_CHANGES); #else /* Reverse Pointer register */ pmhctl->rev_ptr_written = FALSE; mddi_host_reg_out(INTEN, MDDI_INT_REV_DATA_AVAIL | MDDI_INT_ERROR_CONDITIONS | MDDI_INT_LINK_STATE_CHANGES); pmhctl->rtd_counter = mddi_rtd_frequency; pmhctl->client_status_cnt = 0; #endif } else { if (pmhctl->driver_state == MDDI_DRIVER_ENABLED) pmhctl->driver_state = MDDI_DRIVER_DISABLED; } } /* * mddi_host_client_cnt_reset: * reset client_status_cnt to 0 to make sure host does not * send RTD cmd to client right after resume before mddi * client be powered up. this fix "MDDI RTD Failure" problem */ void mddi_host_client_cnt_reset(void) { unsigned long flags; mddi_host_cntl_type *pmhctl; pmhctl = &(mhctl[MDDI_HOST_PRIM]); spin_lock_irqsave(&mddi_host_spin_lock, flags); pmhctl->client_status_cnt = 0; spin_unlock_irqrestore(&mddi_host_spin_lock, flags); } static void mddi_host_powerup(mddi_host_type host_idx) { mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); if (pmhctl->link_state != MDDI_LINK_DISABLED) return; /* enable IO_CLK and hclk to MDDI host core */ mddi_host_enable_io_clock(); mddi_host_initialize_registers(host_idx); mddi_host_configure_interrupts(host_idx, TRUE); pmhctl->link_state = MDDI_LINK_ACTIVATING; /* Link activate command */ mddi_host_reg_out(CMD, MDDI_CMD_LINK_ACTIVE); #ifdef CLKRGM_MDDI_IO_CLOCK_IN_MHZ MDDI_MSG_NOTICE("MDDI Host: Activating Link %d Mbps\n", CLKRGM_MDDI_IO_CLOCK_IN_MHZ * 2); #else MDDI_MSG_NOTICE("MDDI Host: Activating Link\n"); #endif /* Initialize the timer */ if (host_idx == MDDI_HOST_PRIM) mddi_host_timer_service(0); } void mddi_send_fw_link_skew_cal(mddi_host_type host_idx) { mddi_host_reg_out(CMD, MDDI_CMD_FW_LINK_SKEW_CAL); MDDI_MSG_DEBUG("%s: Skew Calibration done!!\n", __func__); } void mddi_host_init(mddi_host_type host_idx) /* Write out the MDDI configuration registers */ { static boolean initialized = FALSE; mddi_host_cntl_type *pmhctl; if (host_idx >= MDDI_NUM_HOST_CORES) { MDDI_MSG_ERR("Invalid host core index\n"); return; } if (!initialized) { uint16 idx; mddi_host_type host; for (host = MDDI_HOST_PRIM; host < MDDI_NUM_HOST_CORES; host++) { pmhctl = &(mhctl[host]); initialized = TRUE; pmhctl->llist_ptr = dma_alloc_coherent(NULL, MDDI_LLIST_POOL_SIZE, &(pmhctl->llist_dma_addr), GFP_KERNEL); pmhctl->llist_dma_ptr = (mddi_linked_list_type *) (void *)pmhctl-> llist_dma_addr; #ifdef FEATURE_MDDI_DISABLE_REVERSE pmhctl->rev_data_buf = NULL; if (pmhctl->llist_ptr == NULL) #else mddi_rev_user.waiting = FALSE; init_completion(&(mddi_rev_user.done_comp)); pmhctl->rev_data_buf = dma_alloc_coherent(NULL, MDDI_MAX_REV_DATA_SIZE, &(pmhctl->rev_data_dma_addr), GFP_KERNEL); if ((pmhctl->llist_ptr == NULL) || (pmhctl->rev_data_buf == NULL)) #endif { MDDI_MSG_CRIT ("unable to alloc non-cached memory\n"); } llist_extern[host] = pmhctl->llist_ptr; llist_dma_extern[host] = pmhctl->llist_dma_ptr; llist_extern_notify[host] = pmhctl->llist_notify; for (idx = 0; idx < UNASSIGNED_INDEX; idx++) { init_completion(& (pmhctl->llist_notify[idx]. done_comp)); } init_completion(&(pmhctl->mddi_llist_avail_comp)); spin_lock_init(&mddi_host_spin_lock); pmhctl->mddi_waiting_for_llist_avail = FALSE; pmhctl->mddi_rev_ptr_write_val = (uint32) (void *)(pmhctl->rev_data_dma_addr); pmhctl->rev_ptr_start = (void *)pmhctl->rev_data_buf; pmhctl->rev_pkt_size = MDDI_DEFAULT_REV_PKT_SIZE; pmhctl->rev_state = MDDI_REV_IDLE; #ifdef IMAGE_MODEM_PROC /* assume hibernation state is last state from APPS proc, so that * we don't reinitialize the host core */ pmhctl->link_state = MDDI_LINK_HIBERNATING; #else pmhctl->link_state = MDDI_LINK_DISABLED; #endif pmhctl->driver_state = MDDI_DRIVER_DISABLED; pmhctl->disable_hibernation = FALSE; /* initialize llist variables */ pmhctl->llist_info.transmitting_start_idx = UNASSIGNED_INDEX; pmhctl->llist_info.transmitting_end_idx = UNASSIGNED_INDEX; pmhctl->llist_info.waiting_start_idx = UNASSIGNED_INDEX; pmhctl->llist_info.waiting_end_idx = UNASSIGNED_INDEX; pmhctl->llist_info.reg_read_idx = UNASSIGNED_INDEX; pmhctl->llist_info.next_free_idx = MDDI_FIRST_DYNAMIC_LLIST_IDX; pmhctl->llist_info.reg_read_waiting = FALSE; mddi_vsync_detect_enabled = FALSE; mddi_gpio.polling_enabled = FALSE; pmhctl->int_type.count = 0; pmhctl->int_type.in_count = 0; pmhctl->int_type.disp_req_count = 0; pmhctl->int_type.state_change_count = 0; pmhctl->int_type.ll_done_count = 0; pmhctl->int_type.rev_avail_count = 0; pmhctl->int_type.error_count = 0; pmhctl->int_type.rev_encap_count = 0; pmhctl->int_type.llist_ptr_write_1 = 0; pmhctl->int_type.llist_ptr_write_2 = 0; pmhctl->stats.fwd_crc_count = 0; pmhctl->stats.rev_crc_count = 0; pmhctl->stats.pri_underflow = 0; pmhctl->stats.sec_underflow = 0; pmhctl->stats.rev_overflow = 0; pmhctl->stats.pri_overwrite = 0; pmhctl->stats.sec_overwrite = 0; pmhctl->stats.rev_overwrite = 0; pmhctl->stats.dma_failure = 0; pmhctl->stats.rtd_failure = 0; pmhctl->stats.reg_read_failure = 0; #ifdef FEATURE_MDDI_UNDERRUN_RECOVERY pmhctl->stats.pri_underrun_detected = 0; #endif pmhctl->log_parms.rtd_cnt = 0; pmhctl->log_parms.rev_enc_cnt = 0; pmhctl->log_parms.vid_cnt = 0; pmhctl->log_parms.reg_acc_cnt = 0; pmhctl->log_parms.cli_stat_cnt = 0; pmhctl->log_parms.cli_cap_cnt = 0; pmhctl->log_parms.reg_read_cnt = 0; pmhctl->log_parms.link_active_cnt = 0; pmhctl->log_parms.link_hibernate_cnt = 0; pmhctl->log_parms.fwd_crc_cnt = 0; pmhctl->log_parms.rev_crc_cnt = 0; pmhctl->log_parms.vsync_response_cnt = 0; prev_parms[host_idx] = pmhctl->log_parms; mddi_client_capability_pkt.packet_length = 0; } #ifndef T_MSM7500 /* tell clock driver we are user of this PLL */ MDDI_HOST_ENABLE_IO_CLOCK; #endif } mddi_host_powerup(host_idx); pmhctl = &(mhctl[host_idx]); } #ifdef CONFIG_FB_MSM_MDDI_AUTO_DETECT static uint32 mddi_client_id; uint32 mddi_get_client_id(void) { #ifndef FEATURE_MDDI_DISABLE_REVERSE mddi_host_type host_idx = MDDI_HOST_PRIM; static boolean client_detection_try = FALSE; mddi_host_cntl_type *pmhctl; unsigned long flags; uint16 saved_rev_pkt_size; int ret; if (!client_detection_try) { /* Toshiba display requires larger drive_lo value */ mddi_host_reg_out(DRIVE_LO, 0x0050); pmhctl = &(mhctl[MDDI_HOST_PRIM]); saved_rev_pkt_size = pmhctl->rev_pkt_size; /* Increase Rev Encap Size */ pmhctl->rev_pkt_size = MDDI_CLIENT_CAPABILITY_REV_PKT_SIZE; mddi_host_reg_out(REV_ENCAP_SZ, pmhctl->rev_pkt_size); /* disable hibernation temporarily */ if (!pmhctl->disable_hibernation) mddi_host_reg_out(CMD, MDDI_CMD_HIBERNATE); mddi_rev_user.waiting = TRUE; INIT_COMPLETION(mddi_rev_user.done_comp); spin_lock_irqsave(&mddi_host_spin_lock, flags); /* turn on clock(s), if they have been disabled */ mddi_host_enable_hclk(); mddi_host_enable_io_clock(); mddi_client_capability_request = TRUE; if (pmhctl->rev_state == MDDI_REV_IDLE) { /* attempt to send the reverse encapsulation now */ mddi_issue_reverse_encapsulation(); } spin_unlock_irqrestore(&mddi_host_spin_lock, flags); wait_for_completion_killable(&(mddi_rev_user.done_comp)); /* Set Rev Encap Size back to its original value */ pmhctl->rev_pkt_size = saved_rev_pkt_size; mddi_host_reg_out(REV_ENCAP_SZ, pmhctl->rev_pkt_size); /* reenable auto-hibernate */ if (!pmhctl->disable_hibernation) mddi_host_reg_out(CMD, MDDI_CMD_HIBERNATE | 1); mddi_host_reg_out(DRIVE_LO, 0x0032); client_detection_try = TRUE; mddi_client_id = (mddi_client_capability_pkt.Mfr_Name<<16) | mddi_client_capability_pkt.Product_Code; if (!mddi_client_id) mddi_disable(1); ret = mddi_client_power(mddi_client_id); if (ret < 0) MDDI_MSG_ERR("mddi_client_power return %d", ret); } #if 0 switch (mddi_client_capability_pkt.Mfr_Name) { case 0x4474: if ((mddi_client_capability_pkt.Product_Code != 0x8960) && (target == DISPLAY_1)) { ret = PRISM_WVGA; } break; case 0xD263: if (target == DISPLAY_1) ret = TOSHIBA_VGA_PRIM; else if (target == DISPLAY_2) ret = TOSHIBA_QCIF_SECD; break; case 0: if (mddi_client_capability_pkt.Product_Code == 0x8835) { if (target == DISPLAY_1) ret = SHARP_QVGA_PRIM; else if (target == DISPLAY_2) ret = SHARP_128x128_SECD; } break; default: break; } if ((!client_detection_try) && (ret != TOSHIBA_VGA_PRIM) && (ret != TOSHIBA_QCIF_SECD)) { /* Not a Toshiba display, so change drive_lo back to default value */ mddi_host_reg_out(DRIVE_LO, 0x0032); } #endif #endif return mddi_client_id; } #endif void mddi_host_powerdown(mddi_host_type host_idx) { mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); if (host_idx >= MDDI_NUM_HOST_CORES) { MDDI_MSG_ERR("Invalid host core index\n"); return; } if (pmhctl->driver_state == MDDI_DRIVER_RESET) { return; } if (host_idx == MDDI_HOST_PRIM) { /* disable timer */ del_timer(&mddi_host_timer); } mddi_host_configure_interrupts(host_idx, FALSE); /* turn on HCLK to MDDI host core if it has been disabled */ mddi_host_enable_hclk(); /* MDDI Reset command */ mddi_host_reg_out(CMD, MDDI_CMD_RESET); /* Pad Control Register */ mddi_host_reg_out(PAD_CTL, 0x0); /* disable IO_CLK and hclk to MDDI host core */ mddi_host_disable_io_clock(); mddi_host_disable_hclk(); pmhctl->link_state = MDDI_LINK_DISABLED; pmhctl->driver_state = MDDI_DRIVER_RESET; MDDI_MSG_NOTICE("MDDI Host: Disabling Link\n"); } uint16 mddi_get_next_free_llist_item(mddi_host_type host_idx, boolean wait) { unsigned long flags; uint16 ret_idx; boolean forced_wait = FALSE; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); ret_idx = pmhctl->llist_info.next_free_idx; pmhctl->llist_info.next_free_idx++; if (pmhctl->llist_info.next_free_idx >= MDDI_NUM_DYNAMIC_LLIST_ITEMS) pmhctl->llist_info.next_free_idx = MDDI_FIRST_DYNAMIC_LLIST_IDX; spin_lock_irqsave(&mddi_host_spin_lock, flags); if (pmhctl->llist_notify[ret_idx].in_use) { if (!wait) { pmhctl->llist_info.next_free_idx = ret_idx; ret_idx = UNASSIGNED_INDEX; } else { forced_wait = TRUE; INIT_COMPLETION(pmhctl->mddi_llist_avail_comp); } } spin_unlock_irqrestore(&mddi_host_spin_lock, flags); if (forced_wait) { wait_for_completion_killable(& (pmhctl-> mddi_llist_avail_comp)); MDDI_MSG_ERR("task waiting on mddi llist item\n"); } if (ret_idx != UNASSIGNED_INDEX) { pmhctl->llist_notify[ret_idx].waiting = FALSE; pmhctl->llist_notify[ret_idx].done_cb = NULL; pmhctl->llist_notify[ret_idx].in_use = TRUE; pmhctl->llist_notify[ret_idx].next_idx = UNASSIGNED_INDEX; } return ret_idx; } uint16 mddi_get_reg_read_llist_item(mddi_host_type host_idx, boolean wait) { #ifdef FEATURE_MDDI_DISABLE_REVERSE MDDI_MSG_CRIT("No reverse link available\n"); (void)wait; return FALSE; #else unsigned long flags; uint16 ret_idx; boolean error = FALSE; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); spin_lock_irqsave(&mddi_host_spin_lock, flags); if (pmhctl->llist_info.reg_read_idx != UNASSIGNED_INDEX) { /* need to block here or is this an error condition? */ error = TRUE; ret_idx = UNASSIGNED_INDEX; } spin_unlock_irqrestore(&mddi_host_spin_lock, flags); if (!error) { ret_idx = pmhctl->llist_info.reg_read_idx = mddi_get_next_free_llist_item(host_idx, wait); /* clear the reg_read_waiting flag */ pmhctl->llist_info.reg_read_waiting = FALSE; } if (error) MDDI_MSG_ERR("***** Reg read still in progress! ****\n"); return ret_idx; #endif } void mddi_queue_forward_packets(uint16 first_llist_idx, uint16 last_llist_idx, boolean wait, mddi_llist_done_cb_type llist_done_cb, mddi_host_type host_idx) { unsigned long flags; mddi_linked_list_type *llist; mddi_linked_list_type *llist_dma; mddi_host_cntl_type *pmhctl = &(mhctl[host_idx]); if ((first_llist_idx >= UNASSIGNED_INDEX) || (last_llist_idx >= UNASSIGNED_INDEX)) { MDDI_MSG_ERR("MDDI queueing invalid linked list\n"); return; } if (pmhctl->link_state == MDDI_LINK_DISABLED) MDDI_MSG_CRIT("MDDI host powered down!\n"); llist = pmhctl->llist_ptr; llist_dma = pmhctl->llist_dma_ptr; /* clean cache so MDDI host can read data */ memory_barrier(); pmhctl->llist_notify[last_llist_idx].waiting = wait; if (wait) INIT_COMPLETION(pmhctl->llist_notify[last_llist_idx].done_comp); pmhctl->llist_notify[last_llist_idx].done_cb = llist_done_cb; spin_lock_irqsave(&mddi_host_spin_lock, flags); if ((pmhctl->llist_info.transmitting_start_idx == UNASSIGNED_INDEX) && (pmhctl->llist_info.waiting_start_idx == UNASSIGNED_INDEX) && (pmhctl->rev_state == MDDI_REV_IDLE)) { /* no packets are currently transmitting */ #ifndef FEATURE_MDDI_DISABLE_REVERSE if (first_llist_idx == pmhctl->llist_info.reg_read_idx) { /* This is the special case where the packet is a register read. */ pmhctl->rev_state = MDDI_REV_REG_READ_ISSUED; mddi_reg_read_retry = 0; /* mddi_rev_reg_read_attempt = 1; */ } #endif /* assign transmitting index values */ pmhctl->llist_info.transmitting_start_idx = first_llist_idx; pmhctl->llist_info.transmitting_end_idx = last_llist_idx; /* turn on clock(s), if they have been disabled */ mddi_host_enable_hclk(); mddi_host_enable_io_clock(); pmhctl->int_type.llist_ptr_write_1++; /* Write to primary pointer register */ dma_coherent_pre_ops(); mddi_host_reg_out(PRI_PTR, &llist_dma[first_llist_idx]); /* enable interrupt when complete */ mddi_host_reg_outm(INTEN, MDDI_INT_PRI_LINK_LIST_DONE, MDDI_INT_PRI_LINK_LIST_DONE); } else if (pmhctl->llist_info.waiting_start_idx == UNASSIGNED_INDEX) { #ifndef FEATURE_MDDI_DISABLE_REVERSE if (first_llist_idx == pmhctl->llist_info.reg_read_idx) { /* * we have a register read to send but need to wait * for current reverse activity to end or there are * packets currently transmitting */ /* mddi_rev_reg_read_attempt = 0; */ pmhctl->llist_info.reg_read_waiting = TRUE; } #endif /* assign waiting index values */ pmhctl->llist_info.waiting_start_idx = first_llist_idx; pmhctl->llist_info.waiting_end_idx = last_llist_idx; } else { uint16 prev_end_idx = pmhctl->llist_info.waiting_end_idx; #ifndef FEATURE_MDDI_DISABLE_REVERSE if (first_llist_idx == pmhctl->llist_info.reg_read_idx) { /* * we have a register read to send but need to wait * for current reverse activity to end or there are * packets currently transmitting */ /* mddi_rev_reg_read_attempt = 0; */ pmhctl->llist_info.reg_read_waiting = TRUE; } #endif llist = pmhctl->llist_ptr; /* clear end flag in previous last packet */ llist[prev_end_idx].link_controller_flags = 0; pmhctl->llist_notify[prev_end_idx].next_idx = first_llist_idx; /* set the next_packet_pointer of the previous last packet */ llist[prev_end_idx].next_packet_pointer = (void *)(&llist_dma[first_llist_idx]); /* clean cache so MDDI host can read data */ memory_barrier(); /* assign new waiting last index value */ pmhctl->llist_info.waiting_end_idx = last_llist_idx; } spin_unlock_irqrestore(&mddi_host_spin_lock, flags); } void mddi_host_write_pix_attr_reg(uint32 value) { (void)value; } void mddi_queue_reverse_encapsulation(boolean wait) { #ifdef FEATURE_MDDI_DISABLE_REVERSE MDDI_MSG_CRIT("No reverse link available\n"); (void)wait; #else unsigned long flags; boolean error = FALSE; mddi_host_type host_idx = MDDI_HOST_PRIM; mddi_host_cntl_type *pmhctl = &(mhctl[MDDI_HOST_PRIM]); spin_lock_irqsave(&mddi_host_spin_lock, flags); /* turn on clock(s), if they have been disabled */ mddi_host_enable_hclk(); mddi_host_enable_io_clock(); if (wait) { if (!mddi_rev_user.waiting) { mddi_rev_user.waiting = TRUE; INIT_COMPLETION(mddi_rev_user.done_comp); } else error = TRUE; } mddi_rev_encap_user_request = TRUE; if (pmhctl->rev_state == MDDI_REV_IDLE) { /* attempt to send the reverse encapsulation now */ mddi_host_type orig_host_idx = mddi_curr_host; mddi_curr_host = host_idx; mddi_issue_reverse_encapsulation(); mddi_curr_host = orig_host_idx; } spin_unlock_irqrestore(&mddi_host_spin_lock, flags); if (error) { MDDI_MSG_ERR("Reverse Encap request already in progress\n"); } else if (wait) wait_for_completion_killable(&(mddi_rev_user.done_comp)); #endif } /* ISR to be executed */ boolean mddi_set_rev_handler(mddi_rev_handler_type handler, uint16 pkt_type) { #ifdef FEATURE_MDDI_DISABLE_REVERSE MDDI_MSG_CRIT("No reverse link available\n"); (void)handler; (void)pkt_type; return (FALSE); #else unsigned long flags; uint16 hdlr; boolean handler_set = FALSE; boolean overwrite = FALSE; mddi_host_type host_idx = MDDI_HOST_PRIM; mddi_host_cntl_type *pmhctl = &(mhctl[MDDI_HOST_PRIM]); /* Disable interrupts */ spin_lock_irqsave(&mddi_host_spin_lock, flags); for (hdlr = 0; hdlr < MAX_MDDI_REV_HANDLERS; hdlr++) { if (mddi_rev_pkt_handler[hdlr].pkt_type == pkt_type) { mddi_rev_pkt_handler[hdlr].handler = handler; if (handler == NULL) { /* clearing handler from table */ mddi_rev_pkt_handler[hdlr].pkt_type = INVALID_PKT_TYPE; handler_set = TRUE; if (pkt_type == 0x10) { /* video stream packet */ /* ensure HCLK on to MDDI host core before register write */ mddi_host_enable_hclk(); /* No longer getting video, so reset rev encap size to default */ pmhctl->rev_pkt_size = MDDI_DEFAULT_REV_PKT_SIZE; mddi_host_reg_out(REV_ENCAP_SZ, pmhctl->rev_pkt_size); } } else { /* already a handler for this packet */ overwrite = TRUE; } break; } } if ((hdlr >= MAX_MDDI_REV_HANDLERS) && (handler != NULL)) { /* assigning new handler */ for (hdlr = 0; hdlr < MAX_MDDI_REV_HANDLERS; hdlr++) { if (mddi_rev_pkt_handler[hdlr].pkt_type == INVALID_PKT_TYPE) { if ((pkt_type == 0x10) && /* video stream packet */ (pmhctl->rev_pkt_size < MDDI_VIDEO_REV_PKT_SIZE)) { /* ensure HCLK on to MDDI host core before register write */ mddi_host_enable_hclk(); /* Increase Rev Encap Size */ pmhctl->rev_pkt_size = MDDI_VIDEO_REV_PKT_SIZE; mddi_host_reg_out(REV_ENCAP_SZ, pmhctl->rev_pkt_size); } mddi_rev_pkt_handler[hdlr].handler = handler; mddi_rev_pkt_handler[hdlr].pkt_type = pkt_type; handler_set = TRUE; break; } } } /* Restore interrupts */ spin_unlock_irqrestore(&mddi_host_spin_lock, flags); if (overwrite) MDDI_MSG_ERR("Overwriting previous rev packet handler\n"); return handler_set; #endif } /* mddi_set_rev_handler */ void mddi_host_disable_hibernation(boolean disable) { mddi_host_type host_idx = MDDI_HOST_PRIM; mddi_host_cntl_type *pmhctl = &(mhctl[MDDI_HOST_PRIM]); if (disable) { pmhctl->disable_hibernation = TRUE; /* hibernation will be turned off by isr next time it is entered */ } else { if (pmhctl->disable_hibernation) { unsigned long flags; spin_lock_irqsave(&mddi_host_spin_lock, flags); if (!MDDI_HOST_IS_HCLK_ON) MDDI_HOST_ENABLE_HCLK; mddi_host_reg_out(CMD, MDDI_CMD_HIBERNATE | 1); spin_unlock_irqrestore(&mddi_host_spin_lock, flags); pmhctl->disable_hibernation = FALSE; } } } void mddi_mhctl_remove(mddi_host_type host_idx) { mddi_host_cntl_type *pmhctl; pmhctl = &(mhctl[host_idx]); dma_free_coherent(NULL, MDDI_LLIST_POOL_SIZE, (void *)pmhctl->llist_ptr, pmhctl->llist_dma_addr); dma_free_coherent(NULL, MDDI_MAX_REV_DATA_SIZE, (void *)pmhctl->rev_data_buf, pmhctl->rev_data_dma_addr); }
Perferom/android_kernel_lge_msm7x27-3.0.x
drivers/video/msm/mddihosti.c
C
gpl-2.0
67,103
# Changelog ### 2.0.0, 2014-07-11 - Full rewrite of the library. ### 1.1.3, 2014-05-20 - Removed unused gesture handler check. See [#545](https://github.com/EightMedia/hammer.js/issues/545) - Changed the default value of `behavior.touchAction` from `none` to `pan-y`, for improved default behavior in IE10> and Chrome35>. It makes the element less blocking and improves the detection of horizontal swipes. See the wiki for more details. ### 1.1.2, 2014-04-25 - Bring back the `NO_MOUSEEVENTS` check. Just has better support this way. It is used to disable binding to mouseevents on most mobile browsers. - Pen support for pointerEvents - Fixes some pointerEvent support issues - Disables gestures on right mousebutton. - Added `utils.setPrefixedCss` to set prefixed css properties. ### 1.1.1, 2014-04-23 - All vars and options renamed to be camelCased for more consistency in the code. Options are still allowed to be set with underscores when creating an instance. - Codestyle changes, and a grunt task that keeps everything the same CS. ### 1.1.0, 2014-04-23 - Rewritten event core event handler. Fixes some issues with the last event data, and more triggers. - Added `EVENT_TOUCH` and `EVENT_RELEASE` event types. These events are triggered inside Hammer when the touches change. This makes some gestures more precise and gives you more control. - Refactored the calculation of velocity and interimDirection/Angle. - Refactored some gestures. - Added CHANGELOG.md! - Added more unit tests. - Added code docs, YUIdoc style. - New gesture event: `gesture`. This is a lowlevel gesture which passes all data. Disabled by default. - Dropped `NO_MOUSEEVENTS` check. This still could be done by the `prevent_mouseevents` option, defined at the `touch` gesture. - The gestures `touch` and `release` are now triggered on every new touch/release instead of start/end. - Removed the option `transform_within_instance`, it wasn't a common use-case and could be easily fixed in the event callback. - Removed the option `transform_always_block` since it did the same as the `prevent_default` option. - Renamed the option `stop_browser_behavior` to `behavior`. - Fixed support of the fakeMultitouch plugin for IE PointerEvents. - Improved performance of the showTouches plugin. - The Showtouches plugin doesn't require an IE check anymore.
khanhduy39nn/kevin
wp-content/plugins/media-grid/js/hammer.js/CHANGELOG.md
Markdown
gpl-2.0
2,333
<?php /** * Single Product Price, including microdata for SEO * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ global $post, $product; ?> <div itemprop="offers" itemscope itemtype="http://schema.org/Offer"> <p itemprop="price" class="price pricelarge"><?php echo $product->get_price_html(); ?></p> <link itemprop="availability" href="http://schema.org/<?php echo $product->is_in_stock() ? 'InStock' : 'OutOfStock'; ?>" /> </div>
cphillipp/greenlogic
wp-content/themes/nevada/woocommerce/single-product/price.php
PHP
gpl-2.0
490
FONT {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px} TD {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px} BODY {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px} P {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px} DIV {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px} INPUT {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px} TEXTAREA {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px} FORM {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px} A:link {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: underline} A:active {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: underline} A:visited {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: underline} A:hover {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: underline} .title {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 13px; FONT-WEIGHT: bold; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: none} .content {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 11px; FONT-FAMILY: Verdana, Helvetica} .storytitle {BACKGROUND: none; COLOR: #363636; FONT-SIZE: 14px; FONT-WEIGHT: bold; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: none} .storycat {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 13px; FONT-WEIGHT: bold; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: underline} .boxtitle {BACKGROUND: none; COLOR: #363636; FONT-SIZE: 11px; FONT-WEIGHT: bold; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: none} .boxcontent {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 12px; FONT-FAMILY: Verdana, Helvetica} .option {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 13px; FONT-WEIGHT: bold; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: none} .tiny {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 10px; FONT-WEIGHT: normal; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: none} .footmsg {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 8px; FONT-WEIGHT: normal; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: none} .footmsg_l {BACKGROUND: none; COLOR: #000000; FONT-SIZE: 8px; FONT-WEIGHT: normal; FONT-FAMILY: Verdana, Helvetica; TEXT-DECORATION: underline} .box {FONT-FAMILY: Verdana,Helvetica; FONT-SIZE: 11px; border: 1px solid #000000; background-color: #FFFFFF}
rotvulpix/php-nuke
html/themes/Slash/style/style.css
CSS
gpl-2.0
2,381
/* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #define pr_fmt(fmt) "BMS: %s: " fmt, __func__ #define DEBUG #include <linux/module.h> #include <linux/types.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/err.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/power_supply.h> #include <linux/spmi.h> #include <linux/rtc.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/qpnp/qpnp-adc.h> #include <linux/qpnp/power-on.h> #include <linux/of_batterydata.h> /* BMS Register Offsets */ #define REVISION1 0x0 #define REVISION2 0x1 #define BMS1_STATUS1 0x8 #define BMS1_MODE_CTL 0X40 /* Coulomb counter clear registers */ #define BMS1_CC_DATA_CTL 0x42 #define BMS1_CC_CLEAR_CTL 0x43 /* BMS Tolerances */ #define BMS1_TOL_CTL 0X44 /* OCV limit registers */ #define BMS1_OCV_USE_LOW_LIMIT_THR0 0x48 #define BMS1_OCV_USE_LOW_LIMIT_THR1 0x49 #define BMS1_OCV_USE_HIGH_LIMIT_THR0 0x4A #define BMS1_OCV_USE_HIGH_LIMIT_THR1 0x4B #define BMS1_OCV_USE_LIMIT_CTL 0x4C /* Delay control */ #define BMS1_S1_DELAY_CTL 0x5A /* OCV interrupt threshold */ #define BMS1_OCV_THR0 0x50 #define BMS1_S2_SAMP_AVG_CTL 0x61 /* SW CC interrupt threshold */ #define BMS1_SW_CC_THR0 0xA0 /* OCV for r registers */ #define BMS1_OCV_FOR_R_DATA0 0x80 #define BMS1_VSENSE_FOR_R_DATA0 0x82 /* Coulomb counter data */ #define BMS1_CC_DATA0 0x8A /* Shadow Coulomb counter data */ #define BMS1_SW_CC_DATA0 0xA8 /* OCV for soc data */ #define BMS1_OCV_FOR_SOC_DATA0 0x90 #define BMS1_VSENSE_PON_DATA0 0x94 #define BMS1_VSENSE_AVG_DATA0 0x98 #define BMS1_VBAT_AVG_DATA0 0x9E /* Extra bms registers */ #define SOC_STORAGE_REG 0xB0 #define IAVG_STORAGE_REG 0xB1 #define BMS_FCC_COUNT 0xB2 #define BMS_FCC_BASE_REG 0xB3 /* FCC updates - 0xB3 to 0xB7 */ #define BMS_CHGCYL_BASE_REG 0xB8 /* FCC chgcyl - 0xB8 to 0xBC */ #define CHARGE_INCREASE_STORAGE 0xBD #define CHARGE_CYCLE_STORAGE_LSB 0xBE /* LSB=0xBE, MSB=0xBF */ /* IADC Channel Select */ #define IADC1_BMS_REVISION2 0x01 #define IADC1_BMS_ADC_CH_SEL_CTL 0x48 #define IADC1_BMS_ADC_INT_RSNSN_CTL 0x49 #define IADC1_BMS_FAST_AVG_EN 0x5B /* Configuration for saving of shutdown soc/iavg */ #define IGNORE_SOC_TEMP_DECIDEG 50 #define IAVG_STEP_SIZE_MA 10 #define IAVG_INVALID 0xFF #define SOC_INVALID 0x7E #define IAVG_SAMPLES 16 /* FCC learning constants */ #define MAX_FCC_CYCLES 5 #define DELTA_FCC_PERCENT 5 #define VALID_FCC_CHGCYL_RANGE 50 #define CHGCYL_RESOLUTION 20 #define FCC_DEFAULT_TEMP 250 #define QPNP_BMS_DEV_NAME "qcom,qpnp-bms" enum { SHDW_CC, CC }; enum { NORESET, RESET }; struct soc_params { int fcc_uah; int cc_uah; int rbatt_mohm; int iavg_ua; int uuc_uah; int ocv_charge_uah; int delta_time_s; }; struct raw_soc_params { uint16_t last_good_ocv_raw; int64_t cc; int64_t shdw_cc; int last_good_ocv_uv; }; struct fcc_sample { int fcc_new; int chargecycles; }; struct bms_irq { unsigned int irq; unsigned long disabled; }; struct bms_wakeup_source { struct wakeup_source source; unsigned long disabled; }; struct qpnp_bms_chip { struct device *dev; struct power_supply bms_psy; bool bms_psy_registered; struct power_supply *batt_psy; struct spmi_device *spmi; wait_queue_head_t bms_wait_queue; u16 base; u16 iadc_base; u16 batt_pres_addr; u16 soc_storage_addr; u8 revision1; u8 revision2; u8 iadc_bms_revision1; u8 iadc_bms_revision2; int battery_present; int battery_status; bool batfet_closed; bool new_battery; bool done_charging; bool last_soc_invalid; /* platform data */ int r_sense_uohm; unsigned int v_cutoff_uv; int max_voltage_uv; int r_conn_mohm; int shutdown_soc_valid_limit; int adjust_soc_low_threshold; int chg_term_ua; enum battery_type batt_type; unsigned int fcc_mah; struct single_row_lut *fcc_temp_lut; struct single_row_lut *fcc_sf_lut; struct pc_temp_ocv_lut *pc_temp_ocv_lut; struct sf_lut *pc_sf_lut; struct sf_lut *rbatt_sf_lut; int default_rbatt_mohm; int rbatt_capacitive_mohm; int rbatt_mohm; struct delayed_work calculate_soc_delayed_work; struct work_struct recalc_work; struct work_struct batfet_open_work; struct mutex bms_output_lock; struct mutex last_ocv_uv_mutex; struct mutex vbat_monitor_mutex; struct mutex soc_invalidation_mutex; struct mutex last_soc_mutex; struct mutex status_lock; bool use_external_rsense; bool use_ocv_thresholds; bool ignore_shutdown_soc; bool shutdown_soc_invalid; int shutdown_soc; int shutdown_iavg_ma; struct wake_lock low_voltage_wake_lock; int low_voltage_threshold; int low_soc_calc_threshold; int low_soc_calculate_soc_ms; int low_voltage_calculate_soc_ms; int calculate_soc_ms; struct bms_wakeup_source soc_wake_source; struct wake_lock cv_wake_lock; uint16_t ocv_reading_at_100; uint16_t prev_last_good_ocv_raw; int insertion_ocv_uv; int last_ocv_uv; int charging_adjusted_ocv; int last_ocv_temp; int last_cc_uah; unsigned long last_soc_change_sec; unsigned long tm_sec; unsigned long report_tm_sec; bool first_time_calc_soc; bool first_time_calc_uuc; int64_t software_cc_uah; int64_t software_shdw_cc_uah; int iavg_samples_ma[IAVG_SAMPLES]; int iavg_index; int iavg_num_samples; struct timespec t_soc_queried; int last_soc; int last_soc_est; int last_soc_unbound; bool was_charging_at_sleep; int charge_start_tm_sec; int catch_up_time_sec; struct single_row_lut *adjusted_fcc_temp_lut; struct qpnp_adc_tm_btm_param vbat_monitor_params; struct qpnp_adc_tm_btm_param die_temp_monitor_params; int temperature_margin; unsigned int vadc_v0625; unsigned int vadc_v1250; int system_load_count; int prev_uuc_iavg_ma; int prev_pc_unusable; int ibat_at_cv_ua; int soc_at_cv; int prev_chg_soc; int calculated_soc; int prev_voltage_based_soc; bool use_voltage_soc; bool in_cv_range; int prev_batt_terminal_uv; int high_ocv_correction_limit_uv; int low_ocv_correction_limit_uv; int flat_ocv_threshold_uv; int hold_soc_est; int ocv_high_threshold_uv; int ocv_low_threshold_uv; unsigned long last_recalc_time; struct fcc_sample *fcc_learning_samples; u8 fcc_sample_count; int enable_fcc_learning; int min_fcc_learning_soc; int min_fcc_ocv_pc; int min_fcc_learning_samples; int start_soc; int end_soc; int start_pc; int start_cc_uah; int start_real_soc; int end_cc_uah; uint16_t fcc_new_mah; int fcc_new_batt_temp; uint16_t charge_cycles; u8 charge_increase; int fcc_resolution; bool battery_removed; struct bms_irq sw_cc_thr_irq; struct bms_irq ocv_thr_irq; struct qpnp_vadc_chip *vadc_dev; struct qpnp_iadc_chip *iadc_dev; struct qpnp_adc_tm_chip *adc_tm_dev; }; static struct of_device_id qpnp_bms_match_table[] = { { .compatible = QPNP_BMS_DEV_NAME }, {} }; static char *qpnp_bms_supplicants[] = { "battery" }; static enum power_supply_property msm_bms_power_props[] = { POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CURRENT_AVG, POWER_SUPPLY_PROP_RESISTANCE, POWER_SUPPLY_PROP_CHARGE_COUNTER, POWER_SUPPLY_PROP_CHARGE_COUNTER_SHADOW, POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CYCLE_COUNT, #if defined(CONFIG_BATTERY_SAMSUNG) POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_AVG, #endif }; static int discard_backup_fcc_data(struct qpnp_bms_chip *chip); static void backup_charge_cycle(struct qpnp_bms_chip *chip); static bool bms_reset; static int qpnp_read_wrapper(struct qpnp_bms_chip *chip, u8 *val, u16 base, int count) { int rc; struct spmi_device *spmi = chip->spmi; rc = spmi_ext_register_readl(spmi->ctrl, spmi->sid, base, val, count); if (rc) { pr_err("SPMI read failed rc=%d\n", rc); return rc; } return 0; } static int qpnp_write_wrapper(struct qpnp_bms_chip *chip, u8 *val, u16 base, int count) { int rc; struct spmi_device *spmi = chip->spmi; rc = spmi_ext_register_writel(spmi->ctrl, spmi->sid, base, val, count); if (rc) { pr_err("SPMI write failed rc=%d\n", rc); return rc; } return 0; } static int qpnp_masked_write_base(struct qpnp_bms_chip *chip, u16 addr, u8 mask, u8 val) { int rc; u8 reg; rc = qpnp_read_wrapper(chip, &reg, addr, 1); if (rc) { pr_err("read failed addr = %03X, rc = %d\n", addr, rc); return rc; } reg &= ~mask; reg |= val & mask; rc = qpnp_write_wrapper(chip, &reg, addr, 1); if (rc) { pr_err("write failed addr = %03X, val = %02x, mask = %02x, reg = %02x, rc = %d\n", addr, val, mask, reg, rc); return rc; } return 0; } static int qpnp_masked_write_iadc(struct qpnp_bms_chip *chip, u16 addr, u8 mask, u8 val) { return qpnp_masked_write_base(chip, chip->iadc_base + addr, mask, val); } static int qpnp_masked_write(struct qpnp_bms_chip *chip, u16 addr, u8 mask, u8 val) { return qpnp_masked_write_base(chip, chip->base + addr, mask, val); } static void bms_stay_awake(struct bms_wakeup_source *source) { if (__test_and_clear_bit(0, &source->disabled)) { __pm_stay_awake(&source->source); pr_debug("enabled source %s\n", source->source.name); } } static void bms_relax(struct bms_wakeup_source *source) { if (!__test_and_set_bit(0, &source->disabled)) { __pm_relax(&source->source); pr_debug("disabled source %s\n", source->source.name); } } static void enable_bms_irq(struct bms_irq *irq) { if (__test_and_clear_bit(0, &irq->disabled)) { enable_irq(irq->irq); pr_debug("enabled irq %d\n", irq->irq); } } static void disable_bms_irq(struct bms_irq *irq) { if (!__test_and_set_bit(0, &irq->disabled)) { disable_irq(irq->irq); pr_debug("disabled irq %d\n", irq->irq); } } #define HOLD_OREG_DATA BIT(0) static int lock_output_data(struct qpnp_bms_chip *chip) { int rc; rc = qpnp_masked_write(chip, BMS1_CC_DATA_CTL, HOLD_OREG_DATA, HOLD_OREG_DATA); if (rc) { pr_err("couldnt lock bms output rc = %d\n", rc); return rc; } return 0; } static int unlock_output_data(struct qpnp_bms_chip *chip) { int rc; rc = qpnp_masked_write(chip, BMS1_CC_DATA_CTL, HOLD_OREG_DATA, 0); if (rc) { pr_err("fail to unlock BMS_CONTROL rc = %d\n", rc); return rc; } return 0; } #define V_PER_BIT_MUL_FACTOR 97656 #define V_PER_BIT_DIV_FACTOR 1000 #define VADC_INTRINSIC_OFFSET 0x6000 static int vadc_reading_to_uv(int reading) { if (reading <= VADC_INTRINSIC_OFFSET) return 0; return (reading - VADC_INTRINSIC_OFFSET) * V_PER_BIT_MUL_FACTOR / V_PER_BIT_DIV_FACTOR; } #define VADC_CALIB_UV 625000 #define VBATT_MUL_FACTOR 3 static int adjust_vbatt_reading(struct qpnp_bms_chip *chip, int reading_uv) { s64 numerator, denominator; if (reading_uv == 0) return 0; /* don't adjust if not calibrated */ if (chip->vadc_v0625 == 0 || chip->vadc_v1250 == 0) { pr_debug("No cal yet return %d\n", VBATT_MUL_FACTOR * reading_uv); return VBATT_MUL_FACTOR * reading_uv; } numerator = ((s64)reading_uv - chip->vadc_v0625) * VADC_CALIB_UV; denominator = (s64)chip->vadc_v1250 - chip->vadc_v0625; if (denominator == 0) return reading_uv * VBATT_MUL_FACTOR; return (VADC_CALIB_UV + div_s64(numerator, denominator)) * VBATT_MUL_FACTOR; } static int convert_vbatt_uv_to_raw(struct qpnp_bms_chip *chip, int unadjusted_vbatt) { int scaled_vbatt = unadjusted_vbatt / VBATT_MUL_FACTOR; if (scaled_vbatt <= 0) return VADC_INTRINSIC_OFFSET; return ((scaled_vbatt * V_PER_BIT_DIV_FACTOR) / V_PER_BIT_MUL_FACTOR) + VADC_INTRINSIC_OFFSET; } static inline int convert_vbatt_raw_to_uv(struct qpnp_bms_chip *chip, uint16_t reading) { int64_t uv; int rc; uv = vadc_reading_to_uv(reading); pr_debug("%u raw converted into %lld uv\n", reading, uv); uv = adjust_vbatt_reading(chip, uv); pr_debug("adjusted into %lld uv\n", uv); rc = qpnp_vbat_sns_comp_result(chip->vadc_dev, &uv); if (rc) pr_debug("could not compensate vbatt\n"); pr_debug("compensated into %lld uv\n", uv); return uv; } #define CC_READING_RESOLUTION_N 542535 #define CC_READING_RESOLUTION_D 100000 static s64 cc_reading_to_uv(s64 reading) { return div_s64(reading * CC_READING_RESOLUTION_N, CC_READING_RESOLUTION_D); } #define QPNP_ADC_GAIN_IDEAL 3291LL static s64 cc_adjust_for_gain(s64 uv, uint16_t gain) { s64 result_uv; pr_debug("adjusting_uv = %lld\n", uv); if (gain == 0) { pr_debug("gain is %d, not adjusting\n", gain); return uv; } pr_debug("adjusting by factor: %lld/%hu = %lld%%\n", QPNP_ADC_GAIN_IDEAL, gain, div_s64(QPNP_ADC_GAIN_IDEAL * 100LL, (s64)gain)); result_uv = div_s64(uv * QPNP_ADC_GAIN_IDEAL, (s64)gain); pr_debug("result_uv = %lld\n", result_uv); return result_uv; } static s64 cc_reverse_adjust_for_gain(struct qpnp_bms_chip *chip, s64 uv) { struct qpnp_iadc_calib calibration; int gain; s64 result_uv; qpnp_iadc_get_gain_and_offset(chip->iadc_dev, &calibration); gain = (int)calibration.gain_raw - (int)calibration.offset_raw; pr_debug("reverse adjusting_uv = %lld\n", uv); if (gain == 0) { pr_debug("gain is %d, not adjusting\n", gain); return uv; } pr_debug("adjusting by factor: %hu/%lld = %lld%%\n", gain, QPNP_ADC_GAIN_IDEAL, div64_s64((s64)gain * 100LL, (s64)QPNP_ADC_GAIN_IDEAL)); result_uv = div64_s64(uv * (s64)gain, QPNP_ADC_GAIN_IDEAL); pr_debug("result_uv = %lld\n", result_uv); return result_uv; } static int convert_vsense_to_uv(struct qpnp_bms_chip *chip, int16_t reading) { struct qpnp_iadc_calib calibration; qpnp_iadc_get_gain_and_offset(chip->iadc_dev, &calibration); return cc_adjust_for_gain(cc_reading_to_uv(reading), calibration.gain_raw - calibration.offset_raw); } static int read_vsense_avg(struct qpnp_bms_chip *chip, int *result_uv) { int rc; int16_t reading; rc = qpnp_read_wrapper(chip, (u8 *)&reading, chip->base + BMS1_VSENSE_AVG_DATA0, 2); if (rc) { pr_err("fail to read VSENSE_AVG rc = %d\n", rc); return rc; } *result_uv = convert_vsense_to_uv(chip, reading); return 0; } static int get_battery_current(struct qpnp_bms_chip *chip, int *result_ua) { int rc, vsense_uv = 0; int64_t temp_current; if (chip->r_sense_uohm == 0) { pr_err("r_sense is zero\n"); return -EINVAL; } mutex_lock(&chip->bms_output_lock); lock_output_data(chip); read_vsense_avg(chip, &vsense_uv); unlock_output_data(chip); mutex_unlock(&chip->bms_output_lock); pr_debug("vsense_uv=%duV\n", vsense_uv); /* cast for signed division */ temp_current = div_s64((vsense_uv * 1000000LL), (int)chip->r_sense_uohm); rc = qpnp_iadc_comp_result(chip->iadc_dev, &temp_current); if (rc) pr_debug("error compensation failed: %d\n", rc); *result_ua = temp_current; pr_debug("err compensated ibat=%duA\n", *result_ua); return 0; } static int get_battery_voltage(struct qpnp_bms_chip *chip, int *result_uv) { int rc; struct qpnp_vadc_result adc_result; rc = qpnp_vadc_read(chip->vadc_dev, VBAT_SNS, &adc_result); if (rc) { pr_err("error reading adc channel = %d, rc = %d\n", VBAT_SNS, rc); return rc; } pr_debug("mvolts phy = %lld meas = 0x%llx\n", adc_result.physical, adc_result.measurement); *result_uv = (int)adc_result.physical; return 0; } #define CC_36_BIT_MASK 0xFFFFFFFFFLL static uint64_t convert_s64_to_s36(int64_t raw64) { return (uint64_t) raw64 & CC_36_BIT_MASK; } #define SIGN_EXTEND_36_TO_64_MASK (-1LL ^ CC_36_BIT_MASK) static int64_t convert_s36_to_s64(uint64_t raw36) { raw36 = raw36 & CC_36_BIT_MASK; /* convert 36 bit signed value into 64 signed value */ return (raw36 >> 35) == 0LL ? raw36 : (SIGN_EXTEND_36_TO_64_MASK | raw36); } static int read_cc_raw(struct qpnp_bms_chip *chip, int64_t *reading, int cc_type) { int64_t raw_reading; int rc; if (cc_type == SHDW_CC) rc = qpnp_read_wrapper(chip, (u8 *)&raw_reading, chip->base + BMS1_SW_CC_DATA0, 5); else rc = qpnp_read_wrapper(chip, (u8 *)&raw_reading, chip->base + BMS1_CC_DATA0, 5); if (rc) { pr_err("Error reading cc: rc = %d\n", rc); return -ENXIO; } *reading = convert_s36_to_s64(raw_reading); return 0; } static int calib_vadc(struct qpnp_bms_chip *chip) { int rc, raw_0625, raw_1250; struct qpnp_vadc_result result; rc = qpnp_vadc_read(chip->vadc_dev, REF_625MV, &result); if (rc) { pr_debug("vadc read failed with rc = %d\n", rc); return rc; } raw_0625 = result.adc_code; rc = qpnp_vadc_read(chip->vadc_dev, REF_125V, &result); if (rc) { pr_debug("vadc read failed with rc = %d\n", rc); return rc; } raw_1250 = result.adc_code; chip->vadc_v0625 = vadc_reading_to_uv(raw_0625); chip->vadc_v1250 = vadc_reading_to_uv(raw_1250); pr_debug("vadc calib: 0625 = %d raw (%d uv), 1250 = %d raw (%d uv)\n", raw_0625, chip->vadc_v0625, raw_1250, chip->vadc_v1250); return 0; } static void convert_and_store_ocv(struct qpnp_bms_chip *chip, struct raw_soc_params *raw, int batt_temp) { int rc; pr_debug("prev_last_good_ocv_raw = %d, last_good_ocv_raw = %d\n", chip->prev_last_good_ocv_raw, raw->last_good_ocv_raw); rc = calib_vadc(chip); if (rc) pr_err("Vadc reference voltage read failed, rc = %d\n", rc); chip->prev_last_good_ocv_raw = raw->last_good_ocv_raw; raw->last_good_ocv_uv = convert_vbatt_raw_to_uv(chip, raw->last_good_ocv_raw); chip->last_ocv_uv = raw->last_good_ocv_uv; chip->last_ocv_temp = batt_temp; chip->software_cc_uah = 0; pr_debug("last_good_ocv_uv = %d\n", raw->last_good_ocv_uv); } #define CLEAR_CC BIT(7) #define CLEAR_SHDW_CC BIT(6) /** * reset both cc and sw-cc. * note: this should only be ever called from one thread * or there may be a race condition where CC is never enabled * again */ static void reset_cc(struct qpnp_bms_chip *chip, u8 flags) { int rc; pr_debug("resetting cc manually with flags %hhu\n", flags); mutex_lock(&chip->bms_output_lock); rc = qpnp_masked_write(chip, BMS1_CC_CLEAR_CTL, flags, flags); if (rc) pr_err("cc reset failed: %d\n", rc); /* wait for 100us for cc to reset */ udelay(100); rc = qpnp_masked_write(chip, BMS1_CC_CLEAR_CTL, flags, 0); if (rc) pr_err("cc reenable failed: %d\n", rc); mutex_unlock(&chip->bms_output_lock); } static int get_battery_status(struct qpnp_bms_chip *chip) { union power_supply_propval ret = {0,}; if (chip->batt_psy == NULL) chip->batt_psy = power_supply_get_by_name("battery"); if (chip->batt_psy) { /* if battery has been registered, use the status property */ chip->batt_psy->get_property(chip->batt_psy, POWER_SUPPLY_PROP_STATUS, &ret); return ret.intval; } /* Default to false if the battery power supply is not registered. */ pr_debug("battery power supply is not registered\n"); return POWER_SUPPLY_STATUS_UNKNOWN; } static bool is_battery_charging(struct qpnp_bms_chip *chip) { return get_battery_status(chip) == POWER_SUPPLY_STATUS_CHARGING; } static bool is_battery_full(struct qpnp_bms_chip *chip) { return get_battery_status(chip) == POWER_SUPPLY_STATUS_FULL; } #define BAT_PRES_BIT BIT(7) static bool is_battery_present(struct qpnp_bms_chip *chip) { union power_supply_propval ret = {0,}; int rc; u8 batt_pres; /* first try to use the batt_pres register if given */ if (chip->batt_pres_addr) { rc = qpnp_read_wrapper(chip, &batt_pres, chip->batt_pres_addr, 1); if (!rc && (batt_pres & BAT_PRES_BIT)) return true; else return false; } if (chip->batt_psy == NULL) chip->batt_psy = power_supply_get_by_name("battery"); if (chip->batt_psy) { /* if battery has been registered, use the present property */ chip->batt_psy->get_property(chip->batt_psy, POWER_SUPPLY_PROP_PRESENT, &ret); return ret.intval; } /* Default to false if the battery power supply is not registered. */ pr_debug("battery power supply is not registered\n"); return false; } static int get_battery_insertion_ocv_uv(struct qpnp_bms_chip *chip) { union power_supply_propval ret = {0,}; int rc, vbat; if (chip->batt_psy == NULL) chip->batt_psy = power_supply_get_by_name("battery"); if (chip->batt_psy) { /* if battery has been registered, use the ocv property */ rc = chip->batt_psy->get_property(chip->batt_psy, POWER_SUPPLY_PROP_VOLTAGE_OCV, &ret); if (rc) { /* * Default to vbatt if the battery OCV is not * registered. */ pr_debug("Battery psy does not have voltage ocv\n"); rc = get_battery_voltage(chip, &vbat); if (rc) return -EINVAL; return vbat; } return ret.intval; } pr_debug("battery power supply is not registered\n"); return -EINVAL; } static bool is_batfet_closed(struct qpnp_bms_chip *chip) { union power_supply_propval ret = {0,}; if (chip->batt_psy == NULL) chip->batt_psy = power_supply_get_by_name("battery"); if (chip->batt_psy) { /* if battery has been registered, use the online property */ chip->batt_psy->get_property(chip->batt_psy, POWER_SUPPLY_PROP_ONLINE, &ret); return !!ret.intval; } /* Default to true if the battery power supply is not registered. */ pr_debug("battery power supply is not registered\n"); return true; } static int get_simultaneous_batt_v_and_i(struct qpnp_bms_chip *chip, int *ibat_ua, int *vbat_uv) { struct qpnp_iadc_result i_result; struct qpnp_vadc_result v_result; enum qpnp_iadc_channels iadc_channel; int rc; iadc_channel = chip->use_external_rsense ? EXTERNAL_RSENSE : INTERNAL_RSENSE; if (is_battery_full(chip)) { rc = get_battery_current(chip, ibat_ua); if (rc) { pr_err("bms current read failed with rc: %d\n", rc); return rc; } rc = qpnp_vadc_read(chip->vadc_dev, VBAT_SNS, &v_result); if (rc) { pr_err("vadc read failed with rc: %d\n", rc); return rc; } *vbat_uv = (int)v_result.physical; } else { rc = qpnp_iadc_vadc_sync_read(chip->iadc_dev, iadc_channel, &i_result, VBAT_SNS, &v_result); if (rc) { pr_err("adc sync read failed with rc: %d\n", rc); return rc; } /* * reverse the current read by the iadc, since the bms uses * flipped battery current polarity. */ *ibat_ua = -1 * (int)i_result.result_ua; *vbat_uv = (int)v_result.physical; } return 0; } static int estimate_ocv(struct qpnp_bms_chip *chip) { int ibat_ua, vbat_uv, ocv_est_uv; int rc; int rbatt_mohm = chip->default_rbatt_mohm + chip->r_conn_mohm + chip->rbatt_capacitive_mohm; rc = get_simultaneous_batt_v_and_i(chip, &ibat_ua, &vbat_uv); if (rc) { pr_err("simultaneous failed rc = %d\n", rc); return rc; } ocv_est_uv = vbat_uv + (ibat_ua * rbatt_mohm) / 1000; pr_debug("estimated pon ocv = %d\n", ocv_est_uv); return ocv_est_uv; } static void reset_for_new_battery(struct qpnp_bms_chip *chip, int batt_temp) { chip->last_ocv_uv = chip->insertion_ocv_uv; mutex_lock(&chip->last_soc_mutex); chip->last_soc = -EINVAL; chip->last_soc_invalid = true; mutex_unlock(&chip->last_soc_mutex); chip->soc_at_cv = -EINVAL; chip->shutdown_soc_invalid = true; chip->shutdown_soc = 0; chip->shutdown_iavg_ma = 0; chip->prev_pc_unusable = -EINVAL; reset_cc(chip, CLEAR_CC | CLEAR_SHDW_CC); chip->software_cc_uah = 0; chip->software_shdw_cc_uah = 0; chip->last_cc_uah = INT_MIN; chip->last_ocv_temp = batt_temp; chip->prev_batt_terminal_uv = 0; if (chip->enable_fcc_learning) { chip->adjusted_fcc_temp_lut = NULL; chip->fcc_new_mah = -EINVAL; /* reset the charge-cycle and charge-increase registers */ chip->charge_increase = 0; chip->charge_cycles = 0; backup_charge_cycle(chip); /* discard all the FCC learnt data and reset the local table */ discard_backup_fcc_data(chip); memset(chip->fcc_learning_samples, 0, chip->min_fcc_learning_samples * sizeof(struct fcc_sample)); } } #define OCV_RAW_UNINITIALIZED 0xFFFF #define MIN_OCV_UV 2000000 static int read_soc_params_raw(struct qpnp_bms_chip *chip, struct raw_soc_params *raw, int batt_temp) { int warm_reset; int rc; mutex_lock(&chip->bms_output_lock); lock_output_data(chip); rc = qpnp_read_wrapper(chip, (u8 *)&raw->last_good_ocv_raw, chip->base + BMS1_OCV_FOR_SOC_DATA0, 2); if (rc) { pr_err("Error reading ocv: rc = %d\n", rc); return -ENXIO; } rc = read_cc_raw(chip, &raw->cc, CC); rc = read_cc_raw(chip, &raw->shdw_cc, SHDW_CC); if (rc) { pr_err("Failed to read raw cc data, rc = %d\n", rc); return rc; } unlock_output_data(chip); mutex_unlock(&chip->bms_output_lock); if (chip->prev_last_good_ocv_raw == OCV_RAW_UNINITIALIZED) { convert_and_store_ocv(chip, raw, batt_temp); pr_debug("PON_OCV_UV = %d, cc = %llx\n", chip->last_ocv_uv, raw->cc); warm_reset = qpnp_pon_is_warm_reset(); if (raw->last_good_ocv_uv < MIN_OCV_UV || warm_reset > 0) { pr_debug("OCV is stale or bad, estimating new OCV.\n"); chip->last_ocv_uv = estimate_ocv(chip); raw->last_good_ocv_uv = chip->last_ocv_uv; reset_cc(chip, CLEAR_CC | CLEAR_SHDW_CC); pr_debug("New PON_OCV_UV = %d, cc = %llx\n", chip->last_ocv_uv, raw->cc); } } else if (chip->new_battery) { /* if a new battery was inserted, estimate the ocv */ reset_for_new_battery(chip, batt_temp); raw->cc = 0; raw->shdw_cc = 0; raw->last_good_ocv_uv = chip->last_ocv_uv; chip->new_battery = false; } else if (chip->done_charging) { chip->done_charging = false; /* if we just finished charging, reset CC and fake 100% */ chip->ocv_reading_at_100 = raw->last_good_ocv_raw; chip->last_ocv_uv = chip->max_voltage_uv; raw->last_good_ocv_uv = chip->max_voltage_uv; raw->cc = 0; raw->shdw_cc = 0; reset_cc(chip, CLEAR_CC | CLEAR_SHDW_CC); chip->last_ocv_temp = batt_temp; chip->software_cc_uah = 0; chip->software_shdw_cc_uah = 0; chip->last_cc_uah = INT_MIN; pr_debug("EOC Battery full ocv_reading = 0x%x\n", chip->ocv_reading_at_100); } else if (chip->prev_last_good_ocv_raw != raw->last_good_ocv_raw) { convert_and_store_ocv(chip, raw, batt_temp); /* forget the old cc value upon ocv */ chip->last_cc_uah = INT_MIN; } else { raw->last_good_ocv_uv = chip->last_ocv_uv; } /* stop faking a high OCV if we get a new OCV */ if (chip->ocv_reading_at_100 != raw->last_good_ocv_raw) chip->ocv_reading_at_100 = OCV_RAW_UNINITIALIZED; pr_debug("last_good_ocv_raw= 0x%x, last_good_ocv_uv= %duV\n", raw->last_good_ocv_raw, raw->last_good_ocv_uv); pr_debug("cc_raw= 0x%llx\n", raw->cc); return 0; } static int calculate_pc(struct qpnp_bms_chip *chip, int ocv_uv, int batt_temp) { int pc; pc = interpolate_pc(chip->pc_temp_ocv_lut, batt_temp / 10, ocv_uv / 1000); pr_debug("pc = %u %% for ocv = %d uv batt_temp = %d\n", pc, ocv_uv, batt_temp); /* Multiply the initial FCC value by the scale factor. */ return pc; } static int calculate_fcc(struct qpnp_bms_chip *chip, int batt_temp) { int fcc_uah; if (chip->adjusted_fcc_temp_lut == NULL) { /* interpolate_fcc returns a mv value. */ fcc_uah = interpolate_fcc(chip->fcc_temp_lut, batt_temp) * 1000; pr_debug("fcc = %d uAh\n", fcc_uah); return fcc_uah; } else { return 1000 * interpolate_fcc(chip->adjusted_fcc_temp_lut, batt_temp); } } /* calculate remaining charge at the time of ocv */ static int calculate_ocv_charge(struct qpnp_bms_chip *chip, struct raw_soc_params *raw, int fcc_uah) { int ocv_uv, pc; ocv_uv = raw->last_good_ocv_uv; pc = calculate_pc(chip, ocv_uv, chip->last_ocv_temp); pr_debug("ocv_uv = %d pc = %d\n", ocv_uv, pc); return (fcc_uah * pc) / 100; } #define CC_READING_TICKS 56 #define SLEEP_CLK_HZ 32764 #define SECONDS_PER_HOUR 3600 static s64 cc_uv_to_pvh(s64 cc_uv) { /* Note that it is necessary need to multiply by 1000000 to convert * from uvh to pvh here. * However, the maximum Coulomb Counter value is 2^35, which can cause * an over flow. * Multiply by 100000 first to perserve as much precision as possible * then multiply by 10 after doing the division in order to avoid * overflow on the maximum Coulomb Counter value. */ return div_s64(cc_uv * CC_READING_TICKS * 100000, SLEEP_CLK_HZ * SECONDS_PER_HOUR) * 10; } /** * calculate_cc() - converts a hardware coulomb counter reading into uah * @chip: the bms chip pointer * @cc: the cc reading from bms h/w * @cc_type: calcualte cc from regular or shadow coulomb counter * @clear_cc: whether this function should clear the hardware counter * after reading * * Converts the 64 bit hardware coulomb counter into microamp-hour by taking * into account hardware resolution and adc errors. * * Return: the coulomb counter based charge in uAh (micro-amp hour) */ static int calculate_cc(struct qpnp_bms_chip *chip, int64_t cc, int cc_type, int clear_cc) { struct qpnp_iadc_calib calibration; struct qpnp_vadc_result result; int64_t cc_voltage_uv, cc_pvh, cc_uah, *software_counter; int rc; software_counter = cc_type == SHDW_CC ? &chip->software_shdw_cc_uah : &chip->software_cc_uah; rc = qpnp_vadc_read(chip->vadc_dev, DIE_TEMP, &result); if (rc) { pr_err("could not read pmic die temperature: %d\n", rc); return *software_counter; } qpnp_iadc_get_gain_and_offset(chip->iadc_dev, &calibration); pr_debug("%scc = %lld, die_temp = %lld\n", cc_type == SHDW_CC ? "shdw_" : "", cc, result.physical); cc_voltage_uv = cc_reading_to_uv(cc); cc_voltage_uv = cc_adjust_for_gain(cc_voltage_uv, calibration.gain_raw - calibration.offset_raw); cc_pvh = cc_uv_to_pvh(cc_voltage_uv); cc_uah = div_s64(cc_pvh, chip->r_sense_uohm); rc = qpnp_iadc_comp_result(chip->iadc_dev, &cc_uah); if (rc) pr_debug("error compensation failed: %d\n", rc); if (clear_cc == RESET) { pr_debug("software_%scc = %lld, added cc_uah = %lld\n", cc_type == SHDW_CC ? "sw_" : "", *software_counter, cc_uah); *software_counter += cc_uah; reset_cc(chip, cc_type == SHDW_CC ? CLEAR_SHDW_CC : CLEAR_CC); return (int)*software_counter; } else { pr_debug("software_%scc = %lld, cc_uah = %lld, total = %lld\n", cc_type == SHDW_CC ? "shdw_" : "", *software_counter, cc_uah, *software_counter + cc_uah); return *software_counter + cc_uah; } } static int get_rbatt(struct qpnp_bms_chip *chip, int soc_rbatt_mohm, int batt_temp) { int rbatt_mohm, scalefactor; rbatt_mohm = chip->default_rbatt_mohm; if (chip->rbatt_sf_lut == NULL) { pr_debug("RBATT = %d\n", rbatt_mohm); return rbatt_mohm; } /* Convert the batt_temp to DegC from deciDegC */ batt_temp = batt_temp / 10; scalefactor = interpolate_scalingfactor(chip->rbatt_sf_lut, batt_temp, soc_rbatt_mohm); rbatt_mohm = (rbatt_mohm * scalefactor) / 100; rbatt_mohm += chip->r_conn_mohm; rbatt_mohm += chip->rbatt_capacitive_mohm; return rbatt_mohm; } #define IAVG_MINIMAL_TIME 2 static void calculate_iavg(struct qpnp_bms_chip *chip, int cc_uah, int *iavg_ua, int delta_time_s) { int delta_cc_uah = 0; /* * use the battery current if called too quickly */ if (delta_time_s < IAVG_MINIMAL_TIME || chip->last_cc_uah == INT_MIN) { get_battery_current(chip, iavg_ua); goto out; } delta_cc_uah = cc_uah - chip->last_cc_uah; *iavg_ua = div_s64((s64)delta_cc_uah * 3600, delta_time_s); out: pr_debug("delta_cc = %d iavg_ua = %d\n", delta_cc_uah, (int)*iavg_ua); /* remember cc_uah */ chip->last_cc_uah = cc_uah; } static int calculate_termination_uuc(struct qpnp_bms_chip *chip, struct soc_params *params, int batt_temp, int uuc_iavg_ma, int *ret_pc_unusable) { int unusable_uv, pc_unusable, uuc_uah; int i = 0; int ocv_mv; int batt_temp_degc = batt_temp / 10; int rbatt_mohm; int delta_uv; int prev_delta_uv = 0; int prev_rbatt_mohm = 0; int uuc_rbatt_mohm; for (i = 0; i <= 100; i++) { ocv_mv = interpolate_ocv(chip->pc_temp_ocv_lut, batt_temp_degc, i); rbatt_mohm = get_rbatt(chip, i, batt_temp); unusable_uv = (rbatt_mohm * uuc_iavg_ma) + (chip->v_cutoff_uv); delta_uv = ocv_mv * 1000 - unusable_uv; if (delta_uv > 0) break; prev_delta_uv = delta_uv; prev_rbatt_mohm = rbatt_mohm; } uuc_rbatt_mohm = linear_interpolate(rbatt_mohm, delta_uv, prev_rbatt_mohm, prev_delta_uv, 0); unusable_uv = (uuc_rbatt_mohm * uuc_iavg_ma) + (chip->v_cutoff_uv); pc_unusable = calculate_pc(chip, unusable_uv, batt_temp); uuc_uah = (params->fcc_uah * pc_unusable) / 100; pr_debug("For uuc_iavg_ma = %d, unusable_rbatt = %d unusable_uv = %d unusable_pc = %d rbatt_pc = %d uuc = %d\n", uuc_iavg_ma, uuc_rbatt_mohm, unusable_uv, pc_unusable, i, uuc_uah); *ret_pc_unusable = pc_unusable; return uuc_uah; } #define TIME_PER_PERCENT_UUC 60 static int adjust_uuc(struct qpnp_bms_chip *chip, struct soc_params *params, int new_pc_unusable, int new_uuc_uah, int batt_temp) { int new_unusable_mv, new_iavg_ma; int batt_temp_degc = batt_temp / 10; int max_percent_change; max_percent_change = max(params->delta_time_s / TIME_PER_PERCENT_UUC, 1); if (chip->prev_pc_unusable == -EINVAL || abs(chip->prev_pc_unusable - new_pc_unusable) <= max_percent_change) { chip->prev_pc_unusable = new_pc_unusable; return new_uuc_uah; } /* the uuc is trying to change more than 1% restrict it */ if (new_pc_unusable > chip->prev_pc_unusable) chip->prev_pc_unusable += max_percent_change; else chip->prev_pc_unusable -= max_percent_change; new_uuc_uah = (params->fcc_uah * chip->prev_pc_unusable) / 100; /* also find update the iavg_ma accordingly */ new_unusable_mv = interpolate_ocv(chip->pc_temp_ocv_lut, batt_temp_degc, chip->prev_pc_unusable); if (new_unusable_mv < chip->v_cutoff_uv/1000) new_unusable_mv = chip->v_cutoff_uv/1000; new_iavg_ma = (new_unusable_mv * 1000 - chip->v_cutoff_uv) / params->rbatt_mohm; if (new_iavg_ma == 0) new_iavg_ma = 1; chip->prev_uuc_iavg_ma = new_iavg_ma; pr_debug("Restricting UUC to %d (%d%%) unusable_mv = %d iavg_ma = %d\n", new_uuc_uah, chip->prev_pc_unusable, new_unusable_mv, new_iavg_ma); return new_uuc_uah; } #define MIN_IAVG_MA 250 static int calculate_unusable_charge_uah(struct qpnp_bms_chip *chip, struct soc_params *params, int batt_temp) { int uuc_uah_iavg; int i; int uuc_iavg_ma = params->iavg_ua / 1000; int pc_unusable; /* * if called first time, fill all the samples with * the shutdown_iavg_ma */ if (chip->first_time_calc_uuc && chip->shutdown_iavg_ma != 0) { pr_debug("Using shutdown_iavg_ma = %d in all samples\n", chip->shutdown_iavg_ma); for (i = 0; i < IAVG_SAMPLES; i++) chip->iavg_samples_ma[i] = chip->shutdown_iavg_ma; chip->iavg_index = 0; chip->iavg_num_samples = IAVG_SAMPLES; } if (params->delta_time_s >= IAVG_MINIMAL_TIME) { /* * if charging use a nominal avg current to keep * a reasonable UUC while charging */ if (uuc_iavg_ma < MIN_IAVG_MA) uuc_iavg_ma = MIN_IAVG_MA; chip->iavg_samples_ma[chip->iavg_index] = uuc_iavg_ma; chip->iavg_index = (chip->iavg_index + 1) % IAVG_SAMPLES; chip->iavg_num_samples++; if (chip->iavg_num_samples >= IAVG_SAMPLES) chip->iavg_num_samples = IAVG_SAMPLES; } /* now that this sample is added calcualte the average */ uuc_iavg_ma = 0; if (chip->iavg_num_samples != 0) { for (i = 0; i < chip->iavg_num_samples; i++) { pr_debug("iavg_samples_ma[%d] = %d\n", i, chip->iavg_samples_ma[i]); uuc_iavg_ma += chip->iavg_samples_ma[i]; } uuc_iavg_ma = DIV_ROUND_CLOSEST(uuc_iavg_ma, chip->iavg_num_samples); } /* * if we're in bms reset mode, force uuc to be 3% of fcc */ if (bms_reset) return (params->fcc_uah * 3) / 100; uuc_uah_iavg = calculate_termination_uuc(chip, params, batt_temp, uuc_iavg_ma, &pc_unusable); pr_debug("uuc_iavg_ma = %d uuc with iavg = %d\n", uuc_iavg_ma, uuc_uah_iavg); chip->prev_uuc_iavg_ma = uuc_iavg_ma; /* restrict the uuc such that it can increase only by one percent */ uuc_uah_iavg = adjust_uuc(chip, params, pc_unusable, uuc_uah_iavg, batt_temp); return uuc_uah_iavg; } static s64 find_ocv_charge_for_soc(struct qpnp_bms_chip *chip, struct soc_params *params, int soc) { return div_s64((s64)soc * (params->fcc_uah - params->uuc_uah), 100) + params->cc_uah + params->uuc_uah; } static int find_pc_for_soc(struct qpnp_bms_chip *chip, struct soc_params *params, int soc) { int ocv_charge_uah = find_ocv_charge_for_soc(chip, params, soc); int pc; pc = DIV_ROUND_CLOSEST((int)ocv_charge_uah * 100, params->fcc_uah); pc = clamp(pc, 0, 100); pr_debug("soc = %d, fcc = %d uuc = %d rc = %d pc = %d\n", soc, params->fcc_uah, params->uuc_uah, ocv_charge_uah, pc); return pc; } #define SIGN(x) ((x) < 0 ? -1 : 1) #define UV_PER_SPIN 50000 static int find_ocv_for_pc(struct qpnp_bms_chip *chip, int batt_temp, int pc) { int new_pc; int batt_temp_degc = batt_temp / 10; int ocv_mv; int delta_mv = 5; int max_spin_count; int count = 0; int sign, new_sign; ocv_mv = interpolate_ocv(chip->pc_temp_ocv_lut, batt_temp_degc, pc); new_pc = interpolate_pc(chip->pc_temp_ocv_lut, batt_temp_degc, ocv_mv); pr_debug("test revlookup pc = %d for ocv = %d\n", new_pc, ocv_mv); max_spin_count = 1 + (chip->max_voltage_uv - chip->v_cutoff_uv) / UV_PER_SPIN; sign = SIGN(pc - new_pc); while (abs(new_pc - pc) != 0 && count < max_spin_count) { /* * If the newly interpolated pc is larger than the lookup pc, * the ocv should be reduced and vice versa */ new_sign = SIGN(pc - new_pc); /* * If the sign has changed, then we have passed the lookup pc. * reduce the ocv step size to get finer results. * * If we have already reduced the ocv step size and still * passed the lookup pc, just stop and use the current ocv. * This can only happen if the batterydata profile is * non-monotonic anyways. */ if (new_sign != sign) { if (delta_mv > 1) delta_mv = 1; else break; } sign = new_sign; ocv_mv = ocv_mv + delta_mv * sign; new_pc = interpolate_pc(chip->pc_temp_ocv_lut, batt_temp_degc, ocv_mv); pr_debug("test revlookup pc = %d for ocv = %d\n", new_pc, ocv_mv); count++; } return ocv_mv * 1000; } static int get_current_time(unsigned long *now_tm_sec) { struct rtc_time tm; struct rtc_device *rtc; int rc; rtc = rtc_class_open(CONFIG_RTC_HCTOSYS_DEVICE); if (rtc == NULL) { pr_err("%s: unable to open rtc device (%s)\n", __FILE__, CONFIG_RTC_HCTOSYS_DEVICE); return -EINVAL; } rc = rtc_read_time(rtc, &tm); if (rc) { pr_err("Error reading rtc device (%s) : %d\n", CONFIG_RTC_HCTOSYS_DEVICE, rc); goto close_time; } rc = rtc_valid_tm(&tm); if (rc) { pr_err("Invalid RTC time (%s): %d\n", CONFIG_RTC_HCTOSYS_DEVICE, rc); goto close_time; } rtc_tm_to_time(&tm, now_tm_sec); close_time: rtc_class_close(rtc); return rc; } /* Returns estimated battery resistance */ static int get_prop_bms_batt_resistance(struct qpnp_bms_chip *chip) { return chip->rbatt_mohm * 1000; } /* Returns instantaneous current in uA */ static int get_prop_bms_current_now(struct qpnp_bms_chip *chip) { int rc, result_ua; rc = get_battery_current(chip, &result_ua); if (rc) { pr_err("failed to get current: %d\n", rc); return rc; } return result_ua; } /* Returns coulomb counter in uAh */ static int get_prop_bms_charge_counter(struct qpnp_bms_chip *chip) { int64_t cc_raw; mutex_lock(&chip->bms_output_lock); lock_output_data(chip); read_cc_raw(chip, &cc_raw, false); unlock_output_data(chip); mutex_unlock(&chip->bms_output_lock); return calculate_cc(chip, cc_raw, CC, NORESET); } /* Returns shadow coulomb counter in uAh */ static int get_prop_bms_charge_counter_shadow(struct qpnp_bms_chip *chip) { int64_t cc_raw; mutex_lock(&chip->bms_output_lock); lock_output_data(chip); read_cc_raw(chip, &cc_raw, true); unlock_output_data(chip); mutex_unlock(&chip->bms_output_lock); return calculate_cc(chip, cc_raw, SHDW_CC, NORESET); } /* Returns full charge design in uAh */ static int get_prop_bms_charge_full_design(struct qpnp_bms_chip *chip) { return chip->fcc_mah * 1000; } /* Returns the current full charge in uAh */ static int get_prop_bms_charge_full(struct qpnp_bms_chip *chip) { int rc; struct qpnp_vadc_result result; rc = qpnp_vadc_read(chip->vadc_dev, LR_MUX1_BATT_THERM, &result); if (rc) { pr_err("Unable to read battery temperature\n"); return rc; } return calculate_fcc(chip, (int)result.physical); } static int calculate_delta_time(unsigned long *time_stamp, int *delta_time_s) { unsigned long now_tm_sec = 0; /* default to delta time = 0 if anything fails */ *delta_time_s = 0; if (get_current_time(&now_tm_sec)) { pr_err("RTC read failed\n"); return 0; } *delta_time_s = (now_tm_sec - *time_stamp); /* remember this time */ *time_stamp = now_tm_sec; return 0; } static void calculate_soc_params(struct qpnp_bms_chip *chip, struct raw_soc_params *raw, struct soc_params *params, int batt_temp) { int soc_rbatt, shdw_cc_uah; calculate_delta_time(&chip->tm_sec, &params->delta_time_s); pr_debug("tm_sec = %ld, delta_s = %d\n", chip->tm_sec, params->delta_time_s); params->fcc_uah = calculate_fcc(chip, batt_temp); pr_debug("FCC = %uuAh batt_temp = %d\n", params->fcc_uah, batt_temp); /* calculate remainging charge */ params->ocv_charge_uah = calculate_ocv_charge( chip, raw, params->fcc_uah); pr_debug("ocv_charge_uah = %uuAh\n", params->ocv_charge_uah); /* calculate cc micro_volt_hour */ params->cc_uah = calculate_cc(chip, raw->cc, CC, RESET); shdw_cc_uah = calculate_cc(chip, raw->shdw_cc, SHDW_CC, RESET); pr_debug("cc_uah = %duAh raw->cc = %llx, shdw_cc_uah = %duAh raw->shdw_cc = %llx\n", params->cc_uah, raw->cc, shdw_cc_uah, raw->shdw_cc); soc_rbatt = ((params->ocv_charge_uah - params->cc_uah) * 100) / params->fcc_uah; if (soc_rbatt < 0) soc_rbatt = 0; params->rbatt_mohm = get_rbatt(chip, soc_rbatt, batt_temp); pr_debug("rbatt_mohm = %d\n", params->rbatt_mohm); if (params->rbatt_mohm != chip->rbatt_mohm) { chip->rbatt_mohm = params->rbatt_mohm; if (chip->bms_psy_registered) power_supply_changed(&chip->bms_psy); } calculate_iavg(chip, params->cc_uah, &params->iavg_ua, params->delta_time_s); params->uuc_uah = calculate_unusable_charge_uah(chip, params, batt_temp); pr_debug("UUC = %uuAh\n", params->uuc_uah); } static int bound_soc(int soc) { soc = max(0, soc); soc = min(100, soc); return soc; } #define IBAT_TOL_MASK 0x0F #define OCV_TOL_MASK 0xF0 #define IBAT_TOL_DEFAULT 0x03 #define IBAT_TOL_NOCHG 0x0F #define OCV_TOL_DEFAULT 0x20 #define OCV_TOL_NO_OCV 0x00 static int stop_ocv_updates(struct qpnp_bms_chip *chip) { pr_debug("stopping ocv updates\n"); return qpnp_masked_write(chip, BMS1_TOL_CTL, OCV_TOL_MASK, OCV_TOL_NO_OCV); } static int reset_bms_for_test(struct qpnp_bms_chip *chip) { int ibat_ua = 0, vbat_uv = 0, rc; int ocv_est_uv; if (!chip) { pr_err("BMS driver has not been initialized yet!\n"); return -EINVAL; } rc = get_simultaneous_batt_v_and_i(chip, &ibat_ua, &vbat_uv); /* * Don't include rbatt and rbatt_capacitative since we expect this to * be used with a fake battery which does not have internal resistances */ ocv_est_uv = vbat_uv + (ibat_ua * chip->r_conn_mohm) / 1000; pr_debug("forcing ocv to be %d due to bms reset mode\n", ocv_est_uv); chip->last_ocv_uv = ocv_est_uv; mutex_lock(&chip->last_soc_mutex); chip->last_soc = -EINVAL; chip->last_soc_invalid = true; mutex_unlock(&chip->last_soc_mutex); reset_cc(chip, CLEAR_CC | CLEAR_SHDW_CC); chip->software_cc_uah = 0; chip->software_shdw_cc_uah = 0; chip->last_cc_uah = INT_MIN; stop_ocv_updates(chip); pr_debug("bms reset to ocv = %duv vbat_ua = %d ibat_ua = %d\n", chip->last_ocv_uv, vbat_uv, ibat_ua); return rc; } /* Samsung wants to enable bms_reset via a api */ void bms_quickstart(void) { struct power_supply *bms_psy = power_supply_get_by_name("bms"); struct qpnp_bms_chip *chip = container_of(bms_psy, struct qpnp_bms_chip, bms_psy); int rc = 0; pr_err("bms quickstart is called\n"); rc = reset_bms_for_test(chip); if (rc) pr_err("%s : failed to reset BMS soc\n", __func__); /* * Set the flag to indicate bms_reset, this will set the * uuc to 3% and skip adjusting the soc */ bms_reset = 1; } EXPORT_SYMBOL_GPL(bms_quickstart); static int bms_reset_set(const char *val, const struct kernel_param *kp) { int rc; rc = param_set_bool(val, kp); if (rc) { pr_err("Unable to set bms_reset: %d\n", rc); return rc; } if (*(bool *)kp->arg) { struct power_supply *bms_psy = power_supply_get_by_name("bms"); struct qpnp_bms_chip *chip = container_of(bms_psy, struct qpnp_bms_chip, bms_psy); rc = reset_bms_for_test(chip); if (rc) { pr_err("Unable to modify bms_reset: %d\n", rc); return rc; } } return 0; } static struct kernel_param_ops bms_reset_ops = { .set = bms_reset_set, .get = param_get_bool, }; module_param_cb(bms_reset, &bms_reset_ops, &bms_reset, 0644); #define SOC_STORAGE_MASK 0xFE static void backup_soc_and_iavg(struct qpnp_bms_chip *chip, int batt_temp, int soc) { u8 temp; int rc; int iavg_ma = chip->prev_uuc_iavg_ma; if (iavg_ma > MIN_IAVG_MA) temp = (iavg_ma - MIN_IAVG_MA) / IAVG_STEP_SIZE_MA; else temp = 0; rc = qpnp_write_wrapper(chip, &temp, chip->base + IAVG_STORAGE_REG, 1); /* don't store soc if temperature is below 5degC */ if (batt_temp > IGNORE_SOC_TEMP_DECIDEG) qpnp_masked_write_base(chip, chip->soc_storage_addr, SOC_STORAGE_MASK, (soc + 1) << 1); } static int scale_soc_while_chg(struct qpnp_bms_chip *chip, int chg_time_sec, int catch_up_sec, int new_soc, int prev_soc) { int scaled_soc; int numerator; /* * Don't report a high value immediately slowly scale the * value from prev_soc to the new soc based on a charge time * weighted average */ pr_debug("cts = %d catch_up_sec = %d\n", chg_time_sec, catch_up_sec); if (catch_up_sec == 0) return new_soc; if (chg_time_sec > catch_up_sec) return new_soc; numerator = (catch_up_sec - chg_time_sec) * prev_soc + chg_time_sec * new_soc; scaled_soc = numerator / catch_up_sec; pr_debug("cts = %d new_soc = %d prev_soc = %d scaled_soc = %d\n", chg_time_sec, new_soc, prev_soc, scaled_soc); return scaled_soc; } /* * bms_fake_battery is set in setups where a battery emulator is used instead * of a real battery. This makes the bms driver report a different/fake value * regardless of the calculated state of charge. */ static int bms_fake_battery = -EINVAL; module_param(bms_fake_battery, int, 0644); static int report_voltage_based_soc(struct qpnp_bms_chip *chip) { pr_debug("Reported voltage based soc = %d\n", chip->prev_voltage_based_soc); return chip->prev_voltage_based_soc; } #define SOC_CATCHUP_SEC_MAX 600 #define SOC_CATCHUP_SEC_PER_PERCENT 60 #define MAX_CATCHUP_SOC (SOC_CATCHUP_SEC_MAX / SOC_CATCHUP_SEC_PER_PERCENT) #define SOC_CHANGE_PER_SEC 5 #define REPORT_SOC_WAIT_MS 10000 static int report_cc_based_soc(struct qpnp_bms_chip *chip) { int soc, soc_change; int time_since_last_change_sec, charge_time_sec = 0; unsigned long last_change_sec; struct timespec now; struct qpnp_vadc_result result; int batt_temp; int rc; bool charging, charging_since_last_report; rc = wait_event_interruptible_timeout(chip->bms_wait_queue, chip->calculated_soc != -EINVAL, round_jiffies_relative(msecs_to_jiffies (REPORT_SOC_WAIT_MS))); if (rc == 0 && chip->calculated_soc == -EINVAL) { pr_debug("calculate soc timed out\n"); } else if (rc == -ERESTARTSYS) { pr_err("Wait for SoC interrupted.\n"); return rc; } rc = qpnp_vadc_read(chip->vadc_dev, LR_MUX1_BATT_THERM, &result); if (rc) { pr_err("error reading adc channel = %d, rc = %d\n", LR_MUX1_BATT_THERM, rc); return rc; } pr_debug("batt_temp phy = %lld meas = 0x%llx\n", result.physical, result.measurement); batt_temp = (int)result.physical; mutex_lock(&chip->last_soc_mutex); soc = chip->calculated_soc; last_change_sec = chip->last_soc_change_sec; calculate_delta_time(&last_change_sec, &time_since_last_change_sec); charging = is_battery_charging(chip); charging_since_last_report = charging || (chip->last_soc_unbound && chip->was_charging_at_sleep); /* * account for charge time - limit it to SOC_CATCHUP_SEC to * avoid overflows when charging continues for extended periods */ if (charging) { if (chip->charge_start_tm_sec == 0) { /* * calculating soc for the first time * after start of chg. Initialize catchup time */ if (abs(soc - chip->last_soc) < MAX_CATCHUP_SOC) chip->catch_up_time_sec = (soc - chip->last_soc) * SOC_CATCHUP_SEC_PER_PERCENT; else chip->catch_up_time_sec = SOC_CATCHUP_SEC_MAX; if (chip->catch_up_time_sec < 0) chip->catch_up_time_sec = 0; chip->charge_start_tm_sec = last_change_sec; } charge_time_sec = min(SOC_CATCHUP_SEC_MAX, (int)last_change_sec - chip->charge_start_tm_sec); /* end catchup if calculated soc and last soc are same */ if (chip->last_soc == soc) chip->catch_up_time_sec = 0; } if (chip->last_soc != -EINVAL) { /* * last_soc < soc ... if we have not been charging at all * since the last time this was called, report previous SoC. * Otherwise, scale and catch up. */ if (chip->last_soc < soc && !charging_since_last_report) soc = chip->last_soc; else if (chip->last_soc < soc && soc != 100) soc = scale_soc_while_chg(chip, charge_time_sec, chip->catch_up_time_sec, soc, chip->last_soc); soc_change = min((int)abs(chip->last_soc - soc), time_since_last_change_sec / SOC_CHANGE_PER_SEC); if (chip->last_soc_unbound) { chip->last_soc_unbound = false; } else { /* * if soc have not been unbound by resume, * only change reported SoC by 1. */ soc_change = min(1, soc_change); } if (soc < chip->last_soc && soc != 0) soc = chip->last_soc - soc_change; if (soc > chip->last_soc && soc != 100) soc = chip->last_soc + soc_change; } if (chip->last_soc != soc && !chip->last_soc_unbound) chip->last_soc_change_sec = last_change_sec; pr_debug("last_soc = %d, calculated_soc = %d, soc = %d, time since last change = %d\n", chip->last_soc, chip->calculated_soc, soc, time_since_last_change_sec); chip->last_soc = bound_soc(soc); backup_soc_and_iavg(chip, batt_temp, chip->last_soc); pr_debug("Reported SOC = %d\n", chip->last_soc); chip->t_soc_queried = now; mutex_unlock(&chip->last_soc_mutex); return soc; } static int report_state_of_charge(struct qpnp_bms_chip *chip) { if (bms_fake_battery != -EINVAL) { pr_debug("Returning Fake SOC = %d%%\n", bms_fake_battery); return bms_fake_battery; } else if (chip->use_voltage_soc) return report_voltage_based_soc(chip); else return report_cc_based_soc(chip); } #define VDD_MAX_ERR 5000 #define VDD_STEP_SIZE 10000 #define MAX_COUNT_BEFORE_RESET_TO_CC 3 static int charging_adjustments(struct qpnp_bms_chip *chip, struct soc_params *params, int soc, int vbat_uv, int ibat_ua, int batt_temp) { int chg_soc, soc_ibat, batt_terminal_uv, weight_ibat, weight_cc; batt_terminal_uv = vbat_uv + (ibat_ua * chip->r_conn_mohm) / 1000; if (chip->soc_at_cv == -EINVAL) { if (batt_terminal_uv >= chip->max_voltage_uv - VDD_MAX_ERR) { chip->soc_at_cv = soc; chip->prev_chg_soc = soc; chip->ibat_at_cv_ua = params->iavg_ua; pr_debug("CC_TO_CV ibat_ua = %d CHG SOC %d\n", ibat_ua, soc); } else { /* In constant current charging return the calc soc */ pr_debug("CC CHG SOC %d\n", soc); } chip->prev_batt_terminal_uv = batt_terminal_uv; chip->system_load_count = 0; return soc; } else if (ibat_ua > 0 && batt_terminal_uv < chip->max_voltage_uv - (VDD_MAX_ERR * 2)) { if (chip->system_load_count > MAX_COUNT_BEFORE_RESET_TO_CC) { chip->soc_at_cv = -EINVAL; pr_debug("Vbat below CV threshold, resetting CC_TO_CV\n"); chip->system_load_count = 0; } else { chip->system_load_count += 1; pr_debug("Vbat below CV threshold, count: %d\n", chip->system_load_count); } return soc; } else if (ibat_ua > 0) { pr_debug("NOT CHARGING SOC %d\n", soc); chip->system_load_count = 0; chip->prev_chg_soc = soc; return soc; } chip->system_load_count = 0; /* * battery is in CV phase - begin linear interpolation of soc based on * battery charge current */ /* * if voltage lessened (possibly because of a system load) * keep reporting the prev chg soc */ if (batt_terminal_uv <= chip->prev_batt_terminal_uv - VDD_STEP_SIZE) { pr_debug("batt_terminal_uv %d < (max = %d - 10000); CC CHG SOC %d\n", batt_terminal_uv, chip->prev_batt_terminal_uv, chip->prev_chg_soc); chip->prev_batt_terminal_uv = batt_terminal_uv; return chip->prev_chg_soc; } soc_ibat = bound_soc(linear_interpolate(chip->soc_at_cv, chip->ibat_at_cv_ua, 100, -1 * chip->chg_term_ua, params->iavg_ua)); weight_ibat = bound_soc(linear_interpolate(1, chip->soc_at_cv, 100, 100, chip->prev_chg_soc)); weight_cc = 100 - weight_ibat; chg_soc = bound_soc(DIV_ROUND_CLOSEST(soc_ibat * weight_ibat + weight_cc * soc, 100)); pr_debug("weight_ibat = %d, weight_cc = %d, soc_ibat = %d, soc_cc = %d\n", weight_ibat, weight_cc, soc_ibat, soc); /* always report a higher soc */ if (chg_soc > chip->prev_chg_soc) { chip->prev_chg_soc = chg_soc; chip->charging_adjusted_ocv = find_ocv_for_pc(chip, batt_temp, find_pc_for_soc(chip, params, chg_soc)); pr_debug("CC CHG ADJ OCV = %d CHG SOC %d\n", chip->charging_adjusted_ocv, chip->prev_chg_soc); } pr_debug("Reporting CHG SOC %d\n", chip->prev_chg_soc); chip->prev_batt_terminal_uv = batt_terminal_uv; return chip->prev_chg_soc; } static void very_low_voltage_check(struct qpnp_bms_chip *chip, int vbat_uv) { /* * if battery is very low (v_cutoff voltage + 20mv) hold * a wakelock untill soc = 0% */ if (vbat_uv <= chip->low_voltage_threshold && !wake_lock_active(&chip->low_voltage_wake_lock)) { pr_debug("voltage = %d low holding wakelock\n", vbat_uv); wake_lock(&chip->low_voltage_wake_lock); } else if (vbat_uv > chip->low_voltage_threshold && wake_lock_active(&chip->low_voltage_wake_lock)) { pr_debug("voltage = %d releasing wakelock\n", vbat_uv); wake_unlock(&chip->low_voltage_wake_lock); } } #define VBATT_ERROR_MARGIN 20000 static void cv_voltage_check(struct qpnp_bms_chip *chip, int vbat_uv) { /* * if battery is very low (v_cutoff voltage + 20mv) hold * a wakelock untill soc = 0% */ if (wake_lock_active(&chip->cv_wake_lock)) { if (chip->soc_at_cv != -EINVAL) { pr_debug("hit CV, releasing cv wakelock\n"); wake_unlock(&chip->cv_wake_lock); } else if (!is_battery_charging(chip)) { pr_debug("charging stopped, releasing cv wakelock\n"); wake_unlock(&chip->cv_wake_lock); } } else if (vbat_uv > chip->max_voltage_uv - VBATT_ERROR_MARGIN && chip->soc_at_cv == -EINVAL && is_battery_charging(chip) && !wake_lock_active(&chip->cv_wake_lock)) { pr_debug("voltage = %d holding cv wakelock\n", vbat_uv); wake_lock(&chip->cv_wake_lock); } } #define NO_ADJUST_HIGH_SOC_THRESHOLD 90 static int adjust_soc(struct qpnp_bms_chip *chip, struct soc_params *params, int soc, int batt_temp) { int ibat_ua = 0, vbat_uv = 0; int ocv_est_uv = 0, soc_est = 0, pc_est = 0, pc = 0; int delta_ocv_uv = 0; int n = 0; int rc_new_uah = 0; int pc_new = 0; int soc_new = 0; int slope = 0; int rc = 0; int delta_ocv_uv_limit = 0; int correction_limit_uv = 0; rc = get_simultaneous_batt_v_and_i(chip, &ibat_ua, &vbat_uv); if (rc < 0) { pr_err("simultaneous vbat ibat failed err = %d\n", rc); goto out; } very_low_voltage_check(chip, vbat_uv); cv_voltage_check(chip, vbat_uv); delta_ocv_uv_limit = DIV_ROUND_CLOSEST(ibat_ua, 1000); ocv_est_uv = vbat_uv + (ibat_ua * params->rbatt_mohm)/1000; pc_est = calculate_pc(chip, ocv_est_uv, batt_temp); soc_est = div_s64((s64)params->fcc_uah * pc_est - params->uuc_uah*100, (s64)params->fcc_uah - params->uuc_uah); soc_est = bound_soc(soc_est); /* never adjust during bms reset mode */ if (bms_reset) { pr_debug("bms reset mode, SOC adjustment skipped\n"); goto out; } if (is_battery_charging(chip)) { soc = charging_adjustments(chip, params, soc, vbat_uv, ibat_ua, batt_temp); /* Skip adjustments if we are in CV or ibat is negative */ if (chip->soc_at_cv != -EINVAL || ibat_ua < 0) goto out; } /* * do not adjust * if soc_est is same as what bms calculated * OR if soc_est > adjust_soc_low_threshold * OR if soc is above 90 * because we might pull it low * and cause a bad user experience */ if (soc_est == soc || soc_est > chip->adjust_soc_low_threshold || soc >= NO_ADJUST_HIGH_SOC_THRESHOLD) goto out; if (chip->last_soc_est == -EINVAL) chip->last_soc_est = soc; n = min(200, max(1 , soc + soc_est + chip->last_soc_est)); chip->last_soc_est = soc_est; pc = calculate_pc(chip, chip->last_ocv_uv, chip->last_ocv_temp); if (pc > 0) { pc_new = calculate_pc(chip, chip->last_ocv_uv - (++slope * 1000), chip->last_ocv_temp); while (pc_new == pc) { /* start taking 10mV steps */ slope = slope + 10; pc_new = calculate_pc(chip, chip->last_ocv_uv - (slope * 1000), chip->last_ocv_temp); } } else { /* * pc is already at the lowest point, * assume 1 millivolt translates to 1% pc */ pc = 1; pc_new = 0; slope = 1; } delta_ocv_uv = div_s64((soc - soc_est) * (s64)slope * 1000, n * (pc - pc_new)); if (abs(delta_ocv_uv) > delta_ocv_uv_limit) { pr_debug("limiting delta ocv %d limit = %d\n", delta_ocv_uv, delta_ocv_uv_limit); if (delta_ocv_uv > 0) delta_ocv_uv = delta_ocv_uv_limit; else delta_ocv_uv = -1 * delta_ocv_uv_limit; pr_debug("new delta ocv = %d\n", delta_ocv_uv); } if (wake_lock_active(&chip->low_voltage_wake_lock)) goto skip_limits; if (chip->last_ocv_uv > chip->flat_ocv_threshold_uv) correction_limit_uv = chip->high_ocv_correction_limit_uv; else correction_limit_uv = chip->low_ocv_correction_limit_uv; if (abs(delta_ocv_uv) > correction_limit_uv) { pr_debug("limiting delta ocv %d limit = %d\n", delta_ocv_uv, correction_limit_uv); if (delta_ocv_uv > 0) delta_ocv_uv = correction_limit_uv; else delta_ocv_uv = -correction_limit_uv; pr_debug("new delta ocv = %d\n", delta_ocv_uv); } skip_limits: chip->last_ocv_uv -= delta_ocv_uv; if (chip->last_ocv_uv >= chip->max_voltage_uv) chip->last_ocv_uv = chip->max_voltage_uv; /* calculate the soc based on this new ocv */ pc_new = calculate_pc(chip, chip->last_ocv_uv, chip->last_ocv_temp); rc_new_uah = (params->fcc_uah * pc_new) / 100; soc_new = (rc_new_uah - params->cc_uah - params->uuc_uah)*100 / (params->fcc_uah - params->uuc_uah); soc_new = bound_soc(soc_new); /* * if soc_new is ZERO force it higher so that phone doesnt report soc=0 * soc = 0 should happen only when soc_est is above a set value */ if (soc_new == 0 && soc_est >= chip->hold_soc_est) soc_new = 1; soc = soc_new; out: pr_debug("ibat_ua = %d, vbat_uv = %d, ocv_est_uv = %d, pc_est = %d, soc_est = %d, n = %d, delta_ocv_uv = %d, last_ocv_uv = %d, pc_new = %d, soc_new = %d, rbatt = %d, slope = %d\n", ibat_ua, vbat_uv, ocv_est_uv, pc_est, soc_est, n, delta_ocv_uv, chip->last_ocv_uv, pc_new, soc_new, params->rbatt_mohm, slope); return soc; } static int clamp_soc_based_on_voltage(struct qpnp_bms_chip *chip, int soc) { int rc, vbat_uv; rc = get_battery_voltage(chip, &vbat_uv); if (rc < 0) { pr_err("adc vbat failed err = %d\n", rc); return soc; } if (soc == 0 && vbat_uv > chip->v_cutoff_uv) { pr_debug("clamping soc to 1, vbat (%d) > cutoff (%d)\n", vbat_uv, chip->v_cutoff_uv); return 1; } else { pr_debug("not clamping, using soc = %d, vbat = %d and cutoff = %d\n", soc, vbat_uv, chip->v_cutoff_uv); return soc; } } static int64_t convert_cc_uah_to_raw(struct qpnp_bms_chip *chip, int64_t cc_uah) { int64_t cc_uv, cc_pvh, cc_raw; cc_pvh = cc_uah * chip->r_sense_uohm; cc_uv = div_s64(cc_pvh * SLEEP_CLK_HZ * SECONDS_PER_HOUR, CC_READING_TICKS * 1000000LL); cc_raw = div_s64(cc_uv * CC_READING_RESOLUTION_D, CC_READING_RESOLUTION_N); return cc_raw; } #define CC_STEP_INCREMENT_UAH 1500 #define OCV_STEP_INCREMENT 0x10 static void configure_soc_wakeup(struct qpnp_bms_chip *chip, struct soc_params *params, int batt_temp, int target_soc) { int target_ocv_uv; int64_t target_cc_uah, cc_raw_64, current_shdw_cc_raw_64; int64_t current_shdw_cc_uah, iadc_comp_factor; uint64_t cc_raw, current_shdw_cc_raw; int16_t ocv_raw, current_ocv_raw; current_shdw_cc_raw = 0; mutex_lock(&chip->bms_output_lock); lock_output_data(chip); qpnp_read_wrapper(chip, (u8 *)&current_ocv_raw, chip->base + BMS1_OCV_FOR_SOC_DATA0, 2); unlock_output_data(chip); mutex_unlock(&chip->bms_output_lock); current_shdw_cc_uah = get_prop_bms_charge_counter_shadow(chip); current_shdw_cc_raw_64 = convert_cc_uah_to_raw(chip, current_shdw_cc_uah); /* * Calculate the target shadow coulomb counter threshold for when * the SoC changes. * * Since the BMS driver resets the shadow coulomb counter every * 20 seconds when the device is awake, calculate the threshold as * a delta from the current shadow coulomb count. */ target_cc_uah = (100 - target_soc) * (params->fcc_uah - params->uuc_uah) / 100 - current_shdw_cc_uah; if (target_cc_uah < 0) { /* * If the target cc is below 0, that means we have already * passed the point where SoC should have fallen. * Set a wakeup in a few more mAh and check back again */ target_cc_uah = CC_STEP_INCREMENT_UAH; } iadc_comp_factor = 100000; qpnp_iadc_comp_result(chip->iadc_dev, &iadc_comp_factor); target_cc_uah = div64_s64(target_cc_uah * 100000, iadc_comp_factor); target_cc_uah = cc_reverse_adjust_for_gain(chip, target_cc_uah); cc_raw_64 = convert_cc_uah_to_raw(chip, target_cc_uah); cc_raw = convert_s64_to_s36(cc_raw_64); target_ocv_uv = find_ocv_for_pc(chip, batt_temp, find_pc_for_soc(chip, params, target_soc)); ocv_raw = convert_vbatt_uv_to_raw(chip, target_ocv_uv); /* * If the current_ocv_raw was updated since reaching 100% and is lower * than the calculated target ocv threshold, set the new target * threshold 1.5mAh lower in order to check if the SoC changed yet. */ if (current_ocv_raw != chip->ocv_reading_at_100 && current_ocv_raw < ocv_raw) ocv_raw = current_ocv_raw - OCV_STEP_INCREMENT; qpnp_write_wrapper(chip, (u8 *)&cc_raw, chip->base + BMS1_SW_CC_THR0, 5); qpnp_write_wrapper(chip, (u8 *)&ocv_raw, chip->base + BMS1_OCV_THR0, 2); pr_debug("current sw_cc_raw = 0x%llx, current ocv = 0x%hx\n", current_shdw_cc_raw, (uint16_t)current_ocv_raw); pr_debug("target_cc_uah = %lld, raw64 = 0x%llx, raw 36 = 0x%llx, ocv_raw = 0x%hx\n", target_cc_uah, (uint64_t)cc_raw_64, cc_raw, (uint16_t)ocv_raw); } static int calculate_raw_soc(struct qpnp_bms_chip *chip, struct raw_soc_params *raw, struct soc_params *params, int batt_temp) { int soc, remaining_usable_charge_uah; /* calculate remaining usable charge */ remaining_usable_charge_uah = params->ocv_charge_uah - params->cc_uah - params->uuc_uah; pr_debug("RUC = %duAh\n", remaining_usable_charge_uah); soc = DIV_ROUND_CLOSEST((remaining_usable_charge_uah * 100), (params->fcc_uah - params->uuc_uah)); if (chip->first_time_calc_soc && soc < 0) { /* * first time calcualtion and the pon ocv is too low resulting * in a bad soc. Adjust ocv to get 0 soc */ pr_debug("soc is %d, adjusting pon ocv to make it 0\n", soc); chip->last_ocv_uv = find_ocv_for_pc(chip, batt_temp, find_pc_for_soc(chip, params, 0)); params->ocv_charge_uah = find_ocv_charge_for_soc(chip, params, 0); remaining_usable_charge_uah = params->ocv_charge_uah - params->cc_uah - params->uuc_uah; soc = DIV_ROUND_CLOSEST((remaining_usable_charge_uah * 100), (params->fcc_uah - params->uuc_uah)); pr_debug("DONE for O soc is %d, pon ocv adjusted to %duV\n", soc, chip->last_ocv_uv); } if (soc > 100) soc = 100; if (soc < 0) { pr_debug("bad rem_usb_chg = %d rem_chg %d, cc_uah %d, unusb_chg %d\n", remaining_usable_charge_uah, params->ocv_charge_uah, params->cc_uah, params->uuc_uah); pr_debug("for bad rem_usb_chg last_ocv_uv = %d batt_temp = %d fcc = %d soc =%d\n", chip->last_ocv_uv, batt_temp, params->fcc_uah, soc); soc = 0; } return soc; } static int calculate_soc_from_voltage(struct qpnp_bms_chip *chip) { int voltage_range_uv, voltage_remaining_uv, voltage_based_soc; int rc, vbat_uv; rc = get_battery_voltage(chip, &vbat_uv); if (rc < 0) { pr_err("adc vbat failed err = %d\n", rc); return rc; } voltage_range_uv = chip->max_voltage_uv - chip->v_cutoff_uv; voltage_remaining_uv = vbat_uv - chip->v_cutoff_uv; voltage_based_soc = voltage_remaining_uv * 100 / voltage_range_uv; voltage_based_soc = clamp(voltage_based_soc, 0, 100); if (chip->prev_voltage_based_soc != voltage_based_soc && chip->bms_psy_registered) { power_supply_changed(&chip->bms_psy); pr_debug("power supply changed\n"); } chip->prev_voltage_based_soc = voltage_based_soc; pr_debug("vbat used = %duv\n", vbat_uv); pr_debug("Calculated voltage based soc = %d\n", voltage_based_soc); return voltage_based_soc; } #define SLEEP_RECALC_INTERVAL 3 static int calculate_state_of_charge(struct qpnp_bms_chip *chip, struct raw_soc_params *raw, int batt_temp) { struct soc_params params; int soc, previous_soc, shutdown_soc, new_calculated_soc; int remaining_usable_charge_uah; calculate_soc_params(chip, raw, &params, batt_temp); if (!is_battery_present(chip)) { #if defined(CONFIG_BATTERY_SAMSUNG) pr_debug("battery gone, reporting SOC based on voltage\n"); new_calculated_soc = calculate_soc_from_voltage(chip); #else pr_debug("battery gone, reporting 100\n"); new_calculated_soc = 100; #endif goto done_calculating; } if (params.fcc_uah - params.uuc_uah <= 0) { pr_debug("FCC = %duAh, UUC = %duAh forcing soc = 0\n", params.fcc_uah, params.uuc_uah); new_calculated_soc = 0; goto done_calculating; } soc = calculate_raw_soc(chip, raw, &params, batt_temp); mutex_lock(&chip->soc_invalidation_mutex); shutdown_soc = chip->shutdown_soc; if (chip->first_time_calc_soc && soc != shutdown_soc && !chip->shutdown_soc_invalid) { /* * soc for the first time - use shutdown soc * to adjust pon ocv since it is a small percent away from * the real soc */ pr_debug("soc = %d before forcing shutdown_soc = %d\n", soc, shutdown_soc); chip->last_ocv_uv = find_ocv_for_pc(chip, batt_temp, find_pc_for_soc(chip, &params, shutdown_soc)); params.ocv_charge_uah = find_ocv_charge_for_soc(chip, &params, shutdown_soc); remaining_usable_charge_uah = params.ocv_charge_uah - params.cc_uah - params.uuc_uah; soc = DIV_ROUND_CLOSEST((remaining_usable_charge_uah * 100), (params.fcc_uah - params.uuc_uah)); pr_debug("DONE for shutdown_soc = %d soc is %d, adjusted ocv to %duV\n", shutdown_soc, soc, chip->last_ocv_uv); } mutex_unlock(&chip->soc_invalidation_mutex); pr_debug("SOC before adjustment = %d\n", soc); new_calculated_soc = adjust_soc(chip, &params, soc, batt_temp); /* always clamp soc due to BMS hw/sw immaturities */ new_calculated_soc = clamp_soc_based_on_voltage(chip, new_calculated_soc); /* * If the battery is full, configure the cc threshold so the system * wakes up after SoC changes */ if (is_battery_full(chip)) configure_soc_wakeup(chip, &params, batt_temp, bound_soc(new_calculated_soc - 1)); done_calculating: mutex_lock(&chip->last_soc_mutex); previous_soc = chip->calculated_soc; chip->calculated_soc = new_calculated_soc; pr_debug("CC based calculated SOC = %d\n", chip->calculated_soc); if (chip->last_soc_invalid) { chip->last_soc_invalid = false; chip->last_soc = -EINVAL; } /* * Check if more than a long time has passed since the last * calculation (more than n times compared to the soc recalculation * rate, where n is defined by SLEEP_RECALC_INTERVAL). If this is true, * then the system must have gone through a long sleep, and SoC can be * allowed to become unbounded by the last reported SoC */ if (params.delta_time_s * 1000 > chip->calculate_soc_ms * SLEEP_RECALC_INTERVAL && !chip->first_time_calc_soc) { chip->last_soc_unbound = true; chip->last_soc_change_sec = chip->last_recalc_time; pr_debug("last_soc unbound because elapsed time = %d\n", params.delta_time_s); } mutex_unlock(&chip->last_soc_mutex); wake_up_interruptible(&chip->bms_wait_queue); if (new_calculated_soc != previous_soc && chip->bms_psy_registered) { power_supply_changed(&chip->bms_psy); pr_debug("power supply changed\n"); } else { /* * Call report state of charge anyways to periodically update * reported SoC. This prevents reported SoC from being stuck * when calculated soc doesn't change. */ report_state_of_charge(chip); } get_current_time(&chip->last_recalc_time); chip->first_time_calc_soc = 0; chip->first_time_calc_uuc = 0; return chip->calculated_soc; } static int recalculate_raw_soc(struct qpnp_bms_chip *chip) { int batt_temp, rc, soc; struct qpnp_vadc_result result; struct raw_soc_params raw; struct soc_params params; bms_stay_awake(&chip->soc_wake_source); if (chip->use_voltage_soc) { soc = calculate_soc_from_voltage(chip); } else { if (!chip->batfet_closed) qpnp_iadc_calibrate_for_trim(chip->iadc_dev, true); rc = qpnp_vadc_read(chip->vadc_dev, LR_MUX1_BATT_THERM, &result); if (rc) { pr_err("error reading vadc LR_MUX1_BATT_THERM = %d, rc = %d\n", LR_MUX1_BATT_THERM, rc); soc = chip->calculated_soc; } else { pr_debug("batt_temp phy = %lld meas = 0x%llx\n", result.physical, result.measurement); batt_temp = (int)result.physical; mutex_lock(&chip->last_ocv_uv_mutex); read_soc_params_raw(chip, &raw, batt_temp); calculate_soc_params(chip, &raw, &params, batt_temp); if (!is_battery_present(chip)) { pr_debug("battery gone\n"); soc = 0; } else if (params.fcc_uah - params.uuc_uah <= 0) { pr_debug("FCC = %duAh, UUC = %duAh forcing soc = 0\n", params.fcc_uah, params.uuc_uah); soc = 0; } else { soc = calculate_raw_soc(chip, &raw, &params, batt_temp); } mutex_unlock(&chip->last_ocv_uv_mutex); } } bms_relax(&chip->soc_wake_source); return soc; } static int recalculate_soc(struct qpnp_bms_chip *chip) { int batt_temp, rc, soc; struct qpnp_vadc_result result; struct raw_soc_params raw; bms_stay_awake(&chip->soc_wake_source); mutex_lock(&chip->vbat_monitor_mutex); if (chip->vbat_monitor_params.state_request != ADC_TM_HIGH_LOW_THR_DISABLE) qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->vbat_monitor_params); mutex_unlock(&chip->vbat_monitor_mutex); if (chip->use_voltage_soc) { soc = calculate_soc_from_voltage(chip); } else { if (!chip->batfet_closed) qpnp_iadc_calibrate_for_trim(chip->iadc_dev, true); rc = qpnp_vadc_read(chip->vadc_dev, LR_MUX1_BATT_THERM, &result); if (rc) { pr_err("error reading vadc LR_MUX1_BATT_THERM = %d, rc = %d\n", LR_MUX1_BATT_THERM, rc); soc = chip->calculated_soc; } else { pr_debug("batt_temp phy = %lld meas = 0x%llx\n", result.physical, result.measurement); batt_temp = (int)result.physical; mutex_lock(&chip->last_ocv_uv_mutex); read_soc_params_raw(chip, &raw, batt_temp); soc = calculate_state_of_charge(chip, &raw, batt_temp); mutex_unlock(&chip->last_ocv_uv_mutex); } } bms_relax(&chip->soc_wake_source); return soc; } static void recalculate_work(struct work_struct *work) { struct qpnp_bms_chip *chip = container_of(work, struct qpnp_bms_chip, recalc_work); recalculate_soc(chip); } static int get_calculation_delay_ms(struct qpnp_bms_chip *chip) { if (wake_lock_active(&chip->low_voltage_wake_lock)) return chip->low_voltage_calculate_soc_ms; else if (chip->calculated_soc < chip->low_soc_calc_threshold) return chip->low_soc_calculate_soc_ms; else return chip->calculate_soc_ms; } static void calculate_soc_work(struct work_struct *work) { struct qpnp_bms_chip *chip = container_of(work, struct qpnp_bms_chip, calculate_soc_delayed_work.work); recalculate_soc(chip); schedule_delayed_work(&chip->calculate_soc_delayed_work, round_jiffies_relative(msecs_to_jiffies (get_calculation_delay_ms(chip)))); } static void configure_vbat_monitor_low(struct qpnp_bms_chip *chip) { mutex_lock(&chip->vbat_monitor_mutex); if (chip->vbat_monitor_params.state_request == ADC_TM_HIGH_LOW_THR_ENABLE) { /* * Battery is now around or below v_cutoff */ pr_debug("battery entered cutoff range\n"); if (!wake_lock_active(&chip->low_voltage_wake_lock)) { pr_debug("voltage low, holding wakelock\n"); wake_lock(&chip->low_voltage_wake_lock); cancel_delayed_work_sync( &chip->calculate_soc_delayed_work); schedule_delayed_work( &chip->calculate_soc_delayed_work, 0); } chip->vbat_monitor_params.state_request = ADC_TM_HIGH_THR_ENABLE; chip->vbat_monitor_params.high_thr = (chip->low_voltage_threshold + VBATT_ERROR_MARGIN); pr_debug("set low thr to %d and high to %d\n", chip->vbat_monitor_params.low_thr, chip->vbat_monitor_params.high_thr); chip->vbat_monitor_params.low_thr = 0; } else if (chip->vbat_monitor_params.state_request == ADC_TM_LOW_THR_ENABLE) { /* * Battery is in normal operation range. */ pr_debug("battery entered normal range\n"); if (wake_lock_active(&chip->cv_wake_lock)) { wake_unlock(&chip->cv_wake_lock); pr_debug("releasing cv wake lock\n"); } chip->in_cv_range = false; chip->vbat_monitor_params.state_request = ADC_TM_HIGH_LOW_THR_ENABLE; chip->vbat_monitor_params.high_thr = chip->max_voltage_uv - VBATT_ERROR_MARGIN; chip->vbat_monitor_params.low_thr = chip->low_voltage_threshold; pr_debug("set low thr to %d and high to %d\n", chip->vbat_monitor_params.low_thr, chip->vbat_monitor_params.high_thr); } qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->vbat_monitor_params); mutex_unlock(&chip->vbat_monitor_mutex); } #define CV_LOW_THRESHOLD_HYST_UV 100000 static void configure_vbat_monitor_high(struct qpnp_bms_chip *chip) { mutex_lock(&chip->vbat_monitor_mutex); if (chip->vbat_monitor_params.state_request == ADC_TM_HIGH_LOW_THR_ENABLE) { /* * Battery is around vddmax */ pr_debug("battery entered vddmax range\n"); chip->in_cv_range = true; if (!wake_lock_active(&chip->cv_wake_lock)) { wake_lock(&chip->cv_wake_lock); pr_debug("holding cv wake lock\n"); } schedule_work(&chip->recalc_work); chip->vbat_monitor_params.state_request = ADC_TM_LOW_THR_ENABLE; chip->vbat_monitor_params.low_thr = (chip->max_voltage_uv - CV_LOW_THRESHOLD_HYST_UV); chip->vbat_monitor_params.high_thr = chip->max_voltage_uv * 2; pr_debug("set low thr to %d and high to %d\n", chip->vbat_monitor_params.low_thr, chip->vbat_monitor_params.high_thr); } else if (chip->vbat_monitor_params.state_request == ADC_TM_HIGH_THR_ENABLE) { /* * Battery is in normal operation range. */ pr_debug("battery entered normal range\n"); if (wake_lock_active(&chip->low_voltage_wake_lock)) { pr_debug("voltage high, releasing wakelock\n"); wake_unlock(&chip->low_voltage_wake_lock); } chip->vbat_monitor_params.state_request = ADC_TM_HIGH_LOW_THR_ENABLE; chip->vbat_monitor_params.high_thr = chip->max_voltage_uv - VBATT_ERROR_MARGIN; chip->vbat_monitor_params.low_thr = chip->low_voltage_threshold; pr_debug("set low thr to %d and high to %d\n", chip->vbat_monitor_params.low_thr, chip->vbat_monitor_params.high_thr); } qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->vbat_monitor_params); mutex_unlock(&chip->vbat_monitor_mutex); } static void btm_notify_vbat(enum qpnp_tm_state state, void *ctx) { struct qpnp_bms_chip *chip = ctx; int vbat_uv; struct qpnp_vadc_result result; int rc; rc = qpnp_vadc_read(chip->vadc_dev, VBAT_SNS, &result); pr_debug("vbat = %lld, raw = 0x%x\n", result.physical, result.adc_code); get_battery_voltage(chip, &vbat_uv); pr_debug("vbat is at %d, state is at %d\n", vbat_uv, state); if (state == ADC_TM_LOW_STATE) { pr_debug("low voltage btm notification triggered\n"); if (vbat_uv - VBATT_ERROR_MARGIN < chip->vbat_monitor_params.low_thr) { configure_vbat_monitor_low(chip); } else { pr_debug("faulty btm trigger, discarding\n"); qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->vbat_monitor_params); } } else if (state == ADC_TM_HIGH_STATE) { pr_debug("high voltage btm notification triggered\n"); if (vbat_uv + VBATT_ERROR_MARGIN > chip->vbat_monitor_params.high_thr) { configure_vbat_monitor_high(chip); } else { pr_debug("faulty btm trigger, discarding\n"); qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->vbat_monitor_params); } } else { pr_debug("unknown voltage notification state: %d\n", state); } if (chip->bms_psy_registered) power_supply_changed(&chip->bms_psy); } static int reset_vbat_monitoring(struct qpnp_bms_chip *chip) { int rc; chip->vbat_monitor_params.state_request = ADC_TM_HIGH_LOW_THR_DISABLE; rc = qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->vbat_monitor_params); if (rc) { pr_err("tm disable failed: %d\n", rc); return rc; } if (wake_lock_active(&chip->low_voltage_wake_lock)) { pr_debug("battery removed, releasing wakelock\n"); wake_unlock(&chip->low_voltage_wake_lock); } if (chip->in_cv_range) { pr_debug("battery removed, removing in_cv_range state\n"); chip->in_cv_range = false; } return 0; } static int setup_vbat_monitoring(struct qpnp_bms_chip *chip) { int rc; chip->vbat_monitor_params.low_thr = chip->low_voltage_threshold; chip->vbat_monitor_params.high_thr = chip->max_voltage_uv - VBATT_ERROR_MARGIN; chip->vbat_monitor_params.state_request = ADC_TM_HIGH_LOW_THR_ENABLE; chip->vbat_monitor_params.channel = VBAT_SNS; chip->vbat_monitor_params.btm_ctx = (void *)chip; chip->vbat_monitor_params.timer_interval = ADC_MEAS1_INTERVAL_1S; chip->vbat_monitor_params.threshold_notification = &btm_notify_vbat; pr_debug("set low thr to %d and high to %d\n", chip->vbat_monitor_params.low_thr, chip->vbat_monitor_params.high_thr); if (!is_battery_present(chip)) { pr_debug("no battery inserted, do not enable vbat monitoring\n"); chip->vbat_monitor_params.state_request = ADC_TM_HIGH_LOW_THR_DISABLE; } else { rc = qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->vbat_monitor_params); if (rc) { pr_err("tm setup failed: %d\n", rc); return rc; } } pr_debug("setup complete\n"); return 0; } static void readjust_fcc_table(struct qpnp_bms_chip *chip) { struct single_row_lut *temp, *old; int i, fcc, ratio; if (!chip->enable_fcc_learning) return; if (!chip->fcc_temp_lut) { pr_err("The static fcc lut table is NULL\n"); return; } temp = devm_kzalloc(chip->dev, sizeof(struct single_row_lut), GFP_KERNEL); if (!temp) { pr_err("Cannot allocate memory for adjusted fcc table\n"); return; } fcc = interpolate_fcc(chip->fcc_temp_lut, chip->fcc_new_batt_temp); temp->cols = chip->fcc_temp_lut->cols; for (i = 0; i < chip->fcc_temp_lut->cols; i++) { temp->x[i] = chip->fcc_temp_lut->x[i]; ratio = div_u64(chip->fcc_temp_lut->y[i] * 1000, fcc); temp->y[i] = (ratio * chip->fcc_new_mah); temp->y[i] /= 1000; } old = chip->adjusted_fcc_temp_lut; chip->adjusted_fcc_temp_lut = temp; devm_kfree(chip->dev, old); } static int read_fcc_data_from_backup(struct qpnp_bms_chip *chip) { int rc, i; u8 fcc = 0, chgcyl = 0; for (i = 0; i < chip->min_fcc_learning_samples; i++) { rc = qpnp_read_wrapper(chip, &fcc, chip->base + BMS_FCC_BASE_REG + i, 1); rc |= qpnp_read_wrapper(chip, &chgcyl, chip->base + BMS_CHGCYL_BASE_REG + i, 1); if (rc) { pr_err("Unable to read FCC data\n"); return rc; } if (fcc == 0 || (fcc == 0xFF && chgcyl == 0xFF)) { /* FCC invalid/not present */ chip->fcc_learning_samples[i].fcc_new = 0; chip->fcc_learning_samples[i].chargecycles = 0; } else { /* valid FCC data */ chip->fcc_sample_count++; chip->fcc_learning_samples[i].fcc_new = fcc * chip->fcc_resolution; chip->fcc_learning_samples[i].chargecycles = chgcyl * CHGCYL_RESOLUTION; } } return 0; } static int discard_backup_fcc_data(struct qpnp_bms_chip *chip) { int rc = 0, i; u8 temp_u8 = 0; chip->fcc_sample_count = 0; for (i = 0; i < chip->min_fcc_learning_samples; i++) { rc = qpnp_write_wrapper(chip, &temp_u8, chip->base + BMS_FCC_BASE_REG + i, 1); rc |= qpnp_write_wrapper(chip, &temp_u8, chip->base + BMS_CHGCYL_BASE_REG + i, 1); if (rc) { pr_err("Unable to clear FCC data\n"); return rc; } } return 0; } static void average_fcc_samples_and_readjust_fcc_table(struct qpnp_bms_chip *chip) { int i, temp_fcc_avg = 0, temp_fcc_delta = 0, new_fcc_avg = 0; struct fcc_sample *ft; for (i = 0; i < chip->min_fcc_learning_samples; i++) temp_fcc_avg += chip->fcc_learning_samples[i].fcc_new; temp_fcc_avg /= chip->min_fcc_learning_samples; temp_fcc_delta = div_u64(temp_fcc_avg * DELTA_FCC_PERCENT, 100); /* fix the fcc if its an outlier i.e. > 5% of the average */ for (i = 0; i < chip->min_fcc_learning_samples; i++) { ft = &chip->fcc_learning_samples[i]; if (abs(ft->fcc_new - temp_fcc_avg) > temp_fcc_delta) new_fcc_avg += temp_fcc_avg; else new_fcc_avg += ft->fcc_new; } new_fcc_avg /= chip->min_fcc_learning_samples; chip->fcc_new_mah = new_fcc_avg; chip->fcc_new_batt_temp = FCC_DEFAULT_TEMP; pr_info("FCC update: New fcc_mah=%d, fcc_batt_temp=%d\n", new_fcc_avg, FCC_DEFAULT_TEMP); readjust_fcc_table(chip); } static void backup_charge_cycle(struct qpnp_bms_chip *chip) { int rc = 0; if (chip->charge_increase >= 0) { rc = qpnp_write_wrapper(chip, &chip->charge_increase, chip->base + CHARGE_INCREASE_STORAGE, 1); if (rc) pr_err("Unable to backup charge_increase\n"); } if (chip->charge_cycles >= 0) { rc = qpnp_write_wrapper(chip, (u8 *)&chip->charge_cycles, chip->base + CHARGE_CYCLE_STORAGE_LSB, 2); if (rc) pr_err("Unable to backup charge_cycles\n"); } } static bool chargecycles_in_range(struct qpnp_bms_chip *chip) { int i, min_cycle, max_cycle, valid_range; /* find the smallest and largest charge cycle */ max_cycle = min_cycle = chip->fcc_learning_samples[0].chargecycles; for (i = 1; i < chip->min_fcc_learning_samples; i++) { if (min_cycle > chip->fcc_learning_samples[i].chargecycles) min_cycle = chip->fcc_learning_samples[i].chargecycles; if (max_cycle < chip->fcc_learning_samples[i].chargecycles) max_cycle = chip->fcc_learning_samples[i].chargecycles; } /* check if chargecyles are in range to continue with FCC update */ valid_range = DIV_ROUND_UP(VALID_FCC_CHGCYL_RANGE, CHGCYL_RESOLUTION) * CHGCYL_RESOLUTION; if (abs(max_cycle - min_cycle) > valid_range) return false; return true; } static int read_chgcycle_data_from_backup(struct qpnp_bms_chip *chip) { int rc; uint16_t temp_u16 = 0; u8 temp_u8 = 0; rc = qpnp_read_wrapper(chip, &temp_u8, chip->base + CHARGE_INCREASE_STORAGE, 1); if (!rc && temp_u8 != 0xFF) chip->charge_increase = temp_u8; rc = qpnp_read_wrapper(chip, (u8 *)&temp_u16, chip->base + CHARGE_CYCLE_STORAGE_LSB, 2); if (!rc && temp_u16 != 0xFFFF) chip->charge_cycles = temp_u16; return rc; } static void attempt_learning_new_fcc(struct qpnp_bms_chip *chip) { pr_debug("Total FCC sample count=%d\n", chip->fcc_sample_count); /* update FCC if we have the required samples */ if ((chip->fcc_sample_count == chip->min_fcc_learning_samples) && chargecycles_in_range(chip)) average_fcc_samples_and_readjust_fcc_table(chip); } static int calculate_real_soc(struct qpnp_bms_chip *chip, int batt_temp, struct raw_soc_params *raw, int cc_uah) { int fcc_uah, rc_uah; fcc_uah = calculate_fcc(chip, batt_temp); rc_uah = calculate_ocv_charge(chip, raw, fcc_uah); return ((rc_uah - cc_uah) * 100) / fcc_uah; } #define MAX_U8_VALUE ((u8)(~0U)) static int backup_new_fcc(struct qpnp_bms_chip *chip, int fcc_mah, int chargecycles) { int rc, min_cycle, i; u8 fcc_new, chgcyl, pos = 0; struct fcc_sample *ft; if ((fcc_mah > (chip->fcc_resolution * MAX_U8_VALUE)) || (chargecycles > (CHGCYL_RESOLUTION * MAX_U8_VALUE))) { pr_warn("FCC/Chgcyl beyond storage limit. FCC=%d, chgcyl=%d\n", fcc_mah, chargecycles); return -EINVAL; } if (chip->fcc_sample_count == chip->min_fcc_learning_samples) { /* search best location - oldest entry */ min_cycle = chip->fcc_learning_samples[0].chargecycles; for (i = 1; i < chip->min_fcc_learning_samples; i++) { if (min_cycle > chip->fcc_learning_samples[i].chargecycles) pos = i; } } else { /* find an empty location */ for (i = 0; i < chip->min_fcc_learning_samples; i++) { ft = &chip->fcc_learning_samples[i]; if (ft->fcc_new == 0 || (ft->fcc_new == 0xFF && ft->chargecycles == 0xFF)) { pos = i; break; } } chip->fcc_sample_count++; } chip->fcc_learning_samples[pos].fcc_new = fcc_mah; chip->fcc_learning_samples[pos].chargecycles = chargecycles; fcc_new = DIV_ROUND_UP(fcc_mah, chip->fcc_resolution); rc = qpnp_write_wrapper(chip, (u8 *)&fcc_new, chip->base + BMS_FCC_BASE_REG + pos, 1); if (rc) return rc; chgcyl = DIV_ROUND_UP(chargecycles, CHGCYL_RESOLUTION); rc = qpnp_write_wrapper(chip, (u8 *)&chgcyl, chip->base + BMS_CHGCYL_BASE_REG + pos, 1); if (rc) return rc; pr_debug("Backup new FCC: fcc_new=%d, chargecycle=%d, pos=%d\n", fcc_new, chgcyl, pos); return rc; } static void update_fcc_learning_table(struct qpnp_bms_chip *chip, int new_fcc_uah, int chargecycles, int batt_temp) { int rc, fcc_default, fcc_temp; /* convert the fcc at batt_temp to new fcc at FCC_DEFAULT_TEMP */ fcc_default = calculate_fcc(chip, FCC_DEFAULT_TEMP) / 1000; fcc_temp = calculate_fcc(chip, batt_temp) / 1000; new_fcc_uah = (new_fcc_uah / fcc_temp) * fcc_default; rc = backup_new_fcc(chip, new_fcc_uah / 1000, chargecycles); if (rc) { pr_err("Unable to backup new FCC\n"); return; } /* check if FCC can be updated */ attempt_learning_new_fcc(chip); } static bool is_new_fcc_valid(int new_fcc_uah, int fcc_uah) { if ((new_fcc_uah >= (fcc_uah / 2)) && ((new_fcc_uah * 100) <= (fcc_uah * 105))) return true; pr_debug("FCC rejected - not within valid limit\n"); return false; } static void fcc_learning_config(struct qpnp_bms_chip *chip, bool start) { int rc, batt_temp; struct raw_soc_params raw; struct qpnp_vadc_result result; int fcc_uah, new_fcc_uah, delta_cc_uah, delta_soc; rc = qpnp_vadc_read(chip->vadc_dev, LR_MUX1_BATT_THERM, &result); if (rc) { pr_err("Unable to read batt_temp\n"); return; } else { batt_temp = (int)result.physical; } rc = read_soc_params_raw(chip, &raw, batt_temp); if (rc) { pr_err("Unable to read CC, cannot update FCC\n"); return; } if (start) { chip->start_pc = interpolate_pc(chip->pc_temp_ocv_lut, batt_temp / 10, raw.last_good_ocv_uv / 1000); chip->start_cc_uah = calculate_cc(chip, raw.cc, CC, NORESET); chip->start_real_soc = calculate_real_soc(chip, batt_temp, &raw, chip->start_cc_uah); pr_debug("start_pc=%d, start_cc=%d, start_soc=%d real_soc=%d\n", chip->start_pc, chip->start_cc_uah, chip->start_soc, chip->start_real_soc); } else { chip->end_cc_uah = calculate_cc(chip, raw.cc, CC, NORESET); delta_soc = 100 - chip->start_real_soc; delta_cc_uah = abs(chip->end_cc_uah - chip->start_cc_uah); new_fcc_uah = div_u64(delta_cc_uah * 100, delta_soc); fcc_uah = calculate_fcc(chip, batt_temp); pr_debug("start_soc=%d, start_pc=%d, start_real_soc=%d, start_cc=%d, end_cc=%d, new_fcc=%d\n", chip->start_soc, chip->start_pc, chip->start_real_soc, chip->start_cc_uah, chip->end_cc_uah, new_fcc_uah); if (is_new_fcc_valid(new_fcc_uah, fcc_uah)) update_fcc_learning_table(chip, new_fcc_uah, chip->charge_cycles, batt_temp); } } #define MAX_CAL_TRIES 200 #define MIN_CAL_UA 3000 static void batfet_open_work(struct work_struct *work) { int i; int rc; int result_ua; u8 orig_delay, sample_delay; struct qpnp_bms_chip *chip = container_of(work, struct qpnp_bms_chip, batfet_open_work); rc = qpnp_read_wrapper(chip, &orig_delay, chip->base + BMS1_S1_DELAY_CTL, 1); sample_delay = 0x0; rc = qpnp_write_wrapper(chip, &sample_delay, chip->base + BMS1_S1_DELAY_CTL, 1); /* * In certain PMICs there is a coupling issue which causes * bad calibration value that result in a huge battery current * even when the BATFET is open. Do continious calibrations until * we hit reasonable cal values which result in low battery current */ for (i = 0; (!chip->batfet_closed) && i < MAX_CAL_TRIES; i++) { rc = qpnp_iadc_calibrate_for_trim(chip->iadc_dev, false); /* * Wait 20mS after calibration and before reading battery * current. The BMS h/w uses calibration values in the * next sampling of vsense. */ msleep(20); rc |= get_battery_current(chip, &result_ua); if (rc == 0 && abs(result_ua) <= MIN_CAL_UA) { pr_debug("good cal at %d attempt\n", i); break; } } pr_debug("batfet_closed = %d i = %d result_ua = %d\n", chip->batfet_closed, i, result_ua); rc = qpnp_write_wrapper(chip, &orig_delay, chip->base + BMS1_S1_DELAY_CTL, 1); } static void charging_began(struct qpnp_bms_chip *chip) { mutex_lock(&chip->last_soc_mutex); chip->charge_start_tm_sec = 0; chip->catch_up_time_sec = 0; mutex_unlock(&chip->last_soc_mutex); chip->start_soc = report_state_of_charge(chip); mutex_lock(&chip->last_ocv_uv_mutex); if (chip->enable_fcc_learning) fcc_learning_config(chip, true); chip->soc_at_cv = -EINVAL; chip->prev_chg_soc = -EINVAL; mutex_unlock(&chip->last_ocv_uv_mutex); } static void charging_ended(struct qpnp_bms_chip *chip) { mutex_lock(&chip->last_soc_mutex); chip->charge_start_tm_sec = 0; chip->catch_up_time_sec = 0; mutex_unlock(&chip->last_soc_mutex); chip->end_soc = report_state_of_charge(chip); mutex_lock(&chip->last_ocv_uv_mutex); chip->soc_at_cv = -EINVAL; chip->prev_chg_soc = -EINVAL; /* update the chargecycles */ if (chip->end_soc > chip->start_soc) { chip->charge_increase += (chip->end_soc - chip->start_soc); if (chip->charge_increase > 100) { chip->charge_cycles++; chip->charge_increase = chip->charge_increase % 100; } if (chip->enable_fcc_learning) backup_charge_cycle(chip); } if (get_battery_status(chip) == POWER_SUPPLY_STATUS_FULL) { if (chip->enable_fcc_learning && (chip->start_soc <= chip->min_fcc_learning_soc) && (chip->start_pc <= chip->min_fcc_ocv_pc)) fcc_learning_config(chip, false); chip->done_charging = true; chip->last_soc_invalid = true; } else if (chip->charging_adjusted_ocv > 0) { pr_debug("Charging stopped before full, adjusted OCV = %d\n", chip->charging_adjusted_ocv); chip->last_ocv_uv = chip->charging_adjusted_ocv; } chip->charging_adjusted_ocv = -EINVAL; mutex_unlock(&chip->last_ocv_uv_mutex); } static void battery_status_check(struct qpnp_bms_chip *chip) { int status = get_battery_status(chip); mutex_lock(&chip->status_lock); if (chip->battery_status != status) { pr_debug("status = %d, shadow status = %d\n", status, chip->battery_status); if (status == POWER_SUPPLY_STATUS_CHARGING) { pr_debug("charging started\n"); charging_began(chip); } else if (chip->battery_status == POWER_SUPPLY_STATUS_CHARGING) { pr_debug("charging ended\n"); charging_ended(chip); } if (status == POWER_SUPPLY_STATUS_FULL) { pr_debug("battery full\n"); enable_bms_irq(&chip->ocv_thr_irq); enable_bms_irq(&chip->sw_cc_thr_irq); recalculate_soc(chip); } else if (chip->battery_status == POWER_SUPPLY_STATUS_FULL) { pr_debug("battery not full any more\n"); disable_bms_irq(&chip->ocv_thr_irq); disable_bms_irq(&chip->sw_cc_thr_irq); } chip->battery_status = status; /* battery charge status has changed, so force a soc * recalculation to update the SoC */ schedule_work(&chip->recalc_work); } mutex_unlock(&chip->status_lock); } #define CALIB_WRKARND_DIG_MAJOR_MAX 0x03 static void batfet_status_check(struct qpnp_bms_chip *chip) { bool batfet_closed; if (chip->iadc_bms_revision2 > CALIB_WRKARND_DIG_MAJOR_MAX) return; batfet_closed = is_batfet_closed(chip); if (chip->batfet_closed != batfet_closed) { chip->batfet_closed = batfet_closed; if (batfet_closed == false) { /* batfet opened */ schedule_work(&chip->batfet_open_work); qpnp_iadc_skip_calibration(chip->iadc_dev); } else { /* batfet closed */ qpnp_iadc_calibrate_for_trim(chip->iadc_dev, true); qpnp_iadc_resume_calibration(chip->iadc_dev); } } } static void battery_insertion_check(struct qpnp_bms_chip *chip) { int present = (int)is_battery_present(chip); int insertion_ocv_uv = get_battery_insertion_ocv_uv(chip); int insertion_ocv_taken = (insertion_ocv_uv > 0); mutex_lock(&chip->vbat_monitor_mutex); if (chip->battery_present != present && (present == insertion_ocv_taken || chip->battery_present == -EINVAL)) { pr_debug("status = %d, shadow status = %d, insertion_ocv_uv = %d\n", present, chip->battery_present, insertion_ocv_uv); if (chip->battery_present != -EINVAL) { if (present) { chip->insertion_ocv_uv = insertion_ocv_uv; setup_vbat_monitoring(chip); chip->new_battery = true; } else { reset_vbat_monitoring(chip); } } chip->battery_present = present; /* a new battery was inserted or removed, so force a soc * recalculation to update the SoC */ schedule_work(&chip->recalc_work); } mutex_unlock(&chip->vbat_monitor_mutex); } /* Returns capacity as a SoC percentage between 0 and 100 */ static int get_prop_bms_capacity(struct qpnp_bms_chip *chip) { return report_state_of_charge(chip); } static void qpnp_bms_external_power_changed(struct power_supply *psy) { struct qpnp_bms_chip *chip = container_of(psy, struct qpnp_bms_chip, bms_psy); battery_insertion_check(chip); batfet_status_check(chip); battery_status_check(chip); } static int qpnp_bms_power_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct qpnp_bms_chip *chip = container_of(psy, struct qpnp_bms_chip, bms_psy); switch (psp) { case POWER_SUPPLY_PROP_CAPACITY: val->intval = get_prop_bms_capacity(chip); break; case POWER_SUPPLY_PROP_STATUS: val->intval = chip->battery_status; break; #if defined(CONFIG_BATTERY_SAMSUNG) case POWER_SUPPLY_PROP_CURRENT_NOW: val->intval = (get_prop_bms_current_now(chip) * -1); break; case POWER_SUPPLY_PROP_CURRENT_AVG: val->intval = (get_prop_bms_current_now(chip) * -1); break; #else case POWER_SUPPLY_PROP_CURRENT_NOW: val->intval = get_prop_bms_current_now(chip); break; #endif case POWER_SUPPLY_PROP_RESISTANCE: val->intval = get_prop_bms_batt_resistance(chip); break; case POWER_SUPPLY_PROP_CHARGE_COUNTER: val->intval = get_prop_bms_charge_counter(chip); break; case POWER_SUPPLY_PROP_CHARGE_COUNTER_SHADOW: val->intval = get_prop_bms_charge_counter_shadow(chip); break; case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN: val->intval = get_prop_bms_charge_full_design(chip); break; case POWER_SUPPLY_PROP_CHARGE_FULL: val->intval = get_prop_bms_charge_full(chip); break; case POWER_SUPPLY_PROP_CYCLE_COUNT: val->intval = chip->charge_cycles; break; #if defined(CONFIG_BATTERY_SAMSUNG) case POWER_SUPPLY_PROP_VOLTAGE_NOW: case POWER_SUPPLY_PROP_VOLTAGE_AVG: { int vbat_uv; get_battery_voltage(chip, &vbat_uv); val->intval = vbat_uv/1000; } break; #endif default: return -EINVAL; } return 0; } #define OCV_USE_LIMIT_EN BIT(7) static int set_ocv_voltage_thresholds(struct qpnp_bms_chip *chip, int low_voltage_threshold, int high_voltage_threshold) { uint16_t low_voltage_raw, high_voltage_raw; int rc; low_voltage_raw = convert_vbatt_uv_to_raw(chip, low_voltage_threshold); high_voltage_raw = convert_vbatt_uv_to_raw(chip, high_voltage_threshold); rc = qpnp_write_wrapper(chip, (u8 *)&low_voltage_raw, chip->base + BMS1_OCV_USE_LOW_LIMIT_THR0, 2); if (rc) { pr_err("Failed to set ocv low voltage threshold: %d\n", rc); return rc; } rc = qpnp_write_wrapper(chip, (u8 *)&high_voltage_raw, chip->base + BMS1_OCV_USE_HIGH_LIMIT_THR0, 2); if (rc) { pr_err("Failed to set ocv high voltage threshold: %d\n", rc); return rc; } rc = qpnp_masked_write(chip, BMS1_OCV_USE_LIMIT_CTL, OCV_USE_LIMIT_EN, OCV_USE_LIMIT_EN); if (rc) { pr_err("Failed to enabled ocv voltage thresholds: %d\n", rc); return rc; } pr_debug("ocv low threshold set to %d uv or 0x%x raw\n", low_voltage_threshold, low_voltage_raw); pr_debug("ocv high threshold set to %d uv or 0x%x raw\n", high_voltage_threshold, high_voltage_raw); return 0; } static int read_shutdown_iavg_ma(struct qpnp_bms_chip *chip) { u8 iavg; int rc; rc = qpnp_read_wrapper(chip, &iavg, chip->base + IAVG_STORAGE_REG, 1); if (rc) { pr_err("failed to read addr = %d %d assuming %d\n", chip->base + IAVG_STORAGE_REG, rc, MIN_IAVG_MA); return MIN_IAVG_MA; } else if (iavg == IAVG_INVALID) { pr_err("invalid iavg read from BMS1_DATA_REG_1, using %d\n", MIN_IAVG_MA); return MIN_IAVG_MA; } else { if (iavg == 0) return MIN_IAVG_MA; else return MIN_IAVG_MA + IAVG_STEP_SIZE_MA * iavg; } } static int read_shutdown_soc(struct qpnp_bms_chip *chip) { u8 stored_soc; int rc, shutdown_soc; /* * The previous SOC is stored in the first 7 bits of the register as * (Shutdown SOC + 1). This allows for register reset values of both * 0x00 and 0x7F. */ rc = qpnp_read_wrapper(chip, &stored_soc, chip->soc_storage_addr, 1); if (rc) { pr_err("failed to read addr = %d %d\n", chip->soc_storage_addr, rc); return SOC_INVALID; } if ((stored_soc >> 1) > 0) shutdown_soc = (stored_soc >> 1) - 1; else shutdown_soc = SOC_INVALID; pr_debug("stored soc = 0x%02x, shutdown_soc = %d\n", stored_soc, shutdown_soc); return shutdown_soc; } #define BAT_REMOVED_OFFMODE_BIT BIT(6) static bool is_battery_replaced_in_offmode(struct qpnp_bms_chip *chip) { u8 batt_pres; int rc; if (chip->batt_pres_addr) { rc = qpnp_read_wrapper(chip, &batt_pres, chip->batt_pres_addr, 1); pr_debug("offmode removed: %02x\n", batt_pres); if (!rc && (batt_pres & BAT_REMOVED_OFFMODE_BIT)) return true; } return false; } static void load_shutdown_data(struct qpnp_bms_chip *chip) { int calculated_soc, shutdown_soc; bool invalid_stored_soc; bool offmode_battery_replaced; bool shutdown_soc_out_of_limit; /* * Read the saved shutdown SoC from the configured register and * check if the value has been reset */ shutdown_soc = read_shutdown_soc(chip); invalid_stored_soc = (shutdown_soc == SOC_INVALID); /* * Do a quick run of SoC calculation to find whether the shutdown soc * is close enough. */ calculated_soc = recalculate_raw_soc(chip); shutdown_soc_out_of_limit = (abs(shutdown_soc - calculated_soc) > chip->shutdown_soc_valid_limit); pr_debug("calculated_soc = %d, valid_limit = %d\n", calculated_soc, chip->shutdown_soc_valid_limit); /* * Check if the battery has been replaced while the system was powered * down. */ offmode_battery_replaced = is_battery_replaced_in_offmode(chip); /* Invalidate the shutdown SoC if any of these conditions hold true */ if (chip->ignore_shutdown_soc || invalid_stored_soc || offmode_battery_replaced || shutdown_soc_out_of_limit) { chip->battery_removed = true; chip->shutdown_soc_invalid = true; chip->shutdown_iavg_ma = 0; pr_debug("Ignoring shutdown SoC: invalid = %d, offmode = %d, out_of_limit = %d\n", invalid_stored_soc, offmode_battery_replaced, shutdown_soc_out_of_limit); } else { chip->shutdown_iavg_ma = read_shutdown_iavg_ma(chip); chip->shutdown_soc = shutdown_soc; } pr_debug("raw_soc = %d shutdown_soc = %d shutdown_iavg = %d shutdown_soc_invalid = %d, battery_removed = %d\n", calculated_soc, chip->shutdown_soc, chip->shutdown_iavg_ma, chip->shutdown_soc_invalid, chip->battery_removed); } static irqreturn_t bms_ocv_thr_irq_handler(int irq, void *_chip) { struct qpnp_bms_chip *chip = _chip; pr_debug("ocv_thr irq triggered\n"); bms_stay_awake(&chip->soc_wake_source); schedule_work(&chip->recalc_work); return IRQ_HANDLED; } static irqreturn_t bms_sw_cc_thr_irq_handler(int irq, void *_chip) { struct qpnp_bms_chip *chip = _chip; pr_debug("sw_cc_thr irq triggered\n"); bms_stay_awake(&chip->soc_wake_source); schedule_work(&chip->recalc_work); return IRQ_HANDLED; } static int64_t read_battery_id(struct qpnp_bms_chip *chip) { int rc; struct qpnp_vadc_result result; rc = qpnp_vadc_read(chip->vadc_dev, LR_MUX2_BAT_ID, &result); if (rc) { pr_err("error reading batt id channel = %d, rc = %d\n", LR_MUX2_BAT_ID, rc); return rc; } return result.physical; } static int set_battery_data(struct qpnp_bms_chip *chip) { int64_t battery_id; int rc = 0, dt_data = false; struct bms_battery_data *batt_data; struct device_node *node; if (chip->batt_type == BATT_DESAY) { batt_data = &desay_5200_data; } else if (chip->batt_type == BATT_PALLADIUM) { batt_data = &palladium_1500_data; } else if (chip->batt_type == BATT_OEM) { #if defined(CONFIG_SEC_AFYON_PROJECT) /* Temporary until we get 2100mAh battery data */ batt_data = &oem_batt_data; #elif defined(CONFIG_SEC_MILLET_PROJECT) batt_data = &samsung_4450mAH_data; #elif defined(CONFIG_SEC_MATISSE_PROJECT) batt_data = &samsung_6800mAH_data; #else batt_data = &oem_batt_data; #endif } else if (chip->batt_type == BATT_QRD_4V35_2000MAH) { batt_data = &QRD_4v35_2000mAh_data; } else if (chip->batt_type == BATT_QRD_4V2_1300MAH) { batt_data = &qrd_4v2_1300mah_data; } else { battery_id = read_battery_id(chip); if (battery_id < 0) { pr_err("cannot read battery id err = %lld\n", battery_id); return battery_id; } node = of_find_node_by_name(chip->spmi->dev.of_node, "qcom,battery-data"); if (!node) { pr_warn("No available batterydata, using palladium 1500\n"); batt_data = &palladium_1500_data; goto assign_data; } batt_data = devm_kzalloc(chip->dev, sizeof(struct bms_battery_data), GFP_KERNEL); if (!batt_data) { pr_err("Could not alloc battery data\n"); batt_data = &palladium_1500_data; goto assign_data; } batt_data->fcc_temp_lut = devm_kzalloc(chip->dev, sizeof(struct single_row_lut), GFP_KERNEL); batt_data->pc_temp_ocv_lut = devm_kzalloc(chip->dev, sizeof(struct pc_temp_ocv_lut), GFP_KERNEL); batt_data->rbatt_sf_lut = devm_kzalloc(chip->dev, sizeof(struct sf_lut), GFP_KERNEL); batt_data->max_voltage_uv = -1; batt_data->cutoff_uv = -1; batt_data->iterm_ua = -1; /* * if the alloced luts are 0s, of_batterydata_read_data ignores * them. */ rc = of_batterydata_read_data(node, batt_data, battery_id); if (rc == 0 && batt_data->fcc_temp_lut && batt_data->pc_temp_ocv_lut && batt_data->rbatt_sf_lut) { dt_data = true; } else { pr_err("battery data load failed, using palladium 1500\n"); devm_kfree(chip->dev, batt_data->fcc_temp_lut); devm_kfree(chip->dev, batt_data->pc_temp_ocv_lut); devm_kfree(chip->dev, batt_data->rbatt_sf_lut); devm_kfree(chip->dev, batt_data); batt_data = &palladium_1500_data; } } assign_data: chip->fcc_mah = batt_data->fcc; chip->fcc_temp_lut = batt_data->fcc_temp_lut; chip->fcc_sf_lut = batt_data->fcc_sf_lut; chip->pc_temp_ocv_lut = batt_data->pc_temp_ocv_lut; chip->pc_sf_lut = batt_data->pc_sf_lut; chip->rbatt_sf_lut = batt_data->rbatt_sf_lut; chip->default_rbatt_mohm = batt_data->default_rbatt_mohm; chip->rbatt_capacitive_mohm = batt_data->rbatt_capacitive_mohm; chip->flat_ocv_threshold_uv = batt_data->flat_ocv_threshold_uv; pr_err("battery capacity: %d mA\n", chip->fcc_mah); /* Override battery properties if specified in the battery profile */ if (batt_data->max_voltage_uv >= 0 && dt_data) chip->max_voltage_uv = batt_data->max_voltage_uv; if (batt_data->cutoff_uv >= 0 && dt_data) chip->v_cutoff_uv = batt_data->cutoff_uv; if (batt_data->iterm_ua >= 0 && dt_data) chip->chg_term_ua = batt_data->iterm_ua; if (chip->pc_temp_ocv_lut == NULL) { pr_err("temp ocv lut table has not been loaded\n"); if (dt_data) { devm_kfree(chip->dev, batt_data->fcc_temp_lut); devm_kfree(chip->dev, batt_data->pc_temp_ocv_lut); devm_kfree(chip->dev, batt_data->rbatt_sf_lut); devm_kfree(chip->dev, batt_data); } return -EINVAL; } if (dt_data) devm_kfree(chip->dev, batt_data); return 0; } static int bms_get_adc(struct qpnp_bms_chip *chip, struct spmi_device *spmi) { int rc = 0; chip->vadc_dev = qpnp_get_vadc(&spmi->dev, "bms"); if (IS_ERR(chip->vadc_dev)) { rc = PTR_ERR(chip->vadc_dev); if (rc != -EPROBE_DEFER) pr_err("vadc property missing, rc=%d\n", rc); return rc; } chip->iadc_dev = qpnp_get_iadc(&spmi->dev, "bms"); if (IS_ERR(chip->iadc_dev)) { rc = PTR_ERR(chip->iadc_dev); if (rc != -EPROBE_DEFER) pr_err("iadc property missing, rc=%d\n", rc); return rc; } chip->adc_tm_dev = qpnp_get_adc_tm(&spmi->dev, "bms"); if (IS_ERR(chip->adc_tm_dev)) { rc = PTR_ERR(chip->adc_tm_dev); if (rc != -EPROBE_DEFER) pr_err("adc-tm not ready, defer probe\n"); return rc; } return 0; } #define SPMI_PROP_READ(chip_prop, qpnp_spmi_property, retval) \ do { \ if (retval) \ break; \ retval = of_property_read_u32(chip->spmi->dev.of_node, \ "qcom," qpnp_spmi_property, \ &chip->chip_prop); \ if (retval) { \ pr_err("Error reading " #qpnp_spmi_property \ " property %d\n", rc); \ } \ } while (0) #define SPMI_PROP_READ_BOOL(chip_prop, qpnp_spmi_property) \ do { \ chip->chip_prop = of_property_read_bool(chip->spmi->dev.of_node,\ "qcom," qpnp_spmi_property); \ } while (0) static inline int bms_read_properties(struct qpnp_bms_chip *chip) { int rc = 0; SPMI_PROP_READ(r_sense_uohm, "r-sense-uohm", rc); SPMI_PROP_READ(v_cutoff_uv, "v-cutoff-uv", rc); SPMI_PROP_READ(max_voltage_uv, "max-voltage-uv", rc); SPMI_PROP_READ(r_conn_mohm, "r-conn-mohm", rc); SPMI_PROP_READ(chg_term_ua, "chg-term-ua", rc); SPMI_PROP_READ(shutdown_soc_valid_limit, "shutdown-soc-valid-limit", rc); SPMI_PROP_READ(adjust_soc_low_threshold, "adjust-soc-low-threshold", rc); SPMI_PROP_READ(batt_type, "batt-type", rc); SPMI_PROP_READ(low_soc_calc_threshold, "low-soc-calculate-soc-threshold", rc); SPMI_PROP_READ(low_soc_calculate_soc_ms, "low-soc-calculate-soc-ms", rc); SPMI_PROP_READ(low_voltage_calculate_soc_ms, "low-voltage-calculate-soc-ms", rc); SPMI_PROP_READ(calculate_soc_ms, "calculate-soc-ms", rc); SPMI_PROP_READ(high_ocv_correction_limit_uv, "high-ocv-correction-limit-uv", rc); SPMI_PROP_READ(low_ocv_correction_limit_uv, "low-ocv-correction-limit-uv", rc); SPMI_PROP_READ(hold_soc_est, "hold-soc-est", rc); SPMI_PROP_READ(ocv_high_threshold_uv, "ocv-voltage-high-threshold-uv", rc); SPMI_PROP_READ(ocv_low_threshold_uv, "ocv-voltage-low-threshold-uv", rc); SPMI_PROP_READ(low_voltage_threshold, "low-voltage-threshold", rc); SPMI_PROP_READ(temperature_margin, "tm-temp-margin", rc); chip->use_external_rsense = of_property_read_bool( chip->spmi->dev.of_node, "qcom,use-external-rsense"); chip->ignore_shutdown_soc = of_property_read_bool( chip->spmi->dev.of_node, "qcom,ignore-shutdown-soc"); chip->use_voltage_soc = of_property_read_bool(chip->spmi->dev.of_node, "qcom,use-voltage-soc"); chip->use_ocv_thresholds = of_property_read_bool( chip->spmi->dev.of_node, "qcom,use-ocv-thresholds"); if (chip->adjust_soc_low_threshold >= 45) chip->adjust_soc_low_threshold = 45; SPMI_PROP_READ_BOOL(enable_fcc_learning, "enable-fcc-learning"); if (chip->enable_fcc_learning) { SPMI_PROP_READ(min_fcc_learning_soc, "min-fcc-learning-soc", rc); SPMI_PROP_READ(min_fcc_ocv_pc, "min-fcc-ocv-pc", rc); SPMI_PROP_READ(min_fcc_learning_samples, "min-fcc-learning-samples", rc); SPMI_PROP_READ(fcc_resolution, "fcc-resolution", rc); if (chip->min_fcc_learning_samples > MAX_FCC_CYCLES) chip->min_fcc_learning_samples = MAX_FCC_CYCLES; chip->fcc_learning_samples = devm_kzalloc(&chip->spmi->dev, (sizeof(struct fcc_sample) * chip->min_fcc_learning_samples), GFP_KERNEL); if (chip->fcc_learning_samples == NULL) return -ENOMEM; pr_debug("min-fcc-soc=%d, min-fcc-pc=%d, min-fcc-cycles=%d\n", chip->min_fcc_learning_soc, chip->min_fcc_ocv_pc, chip->min_fcc_learning_samples); } if (rc) { pr_err("Missing required properties.\n"); return rc; } pr_debug("dts data: r_sense_uohm:%d, v_cutoff_uv:%d, max_v:%d\n", chip->r_sense_uohm, chip->v_cutoff_uv, chip->max_voltage_uv); pr_debug("r_conn:%d, shutdown_soc: %d, adjust_soc_low:%d\n", chip->r_conn_mohm, chip->shutdown_soc_valid_limit, chip->adjust_soc_low_threshold); pr_debug("chg_term_ua:%d, batt_type:%d\n", chip->chg_term_ua, chip->batt_type); pr_debug("ignore_shutdown_soc:%d, use_voltage_soc:%d\n", chip->ignore_shutdown_soc, chip->use_voltage_soc); pr_debug("use external rsense: %d\n", chip->use_external_rsense); return 0; } static inline void bms_initialize_constants(struct qpnp_bms_chip *chip) { chip->prev_pc_unusable = -EINVAL; chip->soc_at_cv = -EINVAL; chip->calculated_soc = -EINVAL; chip->last_soc = -EINVAL; chip->last_soc_est = -EINVAL; chip->battery_present = -EINVAL; chip->battery_status = POWER_SUPPLY_STATUS_UNKNOWN; chip->last_cc_uah = INT_MIN; chip->ocv_reading_at_100 = OCV_RAW_UNINITIALIZED; chip->prev_last_good_ocv_raw = OCV_RAW_UNINITIALIZED; chip->first_time_calc_soc = 1; chip->first_time_calc_uuc = 1; } #define SPMI_FIND_IRQ(chip, irq_name) \ do { \ chip->irq_name##_irq.irq = spmi_get_irq_byname(chip->spmi, \ resource, #irq_name); \ if (chip->irq_name##_irq.irq < 0) { \ pr_err("Unable to get " #irq_name " irq\n"); \ return -ENXIO; \ } \ } while (0) static int bms_find_irqs(struct qpnp_bms_chip *chip, struct spmi_resource *resource) { SPMI_FIND_IRQ(chip, sw_cc_thr); SPMI_FIND_IRQ(chip, ocv_thr); return 0; } #define SPMI_REQUEST_IRQ(chip, rc, irq_name) \ do { \ rc = devm_request_irq(chip->dev, chip->irq_name##_irq.irq, \ bms_##irq_name##_irq_handler, \ IRQF_TRIGGER_RISING, #irq_name, chip); \ if (rc < 0) { \ pr_err("Unable to request " #irq_name " irq: %d\n", rc);\ return -ENXIO; \ } \ } while (0) static int bms_request_irqs(struct qpnp_bms_chip *chip) { int rc; SPMI_REQUEST_IRQ(chip, rc, sw_cc_thr); enable_irq_wake(chip->sw_cc_thr_irq.irq); SPMI_REQUEST_IRQ(chip, rc, ocv_thr); enable_irq_wake(chip->ocv_thr_irq.irq); return 0; } #define REG_OFFSET_PERP_TYPE 0x04 #define REG_OFFSET_PERP_SUBTYPE 0x05 #define BMS_BMS_TYPE 0xD #define BMS_BMS1_SUBTYPE 0x1 #define BMS_IADC_TYPE 0x8 #define BMS_IADC1_SUBTYPE 0x3 #define BMS_IADC2_SUBTYPE 0x5 static int register_spmi(struct qpnp_bms_chip *chip, struct spmi_device *spmi) { struct spmi_resource *spmi_resource; struct resource *resource; int rc; u8 type, subtype; chip->dev = &(spmi->dev); chip->spmi = spmi; spmi_for_each_container_dev(spmi_resource, spmi) { if (!spmi_resource) { pr_err("qpnp_bms: spmi resource absent\n"); return -ENXIO; } resource = spmi_get_resource(spmi, spmi_resource, IORESOURCE_MEM, 0); if (!(resource && resource->start)) { pr_err("node %s IO resource absent!\n", spmi->dev.of_node->full_name); return -ENXIO; } pr_debug("Node name = %s\n", spmi_resource->of_node->name); if (strcmp("qcom,batt-pres-status", spmi_resource->of_node->name) == 0) { chip->batt_pres_addr = resource->start; continue; } else if (strcmp("qcom,soc-storage-reg", spmi_resource->of_node->name) == 0) { chip->soc_storage_addr = resource->start; continue; } rc = qpnp_read_wrapper(chip, &type, resource->start + REG_OFFSET_PERP_TYPE, 1); if (rc) { pr_err("Peripheral type read failed rc=%d\n", rc); return rc; } rc = qpnp_read_wrapper(chip, &subtype, resource->start + REG_OFFSET_PERP_SUBTYPE, 1); if (rc) { pr_err("Peripheral subtype read failed rc=%d\n", rc); return rc; } if (type == BMS_BMS_TYPE && subtype == BMS_BMS1_SUBTYPE) { chip->base = resource->start; rc = bms_find_irqs(chip, spmi_resource); if (rc) { pr_err("Could not find irqs\n"); return rc; } } else if (type == BMS_IADC_TYPE && (subtype == BMS_IADC1_SUBTYPE || subtype == BMS_IADC2_SUBTYPE)) { chip->iadc_base = resource->start; } else { pr_err("Invalid peripheral start=0x%x type=0x%x, subtype=0x%x\n", resource->start, type, subtype); } } if (chip->base == 0) { dev_err(&spmi->dev, "BMS peripheral was not registered\n"); return -EINVAL; } if (chip->iadc_base == 0) { dev_err(&spmi->dev, "BMS_IADC peripheral was not registered\n"); return -EINVAL; } if (chip->soc_storage_addr == 0) { /* default to dvdd backed BMS data reg0 */ chip->soc_storage_addr = chip->base + SOC_STORAGE_REG; } pr_debug("bms-base = 0x%04x, iadc-base = 0x%04x, bat-pres-reg = 0x%04x, soc-storage-reg = 0x%04x\n", chip->base, chip->iadc_base, chip->batt_pres_addr, chip->soc_storage_addr); return 0; } #define ADC_CH_SEL_MASK 0x7 #define ADC_INT_RSNSN_CTL_MASK 0x3 #define ADC_INT_RSNSN_CTL_VALUE_EXT_RENSE 0x2 #define FAST_AVG_EN_MASK 0x80 #define FAST_AVG_EN_VALUE_EXT_RSENSE 0x80 static int read_iadc_channel_select(struct qpnp_bms_chip *chip) { u8 iadc_channel_select; int32_t rds_rsense_nohm; int rc; rc = qpnp_read_wrapper(chip, &iadc_channel_select, chip->iadc_base + IADC1_BMS_ADC_CH_SEL_CTL, 1); if (rc) { pr_err("Error reading bms_iadc channel register %d\n", rc); return rc; } iadc_channel_select &= ADC_CH_SEL_MASK; if (iadc_channel_select != EXTERNAL_RSENSE && iadc_channel_select != INTERNAL_RSENSE) { pr_err("IADC1_BMS_IADC configured incorrectly. Selected channel = %d\n", iadc_channel_select); return -EINVAL; } if (chip->use_external_rsense) { pr_debug("External rsense selected\n"); if (iadc_channel_select == INTERNAL_RSENSE) { pr_debug("Internal rsense detected; Changing rsense to external\n"); rc = qpnp_masked_write_iadc(chip, IADC1_BMS_ADC_CH_SEL_CTL, ADC_CH_SEL_MASK, EXTERNAL_RSENSE); if (rc) { pr_err("Unable to set IADC1_BMS channel %x to %x: %d\n", IADC1_BMS_ADC_CH_SEL_CTL, EXTERNAL_RSENSE, rc); return rc; } reset_cc(chip, CLEAR_CC | CLEAR_SHDW_CC); chip->software_cc_uah = 0; chip->software_shdw_cc_uah = 0; } } else { pr_debug("Internal rsense selected\n"); if (iadc_channel_select == EXTERNAL_RSENSE) { pr_debug("External rsense detected; Changing rsense to internal\n"); rc = qpnp_masked_write_iadc(chip, IADC1_BMS_ADC_CH_SEL_CTL, ADC_CH_SEL_MASK, INTERNAL_RSENSE); if (rc) { pr_err("Unable to set IADC1_BMS channel %x to %x: %d\n", IADC1_BMS_ADC_CH_SEL_CTL, INTERNAL_RSENSE, rc); return rc; } reset_cc(chip, CLEAR_CC | CLEAR_SHDW_CC); chip->software_shdw_cc_uah = 0; } rc = qpnp_iadc_get_rsense(chip->iadc_dev, &rds_rsense_nohm); if (rc) { pr_err("Unable to read RDS resistance value from IADC; rc = %d\n", rc); return rc; } chip->r_sense_uohm = rds_rsense_nohm/1000; pr_debug("rds_rsense = %d nOhm, saved as %d uOhm\n", rds_rsense_nohm, chip->r_sense_uohm); } /* prevent shorting of leads by IADC_BMS when external Rsense is used */ if (chip->use_external_rsense) { if (chip->iadc_bms_revision2 > CALIB_WRKARND_DIG_MAJOR_MAX) { rc = qpnp_masked_write_iadc(chip, IADC1_BMS_ADC_INT_RSNSN_CTL, ADC_INT_RSNSN_CTL_MASK, ADC_INT_RSNSN_CTL_VALUE_EXT_RENSE); if (rc) { pr_err("Unable to set batfet config %x to %x: %d\n", IADC1_BMS_ADC_INT_RSNSN_CTL, ADC_INT_RSNSN_CTL_VALUE_EXT_RENSE, rc); return rc; } } else { /* In older PMICS use FAST_AVG_EN register bit 7 */ rc = qpnp_masked_write_iadc(chip, IADC1_BMS_FAST_AVG_EN, FAST_AVG_EN_MASK, FAST_AVG_EN_VALUE_EXT_RSENSE); if (rc) { pr_err("Unable to set batfet config %x to %x: %d\n", IADC1_BMS_FAST_AVG_EN, FAST_AVG_EN_VALUE_EXT_RSENSE, rc); return rc; } } } return 0; } static int refresh_die_temp_monitor(struct qpnp_bms_chip *chip) { struct qpnp_vadc_result result; int rc; rc = qpnp_vadc_read(chip->vadc_dev, DIE_TEMP, &result); pr_debug("low = %lld, high = %lld\n", result.physical - chip->temperature_margin, result.physical + chip->temperature_margin); chip->die_temp_monitor_params.high_temp = result.physical + chip->temperature_margin; chip->die_temp_monitor_params.low_temp = result.physical - chip->temperature_margin; chip->die_temp_monitor_params.state_request = ADC_TM_HIGH_LOW_THR_ENABLE; return qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->die_temp_monitor_params); } static void btm_notify_die_temp(enum qpnp_tm_state state, void *ctx) { struct qpnp_bms_chip *chip = ctx; struct qpnp_vadc_result result; int rc; rc = qpnp_vadc_read(chip->vadc_dev, DIE_TEMP, &result); if (state == ADC_TM_LOW_STATE) pr_debug("low state triggered\n"); else if (state == ADC_TM_HIGH_STATE) pr_debug("high state triggered\n"); pr_debug("die temp = %lld, raw = 0x%x\n", result.physical, result.adc_code); schedule_work(&chip->recalc_work); refresh_die_temp_monitor(chip); } static int setup_die_temp_monitoring(struct qpnp_bms_chip *chip) { int rc; chip->die_temp_monitor_params.channel = DIE_TEMP; chip->die_temp_monitor_params.btm_ctx = (void *)chip; chip->die_temp_monitor_params.timer_interval = ADC_MEAS1_INTERVAL_1S; chip->die_temp_monitor_params.threshold_notification = &btm_notify_die_temp; rc = refresh_die_temp_monitor(chip); if (rc) { pr_err("tm setup failed: %d\n", rc); return rc; } pr_debug("setup complete\n"); return 0; } static int __devinit qpnp_bms_probe(struct spmi_device *spmi) { struct qpnp_bms_chip *chip; bool warm_reset; int rc, vbatt; chip = devm_kzalloc(&spmi->dev, sizeof(struct qpnp_bms_chip), GFP_KERNEL); if (chip == NULL) { pr_err("kzalloc() failed.\n"); return -ENOMEM; } rc = bms_get_adc(chip, spmi); if (rc < 0) goto error_read; mutex_init(&chip->bms_output_lock); mutex_init(&chip->last_ocv_uv_mutex); mutex_init(&chip->vbat_monitor_mutex); mutex_init(&chip->soc_invalidation_mutex); mutex_init(&chip->last_soc_mutex); mutex_init(&chip->status_lock); init_waitqueue_head(&chip->bms_wait_queue); warm_reset = qpnp_pon_is_warm_reset(); rc = warm_reset; if (rc < 0) goto error_read; rc = register_spmi(chip, spmi); if (rc) { pr_err("error registering spmi resource %d\n", rc); goto error_resource; } rc = qpnp_read_wrapper(chip, &chip->revision1, chip->base + REVISION1, 1); if (rc) { pr_err("error reading version register %d\n", rc); goto error_read; } rc = qpnp_read_wrapper(chip, &chip->revision2, chip->base + REVISION2, 1); if (rc) { pr_err("Error reading version register %d\n", rc); goto error_read; } pr_debug("BMS version: %hhu.%hhu\n", chip->revision2, chip->revision1); rc = qpnp_read_wrapper(chip, &chip->iadc_bms_revision2, chip->iadc_base + REVISION2, 1); if (rc) { pr_err("Error reading version register %d\n", rc); goto error_read; } rc = qpnp_read_wrapper(chip, &chip->iadc_bms_revision1, chip->iadc_base + REVISION1, 1); if (rc) { pr_err("Error reading version register %d\n", rc); goto error_read; } pr_debug("IADC_BMS version: %hhu.%hhu\n", chip->iadc_bms_revision2, chip->iadc_bms_revision1); rc = bms_read_properties(chip); if (rc) { pr_err("Unable to read all bms properties, rc = %d\n", rc); goto error_read; } rc = read_iadc_channel_select(chip); if (rc) { pr_err("Unable to get iadc selected channel = %d\n", rc); goto error_read; } if (chip->use_ocv_thresholds) { rc = set_ocv_voltage_thresholds(chip, chip->ocv_low_threshold_uv, chip->ocv_high_threshold_uv); if (rc) { pr_err("Could not set ocv voltage thresholds: %d\n", rc); goto error_read; } } rc = set_battery_data(chip); if (rc) { pr_err("Bad battery data %d\n", rc); goto error_read; } bms_initialize_constants(chip); wakeup_source_init(&chip->soc_wake_source.source, "qpnp_soc_wake"); wake_lock_init(&chip->low_voltage_wake_lock, WAKE_LOCK_SUSPEND, "qpnp_low_voltage_lock"); wake_lock_init(&chip->cv_wake_lock, WAKE_LOCK_SUSPEND, "qpnp_cv_lock"); INIT_DELAYED_WORK(&chip->calculate_soc_delayed_work, calculate_soc_work); INIT_WORK(&chip->recalc_work, recalculate_work); INIT_WORK(&chip->batfet_open_work, batfet_open_work); dev_set_drvdata(&spmi->dev, chip); device_init_wakeup(&spmi->dev, 1); load_shutdown_data(chip); if (chip->enable_fcc_learning) { if (chip->battery_removed) { rc = discard_backup_fcc_data(chip); if (rc) pr_err("Could not discard backed-up FCC data\n"); } else { rc = read_chgcycle_data_from_backup(chip); if (rc) pr_err("Unable to restore charge-cycle data\n"); rc = read_fcc_data_from_backup(chip); if (rc) pr_err("Unable to restore FCC-learning data\n"); else attempt_learning_new_fcc(chip); } } rc = setup_vbat_monitoring(chip); if (rc < 0) { pr_err("failed to set up voltage notifications: %d\n", rc); goto error_setup; } rc = setup_die_temp_monitoring(chip); if (rc < 0) { pr_err("failed to set up die temp notifications: %d\n", rc); goto error_setup; } battery_insertion_check(chip); batfet_status_check(chip); battery_status_check(chip); calculate_soc_work(&(chip->calculate_soc_delayed_work.work)); /* setup & register the battery power supply */ chip->bms_psy.name = "bms"; chip->bms_psy.type = POWER_SUPPLY_TYPE_BMS; chip->bms_psy.properties = msm_bms_power_props; chip->bms_psy.num_properties = ARRAY_SIZE(msm_bms_power_props); chip->bms_psy.get_property = qpnp_bms_power_get_property; chip->bms_psy.external_power_changed = qpnp_bms_external_power_changed; chip->bms_psy.supplied_to = qpnp_bms_supplicants; chip->bms_psy.num_supplicants = ARRAY_SIZE(qpnp_bms_supplicants); rc = power_supply_register(chip->dev, &chip->bms_psy); if (rc < 0) { pr_err("power_supply_register bms failed rc = %d\n", rc); goto unregister_dc; } chip->bms_psy_registered = true; vbatt = 0; rc = get_battery_voltage(chip, &vbatt); if (rc) { pr_err("error reading vbat_sns adc channel = %d, rc = %d\n", VBAT_SNS, rc); goto unregister_dc; } rc = bms_request_irqs(chip); if (rc) { pr_err("error requesting bms irqs, rc = %d\n", rc); goto unregister_dc; } pr_info("probe success: soc =%d vbatt = %d ocv = %d r_sense_uohm = %u warm_reset = %d\n", get_prop_bms_capacity(chip), vbatt, chip->last_ocv_uv, chip->r_sense_uohm, warm_reset); return 0; unregister_dc: chip->bms_psy_registered = false; power_supply_unregister(&chip->bms_psy); error_setup: dev_set_drvdata(&spmi->dev, NULL); wakeup_source_trash(&chip->soc_wake_source.source); wake_lock_destroy(&chip->low_voltage_wake_lock); wake_lock_destroy(&chip->cv_wake_lock); error_resource: error_read: return rc; } static int qpnp_bms_remove(struct spmi_device *spmi) { dev_set_drvdata(&spmi->dev, NULL); return 0; } static int bms_suspend(struct device *dev) { struct qpnp_bms_chip *chip = dev_get_drvdata(dev); cancel_delayed_work_sync(&chip->calculate_soc_delayed_work); chip->was_charging_at_sleep = is_battery_charging(chip); return 0; } static int bms_resume(struct device *dev) { int rc; int soc_calc_period; int time_until_next_recalc = 0; unsigned long time_since_last_recalc; unsigned long tm_now_sec; struct qpnp_bms_chip *chip = dev_get_drvdata(dev); rc = get_current_time(&tm_now_sec); if (rc) { pr_err("Could not read current time: %d\n", rc); } else { soc_calc_period = get_calculation_delay_ms(chip); time_since_last_recalc = tm_now_sec - chip->last_recalc_time; pr_debug("Time since last recalc: %lu\n", time_since_last_recalc); time_until_next_recalc = max(0, soc_calc_period - (int)(time_since_last_recalc * 1000)); } if (time_until_next_recalc == 0) bms_stay_awake(&chip->soc_wake_source); schedule_delayed_work(&chip->calculate_soc_delayed_work, round_jiffies_relative(msecs_to_jiffies (time_until_next_recalc))); return 0; } static const struct dev_pm_ops qpnp_bms_pm_ops = { .resume = bms_resume, .suspend = bms_suspend, }; static struct spmi_driver qpnp_bms_driver = { .probe = qpnp_bms_probe, .remove = __devexit_p(qpnp_bms_remove), .driver = { .name = QPNP_BMS_DEV_NAME, .owner = THIS_MODULE, .of_match_table = qpnp_bms_match_table, .pm = &qpnp_bms_pm_ops, }, }; static int __init qpnp_bms_init(void) { pr_info("QPNP BMS INIT\n"); return spmi_driver_register(&qpnp_bms_driver); } static void __exit qpnp_bms_exit(void) { pr_info("QPNP BMS EXIT\n"); return spmi_driver_unregister(&qpnp_bms_driver); } module_init(qpnp_bms_init); module_exit(qpnp_bms_exit); MODULE_DESCRIPTION("QPNP BMS Driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:" QPNP_BMS_DEV_NAME);
bigbiff/android_device_samsung_mondrianwfiue
drivers/power/qpnp-bms.c
C
gpl-2.0
126,426
#include "stdafx.h" #include "Emu/Memory/Memory.h" #include "Emu/System.h" #include "Emu/IdManager.h" #include "Emu/SysCalls/Modules.h" extern "C" { #include "libswscale/swscale.h" } #include "cellVpost.h" extern Module cellVpost; s32 cellVpostQueryAttr(vm::cptr<CellVpostCfgParam> cfgParam, vm::ptr<CellVpostAttr> attr) { cellVpost.Warning("cellVpostQueryAttr(cfgParam=*0x%x, attr=*0x%x)", cfgParam, attr); // TODO: check cfgParam and output values attr->delay = 0; attr->memSize = 4 * 1024 * 1024; // 4 MB attr->vpostVerLower = 0x280000; // from dmux attr->vpostVerUpper = 0x260000; return CELL_OK; } s32 cellVpostOpen(vm::cptr<CellVpostCfgParam> cfgParam, vm::cptr<CellVpostResource> resource, vm::ptr<u32> handle) { cellVpost.Warning("cellVpostOpen(cfgParam=*0x%x, resource=*0x%x, handle=*0x%x)", cfgParam, resource, handle); // TODO: check values *handle = Emu.GetIdManager().make<VpostInstance>(cfgParam->outPicFmt == CELL_VPOST_PIC_FMT_OUT_RGBA_ILV); return CELL_OK; } s32 cellVpostOpenEx(vm::cptr<CellVpostCfgParam> cfgParam, vm::cptr<CellVpostResourceEx> resource, vm::ptr<u32> handle) { cellVpost.Warning("cellVpostOpenEx(cfgParam=*0x%x, resource=*0x%x, handle=*0x%x)", cfgParam, resource, handle); // TODO: check values *handle = Emu.GetIdManager().make<VpostInstance>(cfgParam->outPicFmt == CELL_VPOST_PIC_FMT_OUT_RGBA_ILV); return CELL_OK; } s32 cellVpostClose(u32 handle) { cellVpost.Warning("cellVpostClose(handle=0x%x)", handle); const auto vpost = Emu.GetIdManager().get<VpostInstance>(handle); if (!vpost) { return CELL_VPOST_ERROR_C_ARG_HDL_INVALID; } Emu.GetIdManager().remove<VpostInstance>(handle); return CELL_OK; } s32 cellVpostExec(u32 handle, vm::cptr<u8> inPicBuff, vm::cptr<CellVpostCtrlParam> ctrlParam, vm::ptr<u8> outPicBuff, vm::ptr<CellVpostPictureInfo> picInfo) { cellVpost.Log("cellVpostExec(handle=0x%x, inPicBuff=*0x%x, ctrlParam=*0x%x, outPicBuff=*0x%x, picInfo=*0x%x)", handle, inPicBuff, ctrlParam, outPicBuff, picInfo); const auto vpost = Emu.GetIdManager().get<VpostInstance>(handle); if (!vpost) { return CELL_VPOST_ERROR_E_ARG_HDL_INVALID; } s32 w = ctrlParam->inWidth; u32 h = ctrlParam->inHeight; u32 ow = ctrlParam->outWidth; u32 oh = ctrlParam->outHeight; //ctrlParam->inWindow; // ignored if (ctrlParam->inWindow.x) cellVpost.Notice("*** inWindow.x = %d", (u32)ctrlParam->inWindow.x); if (ctrlParam->inWindow.y) cellVpost.Notice("*** inWindow.y = %d", (u32)ctrlParam->inWindow.y); if (ctrlParam->inWindow.width != w) cellVpost.Notice("*** inWindow.width = %d", (u32)ctrlParam->inWindow.width); if (ctrlParam->inWindow.height != h) cellVpost.Notice("*** inWindow.height = %d", (u32)ctrlParam->inWindow.height); //ctrlParam->outWindow; // ignored if (ctrlParam->outWindow.x) cellVpost.Notice("*** outWindow.x = %d", (u32)ctrlParam->outWindow.x); if (ctrlParam->outWindow.y) cellVpost.Notice("*** outWindow.y = %d", (u32)ctrlParam->outWindow.y); if (ctrlParam->outWindow.width != ow) cellVpost.Notice("*** outWindow.width = %d", (u32)ctrlParam->outWindow.width); if (ctrlParam->outWindow.height != oh) cellVpost.Notice("*** outWindow.height = %d", (u32)ctrlParam->outWindow.height); //ctrlParam->execType; // ignored //ctrlParam->scalerType; // ignored //ctrlParam->ipcType; // ignored picInfo->inWidth = w; // copy picInfo->inHeight = h; // copy picInfo->inDepth = CELL_VPOST_PIC_DEPTH_8; // fixed picInfo->inScanType = CELL_VPOST_SCAN_TYPE_P; // TODO picInfo->inPicFmt = CELL_VPOST_PIC_FMT_IN_YUV420_PLANAR; // fixed picInfo->inChromaPosType = ctrlParam->inChromaPosType; // copy picInfo->inPicStruct = CELL_VPOST_PIC_STRUCT_PFRM; // TODO picInfo->inQuantRange = ctrlParam->inQuantRange; // copy picInfo->inColorMatrix = ctrlParam->inColorMatrix; // copy picInfo->outWidth = ow; // copy picInfo->outHeight = oh; // copy picInfo->outDepth = CELL_VPOST_PIC_DEPTH_8; // fixed picInfo->outScanType = CELL_VPOST_SCAN_TYPE_P; // TODO picInfo->outPicFmt = CELL_VPOST_PIC_FMT_OUT_RGBA_ILV; // TODO picInfo->outChromaPosType = ctrlParam->inChromaPosType; // ignored picInfo->outPicStruct = picInfo->inPicStruct; // ignored picInfo->outQuantRange = ctrlParam->inQuantRange; // ignored picInfo->outColorMatrix = ctrlParam->inColorMatrix; // ignored picInfo->userData = ctrlParam->userData; // copy picInfo->reserved1 = 0; picInfo->reserved2 = 0; //u64 stamp0 = get_system_time(); std::unique_ptr<u8[]> pA(new u8[w*h]); memset(pA.get(), ctrlParam->outAlpha, w*h); //u64 stamp1 = get_system_time(); std::unique_ptr<SwsContext, void(*)(SwsContext*)> sws(sws_getContext(w, h, AV_PIX_FMT_YUVA420P, ow, oh, AV_PIX_FMT_RGBA, SWS_BILINEAR, NULL, NULL, NULL), sws_freeContext); //u64 stamp2 = get_system_time(); const u8* in_data[4] = { &inPicBuff[0], &inPicBuff[w * h], &inPicBuff[w * h * 5 / 4], pA.get() }; int in_line[4] = { w, w/2, w/2, w }; u8* out_data[4] = { outPicBuff.get_ptr(), NULL, NULL, NULL }; int out_line[4] = { static_cast<int>(ow*4), 0, 0, 0 }; sws_scale(sws.get(), in_data, in_line, 0, h, out_data, out_line); //ConLog.Write("cellVpostExec() perf (access=%d, getContext=%d, scale=%d, finalize=%d)", //stamp1 - stamp0, stamp2 - stamp1, stamp3 - stamp2, get_system_time() - stamp3); return CELL_OK; } Module cellVpost("cellVpost", []() { REG_FUNC(cellVpost, cellVpostQueryAttr); REG_FUNC(cellVpost, cellVpostOpen); REG_FUNC(cellVpost, cellVpostOpenEx); //REG_FUNC(cellVpost, cellVpostOpenExt); // 0x9f1795df REG_FUNC(cellVpost, cellVpostClose); REG_FUNC(cellVpost, cellVpostExec); });
hgstream/rpcs3
rpcs3/Emu/SysCalls/Modules/cellVpost.cpp
C++
gpl-2.0
5,554
#undef CONFIG_SCSI_AIC7XXX
binhqnguyen/lena
nsc/linux-2.6/include/config/scsi/aic7xxx.h
C
gpl-2.0
27
/* MIPS16 syscall wrappers. Copyright (C) 2013-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #ifndef MIPS16_SYSCALL_H #define MIPS16_SYSCALL_H 1 #define __nomips16 __attribute__ ((nomips16)) union __mips16_syscall_return { long long val; struct { long v0; long v1; } reg; }; long long __nomips16 __mips16_syscall0 (long number); #define __mips16_syscall0(dummy, number) \ __mips16_syscall0 ((long) (number)) long long __nomips16 __mips16_syscall1 (long a0, long number); #define __mips16_syscall1(a0, number) \ __mips16_syscall1 ((long) (a0), \ (long) (number)) long long __nomips16 __mips16_syscall2 (long a0, long a1, long number); #define __mips16_syscall2(a0, a1, number) \ __mips16_syscall2 ((long) (a0), (long) (a1), \ (long) (number)) long long __nomips16 __mips16_syscall3 (long a0, long a1, long a2, long number); #define __mips16_syscall3(a0, a1, a2, number) \ __mips16_syscall3 ((long) (a0), (long) (a1), (long) (a2), \ (long) (number)) long long __nomips16 __mips16_syscall4 (long a0, long a1, long a2, long a3, long number); #define __mips16_syscall4(a0, a1, a2, a3, number) \ __mips16_syscall4 ((long) (a0), (long) (a1), (long) (a2), \ (long) (a3), \ (long) (number)) long long __nomips16 __mips16_syscall5 (long a0, long a1, long a2, long a3, long a4, long number); #define __mips16_syscall5(a0, a1, a2, a3, a4, number) \ __mips16_syscall5 ((long) (a0), (long) (a1), (long) (a2), \ (long) (a3), (long) (a4), \ (long) (number)) long long __nomips16 __mips16_syscall6 (long a0, long a1, long a2, long a3, long a4, long a5, long number); #define __mips16_syscall6(a0, a1, a2, a3, a4, a5, number) \ __mips16_syscall6 ((long) (a0), (long) (a1), (long) (a2), \ (long) (a3), (long) (a4), (long) (a5), \ (long) (number)) long long __nomips16 __mips16_syscall7 (long a0, long a1, long a2, long a3, long a4, long a5, long a6, long number); #define __mips16_syscall7(a0, a1, a2, a3, a4, a5, a6, number) \ __mips16_syscall7 ((long) (a0), (long) (a1), (long) (a2), \ (long) (a3), (long) (a4), (long) (a5), \ (long) (a6), \ (long) (number)) #endif
Chilledheart/glibc
sysdeps/unix/sysv/linux/mips/mips32/mips16/mips16-syscall.h
C
gpl-2.0
2,979
/**************************************************************************** Copyright (c) 2012-2013 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "PluginProtocol.h" #include "PluginUtils.h" #define LOG_TAG "PluginProtocol" namespace cocos2d { namespace plugin { PluginProtocol::~PluginProtocol() { PluginUtils::erasePluginJavaData(this); } const char* PluginProtocol::getPluginVersion() { std::string verName; PluginJavaData* pData = PluginUtils::getPluginJavaData(this); PluginJniMethodInfo t; if (PluginJniHelper::getMethodInfo(t , pData->jclassName.c_str() , "getPluginVersion" , "()Ljava/lang/String;")) { jstring ret = (jstring)(t.env->CallObjectMethod(pData->jobj, t.methodID)); verName = PluginJniHelper::jstring2string(ret); } return verName.c_str(); } const char* PluginProtocol::getSDKVersion() { std::string verName; PluginJavaData* pData = PluginUtils::getPluginJavaData(this); PluginJniMethodInfo t; if (PluginJniHelper::getMethodInfo(t , pData->jclassName.c_str() , "getSDKVersion" , "()Ljava/lang/String;")) { jstring ret = (jstring)(t.env->CallObjectMethod(pData->jobj, t.methodID)); verName = PluginJniHelper::jstring2string(ret); } return verName.c_str(); } void PluginProtocol::setDebugMode(bool isDebugMode) { PluginUtils::callJavaFunctionWithName_oneParam(this, "setDebugMode", "(Z)V", isDebugMode); } void PluginProtocol::callFuncWithParam(const char* funcName, PluginParam* param, ...) { std::vector<PluginParam*> allParams; if (NULL != param) { allParams.push_back(param); va_list argp; PluginParam* pArg = NULL; va_start( argp, param ); while (1) { pArg = va_arg(argp, PluginParam*); if (pArg == NULL) break; allParams.push_back(pArg); } va_end(argp); } callFuncWithParam(funcName, allParams); } void PluginProtocol::callFuncWithParam(const char* funcName, std::vector<PluginParam*> params) { PluginJavaData* pData = PluginUtils::getPluginJavaData(this); if (NULL == pData) { PluginUtils::outputLog(LOG_TAG, "Can't find java data for plugin : %s", this->getPluginName()); return; } int nParamNum = params.size(); if (nParamNum == 0) { PluginUtils::callJavaFunctionWithName(this, funcName); } else { PluginParam* pRetParam = NULL; bool needDel = false; if (nParamNum == 1) { pRetParam = params[0]; } else { std::map<std::string, PluginParam*> allParams; for (int i = 0; i < nParamNum; i++) { PluginParam* pArg = params[i]; if (pArg == NULL) { break; } char strKey[8] = { 0 }; sprintf(strKey, "Param%d", i + 1); allParams[strKey] = pArg; } pRetParam = new PluginParam(allParams); needDel = true; } switch(pRetParam->getCurrentType()) { case PluginParam::kParamTypeInt: PluginUtils::callJavaFunctionWithName_oneParam(this, funcName, "(I)V", pRetParam->getIntValue()); break; case PluginParam::kParamTypeFloat: PluginUtils::callJavaFunctionWithName_oneParam(this, funcName, "(F)V", pRetParam->getFloatValue()); break; case PluginParam::kParamTypeBool: PluginUtils::callJavaFunctionWithName_oneParam(this, funcName, "(Z)V", pRetParam->getBoolValue()); break; case PluginParam::kParamTypeString: { jstring jstr = PluginUtils::getEnv()->NewStringUTF(pRetParam->getStringValue()); PluginUtils::callJavaFunctionWithName_oneParam(this, funcName, "(Ljava/lang/String;)V", jstr); PluginUtils::getEnv()->DeleteLocalRef(jstr); } break; case PluginParam::kParamTypeStringMap: case PluginParam::kParamTypeMap: { jobject jMap = PluginUtils::getJObjFromParam(pRetParam); PluginUtils::callJavaFunctionWithName_oneParam(this, funcName, "(Lorg/json/JSONObject;)V", jMap); PluginUtils::getEnv()->DeleteLocalRef(jMap); } break; default: break; } if (needDel && pRetParam != NULL) { delete pRetParam; pRetParam = NULL; } } } const char* PluginProtocol::callStringFuncWithParam(const char* funcName, PluginParam* param, ...) { CALL_JAVA_FUNC_WITH_VALIST(String) } const char* PluginProtocol::callStringFuncWithParam(const char* funcName, std::vector<PluginParam*> params) { CALL_JAVA_FUNC(const char*, String, "", "Ljava/lang/String;") } int PluginProtocol::callIntFuncWithParam(const char* funcName, PluginParam* param, ...) { CALL_JAVA_FUNC_WITH_VALIST(Int) } int PluginProtocol::callIntFuncWithParam(const char* funcName, std::vector<PluginParam*> params) { CALL_JAVA_FUNC(int, Int, 0, "I") } bool PluginProtocol::callBoolFuncWithParam(const char* funcName, PluginParam* param, ...) { CALL_JAVA_FUNC_WITH_VALIST(Bool) } bool PluginProtocol::callBoolFuncWithParam(const char* funcName, std::vector<PluginParam*> params) { CALL_JAVA_FUNC(bool, Bool, false, "Z") } float PluginProtocol::callFloatFuncWithParam(const char* funcName, PluginParam* param, ...) { CALL_JAVA_FUNC_WITH_VALIST(Float) } float PluginProtocol::callFloatFuncWithParam(const char* funcName, std::vector<PluginParam*> params) { CALL_JAVA_FUNC(float, Float, 0.0f, "F") } }} //namespace cocos2d { namespace plugin {
flavorzyb/cocos2d-x
plugin/protocols/platform/android/PluginProtocol.cpp
C++
gpl-2.0
7,144
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 1997-2008 Morgan Stanley All rights reserved. // See .../src/LICENSE for terms of distribution // // /////////////////////////////////////////////////////////////////////////////// #include <MSGUI/MSHPane.H> static const int MSHPaneDefaultColumnSpacing=8; MSHPane::MSHPane(MSWidget *owner_,const char *title_) : MSPane(owner_,title_) { init(); } MSHPane::MSHPane(MSWidget *owner_,const MSStringVector& title_) : MSPane(owner_,title_) { init(); } void MSHPane::init(void) { _orientation=MSLayoutManager::Horizontal; _rowSpacing=0; _columnSpacing=MSHPaneDefaultColumnSpacing; } MSHPane::~MSHPane(void) {}
rdm/aplus-fsf
src/MSGUI/MSHPane.C
C++
gpl-2.0
726
<?php /* * * Copyright 2001, 2011 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 */ /** * Une classe implantant un controleur * Code adapté du controleur de Philippe Rigaux: * http://www.lamsade.dauphine.fr/rigaux/mysqlphp */ // On empêche l'accès direct au fichier if (basename($_SERVER["SCRIPT_NAME"])==basename(__File__)){ die(); }; include_once('../tbs/tbs_class.php'); // TinyButStrong template engine abstract class Controleur { // Objets utilitaires protected $vue; // Composant "vue" pour produire les pages HTML /** * Constucteur: initialise les objets utilitaires */ function __construct () { /* * Le contrôleur initialise plusieurs objets utilitaires: * une instance du moteur de templates pour gérer la vue */ // Instanciation du moteur de templates $this->vue = new clsTinyButStrong ; } protected function setVarGlobal($nom, $value){ global $$nom; $$nom = $value; } }
tbelliard/gepi
mod_sso_table/lib/Controleur.php
PHP
gpl-2.0
1,773
#ifndef _TBSQBOX_H_ #define _TBSQBOX_H_ #define DVB_USB_LOG_PREFIX "tbsqboxs1" #include "dvb-usb.h" #define deb_xfer(args...) dprintk(dvb_usb_tbsqboxs1_debug, 0x02, args) #endif
ljalves/linux-tbs-drivers
linux/drivers/media/dvb/dvb-usb/tbs-qbox.h
C
gpl-2.0
180
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>File: const.rdoc</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" /> <script type="text/javascript"> // <![CDATA[ function popupCode( url ) { window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400") } function toggleCode( id ) { if ( document.getElementById ) elem = document.getElementById( id ); else if ( document.all ) elem = eval( "document.all." + id ); else return false; elemStyle = elem.style; if ( elemStyle.display != "block" ) { elemStyle.display = "block" } else { elemStyle.display = "none" } return true; } // Make codeblocks hidden by default document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" ) // ]]> </script> </head> <body> <div id="fileHeader"> <h1>const.rdoc</h1> <table class="header-table"> <tr class="top-aligned-row"> <td><strong>Path:</strong></td> <td>rdoc/const.rdoc </td> </tr> <tr class="top-aligned-row"> <td><strong>Last Update:</strong></td> <td>Sun Nov 14 14:53:48 -0800 2010</td> </tr> </table> </div> <!-- banner header --> <div id="bodyContent"> <div id="contextContent"> <div id="description"> <h1>Physical Constants</h1> <p> The GSL physical constants are defined as Ruby constants under the modules </p> <ul> <li><tt>GSL::CONST::MKSA</tt> (MKSA unit) </li> <li><tt>GSL::CONST:CGSM</tt> (CGSM unit) </li> <li><tt>GSL::CONST:NUM</tt> (Dimension-less constants) </li> </ul> <p> For example, the GSL C constant <tt>GSL_CONST_MKSA_SPEED_OF_LIGHT</tt> is represented by a Ruby constant, </p> <pre> GSL_CONST_MKSA_SPEED_OF_LIGHT ---&gt; GSL::CONST::MKSA::SPEED_OF_LIGHT </pre> <p> The following lists a part of the constants. Most of the constants are defined both in the modules <tt>GSL::CONST::MKSA</tt> and <tt>GSL::CONST::CGSM</tt>. See also the <a href="http://www.gnu.org/software/gsl/manual/gsl-ref_37.html#SEC479"target="_top">GSL reference</a> </p> <p> Contents: </p> <ol> <li><a href="const_rdoc.html#1">Fundamental Constants</a> </li> <li><a href="const_rdoc.html#2">Astronomy and Astrophysics</a> </li> <li><a href="const_rdoc.html#3">Atomic and Nuclear Physics</a> </li> <li><a href="const_rdoc.html#4">Measurement of Time</a> </li> <li><a href="const_rdoc.html#5">Imperial Units</a> </li> <li><a href="const_rdoc.html#6">Nautical Units</a> </li> <li><a href="const_rdoc.html#7">Printers Units</a> </li> <li><a href="const_rdoc.html#8">Volume</a> </li> <li><a href="const_rdoc.html#9">Mass and Weight</a> </li> <li><a href="const_rdoc.html#10">Thermal Energy and Power</a> </li> <li><a href="const_rdoc.html#11">Pressure</a> </li> <li><a href="const_rdoc.html#12">Viscosity</a> </li> <li><a href="const_rdoc.html#13">Light and Illumination</a> </li> <li><a href="const_rdoc.html#14">Radioactivity</a> </li> <li><a href="const_rdoc.html#15">Force and Energy</a> </li> <li><a href="const_rdoc.html#16">Prefixes</a> </li> <li><a href="const_rdoc.html#17">Examples</a> </li> </ol> <h2><a href="../.././index.html"name="1"></a> Fundamental Constants</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::SPEED_OF_LIGHT <p> The speed of light in vacuum, c. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::VACUUM_PERMEABILITY <p> The permeability of free space, \mu (not defined in GSL::CONST::CGSM). </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::VACUUM_PERMITTIVITY <p> The permittivity of free space, \epsilon_0 (not defined in GSL::CONST::CGSM). </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::PLANCKS_CONSTANT_H <p> Planck&#8216;s constant, <tt>h</tt>. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::PLANCKS_CONSTANT_HBAR <p> Planck&#8216;s constant divided by 2\pi, \hbar. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::AVOGADRO <p> Avogadro&#8216;s number </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::FARADAY <p> The molar charge of 1 Faraday. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::BOLTZMANN <p> The Boltzmann constant, k. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::STEFAN_BOLTZMANN_CONSTANT <p> The Stefan-Boltzmann constant, \sigma. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::MOLAR_GAS <p> The molar gas constant, R_0. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::STANDARD_GAS_VOLUME <p> The standard gas volume, V_0. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::GAUSS <p> The magnetic field of 1 Gauss. </p> </li> </ul> <h2><a href="../.././index.html"name="2"></a> Astronomy and Astrophysics</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::ASTRONOMICAL_UNIT <p> The length of 1 astronomical unit (mean earth-sun distance), AU. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::GRAVITATIONAL_CONSTANT <p> The gravitational constant, G. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::LIGHT_YEAR <p> The distance of 1 light-year, ly. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::PARSEC <p> The distance of 1 parsec, pc. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::GRAV_ACCEL <p> The standard gravitational acceleration on Earth, g. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::SOLAR_MASS <p> The mass of the Sun. </p> </li> </ul> <h2><a href="../.././index.html"name="3"></a> Atomic and Nuclear Physics</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::ELECTRON_CHARGE <p> The charge of the electron, e. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::CGSM::ELECTRON_CHARGE_ESU <p> The charge of the electron, e, in esu unit (not defined in GSL::CONST::MKSA). </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::ELECTRON_VOLT <p> The energy of 1 electron volt, eV. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::UNIFIED_ATOMIC_MASS <p> The unified atomic mass, amu. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::MASS_ELECTRON <p> The mass of the electron, m_e. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::MASS_MUON <p> The mass of the muon, m_\mu. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::MASS_PROTON <p> The mass of the proton, m_p. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::MASS_NEUTRON <p> The mass of the proton, m_n. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::FINE_STRUCTURE <p> The electromagnetic fine structure constant alpha. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::RYDBERG <p> The Rydberg constant, Ry, in units of energy. This is related to the Rydberg inverse wavelength R by Ry = h c R. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::THOMSON_CROSS_SECTION <p> The Thomson cross section of photon scattering by electrons. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::BOHR_RADIUS <p> The Bohr radius, a_0. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::ANGSTROM <p> The length of 1 angstrom. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::BARN <p> The area of 1 barn. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::BOHR_MAGNETON <p> The Bohr Magneton, mu_B. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::NUCLEAR_MAGNETON <p> The Nuclear Magneton, mu_N. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::ELECTRON_MAGNETIC_MOMENT <p> The absolute value of the magnetic moment of the electron, mu_e. The physical magnetic moment of the electron is negative. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::PROTON_MAGNETIC_MOMENT <p> The magnetic moment of the proton, mu_p. </p> </li> </ul> <h2><a href="../.././index.html"name="4"></a> Measurement of Time</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::MINUTE <p> The number of seconds in 1 minute. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::HOUR <p> The number of seconds in 1 hour. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::DAY <p> The number of seconds in 1 day. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::WEEK <p> The number of seconds in 1 week. </p> </li> </ul> <h2><a href="../.././index.html"name="5"></a> Imperial Units</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::INCH <p> The length of 1 inch. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::FOOT <p> The length of 1 foot. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::YARD <p> The length of 1 yard. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::MILE <p> The length of 1 mile. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::MIL <p> The length of 1 mil (1/1000th of an inch). </p> </li> </ul> <h2><a href="../.././index.html"name="6"></a> Nautical Units</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::NAUTICAL_MILE <p> The length of 1 nautical mile. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::FATHOM <p> The length of 1 fathom. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::KNOT <p> The speed of 1 knot. </p> </li> </ul> <h2><a href="../.././index.html"name="7"></a> Printers Units</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::POINT <p> The length of 1 printer&#8216;s point (1/72 inch). </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::TEXPOINT <p> The length of 1 TeX point (1/72.27 inch). </p> </li> </ul> <h2><a href="../.././index.html"name="8"></a> Volume</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::ACRE <p> The area of 1 acre. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::LITER <p> The volume of 1 liter. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::US_GALLON <p> The volume of 1 US gallon. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::CANADIAN_GALLON <p> The volume of 1 Canadian gallon. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::UK_GALLON <p> The volume of 1 UK gallon. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::QUART <p> The volume of 1 quart. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::PINT <p> The volume of 1 pint. </p> </li> </ul> <h2><a href="../.././index.html"name="9"></a> Mass and Weight</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::POUND_MASS <p> The mass of 1 pound. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::OUNCE_MASS <p> The mass of 1 ounce. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::TON <p> The mass of 1 ton. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::METRIC_TON <p> The mass of 1 metric ton (1000 kg). </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::UK_TON <p> The mass of 1 UK ton. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::TROY_OUNCE <p> The mass of 1 troy ounce. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::CARAT <p> The mass of 1 carat. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::GRAM_FORCE <p> The force of 1 gram weight. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::POUND_FORCE <p> The force of 1 pound weight. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::KILOPOUND_FORCE <p> The force of 1 kilopound weight. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::POUNDAL <p> The force of 1 poundal. </p> </li> </ul> <h2><a href="../.././index.html"name="10"></a> Thermal Energy and Power</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::CALORIE <p> The energy of 1 calorie. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::BTU <p> The energy of 1 British Thermal Unit, btu. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::THERM <p> The energy of 1 Therm. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::HORSEPOWER <p> The power of 1 horsepower. </p> </li> </ul> <h2><a href="../.././index.html"name="11"></a> Pressure</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::BAR <p> The pressure of 1 bar. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::STD_ATMOSPHERE <p> The pressure of 1 standard atmosphere. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::TORR <p> The pressure of 1 torr. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::METER_OF_MERCURY <p> The pressure of 1 meter of mercury. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::INCH_OF_MERCURY <p> The pressure of 1 inch of mercury. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::INCH_OF_WATER <p> The pressure of 1 inch of water. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::PSI <p> The pressure of 1 pound per square inch. </p> </li> </ul> <h2><a href="../.././index.html"name="12"></a> Viscosity</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::POISE <p> The dynamic viscosity of 1 poise. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::STOKES <p> The kinematic viscosity of 1 stokes. </p> </li> </ul> <h2><a href="../.././index.html"name="13"></a> Light and Illumination</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::STILB <p> The luminance of 1 stilb. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::LUMEN <p> The luminous flux of 1 lumen. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::LUX <p> The illuminance of 1 lux. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::PHOT <p> The illuminance of 1 phot. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::FOOTCANDLE <p> The illuminance of 1 footcandle. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::LAMBERT <p> The luminance of 1 lambert. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::FOOTLAMBERT <p> The luminance of 1 footlambert. </p> </li> </ul> <h2><a href="../.././index.html"name="14"></a> Radioactivity</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::CURIE <p> The activity of 1 curie. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::ROENTGEN <p> The exposure of 1 roentgen. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::RAD <p> The absorbed dose of 1 rad. </p> </li> </ul> <h2><a href="../.././index.html"name="15"></a> Force and Energy</h2> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::NEWTON <p> The SI unit of force, 1 Newton. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::DYNE <p> he force of 1 Dyne = 10^-5 Newton. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::JOULE <p> The SI unit of energy, 1 Joule. </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::MKSA::ERG <p> The energy 1 erg = 10^-7 Joule. </p> </li> </ul> <h2><a href="../.././index.html"name="16"></a> Prefixes</h2> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::YOTTA <p> 10^24 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::ZETTA <p> 10^21 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::EXA <p> 10^18 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::PETA <p> 10^15 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::TERA <p> 10^12 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::GIGA <p> 10^9 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::MEGA <p> 10^6 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::KILO <p> 10^3 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::MILLI <p> 10^-3 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::MICRO <p> 10^-6 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::NANO <p> 10^-9 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::PICO <p> 10^-12 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::FEMTO <p> 10^-15 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::ATTO <p> 10^-18 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::ZEPTO <p> 10^-21 </p> </li> </ul> <hr size="1"></hr><ul> <li>GSL::CONST::NUM::YOCTO <p> 10^-24 </p> </li> </ul> <h2><a href="../.././index.html"name="17"></a> Example</h2> <p> The following program demonstrates the use of the physical constants in a calculation. In this case, the goal is to calculate the range of light-travel times from Earth to Mars. </p> <pre> require(&quot;gsl&quot;) include GSL::CONST::MKSA puts(&quot;In MKSA unit&quot;) c = SPEED_OF_LIGHT; au = ASTRONOMICAL_UNIT; minutes = MINUTE; # distance stored in meters r_earth = 1.00 * au; r_mars = 1.52 * au; t_min = (r_mars - r_earth) / c; t_max = (r_mars + r_earth) / c; printf(&quot;light travel time from Earth to Mars:\n&quot;); printf(&quot;c = %e [m/s]\n&quot;, c) printf(&quot;AU = %e [m]\n&quot;, au) printf(&quot;minutes = %e [s]\n&quot;, minutes) printf(&quot;minimum = %.1f minutes\n&quot;, t_min / minutes); printf(&quot;maximum = %.1f minutes\n\n&quot;, t_max / minutes); </pre> <p> <a href="bspline_rdoc.html">prev</a> <a href="graph_rdoc.html">next</a> </p> <p> <a href="ref_rdoc.html">Reference index</a> <a href="index_rdoc.html">top</a> </p> </div> </div> </div> <!-- if includes --> <div id="section"> <!-- if method_list --> </div> <div id="validator-badges"> <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p> </div> </body> </html>
david-macmahon/rb-gsl
html/files/rdoc/const_rdoc.html
HTML
gpl-2.0
17,896
/* * Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "TradeData.h" #include "Item.h" #include "Player.h" #include "WorldSession.h" TradeData* TradeData::GetTraderData() const { return _trader->GetTradeData(); } Item* TradeData::GetItem(TradeSlots slot) const { return !_items[slot].IsEmpty() ? _player->GetItemByGuid(_items[slot]) : nullptr; } bool TradeData::HasItem(ObjectGuid itemGuid) const { for (uint8 i = 0; i < TRADE_SLOT_COUNT; ++i) if (_items[i] == itemGuid) return true; return false; } TradeSlots TradeData::GetTradeSlotForItem(ObjectGuid itemGuid) const { for (uint8 i = 0; i < TRADE_SLOT_COUNT; ++i) if (_items[i] == itemGuid) return TradeSlots(i); return TRADE_SLOT_INVALID; } Item* TradeData::GetSpellCastItem() const { return !_spellCastItem.IsEmpty() ? _player->GetItemByGuid(_spellCastItem) : nullptr; } void TradeData::SetItem(TradeSlots slot, Item* item, bool update /*= false*/) { ObjectGuid itemGuid; if (item) itemGuid = item->GetGUID(); if (_items[slot] == itemGuid && !update) return; _items[slot] = itemGuid; SetAccepted(false); GetTraderData()->SetAccepted(false); Update(); // need remove possible trader spell applied to changed item if (slot == TRADE_SLOT_NONTRADED) GetTraderData()->SetSpell(0); // need remove possible player spell applied (possible move reagent) SetSpell(0); } void TradeData::SetSpell(uint32 spell_id, Item* castItem /*= nullptr*/) { ObjectGuid itemGuid = castItem ? castItem->GetGUID() : ObjectGuid::Empty; if (_spell == spell_id && _spellCastItem == itemGuid) return; _spell = spell_id; _spellCastItem = itemGuid; SetAccepted(false); GetTraderData()->SetAccepted(false); Update(true); // send spell info to item owner Update(false); // send spell info to caster self } void TradeData::SetMoney(uint32 money) { if (_money == money) return; if (!_player->HasEnoughMoney(money)) { TradeStatusInfo info; info.Status = TRADE_STATUS_CLOSE_WINDOW; info.Result = EQUIP_ERR_NOT_ENOUGH_MONEY; _player->GetSession()->SendTradeStatus(info); return; } _money = money; SetAccepted(false); GetTraderData()->SetAccepted(false); Update(true); } void TradeData::Update(bool forTrader /*= true*/) const { if (forTrader) _trader->GetSession()->SendUpdateTrade(true); // player state for trader else _player->GetSession()->SendUpdateTrade(false); // player state for player } void TradeData::SetAccepted(bool state, bool forTrader /*= false*/) { _accepted = state; if (!state) { TradeStatusInfo info; info.Status = TRADE_STATUS_BACK_TO_TRADE; if (forTrader) _trader->GetSession()->SendTradeStatus(info); else _player->GetSession()->SendTradeStatus(info); } }
eilo/TrinityCore
src/server/game/Entities/Player/TradeData.cpp
C++
gpl-2.0
3,744
/* * PMac AWACS lowlevel functions * * Copyright (c) by Takashi Iwai <[email protected]> * code based on dmasound.c. * * 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 <sound/driver.h> #include <asm/io.h> #include <asm/nvram.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/slab.h> #include <sound/core.h> #include "pmac.h" #ifdef CONFIG_ADB_CUDA #define PMAC_AMP_AVAIL #endif #ifdef PMAC_AMP_AVAIL struct awacs_amp { unsigned char amp_master; unsigned char amp_vol[2][2]; unsigned char amp_tone[2]; }; #define CHECK_CUDA_AMP() (sys_ctrler == SYS_CTRLER_CUDA) #endif /* PMAC_AMP_AVAIL */ static void snd_pmac_screamer_wait(struct snd_pmac *chip) { long timeout = 2000; while (!(in_le32(&chip->awacs->codec_stat) & MASK_VALID)) { mdelay(1); if (! --timeout) { snd_printd("snd_pmac_screamer_wait timeout\n"); break; } } } /* * write AWACS register */ static void snd_pmac_awacs_write(struct snd_pmac *chip, int val) { long timeout = 5000000; if (chip->model == PMAC_SCREAMER) snd_pmac_screamer_wait(chip); out_le32(&chip->awacs->codec_ctrl, val | (chip->subframe << 22)); while (in_le32(&chip->awacs->codec_ctrl) & MASK_NEWECMD) { if (! --timeout) { snd_printd("snd_pmac_awacs_write timeout\n"); break; } } } static void snd_pmac_awacs_write_reg(struct snd_pmac *chip, int reg, int val) { snd_pmac_awacs_write(chip, val | (reg << 12)); chip->awacs_reg[reg] = val; } static void snd_pmac_awacs_write_noreg(struct snd_pmac *chip, int reg, int val) { snd_pmac_awacs_write(chip, val | (reg << 12)); } #ifdef CONFIG_PM /* Recalibrate chip */ static void screamer_recalibrate(struct snd_pmac *chip) { if (chip->model != PMAC_SCREAMER) return; /* Sorry for the horrible delays... I hope to get that improved * by making the whole PM process asynchronous in a future version */ snd_pmac_awacs_write_noreg(chip, 1, chip->awacs_reg[1]); if (chip->manufacturer == 0x1) /* delay for broken crystal part */ msleep(750); snd_pmac_awacs_write_noreg(chip, 1, chip->awacs_reg[1] | MASK_RECALIBRATE | MASK_CMUTE | MASK_AMUTE); snd_pmac_awacs_write_noreg(chip, 1, chip->awacs_reg[1]); snd_pmac_awacs_write_noreg(chip, 6, chip->awacs_reg[6]); } #else #define screamer_recalibrate(chip) /* NOP */ #endif /* * additional callback to set the pcm format */ static void snd_pmac_awacs_set_format(struct snd_pmac *chip) { chip->awacs_reg[1] &= ~MASK_SAMPLERATE; chip->awacs_reg[1] |= chip->rate_index << 3; snd_pmac_awacs_write_reg(chip, 1, chip->awacs_reg[1]); } /* * AWACS volume callbacks */ /* * volumes: 0-15 stereo */ static int snd_pmac_awacs_info_volume(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 2; uinfo->value.integer.min = 0; uinfo->value.integer.max = 15; return 0; } static int snd_pmac_awacs_get_volume(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int reg = kcontrol->private_value & 0xff; int lshift = (kcontrol->private_value >> 8) & 0xff; int inverted = (kcontrol->private_value >> 16) & 1; unsigned long flags; int vol[2]; spin_lock_irqsave(&chip->reg_lock, flags); vol[0] = (chip->awacs_reg[reg] >> lshift) & 0xf; vol[1] = chip->awacs_reg[reg] & 0xf; spin_unlock_irqrestore(&chip->reg_lock, flags); if (inverted) { vol[0] = 0x0f - vol[0]; vol[1] = 0x0f - vol[1]; } ucontrol->value.integer.value[0] = vol[0]; ucontrol->value.integer.value[1] = vol[1]; return 0; } static int snd_pmac_awacs_put_volume(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int reg = kcontrol->private_value & 0xff; int lshift = (kcontrol->private_value >> 8) & 0xff; int inverted = (kcontrol->private_value >> 16) & 1; int val, oldval; unsigned long flags; int vol[2]; vol[0] = ucontrol->value.integer.value[0]; vol[1] = ucontrol->value.integer.value[1]; if (inverted) { vol[0] = 0x0f - vol[0]; vol[1] = 0x0f - vol[1]; } vol[0] &= 0x0f; vol[1] &= 0x0f; spin_lock_irqsave(&chip->reg_lock, flags); oldval = chip->awacs_reg[reg]; val = oldval & ~(0xf | (0xf << lshift)); val |= vol[0] << lshift; val |= vol[1]; if (oldval != val) snd_pmac_awacs_write_reg(chip, reg, val); spin_unlock_irqrestore(&chip->reg_lock, flags); return oldval != reg; } #define AWACS_VOLUME(xname, xreg, xshift, xinverted) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = 0, \ .info = snd_pmac_awacs_info_volume, \ .get = snd_pmac_awacs_get_volume, \ .put = snd_pmac_awacs_put_volume, \ .private_value = (xreg) | ((xshift) << 8) | ((xinverted) << 16) } /* * mute master/ogain for AWACS: mono */ static int snd_pmac_awacs_get_switch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int reg = kcontrol->private_value & 0xff; int shift = (kcontrol->private_value >> 8) & 0xff; int invert = (kcontrol->private_value >> 16) & 1; int val; unsigned long flags; spin_lock_irqsave(&chip->reg_lock, flags); val = (chip->awacs_reg[reg] >> shift) & 1; spin_unlock_irqrestore(&chip->reg_lock, flags); if (invert) val = 1 - val; ucontrol->value.integer.value[0] = val; return 0; } static int snd_pmac_awacs_put_switch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int reg = kcontrol->private_value & 0xff; int shift = (kcontrol->private_value >> 8) & 0xff; int invert = (kcontrol->private_value >> 16) & 1; int mask = 1 << shift; int val, changed; unsigned long flags; spin_lock_irqsave(&chip->reg_lock, flags); val = chip->awacs_reg[reg] & ~mask; if (ucontrol->value.integer.value[0] != invert) val |= mask; changed = chip->awacs_reg[reg] != val; if (changed) snd_pmac_awacs_write_reg(chip, reg, val); spin_unlock_irqrestore(&chip->reg_lock, flags); return changed; } #define AWACS_SWITCH(xname, xreg, xshift, xinvert) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = 0, \ .info = snd_pmac_boolean_mono_info, \ .get = snd_pmac_awacs_get_switch, \ .put = snd_pmac_awacs_put_switch, \ .private_value = (xreg) | ((xshift) << 8) | ((xinvert) << 16) } #ifdef PMAC_AMP_AVAIL /* * controls for perch/whisper extension cards, e.g. G3 desktop * * TDA7433 connected via i2c address 0x45 (= 0x8a), * accessed through cuda */ static void awacs_set_cuda(int reg, int val) { struct adb_request req; cuda_request(&req, NULL, 5, CUDA_PACKET, CUDA_GET_SET_IIC, 0x8a, reg, val); while (! req.complete) cuda_poll(); } /* * level = 0 - 14, 7 = 0 dB */ static void awacs_amp_set_tone(struct awacs_amp *amp, int bass, int treble) { amp->amp_tone[0] = bass; amp->amp_tone[1] = treble; if (bass > 7) bass = (14 - bass) + 8; if (treble > 7) treble = (14 - treble) + 8; awacs_set_cuda(2, (bass << 4) | treble); } /* * vol = 0 - 31 (attenuation), 32 = mute bit, stereo */ static int awacs_amp_set_vol(struct awacs_amp *amp, int index, int lvol, int rvol, int do_check) { if (do_check && amp->amp_vol[index][0] == lvol && amp->amp_vol[index][1] == rvol) return 0; awacs_set_cuda(3 + index, lvol); awacs_set_cuda(5 + index, rvol); amp->amp_vol[index][0] = lvol; amp->amp_vol[index][1] = rvol; return 1; } /* * 0 = -79 dB, 79 = 0 dB, 99 = +20 dB */ static void awacs_amp_set_master(struct awacs_amp *amp, int vol) { amp->amp_master = vol; if (vol <= 79) vol = 32 + (79 - vol); else vol = 32 - (vol - 79); awacs_set_cuda(1, vol); } static void awacs_amp_free(struct snd_pmac *chip) { struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return); kfree(amp); chip->mixer_data = NULL; chip->mixer_free = NULL; } /* * mixer controls */ static int snd_pmac_awacs_info_volume_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 2; uinfo->value.integer.min = 0; uinfo->value.integer.max = 31; return 0; } static int snd_pmac_awacs_get_volume_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int index = kcontrol->private_value; struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return -EINVAL); snd_assert(index >= 0 && index <= 1, return -EINVAL); ucontrol->value.integer.value[0] = 31 - (amp->amp_vol[index][0] & 31); ucontrol->value.integer.value[1] = 31 - (amp->amp_vol[index][1] & 31); return 0; } static int snd_pmac_awacs_put_volume_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int index = kcontrol->private_value; int vol[2]; struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return -EINVAL); snd_assert(index >= 0 && index <= 1, return -EINVAL); vol[0] = (31 - (ucontrol->value.integer.value[0] & 31)) | (amp->amp_vol[index][0] & 32); vol[1] = (31 - (ucontrol->value.integer.value[1] & 31)) | (amp->amp_vol[index][1] & 32); return awacs_amp_set_vol(amp, index, vol[0], vol[1], 1); } static int snd_pmac_awacs_get_switch_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int index = kcontrol->private_value; struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return -EINVAL); snd_assert(index >= 0 && index <= 1, return -EINVAL); ucontrol->value.integer.value[0] = (amp->amp_vol[index][0] & 32) ? 0 : 1; ucontrol->value.integer.value[1] = (amp->amp_vol[index][1] & 32) ? 0 : 1; return 0; } static int snd_pmac_awacs_put_switch_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int index = kcontrol->private_value; int vol[2]; struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return -EINVAL); snd_assert(index >= 0 && index <= 1, return -EINVAL); vol[0] = (ucontrol->value.integer.value[0] ? 0 : 32) | (amp->amp_vol[index][0] & 31); vol[1] = (ucontrol->value.integer.value[1] ? 0 : 32) | (amp->amp_vol[index][1] & 31); return awacs_amp_set_vol(amp, index, vol[0], vol[1], 1); } static int snd_pmac_awacs_info_tone_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 1; uinfo->value.integer.min = 0; uinfo->value.integer.max = 14; return 0; } static int snd_pmac_awacs_get_tone_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int index = kcontrol->private_value; struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return -EINVAL); snd_assert(index >= 0 && index <= 1, return -EINVAL); ucontrol->value.integer.value[0] = amp->amp_tone[index]; return 0; } static int snd_pmac_awacs_put_tone_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int index = kcontrol->private_value; struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return -EINVAL); snd_assert(index >= 0 && index <= 1, return -EINVAL); if (ucontrol->value.integer.value[0] != amp->amp_tone[index]) { amp->amp_tone[index] = ucontrol->value.integer.value[0]; awacs_amp_set_tone(amp, amp->amp_tone[0], amp->amp_tone[1]); return 1; } return 0; } static int snd_pmac_awacs_info_master_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 1; uinfo->value.integer.min = 0; uinfo->value.integer.max = 99; return 0; } static int snd_pmac_awacs_get_master_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return -EINVAL); ucontrol->value.integer.value[0] = amp->amp_master; return 0; } static int snd_pmac_awacs_put_master_amp(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); struct awacs_amp *amp = chip->mixer_data; snd_assert(amp, return -EINVAL); if (ucontrol->value.integer.value[0] != amp->amp_master) { amp->amp_master = ucontrol->value.integer.value[0]; awacs_amp_set_master(amp, amp->amp_master); return 1; } return 0; } #define AMP_CH_SPK 0 #define AMP_CH_HD 1 static struct snd_kcontrol_new snd_pmac_awacs_amp_vol[] __initdata = { { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "PC Speaker Playback Volume", .info = snd_pmac_awacs_info_volume_amp, .get = snd_pmac_awacs_get_volume_amp, .put = snd_pmac_awacs_put_volume_amp, .private_value = AMP_CH_SPK, }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Headphone Playback Volume", .info = snd_pmac_awacs_info_volume_amp, .get = snd_pmac_awacs_get_volume_amp, .put = snd_pmac_awacs_put_volume_amp, .private_value = AMP_CH_HD, }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Tone Control - Bass", .info = snd_pmac_awacs_info_tone_amp, .get = snd_pmac_awacs_get_tone_amp, .put = snd_pmac_awacs_put_tone_amp, .private_value = 0, }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Tone Control - Treble", .info = snd_pmac_awacs_info_tone_amp, .get = snd_pmac_awacs_get_tone_amp, .put = snd_pmac_awacs_put_tone_amp, .private_value = 1, }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Amp Master Playback Volume", .info = snd_pmac_awacs_info_master_amp, .get = snd_pmac_awacs_get_master_amp, .put = snd_pmac_awacs_put_master_amp, }, }; static struct snd_kcontrol_new snd_pmac_awacs_amp_hp_sw __initdata = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Headphone Playback Switch", .info = snd_pmac_boolean_stereo_info, .get = snd_pmac_awacs_get_switch_amp, .put = snd_pmac_awacs_put_switch_amp, .private_value = AMP_CH_HD, }; static struct snd_kcontrol_new snd_pmac_awacs_amp_spk_sw __initdata = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "PC Speaker Playback Switch", .info = snd_pmac_boolean_stereo_info, .get = snd_pmac_awacs_get_switch_amp, .put = snd_pmac_awacs_put_switch_amp, .private_value = AMP_CH_SPK, }; #endif /* PMAC_AMP_AVAIL */ /* * mic boost for screamer */ static int snd_pmac_screamer_mic_boost_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 1; uinfo->value.integer.min = 0; uinfo->value.integer.max = 2; return 0; } static int snd_pmac_screamer_mic_boost_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int val; unsigned long flags; spin_lock_irqsave(&chip->reg_lock, flags); if (chip->awacs_reg[6] & MASK_MIC_BOOST) val = 2; else if (chip->awacs_reg[0] & MASK_GAINLINE) val = 1; else val = 0; spin_unlock_irqrestore(&chip->reg_lock, flags); ucontrol->value.integer.value[0] = val; return 0; } static int snd_pmac_screamer_mic_boost_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_pmac *chip = snd_kcontrol_chip(kcontrol); int changed = 0; int val0, val6; unsigned long flags; spin_lock_irqsave(&chip->reg_lock, flags); val0 = chip->awacs_reg[0] & ~MASK_GAINLINE; val6 = chip->awacs_reg[6] & ~MASK_MIC_BOOST; if (ucontrol->value.integer.value[0] > 0) { val0 |= MASK_GAINLINE; if (ucontrol->value.integer.value[0] > 1) val6 |= MASK_MIC_BOOST; } if (val0 != chip->awacs_reg[0]) { snd_pmac_awacs_write_reg(chip, 0, val0); changed = 1; } if (val6 != chip->awacs_reg[6]) { snd_pmac_awacs_write_reg(chip, 6, val6); changed = 1; } spin_unlock_irqrestore(&chip->reg_lock, flags); return changed; } /* * lists of mixer elements */ static struct snd_kcontrol_new snd_pmac_awacs_mixers[] __initdata = { AWACS_VOLUME("Master Playback Volume", 2, 6, 1), AWACS_SWITCH("Master Capture Switch", 1, SHIFT_LOOPTHRU, 0), AWACS_VOLUME("Capture Volume", 0, 4, 0), AWACS_SWITCH("CD Capture Switch", 0, SHIFT_MUX_CD, 0), }; /* FIXME: is this correct order? * screamer (powerbook G3 pismo) seems to have different bits... */ static struct snd_kcontrol_new snd_pmac_awacs_mixers2[] __initdata = { AWACS_SWITCH("Line Capture Switch", 0, SHIFT_MUX_LINE, 0), AWACS_SWITCH("Mic Capture Switch", 0, SHIFT_MUX_MIC, 0), }; static struct snd_kcontrol_new snd_pmac_screamer_mixers2[] __initdata = { AWACS_SWITCH("Line Capture Switch", 0, SHIFT_MUX_MIC, 0), AWACS_SWITCH("Mic Capture Switch", 0, SHIFT_MUX_LINE, 0), }; static struct snd_kcontrol_new snd_pmac_awacs_master_sw __initdata = AWACS_SWITCH("Master Playback Switch", 1, SHIFT_HDMUTE, 1); static struct snd_kcontrol_new snd_pmac_awacs_mic_boost[] __initdata = { AWACS_SWITCH("Mic Boost", 0, SHIFT_GAINLINE, 0), }; static struct snd_kcontrol_new snd_pmac_screamer_mic_boost[] __initdata = { { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Mic Boost", .info = snd_pmac_screamer_mic_boost_info, .get = snd_pmac_screamer_mic_boost_get, .put = snd_pmac_screamer_mic_boost_put, }, }; static struct snd_kcontrol_new snd_pmac_awacs_speaker_vol[] __initdata = { AWACS_VOLUME("PC Speaker Playback Volume", 4, 6, 1), }; static struct snd_kcontrol_new snd_pmac_awacs_speaker_sw __initdata = AWACS_SWITCH("PC Speaker Playback Switch", 1, SHIFT_SPKMUTE, 1); /* * add new mixer elements to the card */ static int build_mixers(struct snd_pmac *chip, int nums, struct snd_kcontrol_new *mixers) { int i, err; for (i = 0; i < nums; i++) { if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&mixers[i], chip))) < 0) return err; } return 0; } /* * restore all registers */ static void awacs_restore_all_regs(struct snd_pmac *chip) { snd_pmac_awacs_write_noreg(chip, 0, chip->awacs_reg[0]); snd_pmac_awacs_write_noreg(chip, 1, chip->awacs_reg[1]); snd_pmac_awacs_write_noreg(chip, 2, chip->awacs_reg[2]); snd_pmac_awacs_write_noreg(chip, 4, chip->awacs_reg[4]); if (chip->model == PMAC_SCREAMER) { snd_pmac_awacs_write_noreg(chip, 5, chip->awacs_reg[5]); snd_pmac_awacs_write_noreg(chip, 6, chip->awacs_reg[6]); snd_pmac_awacs_write_noreg(chip, 7, chip->awacs_reg[7]); } } #ifdef CONFIG_PM static void snd_pmac_awacs_suspend(struct snd_pmac *chip) { snd_pmac_awacs_write_noreg(chip, 1, (chip->awacs_reg[1] | MASK_AMUTE | MASK_CMUTE)); } static void snd_pmac_awacs_resume(struct snd_pmac *chip) { if (machine_is_compatible("PowerBook3,1") || machine_is_compatible("PowerBook3,2")) { msleep(100); snd_pmac_awacs_write_reg(chip, 1, chip->awacs_reg[1] & ~MASK_PAROUT); msleep(300); } awacs_restore_all_regs(chip); if (chip->model == PMAC_SCREAMER) { /* reset power bits in reg 6 */ mdelay(5); snd_pmac_awacs_write_noreg(chip, 6, chip->awacs_reg[6]); } screamer_recalibrate(chip); #ifdef PMAC_AMP_AVAIL if (chip->mixer_data) { struct awacs_amp *amp = chip->mixer_data; awacs_amp_set_vol(amp, 0, amp->amp_vol[0][0], amp->amp_vol[0][1], 0); awacs_amp_set_vol(amp, 1, amp->amp_vol[1][0], amp->amp_vol[1][1], 0); awacs_amp_set_tone(amp, amp->amp_tone[0], amp->amp_tone[1]); awacs_amp_set_master(amp, amp->amp_master); } #endif } #endif /* CONFIG_PM */ #ifdef PMAC_SUPPORT_AUTOMUTE /* * auto-mute stuffs */ static int snd_pmac_awacs_detect_headphone(struct snd_pmac *chip) { return (in_le32(&chip->awacs->codec_stat) & chip->hp_stat_mask) ? 1 : 0; } #ifdef PMAC_AMP_AVAIL static int toggle_amp_mute(struct awacs_amp *amp, int index, int mute) { int vol[2]; vol[0] = amp->amp_vol[index][0] & 31; vol[1] = amp->amp_vol[index][1] & 31; if (mute) { vol[0] |= 32; vol[1] |= 32; } return awacs_amp_set_vol(amp, index, vol[0], vol[1], 1); } #endif static void snd_pmac_awacs_update_automute(struct snd_pmac *chip, int do_notify) { if (chip->auto_mute) { #ifdef PMAC_AMP_AVAIL if (chip->mixer_data) { struct awacs_amp *amp = chip->mixer_data; int changed; if (snd_pmac_awacs_detect_headphone(chip)) { changed = toggle_amp_mute(amp, AMP_CH_HD, 0); changed |= toggle_amp_mute(amp, AMP_CH_SPK, 1); } else { changed = toggle_amp_mute(amp, AMP_CH_HD, 1); changed |= toggle_amp_mute(amp, AMP_CH_SPK, 0); } if (do_notify && ! changed) return; } else #endif { int reg = chip->awacs_reg[1] | (MASK_HDMUTE|MASK_SPKMUTE); if (snd_pmac_awacs_detect_headphone(chip)) reg &= ~MASK_HDMUTE; else reg &= ~MASK_SPKMUTE; if (do_notify && reg == chip->awacs_reg[1]) return; snd_pmac_awacs_write_reg(chip, 1, reg); } if (do_notify) { snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, &chip->master_sw_ctl->id); snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, &chip->speaker_sw_ctl->id); snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, &chip->hp_detect_ctl->id); } } } #endif /* PMAC_SUPPORT_AUTOMUTE */ /* * initialize chip */ int __init snd_pmac_awacs_init(struct snd_pmac *chip) { int err, vol; /* looks like MASK_GAINLINE triggers something, so we set here * as start-up */ chip->awacs_reg[0] = MASK_MUX_CD | 0xff | MASK_GAINLINE; chip->awacs_reg[1] = MASK_CMUTE | MASK_AMUTE; /* FIXME: Only machines with external SRS module need MASK_PAROUT */ if (chip->has_iic || chip->device_id == 0x5 || /*chip->_device_id == 0x8 || */ chip->device_id == 0xb) chip->awacs_reg[1] |= MASK_PAROUT; /* get default volume from nvram */ // vol = (~nvram_read_byte(0x1308) & 7) << 1; // vol = ((pmac_xpram_read( 8 ) & 7 ) << 1 ); vol = 0x0f; /* no, on alsa, muted as default */ vol = vol + (vol << 6); chip->awacs_reg[2] = vol; chip->awacs_reg[4] = vol; if (chip->model == PMAC_SCREAMER) { chip->awacs_reg[5] = vol; /* FIXME: screamer has loopthru vol control */ chip->awacs_reg[6] = MASK_MIC_BOOST; /* FIXME: maybe should be vol << 3 for PCMCIA speaker */ chip->awacs_reg[7] = 0; } awacs_restore_all_regs(chip); chip->manufacturer = (in_le32(&chip->awacs->codec_stat) >> 8) & 0xf; screamer_recalibrate(chip); chip->revision = (in_le32(&chip->awacs->codec_stat) >> 12) & 0xf; #ifdef PMAC_AMP_AVAIL if (chip->revision == 3 && chip->has_iic && CHECK_CUDA_AMP()) { struct awacs_amp *amp = kmalloc(sizeof(*amp), GFP_KERNEL); if (! amp) return -ENOMEM; chip->mixer_data = amp; memset(amp, 0, sizeof(*amp)); chip->mixer_free = awacs_amp_free; awacs_amp_set_vol(amp, 0, 63, 63, 0); /* mute and zero vol */ awacs_amp_set_vol(amp, 1, 63, 63, 0); awacs_amp_set_tone(amp, 7, 7); /* 0 dB */ awacs_amp_set_master(amp, 79); /* 0 dB */ } #endif /* PMAC_AMP_AVAIL */ if (chip->hp_stat_mask == 0) { /* set headphone-jack detection bit */ switch (chip->model) { case PMAC_AWACS: chip->hp_stat_mask = 0x04; break; case PMAC_SCREAMER: switch (chip->device_id) { case 0x08: /* 1 = side jack, 2 = front jack */ chip->hp_stat_mask = 0x03; break; case 0x00: case 0x05: chip->hp_stat_mask = 0x04; break; default: chip->hp_stat_mask = 0x08; break; } break; default: snd_BUG(); break; } } /* * build mixers */ strcpy(chip->card->mixername, "PowerMac AWACS"); if ((err = build_mixers(chip, ARRAY_SIZE(snd_pmac_awacs_mixers), snd_pmac_awacs_mixers)) < 0) return err; if (chip->model == PMAC_SCREAMER) err = build_mixers(chip, ARRAY_SIZE(snd_pmac_screamer_mixers2), snd_pmac_screamer_mixers2); else err = build_mixers(chip, ARRAY_SIZE(snd_pmac_awacs_mixers2), snd_pmac_awacs_mixers2); if (err < 0) return err; chip->master_sw_ctl = snd_ctl_new1(&snd_pmac_awacs_master_sw, chip); if ((err = snd_ctl_add(chip->card, chip->master_sw_ctl)) < 0) return err; #ifdef PMAC_AMP_AVAIL if (chip->mixer_data) { /* use amplifier. the signal is connected from route A * to the amp. the amp has its headphone and speaker * volumes and mute switches, so we use them instead of * screamer registers. * in this case, it seems the route C is not used. */ if ((err = build_mixers(chip, ARRAY_SIZE(snd_pmac_awacs_amp_vol), snd_pmac_awacs_amp_vol)) < 0) return err; /* overwrite */ chip->master_sw_ctl = snd_ctl_new1(&snd_pmac_awacs_amp_hp_sw, chip); if ((err = snd_ctl_add(chip->card, chip->master_sw_ctl)) < 0) return err; chip->speaker_sw_ctl = snd_ctl_new1(&snd_pmac_awacs_amp_spk_sw, chip); if ((err = snd_ctl_add(chip->card, chip->speaker_sw_ctl)) < 0) return err; } else #endif /* PMAC_AMP_AVAIL */ { /* route A = headphone, route C = speaker */ if ((err = build_mixers(chip, ARRAY_SIZE(snd_pmac_awacs_speaker_vol), snd_pmac_awacs_speaker_vol)) < 0) return err; chip->speaker_sw_ctl = snd_ctl_new1(&snd_pmac_awacs_speaker_sw, chip); if ((err = snd_ctl_add(chip->card, chip->speaker_sw_ctl)) < 0) return err; } if (chip->model == PMAC_SCREAMER) { if ((err = build_mixers(chip, ARRAY_SIZE(snd_pmac_screamer_mic_boost), snd_pmac_screamer_mic_boost)) < 0) return err; } else { if ((err = build_mixers(chip, ARRAY_SIZE(snd_pmac_awacs_mic_boost), snd_pmac_awacs_mic_boost)) < 0) return err; } /* * set lowlevel callbacks */ chip->set_format = snd_pmac_awacs_set_format; #ifdef CONFIG_PM chip->suspend = snd_pmac_awacs_suspend; chip->resume = snd_pmac_awacs_resume; #endif #ifdef PMAC_SUPPORT_AUTOMUTE if ((err = snd_pmac_add_automute(chip)) < 0) return err; chip->detect_headphone = snd_pmac_awacs_detect_headphone; chip->update_automute = snd_pmac_awacs_update_automute; snd_pmac_awacs_update_automute(chip, 0); /* update the status only */ #endif if (chip->model == PMAC_SCREAMER) { snd_pmac_awacs_write_noreg(chip, 6, chip->awacs_reg[6]); snd_pmac_awacs_write_noreg(chip, 0, chip->awacs_reg[0]); } return 0; }
me-oss/me-linux
sound/ppc/awacs.c
C
gpl-2.0
26,695
<?php final class ITSEC_Security_Check_Feedback_Renderer { public static function render( $data ) { $section_groups = array(); foreach ( $data['sections'] as $name => $args ) { $section_groups[$args['status']][$name] = $args; } if ( isset( $section_groups['call-to-action'] ) ) { self::render_sections( 'call-to-action', $section_groups['call-to-action'] ); } if ( isset( $section_groups['action-taken'] ) ) { self::render_sections( 'action-taken', $section_groups['action-taken'] ); } if ( isset( $section_groups['confirmation'] ) ) { self::render_sections( 'confirmation', $section_groups['confirmation'] ); } if ( isset( $section_groups['error'] ) ) { self::render_sections( 'error', $section_groups['error'] ); } } private static function render_sections( $status, $sections ) { foreach ( $sections as $name => $args ) { $classes = array( 'itsec-security-check-container', "itsec-security-check-container-$status" ); if ( $args['interactive'] ) { $classes[] = 'itsec-security-check-container-is-interactive'; } echo '<div class="' . self::esc_attr( implode( ' ', $classes ) ) . '"'; if ( ! empty( $id ) ) { echo " id=\"$id\""; } echo ">\n"; if ( $args['interactive'] ) { echo '<div class="itsec-security-check-feedback"></div>'; } foreach ( $args['entries'] as $entry ) { self::render_entry( $entry ); } echo "</div>\n"; } } private static function render_entry( $entry ) { if ( empty( $entry['type'] ) ) { return; } if ( 'text' === $entry['type'] ) { if ( isset( $entry['value'] ) ) { echo "<p>{$entry['value']}</p>\n"; } } else if ( 'input' === $entry['type'] ) { if ( empty( $entry['input'] ) ) { return; } $defaults = array( 'format' => '%1$s', 'value' => '', 'style_class' => '', 'data' => array(), ); $entry = array_merge( $defaults, $entry ); if ( ! empty( $entry['value_alias'] ) ) { $entry['value'] = self::get_alias_value( $entry['value_alias'] ); } $data_attrs = array(); foreach ( (array) $entry['data'] as $key => $val ) { $key = preg_replace( '/[^a-zA-Z0-9\-_]+/', '', $key ); $val = self::esc_attr( $val ); $data_attrs[] = " data-$key=\"$val\""; } if ( 'select' === $entry['input'] ) { if ( empty( $entry['name'] ) || empty( $entry['options'] ) ) { return; } $options = "\n"; foreach ( $entry['options'] as $value => $description ) { $option = '<option value="' . self::esc_attr( $value ) . '"'; if ( $value === $entry['value'] ) { $option .= ' selected="selected"'; } $option .= '>' . self::esc_html( $description ) . "</option>\n"; $options .= $option; } $input_format = '<select name="%1$s" class="%2$s"%3$s>%4$s</select>'; $input = sprintf( $input_format, self::esc_attr( $entry['name'] ), self::esc_attr( $entry['style_class'] ), implode( '', $data_attrs ), $options ); } else if ( 'textarea' === $entry['input'] ) { if ( empty( $entry['name'] ) ) { return; } $input_format = '<textarea name="%1$s" class="%2$s"%3$s>%4$s</textarea>'; $input = sprintf( $input_format, self::esc_attr( $entry['name'] ), self::esc_attr( $entry['style_class'] ), implode( '', $data_attrs ), self::esc_html( $entry['value'] ) ); } else { if ( empty( $entry['name'] ) ) { return; } $input_format = '<input type="%1$s" name="%2$s" value="%3$s" class="%4$s"%5$s />'; $input = sprintf( $input_format, self::esc_attr( $entry['input'] ), self::esc_attr( $entry['name'] ), self::esc_attr( $entry['value'] ), self::esc_attr( $entry['style_class'] ), implode( '', $data_attrs ) ); } echo '<p><label>'; printf( $entry['format'], $input ); echo "</label></p>\n"; } } private static function esc_attr( $attr ) { return esc_attr( $attr ); } private static function esc_html( $html ) { return esc_html( $html ); } private static function get_alias_value( $alias ) { if ( 'email' === $alias ) { return get_option( 'admin_email' ); } } }
fyberoptik/gd_p_wp
wp-content/plugins/better-wp-security/core/modules/security-check/feedback-renderer.php
PHP
gpl-2.0
4,106
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from .. import Rule from ....lib.childreftype import ChildRefType #------------------------------------------------------------------------- # "People who were adopted" #------------------------------------------------------------------------- class HaveAltFamilies(Rule): """People who were adopted""" name = _('Adopted people') description = _("Matches people who were adopted") category = _('Family filters') def apply(self,db,person): for fhandle in person.get_parent_family_handle_list(): family = db.get_family_from_handle(fhandle) if family: ref = [ ref for ref in family.get_child_ref_list() \ if ref.ref == person.handle] if ref[0].get_father_relation() == ChildRefType.ADOPTED \ or ref[0].get_mother_relation() == ChildRefType.ADOPTED: return True return False
sam-m888/gramps
gramps/gen/filters/rules/person/_havealtfamilies.py
Python
gpl-2.0
2,172
/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "generatorsetqtscript.h" #include "reporthandler.h" #include "classgenerator.h" #include "shellheadergenerator.h" #include "shellimplgenerator.h" #include "docgenerator.h" GeneratorSet *GeneratorSet::getInstance() { return new GeneratorSetQtScript(); } GeneratorSetQtScript::GeneratorSetQtScript() {} QString GeneratorSetQtScript::usage() { QString usage = "QtScript:\n" " --nothing-to-report-yet \n"; return usage; } bool GeneratorSetQtScript::readParameters(const QMap<QString, QString> args) { return GeneratorSet::readParameters(args); } void GeneratorSetQtScript::buildModel(const QString pp_file) { // Building the code inforamation... ReportHandler::setContext("MetaJavaBuilder"); builder.setFileName(pp_file); builder.build(); } void GeneratorSetQtScript::dumpObjectTree() { } QString GeneratorSetQtScript::generate() { AbstractMetaClassList classes = builder.classesTopologicalSorted(); QSet<QString> declaredTypeNames = builder.qtMetaTypeDeclaredTypeNames(); PriGenerator priGenerator; priGenerator.setOutputDirectory(outDir); SetupGenerator setupGenerator; setupGenerator.setOutputDirectory(outDir); setupGenerator.setQtMetaTypeDeclaredTypeNames(declaredTypeNames); ClassGenerator classGenerator(&priGenerator, &setupGenerator); classGenerator.setOutputDirectory(outDir); classGenerator.setClasses(classes); classGenerator.setQtMetaTypeDeclaredTypeNames(declaredTypeNames); classGenerator.generate(); ShellImplGenerator shellImplGenerator(&priGenerator); shellImplGenerator.setOutputDirectory(outDir); shellImplGenerator.setClasses(classes); shellImplGenerator.setQtMetaTypeDeclaredTypeNames(declaredTypeNames); shellImplGenerator.generate(); ShellHeaderGenerator shellHeaderGenerator(&priGenerator); shellHeaderGenerator.setOutputDirectory(outDir); shellHeaderGenerator.setClasses(classes); shellHeaderGenerator.generate(); DocGenerator docGenerator; docGenerator.setOutputDirectory(outDir); docGenerator.setClasses(classes); docGenerator.generate(); priGenerator.generate(); setupGenerator.generate(); return QString("Classes in typesystem: %1\n" "Generated:\n" " - classes...: %2 (%3)\n" " - header....: %4 (%5)\n" " - impl......: %6 (%7)\n" " - modules...: %8 (%9)\n" " - pri.......: %10 (%11)\n" ) .arg(builder.classes().size()) .arg(classGenerator.numGenerated()) .arg(classGenerator.numGeneratedAndWritten()) .arg(shellHeaderGenerator.numGenerated()) .arg(shellHeaderGenerator.numGeneratedAndWritten()) .arg(shellImplGenerator.numGenerated()) .arg(shellImplGenerator.numGeneratedAndWritten()) .arg(setupGenerator.numGenerated()) .arg(setupGenerator.numGeneratedAndWritten()) .arg(priGenerator.numGenerated()) .arg(priGenerator.numGeneratedAndWritten()); }
deavid/alepherp
qtscriptgenerator-src-0.2.0/generator/generatorsetqtscript.cpp
C++
gpl-2.0
4,618
# -*- coding: utf-8 -*- #-------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer # Homepage: http://www.softwarepublico.gov.br # Contact: [email protected] # License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) #-------------------------------------------------------------------------- # Este programa e software livre; voce pode redistribui-lo e/ou # modifica-lo sob os termos da Licenca Publica Geral GNU, conforme # publicada pela Free Software Foundation; de acordo com a versao 2 # da Licenca. # # Este programa eh distribuido na expectativa de ser util, mas SEM # QUALQUER GARANTIA; sem mesmo a garantia implicita de # COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. #-------------------------------------------------------------------------- # Author: Victor Hugo Souza (victorhos-at-hotmail.com) # Contributions: Dogu Baran Aydogan # Initial date: 8 May 2020 import threading import time import numpy as np import queue from invesalius.pubsub import pub as Publisher import vtk import invesalius.constants as const import invesalius.data.imagedata_utils as img_utils # Nice print for arrays # np.set_printoptions(precision=2) # np.set_printoptions(suppress=True) def compute_directions(trk_n, alpha=255): """Compute direction of a single tract in each point and return as an RGBA color :param trk_n: nx3 array of doubles (x, y, z) point coordinates composing the tract :type trk_n: numpy.ndarray :param alpha: opacity value in the interval [0, 255]. The 0 is no opacity (total transparency). :type alpha: int :return: nx3 array of int (x, y, z) RGB colors in the range 0 - 255 :rtype: numpy.ndarray """ # trk_d = np.diff(trk_n, axis=0, append=2*trk_n[np.newaxis, -1, :]) trk_d = np.diff(trk_n, axis=0, append=trk_n[np.newaxis, -2, :]) trk_d[-1, :] *= -1 # check that linalg norm makes second norm # https://stackoverflow.com/questions/21030391/how-to-normalize-an-array-in-numpy direction = 255 * np.absolute((trk_d / np.linalg.norm(trk_d, axis=1)[:, None])) direction = np.hstack([direction, alpha * np.ones([direction.shape[0], 1])]) return direction.astype(int) def compute_tubes(trk, direction): """Compute and assign colors to a vtkTube for visualization of a single tract :param trk: nx3 array of doubles (x, y, z) point coordinates composing the tract :type trk: numpy.ndarray :param direction: nx3 array of int (x, y, z) RGB colors in the range 0 - 255 :type direction: numpy.ndarray :return: a vtkTubeFilter instance :rtype: vtkTubeFilter """ numb_points = trk.shape[0] points = vtk.vtkPoints() lines = vtk.vtkCellArray() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(4) k = 0 lines.InsertNextCell(numb_points) for j in range(numb_points): points.InsertNextPoint(trk[j, :]) colors.InsertNextTuple(direction[j, :]) lines.InsertCellPoint(k) k += 1 trk_data = vtk.vtkPolyData() trk_data.SetPoints(points) trk_data.SetLines(lines) trk_data.GetPointData().SetScalars(colors) # make it a tube trk_tube = vtk.vtkTubeFilter() trk_tube.SetRadius(0.5) trk_tube.SetNumberOfSides(4) trk_tube.SetInputData(trk_data) trk_tube.Update() return trk_tube def create_branch(out_list, n_block): """Adds a set of tracts to given position in a given vtkMultiBlockDataSet :param out_list: List of vtkTubeFilters representing the tracts :type out_list: list :param n_block: The location in the given vtkMultiBlockDataSet to insert the new tracts :type n_block: int :return: The collection of tracts (streamlines) as a vtkMultiBlockDataSet :rtype: vtkMultiBlockDataSet """ # create a branch and add the streamlines branch = vtk.vtkMultiBlockDataSet() # create tracts only when at least one was computed # print("Len outlist in root: ", len(out_list)) # TODO: check if this if statement is required, because we should # call this function only when tracts exist if not out_list.count(None) == len(out_list): for n, tube in enumerate(out_list): branch.SetBlock(n_block + n, tube.GetOutput()) return branch def compute_tracts(trk_list, n_tract=0, alpha=255): """Convert the list of all computed tracts given by Trekker run and returns a vtkMultiBlockDataSet :param trk_list: List of lists containing the computed tracts and corresponding coordinates :type trk_list: list :param n_tract: The integer ID of the block in the vtkMultiBlockDataSet :type n_tract: int :param alpha: The transparency of the streamlines from 0 to 255 (transparent to opaque) :type alpha: int :return: The updated collection of tracts as a vtkMultiBlockDataSet :rtype: vtkMultiBlockDataSet """ # Transform tracts to array trk_arr = [np.asarray(trk_n).T if trk_n else None for trk_n in trk_list] # Compute the directions trk_dir = [compute_directions(trk_n, alpha) for trk_n in trk_arr] # Compute the vtk tubes out_list = [compute_tubes(trk_arr_n, trk_dir_n) for trk_arr_n, trk_dir_n in zip(trk_arr, trk_dir)] # create a branch and add the tracts branch = create_branch(out_list, n_tract) return branch def compute_and_visualize_tracts(trekker, position, affine, affine_vtk, n_tracts_max): """ Compute tractograms using the Trekker library. :param trekker: Trekker library instance :type trekker: Trekker.T :param position: 3 double coordinates (x, y, z) in list or array :type position: list :param affine: 4 x 4 numpy double array :type affine: numpy.ndarray :param affine_vtk: vtkMatrix4x4 isntance with affine transformation matrix :type affine_vtk: vtkMatrix4x4 :param n_tracts_max: maximum number of tracts to compute :type n_tracts_max: int """ # root = vtk.vtkMultiBlockDataSet() # Juuso's # seed = np.array([[-8.49, -8.39, 2.5]]) # Baran M1 # seed = np.array([[27.53, -77.37, 46.42]]) seed_trk = img_utils.convert_world_to_voxel(position, affine) bundle = vtk.vtkMultiBlockDataSet() n_branches, n_tracts, count_loop = 0, 0, 0 n_threads = 2 * const.N_CPU - 1 while n_tracts < n_tracts_max: n_param = 1 + (count_loop % 10) # rescale the alpha value that defines the opacity of the branch # the n interval is [1, 10] and the new interval is [51, 255] # the new interval is defined to have no 0 opacity (minimum is 51, i.e., 20%) alpha = (n_param - 1) * (255 - 51) / (10 - 1) + 51 trekker.minFODamp(n_param * 0.01) # print("seed example: {}".format(seed_trk)) trekker.seed_coordinates(np.repeat(seed_trk, n_threads, axis=0)) # print("trk list len: ", len(trekker.run())) trk_list = trekker.run() n_tracts += len(trk_list) if len(trk_list): branch = compute_tracts(trk_list, n_tract=0, alpha=alpha) bundle.SetBlock(n_branches, branch) n_branches += 1 count_loop += 1 if (count_loop == 20) and (n_tracts == 0): break Publisher.sendMessage('Remove tracts') if n_tracts: Publisher.sendMessage('Update tracts', root=bundle, affine_vtk=affine_vtk, coord_offset=position, coord_offset_w=seed_trk[0].tolist()) class ComputeTractsThread(threading.Thread): # TODO: Remove this class and create a case where no ACT is provided in the class ComputeTractsACTThread def __init__(self, inp, queues, event, sle): """Class (threading) to compute real time tractography data for visualization. Tracts are computed using the Trekker library by Baran Aydogan (https://dmritrekker.github.io/) For VTK visualization, each tract (fiber) is a constructed as a tube and many tubes combined in one vtkMultiBlockDataSet named as a branch. Several branches are combined in another vtkMultiBlockDataSet named as bundle, to obtain fast computation and visualization. The bundle dataset is mapped to a single vtkActor. Mapper and Actor are computer in the data/viewer_volume.py module for easier handling in the invesalius 3D scene. Sleep function in run method is used to avoid blocking GUI and more fluent, real-time navigation :param inp: List of inputs: trekker instance, affine numpy array, seed_offset, seed_radius, n_threads :type inp: list :param queues: Queue list with coord_tracts_queue (Queue instance that manage co-registered coordinates) and tracts_queue (Queue instance that manage the tracts to be visualized) :type queues: list[queue.Queue, queue.Queue] :param event: Threading event to coordinate when tasks as done and allow UI release :type event: threading.Event :param sle: Sleep pause in seconds :type sle: float """ threading.Thread.__init__(self, name='ComputeTractsThread') self.inp = inp # self.coord_queue = coord_queue self.coord_tracts_queue = queues[0] self.tracts_queue = queues[1] # self.visualization_queue = visualization_queue self.event = event self.sle = sle def run(self): trekker, affine, offset, n_tracts_total, seed_radius, n_threads, act_data, affine_vtk, img_shift = self.inp # n_threads = n_tracts_total n_threads = int(n_threads/4) p_old = np.array([[0., 0., 0.]]) n_tracts = 0 # Compute the tracts # print('ComputeTractsThread: event {}'.format(self.event.is_set())) while not self.event.is_set(): try: # print("Computing tracts") # get from the queue the coordinates, coregistration transformation matrix, and flipped matrix # print("Here") m_img_flip = self.coord_tracts_queue.get_nowait() # coord, m_img, m_img_flip = self.coord_queue.get_nowait() # print('ComputeTractsThread: get {}'.format(count)) # TODO: Remove this is not needed # 20200402: in this new refactored version the m_img comes different than the position # the new version m_img is already flixped in y, which means that Y is negative # if only the Y is negative maybe no need for the flip_x funtcion at all in the navigation # but check all coord_queue before why now the m_img comes different than position # 20200403: indeed flip_x is just a -1 multiplication to the Y coordinate, remove function flip_x # m_img_flip = m_img.copy() # m_img_flip[1, -1] = -m_img_flip[1, -1] # translate the coordinate along the normal vector of the object/coil coord_offset = m_img_flip[:3, -1] - offset * m_img_flip[:3, 2] # coord_offset = np.array([[27.53, -77.37, 46.42]]) dist = abs(np.linalg.norm(p_old - np.asarray(coord_offset))) p_old = coord_offset.copy() # print("p_new_shape", coord_offset.shape) # print("m_img_flip_shape", m_img_flip.shape) seed_trk = img_utils.convert_world_to_voxel(coord_offset, affine) # Juuso's # seed_trk = np.array([[-8.49, -8.39, 2.5]]) # Baran M1 # seed_trk = np.array([[27.53, -77.37, 46.42]]) # print("Seed: {}".format(seed)) # set the seeds for trekker, one seed is repeated n_threads times # trekker has internal multiprocessing approach done in C. Here the number of available threads is give, # but in case a large number of tracts is requested, it will compute all in parallel automatically # for a more fluent navigation, better to compute the maximum number the computer handles trekker.seed_coordinates(np.repeat(seed_trk, n_threads, axis=0)) # run the trekker, this is the slowest line of code, be careful to just use once! trk_list = trekker.run() if len(trk_list) > 2: # print("dist: {}".format(dist)) if dist >= seed_radius: # when moving the coil further than the seed_radius restart the bundle computation bundle = vtk.vtkMultiBlockDataSet() n_branches = 0 branch = compute_tracts(trk_list, n_tract=0, alpha=255) bundle.SetBlock(n_branches, branch) n_branches += 1 n_tracts = branch.GetNumberOfBlocks() # TODO: maybe keep computing even if reaches the maximum elif dist < seed_radius and n_tracts < n_tracts_total: # compute tracts blocks and add to bungle until reaches the maximum number of tracts branch = compute_tracts(trk_list, n_tract=0, alpha=255) if bundle: bundle.SetBlock(n_branches, branch) n_tracts += branch.GetNumberOfBlocks() n_branches += 1 else: bundle = None # rethink if this should be inside the if condition, it may lock the thread if no tracts are found # use no wait to ensure maximum speed and avoid visualizing old tracts in the queue, this might # be more evident in slow computer or for heavier tract computations, it is better slow update # than visualizing old data # self.visualization_queue.put_nowait([coord, m_img, bundle]) self.tracts_queue.put_nowait((bundle, affine_vtk, coord_offset)) # print('ComputeTractsThread: put {}'.format(count)) self.coord_tracts_queue.task_done() # self.coord_queue.task_done() # print('ComputeTractsThread: done {}'.format(count)) # sleep required to prevent user interface from being unresponsive time.sleep(self.sle) # if no coordinates pass except queue.Empty: # print("Empty queue in tractography") pass # if queue is full mark as done (may not be needed in this new "nowait" method) except queue.Full: # self.coord_queue.task_done() self.coord_tracts_queue.task_done() class ComputeTractsACTThread(threading.Thread): def __init__(self, input_list, queues, event, sleep_thread): """Class (threading) to compute real time tractography data for visualization. Tracts are computed using the Trekker library by Baran Aydogan (https://dmritrekker.github.io/) For VTK visualization, each tract (fiber) is a constructed as a tube and many tubes combined in one vtkMultiBlockDataSet named as a branch. Several branches are combined in another vtkMultiBlockDataSet named as bundle, to obtain fast computation and visualization. The bundle dataset is mapped to a single vtkActor. Mapper and Actor are computer in the data/viewer_volume.py module for easier handling in the invesalius 3D scene. Sleep function in run method is used to avoid blocking GUI and more fluent, real-time navigation :param input_list: List of inputs: trekker instance, affine numpy array, seed offset, total number of tracts, seed radius, number of threads in computer, ACT data array, affine vtk matrix, image shift for vtk to mri transformation :type input_list: list :param queues: Queue list with coord_tracts_queue (Queue instance that manage co-registered coordinates) and tracts_queue (Queue instance that manage the tracts to be visualized) :type queues: list[queue.Queue, queue.Queue] :param event: Threading event to coordinate when tasks as done and allow UI release :type event: threading.Event :param sleep_thread: Sleep pause in seconds :type sleep_thread: float """ threading.Thread.__init__(self, name='ComputeTractsThreadACT') self.input_list = input_list self.coord_tracts_queue = queues[0] self.tracts_queue = queues[1] self.event = event self.sleep_thread = sleep_thread def run(self): trekker, affine, offset, n_tracts_total, seed_radius, n_threads, act_data, affine_vtk, img_shift = self.input_list p_old = np.array([[0., 0., 0.]]) n_branches, n_tracts, count_loop = 0, 0, 0 bundle = None dist_radius = 1.5 # TODO: Try a denser and bigger grid, because it's just a matrix multiplication # maybe 15 mm below the coil offset by default and 5 cm deep # create the rectangular grid to find the gray-white matter boundary coord_list_w = img_utils.create_grid((-2, 2), (0, 20), offset - 5, 1) # create the spherical grid to sample around the seed location samples_in_sphere = img_utils.random_sample_sphere(radius=seed_radius, size=100) coord_list_sphere = np.hstack([samples_in_sphere, np.ones([samples_in_sphere.shape[0], 1])]).T m_seed = np.identity(4) # Compute the tracts while not self.event.is_set(): try: # get from the queue the coordinates, coregistration transformation matrix, and flipped matrix m_img_flip = self.coord_tracts_queue.get_nowait() # DEBUG: Uncomment the m_img_flip below so that distance is fixed and tracts keep computing # m_img_flip[:3, -1] = (5., 10., 12.) dist = abs(np.linalg.norm(p_old - np.asarray(m_img_flip[:3, -1]))) p_old = m_img_flip[:3, -1].copy() # Uncertainty visualization -- # each tract branch is computed with one minFODamp adjusted from 0.01 to 0.1 # the higher the minFODamp the more the streamlines are faithful to the data, so they become more strict # but also may loose some connections. # the lower the more relaxed streamline also increases the chance of false positives n_param = 1 + (count_loop % 10) # rescale the alpha value that defines the opacity of the branch # the n interval is [1, 10] and the new interval is [51, 255] # the new interval is defined to have no 0 opacity (minimum is 51, i.e., 20%) alpha = (n_param - 1) * (255 - 51) / (10 - 1) + 51 trekker.minFODamp(n_param * 0.01) # --- try: # The original seed location is replaced by the gray-white matter interface that is closest to # the coil center coord_list_w_tr = m_img_flip @ coord_list_w coord_offset = grid_offset(act_data, coord_list_w_tr, img_shift) except IndexError: # This error might be caused by the coordinate exceeding the image array dimensions. # This happens during navigation because the coil location can have coordinates outside the image # boundaries # Translate the coordinate along the normal vector of the object/coil coord_offset = m_img_flip[:3, -1] - offset * m_img_flip[:3, 2] # --- # Spherical sampling of seed coordinates --- # compute the samples of a sphere centered on seed coordinate offset by the grid # given in the invesalius-vtk space samples = np.random.choice(coord_list_sphere.shape[1], size=100) m_seed[:-1, -1] = coord_offset.copy() # translate the spherical grid samples to the coil location in invesalius-vtk space seed_trk_r_inv = m_seed @ coord_list_sphere[:, samples] coord_offset_w = np.hstack((coord_offset, 1.0)).reshape([4, 1]) try: # Anatomic constrained seed computation --- # find only the samples inside the white matter as with the ACT enabled in the Trekker, # it does not compute any tracts outside the white matter # convert from inveslaius-vtk to mri space seed_trk_r_mri = seed_trk_r_inv[:3, :].T.astype(int) + np.array([[0, img_shift, 0]], dtype=np.int32) labs = act_data[seed_trk_r_mri[..., 0], seed_trk_r_mri[..., 1], seed_trk_r_mri[..., 2]] # find all samples in the white matter labs_id = np.where(labs == 1) # Trekker has internal multiprocessing approach done in C. Here the number of available threads - 1 # is given, but in case a large number of tracts is requested, it will compute all in parallel # automatically for a more fluent navigation, better to compute the maximum number the computer can # handle otherwise gets too slow for the multithreading in Python seed_trk_r_inv_sampled = seed_trk_r_inv[:, labs_id[0][:n_threads]] except IndexError: # same as on the grid offset above, if the coil is too far from the mri volume the array indices # are beyond the mri boundaries # in this case use the grid center instead of the spherical samples seed_trk_r_inv_sampled = coord_offset_w.copy() # convert to the world coordinate system for trekker seed_trk_r_world_sampled = np.linalg.inv(affine) @ seed_trk_r_inv_sampled seed_trk_r_world_sampled = seed_trk_r_world_sampled.T[:, :3] # convert to the world coordinate system for saving in the marker list coord_offset_w = np.linalg.inv(affine) @ coord_offset_w coord_offset_w = np.squeeze(coord_offset_w.T[:, :3]) # DEBUG: uncomment the seed_trk below # seed_trk.shape == [1, 3] # Juuso's # seed_trk = np.array([[-8.49, -8.39, 2.5]]) # Baran M1 # seed_trk = np.array([[27.53, -77.37, 46.42]]) # print("Given: {}".format(seed_trk.shape)) # print("Seed: {}".format(seed)) # joonas seed that has good tracts # seed_trk = np.array([[29.12, -13.33, 31.65]]) # seed_trk_img = np.array([[117, 127, 161]]) # When moving the coil further than the seed_radius restart the bundle computation # Currently, it stops to compute tracts when the maximum number of tracts is reached maybe keep # computing even if reaches the maximum if dist >= dist_radius: bundle = None n_tracts, n_branches = 0, 0 # we noticed that usually the navigation lags or crashes when moving the coil location # to reduce the overhead for when the coil is moving, we compute only half the number of tracts # that should be computed when the coil is fixed in the same location # required input is Nx3 array trekker.seed_coordinates(seed_trk_r_world_sampled[::2, :]) # run the trekker, this is the slowest line of code, be careful to just use once! trk_list = trekker.run() # check if any tract was found, otherwise doesn't count if len(trk_list): # a bundle consists for multiple branches and each branch consists of multiple streamlines # every iteration in the main loop adds a branch to the bundle branch = compute_tracts(trk_list, n_tract=0, alpha=alpha) n_tracts = branch.GetNumberOfBlocks() # create and add branch to the bundle bundle = vtk.vtkMultiBlockDataSet() bundle.SetBlock(n_branches, branch) n_branches = 1 elif dist < dist_radius and n_tracts < n_tracts_total: # when the coil is fixed in place and the number of tracts is smaller than the total if not bundle: # same as above, when creating the bundle (vtkMultiBlockDataSet) we only compute half the number # of tracts to reduce the overhead bundle = vtk.vtkMultiBlockDataSet() # required input is Nx3 array trekker.seed_coordinates(seed_trk_r_world_sampled[::2, :]) n_tracts, n_branches = 0, 0 else: # if the bundle exists compute all tracts requested # required input is Nx3 array trekker.seed_coordinates(seed_trk_r_world_sampled) trk_list = trekker.run() if len(trk_list): # compute tract blocks and add to bundle until reaches the maximum number of tracts # the alpha changes depending on the parameter set branch = compute_tracts(trk_list, n_tract=0, alpha=alpha) n_tracts += branch.GetNumberOfBlocks() # add branch to the bundle bundle.SetBlock(n_branches, branch) n_branches += 1 # keep adding to the number of loops even if the tracts were not find # this will keep the minFODamp changing and new seed coordinates being tried which would allow # higher probability of finding tracts count_loop += 1 # use "nowait" to ensure maximum speed and avoid visualizing old tracts in the queue, this might # be more evident in slow computer or for heavier tract computations, it is better slow update # than visualizing old data self.tracts_queue.put_nowait((bundle, affine_vtk, coord_offset, coord_offset_w)) self.coord_tracts_queue.task_done() # sleep required to prevent user interface from being unresponsive time.sleep(self.sleep_thread) # if no coordinates pass except queue.Empty: pass # if queue is full mark as done (may not be needed in this new "nowait" method) except queue.Full: self.coord_tracts_queue.task_done() def set_trekker_parameters(trekker, params): """Set all user-defined parameters for tractography computation using the Trekker library :param trekker: Trekker instance :type trekker: Trekker.T :param params: Dictionary containing the parameters values to set in Trekker. Initial values are in constants.py :type params: dict :return: List containing the Trekker instance and number of threads for parallel processing in the computer :rtype: list """ trekker.seed_maxTrials(params['seed_max']) trekker.stepSize(params['step_size']) # minFODamp is not set because it should vary in the loop to create the # different transparency tracts # trekker.minFODamp(params['min_fod']) trekker.probeQuality(params['probe_quality']) trekker.maxEstInterval(params['max_interval']) trekker.minRadiusOfCurvature(params['min_radius_curvature']) trekker.probeLength(params['probe_length']) trekker.writeInterval(params['write_interval']) # these two does not need to be set in the new package # trekker.maxLength(params['max_length']) trekker.minLength(params['min_length']) trekker.maxSamplingPerStep(params['max_sampling_step']) trekker.dataSupportExponent(params['data_support_exponent']) #trekker.useBestAtInit(params['use_best_init']) #trekker.initMaxEstTrials(params['init_max_est_trials']) # check number if number of cores is valid in configuration file, # otherwise use the maximum number of threads which is usually 2*N_CPUS n_threads = 2 * const.N_CPU - 1 if isinstance((params['numb_threads']), int) and params['numb_threads'] <= (2*const.N_CPU-1): n_threads = params['numb_threads'] trekker.numberOfThreads(n_threads) # print("Trekker config updated: n_threads, {}; seed_max, {}".format(n_threads, params['seed_max'])) return trekker, n_threads def grid_offset(data, coord_list_w_tr, img_shift): # convert to int so coordinates can be used as indices in the MRI image space coord_list_w_tr_mri = coord_list_w_tr[:3, :].T.astype(int) + np.array([[0, img_shift, 0]]) #FIX: IndexError: index 269 is out of bounds for axis 2 with size 256 # error occurs when running line "labs = data[coord..." # need to check why there is a coordinate outside the MRI bounds # extract the first occurrence of a specific label from the MRI image labs = data[coord_list_w_tr_mri[..., 0], coord_list_w_tr_mri[..., 1], coord_list_w_tr_mri[..., 2]] lab_first = np.where(labs == 1) if not lab_first: pt_found_inv = None else: pt_found = coord_list_w_tr[:, lab_first[0][0]][:3] # convert coordinate back to invesalius 3D space pt_found_inv = pt_found - np.array([0., img_shift, 0.]) # lab_first = np.argmax(labs == 1) # if labs[lab_first] == 1: # pt_found = coord_list_w_tr_mri[lab_first, :] # # convert coordinate back to invesalius 3D space # pt_found_inv = pt_found - np.array([0., img_shift, 0.]) # else: # pt_found_inv = None # # convert to world coordinate space to use as seed for fiber tracking # pt_found_tr = np.append(pt_found, 1)[np.newaxis, :].T # # default affine in invesalius is actually the affine inverse # pt_found_tr = np.linalg.inv(affine) @ pt_found_tr # pt_found_tr = pt_found_tr[:3, 0, np.newaxis].T return pt_found_inv
paulojamorim/invesalius3
invesalius/data/tractography.py
Python
gpl-2.0
30,765
/* * linux/arch/arm/drivers/scsi/arxescsi.c * * Copyright (C) 1997-2000 Russell King, Stefan Hanske * * This driver is based on experimentation. Hence, it may have made * assumptions about the particular card that I have available, and * may not be reliable! * * Changelog: * 30-08-1997 RMK 0.0.0 Created, READONLY version as cumana_2.c * 22-01-1998 RMK 0.0.1 Updated to 2.1.80 * 15-04-1998 RMK 0.0.1 Only do PIO if FAS216 will allow it. * 11-06-1998 SH 0.0.2 Changed to support ARXE 16-bit SCSI card * enabled writing * 01-01-2000 SH 0.1.0 Added *real* pseudo dma writing * (arxescsi_pseudo_dma_write) * 02-04-2000 RMK 0.1.1 Updated for new error handling code. * 22-10-2000 SH Updated for new registering scheme. */ #include <linux/module.h> #include <linux/blkdev.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/ioport.h> #include <linux/sched.h> #include <linux/proc_fs.h> #include <linux/unistd.h> #include <linux/stat.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/interrupt.h> #include <asm/dma.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/ecard.h> #include "../scsi.h" #include <scsi/scsi_host.h> #include "fas216.h" struct arxescsi_info { FAS216_Info info; struct expansion_card *ec; }; #define DMADATA_OFFSET (0x200) #define DMASTAT_OFFSET (0x600) #define DMASTAT_DRQ (1 << 0) #define CSTATUS_IRQ (1 << 0) #define VERSION "1.10 (23/01/2003 2.5.57)" /* * Function: int arxescsi_dma_setup(host, SCpnt, direction, min_type) * Purpose : initialises DMA/PIO * Params : host - host * SCpnt - command * direction - DMA on to/off of card * min_type - minimum DMA support that we must have for this transfer * Returns : 0 if we should not set CMD_WITHDMA for transfer info command */ static fasdmatype_t arxescsi_dma_setup(struct Scsi_Host *host, Scsi_Pointer *SCp, fasdmadir_t direction, fasdmatype_t min_type) { /* * We don't do real DMA */ return fasdma_pseudo; } static void arxescsi_pseudo_dma_write(unsigned char *addr, unsigned char *base) { __asm__ __volatile__( " stmdb sp!, {r0-r12}\n" " mov r3, %0\n" " mov r1, %1\n" " add r2, r1, #512\n" " mov r4, #256\n" ".loop_1: ldmia r3!, {r6, r8, r10, r12}\n" " mov r5, r6, lsl #16\n" " mov r7, r8, lsl #16\n" ".loop_2: ldrb r0, [r1, #1536]\n" " tst r0, #1\n" " beq .loop_2\n" " stmia r2, {r5-r8}\n\t" " mov r9, r10, lsl #16\n" " mov r11, r12, lsl #16\n" ".loop_3: ldrb r0, [r1, #1536]\n" " tst r0, #1\n" " beq .loop_3\n" " stmia r2, {r9-r12}\n" " subs r4, r4, #16\n" " bne .loop_1\n" " ldmia sp!, {r0-r12}\n" : : "r" (addr), "r" (base)); } /* * Function: int arxescsi_dma_pseudo(host, SCpnt, direction, transfer) * Purpose : handles pseudo DMA * Params : host - host * SCpnt - command * direction - DMA on to/off of card * transfer - minimum number of bytes we expect to transfer */ static void arxescsi_dma_pseudo(struct Scsi_Host *host, Scsi_Pointer *SCp, fasdmadir_t direction, int transfer) { struct arxescsi_info *info = (struct arxescsi_info *)host->hostdata; unsigned int length, error = 0; unsigned char *base = info->info.scsi.io_base; unsigned char *addr; length = SCp->this_residual; addr = SCp->ptr; if (direction == DMA_OUT) { unsigned int word; while (length > 256) { if (readb(base + 0x80) & STAT_INT) { error = 1; break; } arxescsi_pseudo_dma_write(addr, base); addr += 256; length -= 256; } if (!error) while (length > 0) { if (readb(base + 0x80) & STAT_INT) break; if (!(readb(base + DMASTAT_OFFSET) & DMASTAT_DRQ)) continue; word = *addr | *(addr + 1) << 8; writew(word, base + DMADATA_OFFSET); if (length > 1) { addr += 2; length -= 2; } else { addr += 1; length -= 1; } } } else { if (transfer && (transfer & 255)) { while (length >= 256) { if (readb(base + 0x80) & STAT_INT) { error = 1; break; } if (!(readb(base + DMASTAT_OFFSET) & DMASTAT_DRQ)) continue; readsw(base + DMADATA_OFFSET, addr, 256 >> 1); addr += 256; length -= 256; } } if (!(error)) while (length > 0) { unsigned long word; if (readb(base + 0x80) & STAT_INT) break; if (!(readb(base + DMASTAT_OFFSET) & DMASTAT_DRQ)) continue; word = readw(base + DMADATA_OFFSET); *addr++ = word; if (--length > 0) { *addr++ = word >> 8; length --; } } } } /* * Function: int arxescsi_dma_stop(host, SCpnt) * Purpose : stops DMA/PIO * Params : host - host * SCpnt - command */ static void arxescsi_dma_stop(struct Scsi_Host *host, Scsi_Pointer *SCp) { /* * no DMA to stop */ } /* * Function: const char *arxescsi_info(struct Scsi_Host * host) * Purpose : returns a descriptive string about this interface, * Params : host - driver host structure to return info for. * Returns : pointer to a static buffer containing null terminated string. */ static const char *arxescsi_info(struct Scsi_Host *host) { struct arxescsi_info *info = (struct arxescsi_info *)host->hostdata; static char string[150]; sprintf(string, "%s (%s) in slot %d v%s", host->hostt->name, info->info.scsi.type, info->ec->slot_no, VERSION); return string; } /* * Function: int arxescsi_proc_info(char *buffer, char **start, off_t offset, * int length, int host_no, int inout) * Purpose : Return information about the driver to a user process accessing * the /proc filesystem. * Params : buffer - a buffer to write information to * start - a pointer into this buffer set by this routine to the start * of the required information. * offset - offset into information that we have read upto. * length - length of buffer * host_no - host number to return information for * inout - 0 for reading, 1 for writing. * Returns : length of data written to buffer. */ static int arxescsi_proc_info(struct Scsi_Host *host, char *buffer, char **start, off_t offset, int length, int inout) { struct arxescsi_info *info; char *p = buffer; int pos; info = (struct arxescsi_info *)host->hostdata; if (inout == 1) return -EINVAL; p += sprintf(p, "ARXE 16-bit SCSI driver v%s\n", VERSION); p += fas216_print_host(&info->info, p); p += fas216_print_stats(&info->info, p); p += fas216_print_devices(&info->info, p); *start = buffer + offset; pos = p - buffer - offset; if (pos > length) pos = length; return pos; } static Scsi_Host_Template arxescsi_template = { .proc_info = arxescsi_proc_info, .name = "ARXE SCSI card", .info = arxescsi_info, .queuecommand = fas216_noqueue_command, .eh_host_reset_handler = fas216_eh_host_reset, .eh_bus_reset_handler = fas216_eh_bus_reset, .eh_device_reset_handler = fas216_eh_device_reset, .eh_abort_handler = fas216_eh_abort, .can_queue = 0, .this_id = 7, .sg_tablesize = SG_ALL, .cmd_per_lun = 1, .use_clustering = DISABLE_CLUSTERING, .proc_name = "arxescsi", }; static int __devinit arxescsi_probe(struct expansion_card *ec, const struct ecard_id *id) { struct Scsi_Host *host; struct arxescsi_info *info; unsigned long resbase, reslen; unsigned char *base; int ret; resbase = ecard_resource_start(ec, ECARD_RES_MEMC); reslen = ecard_resource_len(ec, ECARD_RES_MEMC); if (!request_mem_region(resbase, reslen, "arxescsi")) { ret = -EBUSY; goto out; } base = ioremap(resbase, reslen); if (!base) { ret = -ENOMEM; goto out_region; } host = scsi_host_alloc(&arxescsi_template, sizeof(struct arxescsi_info)); if (!host) { ret = -ENOMEM; goto out_unmap; } host->base = (unsigned long)base; host->irq = NO_IRQ; host->dma_channel = NO_DMA; info = (struct arxescsi_info *)host->hostdata; info->ec = ec; info->info.scsi.io_base = base + 0x2000; info->info.scsi.irq = host->irq; info->info.scsi.io_shift = 5; info->info.ifcfg.clockrate = 24; /* MHz */ info->info.ifcfg.select_timeout = 255; info->info.ifcfg.asyncperiod = 200; /* ns */ info->info.ifcfg.sync_max_depth = 0; info->info.ifcfg.cntl3 = CNTL3_FASTSCSI | CNTL3_FASTCLK; info->info.ifcfg.disconnect_ok = 0; info->info.ifcfg.wide_max_size = 0; info->info.ifcfg.capabilities = FASCAP_PSEUDODMA; info->info.dma.setup = arxescsi_dma_setup; info->info.dma.pseudo = arxescsi_dma_pseudo; info->info.dma.stop = arxescsi_dma_stop; ec->irqaddr = base; ec->irqmask = CSTATUS_IRQ; ret = fas216_init(host); if (ret) goto out_unregister; ret = fas216_add(host, &ec->dev); if (ret == 0) goto out; fas216_release(host); out_unregister: scsi_host_put(host); out_unmap: iounmap(base); out_region: release_mem_region(resbase, reslen); out: return ret; } static void __devexit arxescsi_remove(struct expansion_card *ec) { struct Scsi_Host *host = ecard_get_drvdata(ec); unsigned long resbase, reslen; ecard_set_drvdata(ec, NULL); fas216_remove(host); iounmap((void *)host->base); resbase = ecard_resource_start(ec, ECARD_RES_MEMC); reslen = ecard_resource_len(ec, ECARD_RES_MEMC); release_mem_region(resbase, reslen); fas216_release(host); scsi_host_put(host); } static const struct ecard_id arxescsi_cids[] = { { MANU_ARXE, PROD_ARXE_SCSI }, { 0xffff, 0xffff }, }; static struct ecard_driver arxescsi_driver = { .probe = arxescsi_probe, .remove = __devexit_p(arxescsi_remove), .id_table = arxescsi_cids, .drv = { .name = "arxescsi", }, }; static int __init init_arxe_scsi_driver(void) { return ecard_register_driver(&arxescsi_driver); } static void __exit exit_arxe_scsi_driver(void) { ecard_remove_driver(&arxescsi_driver); } module_init(init_arxe_scsi_driver); module_exit(exit_arxe_scsi_driver); MODULE_AUTHOR("Stefan Hanske"); MODULE_DESCRIPTION("ARXESCSI driver for Acorn machines"); MODULE_LICENSE("GPL");
z3bu/AH4222
kernel/linux/drivers/scsi/arm/arxescsi.c
C
gpl-2.0
10,371
;; Constraint definitions for ARM and Thumb ;; Copyright (C) 2006, 2007, 2008 Free Software Foundation, Inc. ;; Contributed by ARM Ltd. ;; 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/>. ;; The following register constraints have been used: ;; - in ARM/Thumb-2 state: f, t, v, w, x, y, z ;; - in Thumb state: h, b ;; - in both states: l, c, k ;; In ARM state, 'l' is an alias for 'r' ;; The following normal constraints have been used: ;; in ARM/Thumb-2 state: G, H, I, J, K, L, M ;; in Thumb-1 state: I, J, K, L, M, N, O ;; The following multi-letter normal constraints have been used: ;; in ARM/Thumb-2 state: Da, Db, Dc, Dn, Dl, DL, Dv ;; The following memory constraints have been used: ;; in ARM/Thumb-2 state: Q, Ut, Uv, Uy, Un, Us ;; in ARM state: Uq (define_register_constraint "f" "TARGET_ARM ? FPA_REGS : NO_REGS" "Legacy FPA registers @code{f0}-@code{f7}.") (define_register_constraint "t" "TARGET_32BIT ? VFP_LO_REGS : NO_REGS" "The VFP registers @code{s0}-@code{s31}.") (define_register_constraint "v" "TARGET_ARM ? CIRRUS_REGS : NO_REGS" "The Cirrus Maverick co-processor registers.") (define_register_constraint "w" "TARGET_32BIT ? (TARGET_VFPD32 ? VFP_REGS : VFP_LO_REGS) : NO_REGS" "The VFP registers @code{d0}-@code{d15}, or @code{d0}-@code{d31} for VFPv3.") (define_register_constraint "x" "TARGET_32BIT ? VFP_D0_D7_REGS : NO_REGS" "The VFP registers @code{d0}-@code{d7}.") (define_register_constraint "y" "TARGET_REALLY_IWMMXT ? IWMMXT_REGS : NO_REGS" "The Intel iWMMX co-processor registers.") (define_register_constraint "z" "TARGET_REALLY_IWMMXT ? IWMMXT_GR_REGS : NO_REGS" "The Intel iWMMX GR registers.") (define_register_constraint "l" "TARGET_THUMB ? LO_REGS : GENERAL_REGS" "In Thumb state the core registers @code{r0}-@code{r7}.") (define_register_constraint "h" "TARGET_THUMB ? HI_REGS : NO_REGS" "In Thumb state the core registers @code{r8}-@code{r15}.") (define_register_constraint "k" "STACK_REG" "@internal The stack register.") (define_register_constraint "b" "TARGET_THUMB ? BASE_REGS : NO_REGS" "@internal Thumb only. The union of the low registers and the stack register.") (define_register_constraint "c" "CC_REG" "@internal The condition code register.") (define_constraint "I" "In ARM/Thumb-2 state a constant that can be used as an immediate value in a Data Processing instruction. In Thumb-1 state a constant in the range 0-255." (and (match_code "const_int") (match_test "TARGET_32BIT ? const_ok_for_arm (ival) : ival >= 0 && ival <= 255"))) (define_constraint "J" "In ARM/Thumb-2 state a constant in the range @minus{}4095-4095. In Thumb-1 state a constant in the range @minus{}255-@minus{}1." (and (match_code "const_int") (match_test "TARGET_32BIT ? (ival >= -4095 && ival <= 4095) : (ival >= -255 && ival <= -1)"))) (define_constraint "K" "In ARM/Thumb-2 state a constant that satisfies the @code{I} constraint if inverted. In Thumb-1 state a constant that satisfies the @code{I} constraint multiplied by any power of 2." (and (match_code "const_int") (match_test "TARGET_32BIT ? const_ok_for_arm (~ival) : thumb_shiftable_const (ival)"))) (define_constraint "L" "In ARM/Thumb-2 state a constant that satisfies the @code{I} constraint if negated. In Thumb-1 state a constant in the range @minus{}7-7." (and (match_code "const_int") (match_test "TARGET_32BIT ? const_ok_for_arm (-ival) : (ival >= -7 && ival <= 7)"))) ;; The ARM state version is internal... ;; @internal In ARM/Thumb-2 state a constant in the range 0-32 or any ;; power of 2. (define_constraint "M" "In Thumb-1 state a constant that is a multiple of 4 in the range 0-1020." (and (match_code "const_int") (match_test "TARGET_32BIT ? ((ival >= 0 && ival <= 32) || ((ival & (ival - 1)) == 0)) : ((ival >= 0 && ival <= 1020) && ((ival & 3) == 0))"))) (define_constraint "N" "In ARM/Thumb-2 state a constant suitable for a MOVW instruction. In Thumb-1 state a constant in the range 0-31." (and (match_code "const_int") (match_test "TARGET_32BIT ? arm_arch_thumb2 && ((ival & 0xffff0000) == 0) : (ival >= 0 && ival <= 31)"))) (define_constraint "O" "In Thumb-1 state a constant that is a multiple of 4 in the range @minus{}508-508." (and (match_code "const_int") (match_test "TARGET_THUMB1 && ival >= -508 && ival <= 508 && ((ival & 3) == 0)"))) (define_constraint "G" "In ARM/Thumb-2 state a valid FPA immediate constant." (and (match_code "const_double") (match_test "TARGET_32BIT && arm_const_double_rtx (op)"))) (define_constraint "H" "In ARM/Thumb-2 state a valid FPA immediate constant when negated." (and (match_code "const_double") (match_test "TARGET_32BIT && neg_const_double_rtx_ok_for_fpa (op)"))) (define_constraint "Da" "@internal In ARM/Thumb-2 state a const_int, const_double or const_vector that can be generated with two Data Processing insns." (and (match_code "const_double,const_int,const_vector") (match_test "TARGET_32BIT && arm_const_double_inline_cost (op) == 2"))) (define_constraint "Db" "@internal In ARM/Thumb-2 state a const_int, const_double or const_vector that can be generated with three Data Processing insns." (and (match_code "const_double,const_int,const_vector") (match_test "TARGET_32BIT && arm_const_double_inline_cost (op) == 3"))) (define_constraint "Dc" "@internal In ARM/Thumb-2 state a const_int, const_double or const_vector that can be generated with four Data Processing insns. This pattern is disabled if optimizing for space or when we have load-delay slots to fill." (and (match_code "const_double,const_int,const_vector") (match_test "TARGET_32BIT && arm_const_double_inline_cost (op) == 4 && !(optimize_size || arm_ld_sched)"))) (define_constraint "Dn" "@internal In ARM/Thumb-2 state a const_vector which can be loaded with a Neon vmov immediate instruction." (and (match_code "const_vector") (match_test "TARGET_32BIT && imm_for_neon_mov_operand (op, GET_MODE (op))"))) (define_constraint "Dl" "@internal In ARM/Thumb-2 state a const_vector which can be used with a Neon vorr or vbic instruction." (and (match_code "const_vector") (match_test "TARGET_32BIT && imm_for_neon_logic_operand (op, GET_MODE (op))"))) (define_constraint "DL" "@internal In ARM/Thumb-2 state a const_vector which can be used with a Neon vorn or vand instruction." (and (match_code "const_vector") (match_test "TARGET_32BIT && imm_for_neon_inv_logic_operand (op, GET_MODE (op))"))) (define_constraint "Dv" "@internal In ARM/Thumb-2 state a const_double which can be used with a VFP fconsts or fconstd instruction." (and (match_code "const_double") (match_test "TARGET_32BIT && vfp3_const_double_rtx (op)"))) (define_memory_constraint "Ut" "@internal In ARM/Thumb-2 state an address valid for loading/storing opaque structure types wider than TImode." (and (match_code "mem") (match_test "TARGET_32BIT && neon_struct_mem_operand (op)"))) (define_memory_constraint "Uv" "@internal In ARM/Thumb-2 state a valid VFP load/store address." (and (match_code "mem") (match_test "TARGET_32BIT && arm_coproc_mem_operand (op, FALSE)"))) (define_memory_constraint "Uy" "@internal In ARM/Thumb-2 state a valid iWMMX load/store address." (and (match_code "mem") (match_test "TARGET_32BIT && arm_coproc_mem_operand (op, TRUE)"))) (define_memory_constraint "Un" "@internal In ARM/Thumb-2 state a valid address for Neon element and structure load/store instructions." (and (match_code "mem") (match_test "TARGET_32BIT && neon_vector_mem_operand (op, FALSE)"))) (define_memory_constraint "Us" "@internal In ARM/Thumb-2 state a valid address for non-offset loads/stores of quad-word values in four ARM registers." (and (match_code "mem") (match_test "TARGET_32BIT && neon_vector_mem_operand (op, TRUE)"))) (define_memory_constraint "Uq" "@internal In ARM state an address valid in ldrsb instructions." (and (match_code "mem") (match_test "TARGET_ARM && arm_legitimate_address_p (GET_MODE (op), XEXP (op, 0), SIGN_EXTEND, 0)"))) (define_memory_constraint "Q" "@internal In ARM/Thumb-2 state an address that is a single base register." (and (match_code "mem") (match_test "REG_P (XEXP (op, 0))"))) ;; We used to have constraint letters for S and R in ARM state, but ;; all uses of these now appear to have been removed. ;; Additionally, we used to have a Q constraint in Thumb state, but ;; this wasn't really a valid memory constraint. Again, all uses of ;; this now seem to have been removed.
gittup/gcc
gcc/config/arm/constraints.md
Markdown
gpl-2.0
9,302
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.db.block; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import com.caucho.management.server.AbstractManagedObject; import com.caucho.management.server.BlockManagerMXBean; import com.caucho.util.ConcurrentArrayList; import com.caucho.util.L10N; import com.caucho.util.LongKeyLruCache; /** * Manages the block cache */ public final class BlockManager extends AbstractManagedObject implements BlockManagerMXBean { private static final Logger log = Logger.getLogger(BlockManager.class.getName()); private static final L10N L = new L10N(BlockManager.class); private static BlockManager _staticManager; private final byte []_storeMask = new byte[8192]; private final ConcurrentArrayList<BlockStore> _storeList = new ConcurrentArrayList<BlockStore>(BlockStore.class); private LongKeyLruCache<Block> _blockCache; private boolean _isEnableMmap = true; private final AtomicLong _blockWriteCount = new AtomicLong(); private final AtomicLong _blockReadCount = new AtomicLong(); private BlockManager(int capacity) { super(ClassLoader.getSystemClassLoader()); _blockCache = new LongKeyLruCache<Block>(capacity); // the first store id is not available to allow for tests for zero. _storeMask[0] |= 1; registerSelf(); } /** * Returns the block manager, ensuring a minimum number of entries. */ public static synchronized BlockManager create() { if (_staticManager == null) { int minEntries = (int) defaultCapacity(); _staticManager = new BlockManager(minEntries); } return _staticManager; } private static long defaultCapacity() { long meg = 1024 * 1024; long minSize = 1 * meg; long maxSize = 128 * meg; long maxMemory = getMaxMemory(); long memorySize; memorySize = ((maxMemory / meg) / 8) * meg; if (memorySize < minSize) { memorySize = minSize; } if (maxSize < memorySize) { memorySize = maxSize; } int blockCount = (int) (memorySize / BlockStore.BLOCK_SIZE); int size = 256; // force to be a smaller power of 2 for (; 2 * size <= blockCount; size *= 2) { } return size; } private static long getMaxMemory() { try { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heap = null; if (memoryBean != null) { heap = memoryBean.getHeapMemoryUsage(); } if (heap != null) { return Math.max(heap.getMax(), heap.getCommitted()); } else { Runtime runtime = Runtime.getRuntime(); return Math.max(runtime.maxMemory(), runtime.totalMemory()); } } catch (Exception e) { e.printStackTrace(); } return Runtime.getRuntime().maxMemory(); } public static BlockManager getBlockManager() { return _staticManager; } /** * Ensures the cache has a minimum number of blocks. * * @param minCapacity the minimum capacity in blocks */ public void ensureCapacity(int minCapacity) { _blockCache = _blockCache.ensureCapacity(minCapacity); } /** * Ensures the cache has a minimum number of blocks. * * @param minCapacity the minimum capacity in blocks */ public void setCapacity(int minCapacity) { if (minCapacity > 1024 * 1024 / BlockStore.BLOCK_SIZE) { _blockCache = _blockCache.setCapacity(minCapacity); } } public void ensureMemoryCapacity(long memorySize) { int blocks = (int) (memorySize + BlockStore.BLOCK_SIZE - 1) / BlockStore.BLOCK_SIZE; ensureCapacity(blocks); } public long getBlockCacheMemoryCapacity() { return _blockCache.getCapacity() * BlockStore.BLOCK_SIZE; } public boolean isEnableMmap() { return _isEnableMmap; } public void setEnableMmap(boolean isEnable) { _isEnableMmap = isEnable; } /** * Allocates a store id. */ public int allocateStoreId() { synchronized (_storeMask) { for (int i = 0; i < _storeMask.length; i++) { int mask = _storeMask[i]; if (mask != 0xff) { for (int j = 0; j < 8; j++) { if ((mask & (1 << j)) == 0) { _storeMask[i] |= (1 << j); return 8 * i + j; } } } } throw new IllegalStateException(L.l("All store ids used.")); } } void addStore(BlockStore store) { _storeList.add(store); } /** * Frees blocks with the given store. */ public void flush(BlockStore store) { ArrayList<Block> dirtyBlocks = new ArrayList<Block>(); synchronized (_blockCache) { Iterator<Block> values = _blockCache.values(); while (values.hasNext()) { Block block = values.next(); if (block != null && block.getStore() == store) { if (block.isDirty()) { dirtyBlocks.add(block); } } } } for (Block block : dirtyBlocks) { // block.allocate(); store.getWriter().addDirtyBlock(block); } } /** * Flushes all blocks. */ public void flush() { ArrayList<Block> dirtyBlocks = new ArrayList<Block>(); synchronized (_blockCache) { Iterator<Block> values = _blockCache.values(); while (values.hasNext()) { Block block = values.next(); if (block.isDirty()) { dirtyBlocks.add(block); } } } for (Block block : dirtyBlocks) { BlockStore store = block.getStore(); // block.allocate(); store.getWriter().addDirtyBlock(block); } } /** * Frees blocks with the given store. */ public void freeStore(BlockStore store) { _storeList.remove(store); ArrayList<Block> removeBlocks = new ArrayList<Block>(); synchronized (_blockCache) { Iterator<Block> iter = _blockCache.values(); while (iter.hasNext()) { Block block = iter.next(); if (block != null && block.getStore() == store) { removeBlocks.add(block); } } } for (Block block : removeBlocks) { _blockCache.remove(block.getBlockId()); } } /** * Frees a store id. */ public void freeStoreId(int storeId) { synchronized (_storeMask) { if (storeId <= 0) throw new IllegalArgumentException(String.valueOf(storeId)); _storeMask[storeId / 8] &= ~(1 << storeId % 8); } } void destroy() { for (BlockStore store : _storeList.toArray()) { try { store.close(); } catch (Exception e) { log.log(Level.WARNING, e.toString(), e); } } } /** * Gets the table's block. */ Block getBlock(BlockStore store, long blockId) { long storeId = blockId & BlockStore.BLOCK_INDEX_MASK; if (storeId != store.getId()) { throw stateError("illegal block: " + Long.toHexString(blockId)); } Block block = _blockCache.get(blockId); while (block == null || ! block.allocate()) { block = new Block(store, blockId); Block oldBlock = _blockCache.putIfAbsent(blockId, block); // needs to be outside the synchronized because the put // can cause an LRU drop which might lead to a dirty write if (oldBlock != null) { block.free(); block = oldBlock; } } if (blockId != block.getBlockId() || (blockId & BlockStore.BLOCK_INDEX_MASK) != store.getId() || block.getStore() != store) { throw stateError("BLOCK: " + Long.toHexString(blockId) + " " + Long.toHexString(block.getBlockId()) + " " + store + " " + block.getStore()); } return block; } final boolean copyDirtyBlock(Block block) { BlockStore store = block.getStore(); long blockId = block.getBlockId(); // Find any matching block in the process of being written return store.getWriter().copyDirtyBlock(blockId, block); } public void clear() { _blockCache.clear(); } // // management/statistics // /** * The managed name is null */ @Override public String getName() { return null; } /** * The managed type is BlockManager */ @Override public String getType() { return "BlockManager"; } /** * Returns the capacity. */ @Override public long getBlockCapacity() { return _blockCache.getCapacity(); } /** * Returns the capacity in bytes. */ @Override public long getMemorySize() { return _blockCache.getCapacity() * BlockStore.BLOCK_SIZE; } /** * Returns the hit count. */ @Override public long getHitCountTotal() { return _blockCache.getHitCount(); } /** * Returns the miss count. */ @Override public long getMissCountTotal() { return _blockCache.getMissCount(); } @Override public double getMissRate() { long missCount = getMissCountTotal(); long hitCount = getHitCountTotal(); double accessCount = hitCount + missCount; if (accessCount == 0) accessCount = 1; return missCount / accessCount; } final void addBlockRead() { _blockReadCount.incrementAndGet(); } /** * Returns the read count. */ @Override public long getBlockReadCountTotal() { return _blockReadCount.get(); } final void addBlockWrite() { _blockWriteCount.incrementAndGet(); } /** * Returns the write count. */ @Override public long getBlockWriteCountTotal() { return _blockWriteCount.get(); } private static IllegalStateException stateError(String msg) { IllegalStateException e = new IllegalStateException(msg); e.fillInStackTrace(); log.log(Level.WARNING, e.toString(), e); return e; } }
mdaniel/svn-caucho-com-resin
modules/resin/src/com/caucho/db/block/BlockManager.java
Java
gpl-2.0
11,079
/* * Driver for M5MO (5MP Camera) from NEC * * 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 __M5MO_H #define __M5MO_H #include <linux/wakelock.h> #define CONFIG_CAM_DEBUG #define cam_warn(fmt, ...) \ do { \ printk(KERN_WARNING "%s: " fmt, __func__, ##__VA_ARGS__); \ } while (0) #define cam_err(fmt, ...) \ do { \ printk(KERN_ERR "%s: " fmt, __func__, ##__VA_ARGS__); \ } while (0) #define cam_info(fmt, ...) \ do { \ printk(KERN_INFO "%s: " fmt, __func__, ##__VA_ARGS__); \ } while (0) #ifdef CONFIG_CAM_DEBUG #define CAM_DEBUG (1 << 0) #define CAM_TRACE (1 << 1) #define CAM_I2C (1 << 2) #define cam_dbg(fmt, ...) \ do { \ if (to_state(sd)->dbg_level & CAM_DEBUG) \ printk(KERN_DEBUG "%s: " fmt, __func__, ##__VA_ARGS__); \ } while (0) #define cam_trace(fmt, ...) \ do { \ if (to_state(sd)->dbg_level & CAM_TRACE) \ printk(KERN_DEBUG "%s: " fmt, __func__, ##__VA_ARGS__); \ } while (0) #define cam_i2c_dbg(fmt, ...) \ do { \ if (to_state(sd)->dbg_level & CAM_I2C) \ printk(KERN_DEBUG "%s: " fmt, __func__, ##__VA_ARGS__); \ } while (0) #else #define cam_dbg(fmt, ...) #define cam_trace(fmt, ...) #define cam_i2c_dbg(fmt, ...) #endif enum m5mo_prev_frmsize { M5MO_PREVIEW_QCIF, M5MO_PREVIEW_QCIF2, M5MO_PREVIEW_QVGA, M5MO_PREVIEW_VGA, M5MO_PREVIEW_D1, M5MO_PREVIEW_WVGA, M5MO_PREVIEW_720P, M5MO_PREVIEW_1080P, M5MO_PREVIEW_HDR, }; enum m5mo_cap_frmsize { M5MO_CAPTURE_VGA, /* 640 x 480 */ M5MO_CAPTURE_WVGA, /* 800 x 480 */ M5MO_CAPTURE_W1MP, /* 1600 x 960 */ M5MO_CAPTURE_2MP, /* UXGA - 1600 x 1200 */ M5MO_CAPTURE_W2MP, /* 2048 x 1232 */ M5MO_CAPTURE_3MP, /* QXGA - 2048 x 1536 */ M5MO_CAPTURE_W4MP, /* WQXGA - 2560 x 1536 */ M5MO_CAPTURE_5MP, /* 2560 x 1920 */ M5MO_CAPTURE_W6MP, /* 3072 x 1856 */ M5MO_CAPTURE_7MP, /* 3072 x 2304 */ M5MO_CAPTURE_W7MP, /* WQXGA - 2560 x 1536 */ M5MO_CAPTURE_8MP, /* 3264 x 2448 */ }; struct m5mo_control { u32 id; s32 value; s32 minimum; /* Note signedness */ s32 maximum; s32 step; s32 default_value; }; struct m5mo_frmsizeenum { unsigned int index; unsigned int width; unsigned int height; u8 reg_val; /* a value for category parameter */ }; struct m5mo_isp { wait_queue_head_t wait; unsigned int irq; /* irq issued by ISP */ unsigned int issued; unsigned int int_factor; unsigned int bad_fw:1; }; struct m5mo_jpeg { int quality; unsigned int main_size; /* Main JPEG file size */ unsigned int thumb_size; /* Thumbnail file size */ unsigned int main_offset; unsigned int thumb_offset; unsigned int postview_offset; }; struct m5mo_focus { unsigned int start:1; unsigned int lock:1; unsigned int touch:1; unsigned int mode; #if defined(CONFIG_TARGET_LOCALE_NA) unsigned int ui_mode; unsigned int mode_select; #endif unsigned int status; unsigned int pos_x; unsigned int pos_y; }; struct m5mo_exif { char unique_id[7]; u32 exptime; /* us */ u16 flash; u16 iso; int tv; /* shutter speed */ int bv; /* brightness */ int ebv; /* exposure bias */ }; struct m5mo_state { struct m5mo_platform_data *pdata; struct v4l2_subdev sd; struct wake_lock wake_lock; struct m5mo_isp isp; const struct m5mo_frmsizeenum *preview; const struct m5mo_frmsizeenum *capture; enum v4l2_pix_format_mode format_mode; enum v4l2_sensor_mode sensor_mode; enum v4l2_flash_mode flash_mode; enum v4l2_scene_mode scene_mode; int vt_mode; int zoom; unsigned int fps; struct m5mo_focus focus; struct m5mo_jpeg jpeg; struct m5mo_exif exif; char *fw_version; #ifdef CONFIG_CAM_DEBUG u8 dbg_level; #endif unsigned int face_beauty:1; unsigned int recording:1; unsigned int check_dataline:1; }; /* Category */ #define M5MO_CATEGORY_SYS 0x00 #define M5MO_CATEGORY_PARM 0x01 #define M5MO_CATEGORY_MON 0x02 #define M5MO_CATEGORY_AE 0x03 #define M5MO_CATEGORY_WB 0x06 #define M5MO_CATEGORY_EXIF 0x07 #define M5MO_CATEGORY_FD 0x09 #define M5MO_CATEGORY_LENS 0x0A #define M5MO_CATEGORY_CAPPARM 0x0B #define M5MO_CATEGORY_CAPCTRL 0x0C #define M5MO_CATEGORY_TEST 0x0D #define M5MO_CATEGORY_ADJST 0x0E #define M5MO_CATEGORY_FLASH 0x0F /* F/W update */ /* M5MO_CATEGORY_SYS: 0x00 */ #define M5MO_SYS_PJT_CODE 0x01 #define M5MO_SYS_VER_FW 0x02 #define M5MO_SYS_VER_HW 0x04 #define M5MO_SYS_VER_PARAM 0x06 #define M5MO_SYS_VER_AWB 0x08 #define M5MO_SYS_USER_VER 0x0A #define M5MO_SYS_MODE 0x0B #define M5MO_SYS_ESD_INT 0x0E #define M5MO_SYS_INT_FACTOR 0x10 #define M5MO_SYS_INT_EN 0x11 /* M5MO_CATEGORY_PARAM: 0x01 */ #define M5MO_PARM_OUT_SEL 0x00 #define M5MO_PARM_MON_SIZE 0x01 #define M5MO_PARM_EFFECT 0x0B #define M5MO_PARM_FLEX_FPS 0x31 #define M5MO_PARM_HDMOVIE 0x32 /* M5MO_CATEGORY_MON: 0x02 */ #define M5MO_MON_ZOOM 0x01 #define M5MO_MON_MON_REVERSE 0x05 #define M5MO_MON_MON_MIRROR 0x06 #define M5MO_MON_SHOT_REVERSE 0x07 #define M5MO_MON_SHOT_MIRROR 0x08 #define M5MO_MON_CFIXB 0x09 #define M5MO_MON_CFIXR 0x0A #define M5MO_MON_COLOR_EFFECT 0x0B #define M5MO_MON_CHROMA_LVL 0x0F #define M5MO_MON_EDGE_LVL 0x11 #define M5MO_MON_TONE_CTRL 0x25 /* M5MO_CATEGORY_AE: 0x03 */ #define M5MO_AE_LOCK 0x00 #define M5MO_AE_MODE 0x01 #define M5MO_AE_ISOSEL 0x05 #define M5MO_AE_FLICKER 0x06 #define M5MO_AE_EP_MODE_MON 0x0A #define M5MO_AE_EP_MODE_CAP 0x0B #define M5MO_AE_AUTO_BRACKET_EV 0x20 #define M5MO_AE_ONESHOT_MAX_EXP 0x36 #define M5MO_AE_INDEX 0x38 /* M5MO_CATEGORY_WB: 0x06 */ #define M5MO_AWB_LOCK 0x00 #define M5MO_WB_AWB_MODE 0x02 #define M5MO_WB_AWB_MANUAL 0x03 /* M5MO_CATEGORY_EXIF: 0x07 */ #define M5MO_EXIF_EXPTIME_NUM 0x00 #define M5MO_EXIF_EXPTIME_DEN 0x04 #define M5MO_EXIF_TV_NUM 0x08 #define M5MO_EXIF_TV_DEN 0x0C #define M5MO_EXIF_BV_NUM 0x18 #define M5MO_EXIF_BV_DEN 0x1C #define M5MO_EXIF_EBV_NUM 0x20 #define M5MO_EXIF_EBV_DEN 0x24 #define M5MO_EXIF_ISO 0x28 #define M5MO_EXIF_FLASH 0x2A /* M5MO_CATEGORY_FD: 0x09 */ #define M5MO_FD_CTL 0x00 #define M5MO_FD_SIZE 0x01 #define M5MO_FD_MAX 0x02 /* M5MO_CATEGORY_LENS: 0x0A */ #define M5MO_LENS_AF_MODE 0x01 #define M5MO_LENS_AF_START 0x02 #define M5MO_LENS_AF_STATUS 0x03 #define M5MO_LENS_AF_MODE_SELECT 0x05 #define M5MO_LENS_AF_UPBYTE_STEP 0x06 #define M5MO_LENS_AF_LOWBYTE_STEP 0x07 #define M5MO_LENS_AF_CAL 0x1D #define M5MO_LENS_AF_TOUCH_POSX 0x30 #define M5MO_LENS_AF_TOUCH_POSY 0x32 /* M5MO_CATEGORY_CAPPARM: 0x0B */ #define M5MO_CAPPARM_YUVOUT_MAIN 0x00 #define M5MO_CAPPARM_MAIN_IMG_SIZE 0x01 #define M5MO_CAPPARM_YUVOUT_PREVIEW 0x05 #define M5MO_CAPPARM_PREVIEW_IMG_SIZE 0x06 #define M5MO_CAPPARM_YUVOUT_THUMB 0x0A #define M5MO_CAPPARM_THUMB_IMG_SIZE 0x0B #define M5MO_CAPPARM_JPEG_SIZE_MAX 0x0F #define M5MO_CAPPARM_JPEG_RATIO 0x17 #define M5MO_CAPPARM_MCC_MODE 0x1D #define M5MO_CAPPARM_WDR_EN 0x2C #define M5MO_CAPPARM_LIGHT_CTRL 0x40 #define M5MO_CAPPARM_FLASH_CTRL 0x41 #define M5MO_CAPPARM_JPEG_RATIO_OFS 0x34 #define M5MO_CAPPARM_THUMB_JPEG_MAX 0x3C #define M5MO_CAPPARM_AFB_CAP_EN 0x53 /* M5MO_CATEGORY_CAPCTRL: 0x0C */ #define M5MO_CAPCTRL_CAP_MODE 0x00 #define M5MO_CAPCTRL_CAP_FRM_COUNT 0x02 #define M5MO_CAPCTRL_FRM_SEL 0x06 #define M5MO_CAPCTRL_TRANSFER 0x09 #define M5MO_CAPCTRL_IMG_SIZE 0x0D #define M5MO_CAPCTRL_THUMB_SIZE 0x11 /* M5MO_CATEGORY_ADJST: 0x0E */ #define M5MO_ADJST_AWB_RG_H 0x3C #define M5MO_ADJST_AWB_RG_L 0x3D #define M5MO_ADJST_AWB_BG_H 0x3E #define M5MO_ADJST_AWB_BG_L 0x3F /* M5MO_CATEGORY_FLASH: 0x0F */ #define M5MO_FLASH_ADDR 0x00 #define M5MO_FLASH_BYTE 0x04 #define M5MO_FLASH_ERASE 0x06 #define M5MO_FLASH_WR 0x07 #define M5MO_FLASH_RAM_CLEAR 0x08 #define M5MO_FLASH_CAM_START 0x12 #define M5MO_FLASH_SEL 0x13 /* M5MO_CATEGORY_TEST: 0x0D */ #define M5MO_TEST_OUTPUT_YCO_TEST_DATA 0x1B #define M5MO_TEST_ISP_PROCESS 0x59 /* M5MO Sensor Mode */ #define M5MO_SYSINIT_MODE 0x0 #define M5MO_PARMSET_MODE 0x1 #define M5MO_MONITOR_MODE 0x2 #define M5MO_STILLCAP_MODE 0x3 /* Interrupt Factor */ #define M5MO_INT_SOUND (1 << 7) #define M5MO_INT_LENS_INIT (1 << 6) #define M5MO_INT_FD (1 << 5) #define M5MO_INT_FRAME_SYNC (1 << 4) #define M5MO_INT_CAPTURE (1 << 3) #define M5MO_INT_ZOOM (1 << 2) #define M5MO_INT_AF (1 << 1) #define M5MO_INT_MODE (1 << 0) /* ESD Interrupt */ #define M5MO_INT_ESD (1 << 0) #endif /* __M5MO_H */
epic4g/samsung-kernel-c1spr-EK02
drivers/media/video/m5mo.h
C
gpl-2.0
8,363
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <linux/fou.h> #include <net/if.h> #include <netinet/in.h> #include <linux/ip.h> #include "conf-parser.h" #include "fou-tunnel.h" #include "ip-protocol-list.h" #include "netlink-util.h" #include "networkd-manager.h" #include "parse-util.h" #include "string-table.h" #include "string-util.h" #include "util.h" static const char* const fou_encap_type_table[_NETDEV_FOO_OVER_UDP_ENCAP_MAX] = { [NETDEV_FOO_OVER_UDP_ENCAP_DIRECT] = "FooOverUDP", [NETDEV_FOO_OVER_UDP_ENCAP_GUE] = "GenericUDPEncapsulation", }; DEFINE_STRING_TABLE_LOOKUP(fou_encap_type, FooOverUDPEncapType); DEFINE_CONFIG_PARSE_ENUM(config_parse_fou_encap_type, fou_encap_type, FooOverUDPEncapType, "Failed to parse Encapsulation="); static int netdev_fill_fou_tunnel_message(NetDev *netdev, sd_netlink_message **ret) { _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL; FouTunnel *t; uint8_t encap_type; int r; assert(netdev); t = FOU(netdev); assert(t); r = sd_genl_message_new(netdev->manager->genl, FOU_GENL_NAME, FOU_CMD_ADD, &m); if (r < 0) return log_netdev_error_errno(netdev, r, "Failed to allocate generic netlink message: %m"); r = sd_netlink_message_append_u16(m, FOU_ATTR_PORT, htobe16(t->port)); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_PORT attribute: %m"); if (IN_SET(t->peer_family, AF_INET, AF_INET6)) { r = sd_netlink_message_append_u16(m, FOU_ATTR_PEER_PORT, htobe16(t->peer_port)); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_PEER_PORT attribute: %m"); } switch (t->fou_encap_type) { case NETDEV_FOO_OVER_UDP_ENCAP_DIRECT: encap_type = FOU_ENCAP_DIRECT; break; case NETDEV_FOO_OVER_UDP_ENCAP_GUE: encap_type = FOU_ENCAP_GUE; break; default: assert_not_reached(); } r = sd_netlink_message_append_u8(m, FOU_ATTR_TYPE, encap_type); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_TYPE attribute: %m"); r = sd_netlink_message_append_u8(m, FOU_ATTR_AF, AF_INET); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_AF attribute: %m"); r = sd_netlink_message_append_u8(m, FOU_ATTR_IPPROTO, t->fou_protocol); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_IPPROTO attribute: %m"); if (t->local_family == AF_INET) { r = sd_netlink_message_append_in_addr(m, FOU_ATTR_LOCAL_V4, &t->local.in); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_LOCAL_V4 attribute: %m"); } else if (t->local_family == AF_INET6) { r = sd_netlink_message_append_in6_addr(m, FOU_ATTR_LOCAL_V6, &t->local.in6); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_LOCAL_V6 attribute: %m"); } if (t->peer_family == AF_INET) { r = sd_netlink_message_append_in_addr(m, FOU_ATTR_PEER_V4, &t->peer.in); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_PEER_V4 attribute: %m"); } else if (t->peer_family == AF_INET6){ r = sd_netlink_message_append_in6_addr(m, FOU_ATTR_PEER_V6, &t->peer.in6); if (r < 0) return log_netdev_error_errno(netdev, r, "Could not append FOU_ATTR_PEER_V6 attribute: %m"); } *ret = TAKE_PTR(m); return 0; } static int fou_tunnel_create_handler(sd_netlink *rtnl, sd_netlink_message *m, NetDev *netdev) { int r; assert(netdev); assert(netdev->state != _NETDEV_STATE_INVALID); r = sd_netlink_message_get_errno(m); if (r == -EEXIST) log_netdev_info(netdev, "netdev exists, using existing without changing its parameters"); else if (r < 0) { log_netdev_warning_errno(netdev, r, "netdev could not be created: %m"); netdev_enter_failed(netdev); return 1; } log_netdev_debug(netdev, "FooOverUDP tunnel is created"); return 1; } static int netdev_fou_tunnel_create(NetDev *netdev) { _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL; int r; assert(netdev); assert(FOU(netdev)); r = netdev_fill_fou_tunnel_message(netdev, &m); if (r < 0) return r; r = netlink_call_async(netdev->manager->genl, NULL, m, fou_tunnel_create_handler, netdev_destroy_callback, netdev); if (r < 0) return log_netdev_error_errno(netdev, r, "Failed to create FooOverUDP tunnel: %m"); netdev_ref(netdev); return 0; } int config_parse_ip_protocol( const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata) { uint8_t *ret = data; unsigned protocol; /* linux/fou.h defines the netlink field as one byte, so we need to reject protocols numbers that * don't fit in one byte. */ int r; assert(filename); assert(section); assert(lvalue); assert(rvalue); assert(data); r = parse_ip_protocol(rvalue); if (r >= 0) protocol = r; else { r = safe_atou(rvalue, &protocol); if (r < 0) log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse IP protocol '%s' for FooOverUDP tunnel, " "ignoring assignment: %m", rvalue); return 0; } if (protocol > UINT8_MAX) { log_syntax(unit, LOG_WARNING, filename, line, 0, "IP protocol '%s' for FooOverUDP tunnel out of range, " "ignoring assignment: %m", rvalue); return 0; } *ret = protocol; return 0; } int config_parse_fou_tunnel_address( const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata) { union in_addr_union *addr = data; FouTunnel *t = userdata; int r, *f; assert(filename); assert(lvalue); assert(rvalue); assert(data); if (streq(lvalue, "Local")) f = &t->local_family; else f = &t->peer_family; r = in_addr_from_string_auto(rvalue, f, addr); if (r < 0) log_syntax(unit, LOG_WARNING, filename, line, r, "FooOverUDP tunnel '%s' address is invalid, ignoring assignment: %s", lvalue, rvalue); return 0; } static int netdev_fou_tunnel_verify(NetDev *netdev, const char *filename) { FouTunnel *t; assert(netdev); assert(filename); t = FOU(netdev); assert(t); switch (t->fou_encap_type) { case NETDEV_FOO_OVER_UDP_ENCAP_DIRECT: if (t->fou_protocol <= 0) return log_netdev_error_errno(netdev, SYNTHETIC_ERRNO(EINVAL), "FooOverUDP protocol not configured in %s. Rejecting configuration.", filename); break; case NETDEV_FOO_OVER_UDP_ENCAP_GUE: if (t->fou_protocol > 0) return log_netdev_error_errno(netdev, SYNTHETIC_ERRNO(EINVAL), "FooOverUDP GUE can't be set with protocol configured in %s. Rejecting configuration.", filename); break; default: assert_not_reached(); } if (t->peer_family == AF_UNSPEC && t->peer_port > 0) return log_netdev_error_errno(netdev, SYNTHETIC_ERRNO(EINVAL), "FooOverUDP peer port is set but peer address not configured in %s. Rejecting configuration.", filename); else if (t->peer_family != AF_UNSPEC && t->peer_port == 0) return log_netdev_error_errno(netdev, SYNTHETIC_ERRNO(EINVAL), "FooOverUDP peer port not set but peer address is configured in %s. Rejecting configuration.", filename); return 0; } static void fou_tunnel_init(NetDev *netdev) { FouTunnel *t; assert(netdev); t = FOU(netdev); assert(t); t->fou_encap_type = NETDEV_FOO_OVER_UDP_ENCAP_DIRECT; } const NetDevVTable foutnl_vtable = { .object_size = sizeof(FouTunnel), .init = fou_tunnel_init, .sections = NETDEV_COMMON_SECTIONS "FooOverUDP\0", .create = netdev_fou_tunnel_create, .create_type = NETDEV_CREATE_INDEPENDENT, .config_verify = netdev_fou_tunnel_verify, };
tblume/systemd-upstream
src/network/netdev/fou-tunnel.c
C
gpl-2.0
10,039
/* * Mach Operating System * Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or [email protected] * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* * Mach kernel debugging interface type declarations */ #ifndef _MACH_DEBUG_MACH_DEBUG_TYPES_H_ #define _MACH_DEBUG_MACH_DEBUG_TYPES_H_ #include <mach_debug/ipc_info.h> #include <mach_debug/vm_info.h> #include <mach_debug/slab_info.h> #include <mach_debug/hash_info.h> typedef char symtab_name_t[32]; /* * A fixed-length string data type intended for names given to * kernel objects. * * Note that it is not guaranteed that the in-kernel data * structure will hold KERNEL_DEBUG_NAME_MAX bytes. The given * name will be truncated to fit into the target data structure. */ #define KERNEL_DEBUG_NAME_MAX (64) typedef char kernel_debug_name_t[KERNEL_DEBUG_NAME_MAX]; #endif /* _MACH_DEBUG_MACH_DEBUG_TYPES_H_ */
sebastianscatularo/gnumach
include/mach_debug/mach_debug_types.h
C
gpl-2.0
1,761
/* zipios++/zipios-config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the <inttypes.h> header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the <memory.h> header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the <stdint.h> header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the <stdlib.h> header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the <strings.h> header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the <string.h> header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the <sys/stat.h> header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the <sys/types.h> header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the <unistd.h> header file. */ #undef HAVE_UNISTD_H /* Define if zlib has zError */ #undef HAVE_ZERROR /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION #define HAVE_STD_IOSTREAM /* Define if the std compliant iostream library should be used (if present) */ #define USE_STD_IOSTREAM /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus #undef inline #endif
raoulb/Enigma
Xcode/Enigma/Enigma/zipios++/zipios-config.h
C
gpl-2.0
1,738
/****************************************************************************** * * * * Copyright (C) 1997-2011 by Dimitri van Heesch. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * */ #include "filename.h" #include "util.h" FileName::FileName(const char *fn,const char *n) : FileList() { setAutoDelete(TRUE); fName=fn; name=n; } FileName::~FileName() { } void FileName::generateDiskNames() { //QCString commonPrefix; FileDef *fd=first(); int count=0; while (fd) { if (!fd->isReference()) count++; fd=next(); } if (count==1) { fd=first(); // skip references while (fd && fd->isReference()) fd=next(); // name if unique, so diskname is simply the name //printf("!!!!!!!! Unique disk name=%s for fd=%s\n",name.data(),fd->diskname.data()); fd->diskname=name.copy(); } else if (count>1) // multiple occurrences of the same file name { //printf("Multiple occurrences of %s\n",name.data()); int i=0,j=0; bool found=FALSE; while (!found) // search for the common prefix of all paths { fd=first(); while (fd && fd->isReference()) fd=next(); char c=fd->path.at(i); if (c=='/') j=i; // remember last position of dirname fd=next(); while (fd && !found) { if (!fd->isReference()) { //printf("i=%d j=%d fd->path=`%s' fd->name=`%s'\n",i,j,fd->path.left(i).data(),fd->name().data()); if (i==(int)fd->path.length()) { //warning("Warning: Input file %s found multiple times!\n" // " The generated documentation for this file may not be correct!\n",fd->absFilePath().data()); found=TRUE; } else if (fd->path[i]!=c) { found=TRUE; } } fd=next(); } i++; } fd=first(); while (fd) { //printf("fd->setName(%s)\n",(fd->path.right(fd->path.length()-j-1)+name).data()); if (!fd->isReference()) { QCString prefix = fd->path.right(fd->path.length()-j-1); fd->setName(prefix+name); //printf("!!!!!!!! non unique disk name=%s for fd=%s\n",(prefix+name).data(),fd->diskname.data()); fd->diskname=prefix+name; } fd=next(); } } } int FileName::compareItems(GCI item1, GCI item2) { FileName *f1=(FileName *)item1; FileName *f2=(FileName *)item2; return stricmp(f1->fileName(),f2->fileName()); } FileNameIterator::FileNameIterator(const FileName &fname) : QListIterator<FileDef>(fname) { } FileNameList::FileNameList() : QList<FileName>() { } FileNameList::~FileNameList() { } void FileNameList::generateDiskNames() { FileName *fn=first(); while (fn) { fn->generateDiskNames(); fn=next(); } } int FileNameList::compareItems(GCI item1, GCI item2) { FileName *f1=(FileName *)item1; FileName *f2=(FileName *)item2; //printf("FileNameList::compareItems `%s'<->`%s'\n", // f1->fileName(),f2->fileName()); return Config_getBool("FULL_PATH_NAMES") ? stricmp(f1->fullName(),f2->fullName()) : stricmp(f1->fileName(),f2->fileName()); } FileNameListIterator::FileNameListIterator(const FileNameList &fnlist) : QListIterator<FileName>(fnlist) { }
ineb9/Siemensdoc
src/filename.cpp
C++
gpl-2.0
3,738
<?php /** * Contain classes to list log entries * * Copyright © 2004 Brion Vibber <[email protected]>, 2008 Aaron Schulz * https://www.mediawiki.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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ /** * @ingroup Pager */ class LogPager extends ReverseChronologicalPager { /** @var array Log types */ private $types = array(); /** @var string Events limited to those by performer when set */ private $performer = ''; /** @var string|Title Events limited to those about Title when set */ private $title = ''; /** @var string */ private $pattern = ''; /** @var string */ private $typeCGI = ''; /** @var LogEventsList */ public $mLogEventsList; /** * Constructor * * @param LogEventsList $list * @param string|array $types Log types to show * @param string $performer The user who made the log entries * @param string|Title $title The page title the log entries are for * @param string $pattern Do a prefix search rather than an exact title match * @param array $conds Extra conditions for the query * @param int|bool $year The year to start from. Default: false * @param int|bool $month The month to start from. Default: false * @param string $tagFilter Tag */ public function __construct( $list, $types = array(), $performer = '', $title = '', $pattern = '', $conds = array(), $year = false, $month = false, $tagFilter = '' ) { parent::__construct( $list->getContext() ); $this->mConds = $conds; $this->mLogEventsList = $list; $this->limitType( $types ); // also excludes hidden types $this->limitPerformer( $performer ); $this->limitTitle( $title, $pattern ); $this->getDateCond( $year, $month ); $this->mTagFilter = $tagFilter; $this->mDb = wfGetDB( DB_SLAVE, 'logpager' ); } public function getDefaultQuery() { $query = parent::getDefaultQuery(); $query['type'] = $this->typeCGI; // arrays won't work here $query['user'] = $this->performer; $query['month'] = $this->mMonth; $query['year'] = $this->mYear; return $query; } // Call ONLY after calling $this->limitType() already! public function getFilterParams() { global $wgFilterLogTypes; $filters = array(); if ( count( $this->types ) ) { return $filters; } foreach ( $wgFilterLogTypes as $type => $default ) { // Avoid silly filtering if ( $type !== 'patrol' || $this->getUser()->useNPPatrol() ) { $hide = $this->getRequest()->getInt( "hide_{$type}_log", $default ); $filters[$type] = $hide; if ( $hide ) { $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type ); } } } return $filters; } /** * Set the log reader to return only entries of the given type. * Type restrictions enforced here * * @param string|array $types Log types ('upload', 'delete', etc); * empty string means no restriction */ private function limitType( $types ) { global $wgLogRestrictions; $user = $this->getUser(); // If $types is not an array, make it an array $types = ( $types === '' ) ? array() : (array)$types; // Don't even show header for private logs; don't recognize it... $needReindex = false; foreach ( $types as $type ) { if ( isset( $wgLogRestrictions[$type] ) && !$user->isAllowed( $wgLogRestrictions[$type] ) ) { $needReindex = true; $types = array_diff( $types, array( $type ) ); } } if ( $needReindex ) { // Lots of this code makes assumptions that // the first entry in the array is $types[0]. $types = array_values( $types ); } $this->types = $types; // Don't show private logs to unprivileged users. // Also, only show them upon specific request to avoid suprises. $audience = $types ? 'user' : 'public'; $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience, $user ); if ( $hideLogs !== false ) { $this->mConds[] = $hideLogs; } if ( count( $types ) ) { $this->mConds['log_type'] = $types; // Set typeCGI; used in url param for paging if ( count( $types ) == 1 ) { $this->typeCGI = $types[0]; } } } /** * Set the log reader to return only entries by the given user. * * @param string $name (In)valid user name * @return void */ private function limitPerformer( $name ) { if ( $name == '' ) { return; } $usertitle = Title::makeTitleSafe( NS_USER, $name ); if ( is_null( $usertitle ) ) { return; } /* Fetch userid at first, if known, provides awesome query plan afterwards */ $userid = User::idFromName( $name ); if ( !$userid ) { $this->mConds['log_user_text'] = IP::sanitizeIP( $name ); } else { $this->mConds['log_user'] = $userid; } // Paranoia: avoid brute force searches (bug 17342) $user = $this->getUser(); if ( !$user->isAllowed( 'deletedhistory' ) ) { $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::DELETED_USER ) . ' = 0'; } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) { $this->mConds[] = $this->mDb->bitAnd( 'log_deleted', LogPage::SUPPRESSED_USER ) . ' != ' . LogPage::SUPPRESSED_USER; } $this->performer = $usertitle->getText(); } /** * Set the log reader to return only entries affecting the given page. * (For the block and rights logs, this is a user page.) * * @param string|Title $page Title name * @param string $pattern * @return void */ private function limitTitle( $page, $pattern ) { global $wgMiserMode, $wgUserrightsInterwikiDelimiter; if ( $page instanceof Title ) { $title = $page; } else { $title = Title::newFromText( $page ); if ( strlen( $page ) == 0 || !$title instanceof Title ) { return; } } $this->title = $title->getPrefixedText(); $ns = $title->getNamespace(); $db = $this->mDb; $doUserRightsLogLike = false; if ( $this->types == array( 'rights' ) ) { $parts = explode( $wgUserrightsInterwikiDelimiter, $title->getDBKey() ); if ( count( $parts ) == 2 ) { list( $name, $database ) = array_map( 'trim', $parts ); if ( strstr( $database, '*' ) ) { // Search for wildcard in database name $doUserRightsLogLike = true; } } } /** * Using the (log_namespace, log_title, log_timestamp) index with a * range scan (LIKE) on the first two parts, instead of simple equality, * makes it unusable for sorting. Sorted retrieval using another index * would be possible, but then we might have to scan arbitrarily many * nodes of that index. Therefore, we need to avoid this if $wgMiserMode * is on. * * This is not a problem with simple title matches, because then we can * use the page_time index. That should have no more than a few hundred * log entries for even the busiest pages, so it can be safely scanned * in full to satisfy an impossible condition on user or similar. */ $this->mConds['log_namespace'] = $ns; if ( $doUserRightsLogLike ) { $params = array( $name . $wgUserrightsInterwikiDelimiter ); foreach ( explode( '*', $database ) as $databasepart ) { $params[] = $databasepart; $params[] = $db->anyString(); } array_pop( $params ); // Get rid of the last % we added. $this->mConds[] = 'log_title' . $db->buildLike( $params ); } elseif ( $pattern && !$wgMiserMode ) { $this->mConds[] = 'log_title' . $db->buildLike( $title->getDBkey(), $db->anyString() ); $this->pattern = $pattern; } else { $this->mConds['log_title'] = $title->getDBkey(); } // Paranoia: avoid brute force searches (bug 17342) $user = $this->getUser(); if ( !$user->isAllowed( 'deletedhistory' ) ) { $this->mConds[] = $db->bitAnd( 'log_deleted', LogPage::DELETED_ACTION ) . ' = 0'; } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) { $this->mConds[] = $db->bitAnd( 'log_deleted', LogPage::SUPPRESSED_ACTION ) . ' != ' . LogPage::SUPPRESSED_ACTION; } } /** * Constructs the most part of the query. Extra conditions are sprinkled in * all over this class. * @return array */ public function getQueryInfo() { $basic = DatabaseLogEntry::getSelectQueryData(); $tables = $basic['tables']; $fields = $basic['fields']; $conds = $basic['conds']; $options = $basic['options']; $joins = $basic['join_conds']; $index = array(); # Add log_search table if there are conditions on it. # This filters the results to only include log rows that have # log_search records with the specified ls_field and ls_value values. if ( array_key_exists( 'ls_field', $this->mConds ) ) { $tables[] = 'log_search'; $index['log_search'] = 'ls_field_val'; $index['logging'] = 'PRIMARY'; if ( !$this->hasEqualsClause( 'ls_field' ) || !$this->hasEqualsClause( 'ls_value' ) ) { # Since (ls_field,ls_value,ls_logid) is unique, if the condition is # to match a specific (ls_field,ls_value) tuple, then there will be # no duplicate log rows. Otherwise, we need to remove the duplicates. $options[] = 'DISTINCT'; } } if ( count( $index ) ) { $options['USE INDEX'] = $index; } # Don't show duplicate rows when using log_search $joins['log_search'] = array( 'INNER JOIN', 'ls_log_id=log_id' ); $info = array( 'tables' => $tables, 'fields' => $fields, 'conds' => array_merge( $conds, $this->mConds ), 'options' => $options, 'join_conds' => $joins, ); # Add ChangeTags filter query ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'], $info['join_conds'], $info['options'], $this->mTagFilter ); return $info; } /** * Checks if $this->mConds has $field matched to a *single* value * @param string $field * @return bool */ protected function hasEqualsClause( $field ) { return ( array_key_exists( $field, $this->mConds ) && ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 ) ); } function getIndexField() { return 'log_timestamp'; } public function getStartBody() { # Do a link batch query if ( $this->getNumRows() > 0 ) { $lb = new LinkBatch; foreach ( $this->mResult as $row ) { $lb->add( $row->log_namespace, $row->log_title ); $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) ); $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) ); $formatter = LogFormatter::newFromRow( $row ); foreach ( $formatter->getPreloadTitles() as $title ) { $lb->addObj( $title ); } } $lb->execute(); $this->mResult->seek( 0 ); } return ''; } public function formatRow( $row ) { return $this->mLogEventsList->logLine( $row ); } public function getType() { return $this->types; } /** * @return string */ public function getPerformer() { return $this->performer; } /** * @return string */ public function getPage() { return $this->title; } public function getPattern() { return $this->pattern; } public function getYear() { return $this->mYear; } public function getMonth() { return $this->mMonth; } public function getTagFilter() { return $this->mTagFilter; } public function doQuery() { // Workaround MySQL optimizer bug $this->mDb->setBigSelects(); parent::doQuery(); $this->mDb->setBigSelects( 'default' ); } }
saper/MediaWiki
includes/logging/LogPager.php
PHP
gpl-2.0
11,864
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * * File Name : lis3dh_acc.c * Authors : MSH - Motion Mems BU - Application Team * : Matteo Dameno ([email protected]) * : Carmine Iascone ([email protected]) * : Both authors are willing to be considered the contact * : and update points for the driver. * Version : V.1.0.8 * Date : 2010/Apr/01 * Description : LIS3DH accelerometer sensor API * ******************************************************************************* * * 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 PRESENT SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, FOR THE SOLE * PURPOSE TO SUPPORT YOUR APPLICATION DEVELOPMENT. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * THIS SOFTWARE IS SPECIFICALLY DESIGNED FOR EXCLUSIVE USE WITH ST PARTS. * ****************************************************************************** Revision 1.0.0 05/11/09 First Release; Revision 1.0.3 22/01/2010 Linux K&R Compliant Release; Revision 1.0.5 16/08/2010 modified _get_acceleration_data function; modified _update_odr function; manages 2 interrupts; Revision 1.0.6 15/11/2010 supports sysfs; no more support for ioctl; Revision 1.0.7 26/11/2010 checks for availability of interrupts pins correction on FUZZ and FLAT values; Revision 1.0.8 2010/Apr/01 corrects a bug in interrupt pin management in 1.0.7 ******************************************************************************/ /*============================================================================== History Problem NO. Name Time Reason ==============================================================================*/ #include <linux/err.h> #include <linux/errno.h> #include <linux/delay.h> #include <linux/fs.h> #include <linux/i2c.h> #include <linux/input.h> #include <linux/uaccess.h> #include <linux/workqueue.h> #include <linux/irq.h> #include <linux/gpio.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/lis3dh.h> #include <linux/board_sensors.h> //#include <linux/input/lis3dh.h> #define DEBUG 1 #define G_MAX 16000 #define SENSITIVITY_2G 1 /** mg/LSB */ #define SENSITIVITY_4G 2 /** mg/LSB */ #define SENSITIVITY_8G 4 /** mg/LSB */ #define SENSITIVITY_16G 12 /** mg/LSB */ /* Accelerometer Sensor Operating Mode */ #define LIS3DH_ACC_ENABLE 0x01 #define LIS3DH_ACC_DISABLE 0x00 #define HIGH_RESOLUTION 0x08 #define AXISDATA_REG 0x28 #define WHOAMI_LIS3DH_ACC 0x33 /* Expected content for WAI */ /* CONTROL REGISTERS */ #define WHO_AM_I 0x0F /* WhoAmI register */ #define TEMP_CFG_REG 0x1F /* temper sens control reg */ /* ctrl 1: ODR3 ODR2 ODR ODR0 LPen Zenable Yenable Zenable */ #define CTRL_REG1 0x20 /* control reg 1 */ #define CTRL_REG2 0x21 /* control reg 2 */ #define CTRL_REG3 0x22 /* control reg 3 */ #define CTRL_REG4 0x23 /* control reg 4 */ #define CTRL_REG5 0x24 /* control reg 5 */ #define CTRL_REG6 0x25 /* control reg 6 */ #define FIFO_CTRL_REG 0x2E /* FiFo control reg */ #define INT_CFG1 0x30 /* interrupt 1 config */ #define INT_SRC1 0x31 /* interrupt 1 source */ #define INT_THS1 0x32 /* interrupt 1 threshold */ #define INT_DUR1 0x33 /* interrupt 1 duration */ #define TT_CFG 0x38 /* tap config */ #define TT_SRC 0x39 /* tap source */ #define TT_THS 0x3A /* tap threshold */ #define TT_LIM 0x3B /* tap time limit */ #define TT_TLAT 0x3C /* tap time latency */ #define TT_TW 0x3D /* tap time window */ /* end CONTROL REGISTRES */ #define ENABLE_HIGH_RESOLUTION 1 #define LIS3DH_ACC_PM_OFF 0x00 #define LIS3DH_ACC_ENABLE_ALL_AXES 0x07 #define PMODE_MASK 0x08 #define ODR_MASK 0XF0 #define ODR1 0x10 /* 1Hz output data rate */ #define ODR10 0x20 /* 10Hz output data rate */ #define ODR25 0x30 /* 25Hz output data rate */ #define ODR50 0x40 /* 50Hz output data rate */ #define ODR100 0x50 /* 100Hz output data rate */ #define ODR200 0x60 /* 200Hz output data rate */ #define ODR400 0x70 /* 400Hz output data rate */ #define ODR1250 0x90 /* 1250Hz output data rate */ #define IA 0x40 #define ZH 0x20 #define ZL 0x10 #define YH 0x08 #define YL 0x04 #define XH 0x02 #define XL 0x01 /* */ /* CTRL REG BITS*/ #define CTRL_REG3_I1_AOI1 0x40 #define CTRL_REG6_I2_TAPEN 0x80 #define CTRL_REG6_HLACTIVE 0x02 /* */ #define NO_MASK 0xFF #define INT1_DURATION_MASK 0x7F #define INT1_THRESHOLD_MASK 0x7F #define TAP_CFG_MASK 0x3F #define TAP_THS_MASK 0x7F #define TAP_TLIM_MASK 0x7F #define TAP_TLAT_MASK NO_MASK #define TAP_TW_MASK NO_MASK /* TAP_SOURCE_REG BIT */ #define DTAP 0x20 #define STAP 0x10 #define SIGNTAP 0x08 #define ZTAP 0x04 #define YTAP 0x02 #define XTAZ 0x01 #define FUZZ 0 #define FLAT 0 #define I2C_RETRY_DELAY 5 #define I2C_RETRIES 5 #define I2C_AUTO_INCREMENT 0x80 /* RESUME STATE INDICES */ #define RES_CTRL_REG1 0 #define RES_CTRL_REG2 1 #define RES_CTRL_REG3 2 #define RES_CTRL_REG4 3 #define RES_CTRL_REG5 4 #define RES_CTRL_REG6 5 #define RES_INT_CFG1 6 #define RES_INT_THS1 7 #define RES_INT_DUR1 8 #define RES_TT_CFG 9 #define RES_TT_THS 10 #define RES_TT_LIM 11 #define RES_TT_TLAT 12 #define RES_TT_TW 13 #define RES_TEMP_CFG_REG 14 #define RES_REFERENCE_REG 15 #define RES_FIFO_CTRL_REG 16 #define RESUME_ENTRIES 17 /* end RESUME STATE INDICES */ static int16_t accl_data[3] = {0, 0, 0}; struct { unsigned int cutoff_ms; unsigned int mask; } lis3dh_acc_odr_table[] = { { 1, ODR1250 }, { 3, ODR400 }, { 5, ODR200 }, { 10, ODR100 }, { 20, ODR50 }, { 40, ODR25 }, { 100, ODR10 }, { 1000, ODR1 }, }; struct lis3dh_acc_data { struct i2c_client *client; struct lis3dh_acc_platform_data *pdata; struct mutex lock; struct delayed_work input_work; struct input_dev *input_dev; int hw_initialized; /* hw_working=-1 means not tested yet */ int hw_working; atomic_t enabled; int on_before_suspend; u8 sensitivity; u8 resume_state[RESUME_ENTRIES]; int irq1; struct work_struct irq1_work; struct workqueue_struct *irq1_work_queue; int irq2; struct work_struct irq2_work; struct workqueue_struct *irq2_work_queue; #ifdef DEBUG u8 reg_addr; #endif }; static int lis3dh_acc_i2c_read(struct lis3dh_acc_data *acc, u8 * buf, int len) { int err; int tries = 0; struct i2c_msg msgs[] = { { .addr = acc->client->addr, .flags = acc->client->flags & I2C_M_TEN, .len = 1, .buf = buf, }, { .addr = acc->client->addr, .flags = (acc->client->flags & I2C_M_TEN) | I2C_M_RD, .len = len, .buf = buf, }, }; do { err = i2c_transfer(acc->client->adapter, msgs, 2); if (err != 2) msleep_interruptible(I2C_RETRY_DELAY); } while ((err != 2) && (++tries < I2C_RETRIES)); if (err != 2) { dev_err(&acc->client->dev, "read transfer error\n"); err = -EIO; } else { err = 0; } return err; } static int lis3dh_acc_i2c_write(struct lis3dh_acc_data *acc, u8 * buf, int len) { int err; int tries = 0; struct i2c_msg msgs[] = { { .addr = acc->client->addr, .flags = acc->client->flags & I2C_M_TEN, .len = len + 1, .buf = buf, }, }; do { err = i2c_transfer(acc->client->adapter, msgs, 1); if (err != 1) msleep_interruptible(I2C_RETRY_DELAY); } while ((err != 1) && (++tries < I2C_RETRIES)); if (err != 1) { dev_err(&acc->client->dev, "write transfer error\n"); err = -EIO; } else { err = 0; } return err; } static int lis3dh_acc_hw_init(struct lis3dh_acc_data *acc) { int err = -1; u8 buf[7]; printk(KERN_INFO "%s: hw init start\n", LIS3DH_ACC_DEV_NAME); buf[0] = WHO_AM_I; err = lis3dh_acc_i2c_read(acc, buf, 1); if (err < 0) { dev_warn(&acc->client->dev, "Error reading WHO_AM_I: is device " "available/working?\n"); goto err_firstread; } else acc->hw_working = 1; if (buf[0] != WHOAMI_LIS3DH_ACC) { dev_err(&acc->client->dev, "device unknown. Expected: 0x%x," " Replies: 0x%x\n", WHOAMI_LIS3DH_ACC, buf[0]); err = -1; /* choose the right coded error */ goto err_unknown_device; } buf[0] = CTRL_REG1; buf[1] = acc->resume_state[RES_CTRL_REG1]; err = lis3dh_acc_i2c_write(acc, buf, 1); if (err < 0) goto err_resume_state; buf[0] = TEMP_CFG_REG; buf[1] = acc->resume_state[RES_TEMP_CFG_REG]; err = lis3dh_acc_i2c_write(acc, buf, 1); if (err < 0) goto err_resume_state; buf[0] = FIFO_CTRL_REG; buf[1] = acc->resume_state[RES_FIFO_CTRL_REG]; err = lis3dh_acc_i2c_write(acc, buf, 1); if (err < 0) goto err_resume_state; buf[0] = (I2C_AUTO_INCREMENT | TT_THS); buf[1] = acc->resume_state[RES_TT_THS]; buf[2] = acc->resume_state[RES_TT_LIM]; buf[3] = acc->resume_state[RES_TT_TLAT]; buf[4] = acc->resume_state[RES_TT_TW]; err = lis3dh_acc_i2c_write(acc, buf, 4); if (err < 0) goto err_resume_state; buf[0] = TT_CFG; buf[1] = acc->resume_state[RES_TT_CFG]; err = lis3dh_acc_i2c_write(acc, buf, 1); if (err < 0) goto err_resume_state; buf[0] = (I2C_AUTO_INCREMENT | INT_THS1); buf[1] = acc->resume_state[RES_INT_THS1]; buf[2] = acc->resume_state[RES_INT_DUR1]; err = lis3dh_acc_i2c_write(acc, buf, 2); if (err < 0) goto err_resume_state; buf[0] = INT_CFG1; buf[1] = acc->resume_state[RES_INT_CFG1]; err = lis3dh_acc_i2c_write(acc, buf, 1); if (err < 0) goto err_resume_state; buf[0] = (I2C_AUTO_INCREMENT | CTRL_REG2); buf[1] = acc->resume_state[RES_CTRL_REG2]; buf[2] = acc->resume_state[RES_CTRL_REG3]; buf[3] = acc->resume_state[RES_CTRL_REG4]; buf[4] = acc->resume_state[RES_CTRL_REG5]; buf[5] = acc->resume_state[RES_CTRL_REG6]; err = lis3dh_acc_i2c_write(acc, buf, 5); if (err < 0) goto err_resume_state; acc->hw_initialized = 1; printk(KERN_INFO "%s: hw init done\n", LIS3DH_ACC_DEV_NAME); return 0; err_firstread: acc->hw_working = 0; err_unknown_device: err_resume_state: acc->hw_initialized = 0; dev_err(&acc->client->dev, "hw init error 0x%x,0x%x: %d\n", buf[0], buf[1], err); return err; } static void lis3dh_acc_device_power_off(struct lis3dh_acc_data *acc) { int err; u8 buf[2] = { CTRL_REG1, LIS3DH_ACC_PM_OFF }; err = lis3dh_acc_i2c_write(acc, buf, 1); if (err < 0) dev_err(&acc->client->dev, "soft power off failed: %d\n", err); if (acc->pdata->power_off) { if(acc->pdata->gpio_int1) disable_irq_nosync(acc->irq1); if(acc->pdata->gpio_int2) disable_irq_nosync(acc->irq2); acc->pdata->power_off(); acc->hw_initialized = 0; } if (acc->hw_initialized) { if(acc->pdata->gpio_int1) disable_irq_nosync(acc->irq1); if(acc->pdata->gpio_int2) disable_irq_nosync(acc->irq2); acc->hw_initialized = 0; } } static int lis3dh_acc_device_power_on(struct lis3dh_acc_data *acc) { int err = -1; if (acc->pdata->power_on) { err = acc->pdata->power_on(); if (err < 0) { dev_err(&acc->client->dev, "power_on failed: %d\n", err); return err; } if(acc->pdata->gpio_int1 >= 0) enable_irq(acc->irq1); if(acc->pdata->gpio_int2 >= 0) enable_irq(acc->irq2); } if (!acc->hw_initialized) { err = lis3dh_acc_hw_init(acc); if (acc->hw_working == 1 && err < 0) { lis3dh_acc_device_power_off(acc); return err; } } if (acc->hw_initialized) { if(acc->pdata->gpio_int1 >= 0) enable_irq(acc->irq1); if(acc->pdata->gpio_int2 >= 0) enable_irq(acc->irq2); } return 0; } static irqreturn_t lis3dh_acc_isr1(int irq, void *dev) { struct lis3dh_acc_data *acc = dev; disable_irq_nosync(irq); queue_work(acc->irq1_work_queue, &acc->irq1_work); printk(KERN_INFO "%s: isr1 queued\n", LIS3DH_ACC_DEV_NAME); return IRQ_HANDLED; } static irqreturn_t lis3dh_acc_isr2(int irq, void *dev) { struct lis3dh_acc_data *acc = dev; disable_irq_nosync(irq); queue_work(acc->irq2_work_queue, &acc->irq2_work); printk(KERN_INFO "%s: isr2 queued\n", LIS3DH_ACC_DEV_NAME); return IRQ_HANDLED; } static void lis3dh_acc_irq1_work_func(struct work_struct *work) { struct lis3dh_acc_data *acc = container_of(work, struct lis3dh_acc_data, irq1_work); /* TODO add interrupt service procedure. ie:lis3dh_acc_get_int1_source(acc); */ ; /* */ printk(KERN_INFO "%s: IRQ1 triggered\n", LIS3DH_ACC_DEV_NAME); enable_irq(acc->irq1); } static void lis3dh_acc_irq2_work_func(struct work_struct *work) { struct lis3dh_acc_data *acc = container_of(work, struct lis3dh_acc_data, irq2_work); /* TODO add interrupt service procedure. ie:lis3dh_acc_get_tap_source(acc); */ ; /* */ printk(KERN_INFO "%s: IRQ2 triggered\n", LIS3DH_ACC_DEV_NAME); enable_irq(acc->irq2); } int lis3dh_acc_update_g_range(struct lis3dh_acc_data *acc, u8 new_g_range) { int err=-1; u8 sensitivity; u8 buf[2]; u8 updated_val; u8 init_val; u8 new_val; u8 mask = LIS3DH_ACC_FS_MASK | HIGH_RESOLUTION; switch (new_g_range) { case LIS3DH_ACC_G_2G: sensitivity = SENSITIVITY_2G; break; case LIS3DH_ACC_G_4G: sensitivity = SENSITIVITY_4G; break; case LIS3DH_ACC_G_8G: sensitivity = SENSITIVITY_8G; break; case LIS3DH_ACC_G_16G: sensitivity = SENSITIVITY_16G; break; default: dev_err(&acc->client->dev, "invalid g range requested: %u\n", new_g_range); return -EINVAL; } if (atomic_read(&acc->enabled)) { /* Updates configuration register 4, * which contains g range setting */ buf[0] = CTRL_REG4; err = lis3dh_acc_i2c_read(acc, buf, 1); if (err < 0) goto error; init_val = buf[0]; acc->resume_state[RES_CTRL_REG4] = init_val; new_val = new_g_range | HIGH_RESOLUTION; updated_val = ((mask & new_val) | ((~mask) & init_val)); buf[1] = updated_val; buf[0] = CTRL_REG4; err = lis3dh_acc_i2c_write(acc, buf, 1); if (err < 0) goto error; acc->resume_state[RES_CTRL_REG4] = updated_val; acc->sensitivity = sensitivity; } return err; error: dev_err(&acc->client->dev, "update g range failed 0x%x,0x%x: %d\n", buf[0], buf[1], err); return err; } int lis3dh_acc_update_odr(struct lis3dh_acc_data *acc, int poll_interval_ms) { int err = -1; int i; u8 config[2]; /* Following, looks for the longest possible odr interval scrolling the * odr_table vector from the end (shortest interval) backward (longest * interval), to support the poll_interval requested by the system. * It must be the longest interval lower then the poll interval.*/ for (i = ARRAY_SIZE(lis3dh_acc_odr_table) - 1; i >= 0; i--) { if (lis3dh_acc_odr_table[i].cutoff_ms <= poll_interval_ms) break; } config[1] = lis3dh_acc_odr_table[i].mask; config[1] |= LIS3DH_ACC_ENABLE_ALL_AXES; /* If device is currently enabled, we need to write new * configuration out to it */ if (atomic_read(&acc->enabled)) { config[0] = CTRL_REG1; err = lis3dh_acc_i2c_write(acc, config, 1); if (err < 0) goto error; acc->resume_state[RES_CTRL_REG1] = config[1]; } return err; error: dev_err(&acc->client->dev, "update odr failed 0x%x,0x%x: %d\n", config[0], config[1], err); return err; } static int lis3dh_acc_register_write(struct lis3dh_acc_data *acc, u8 *buf, u8 reg_address, u8 new_value) { int err = -1; /* Sets configuration register at reg_address * NOTE: this is a straight overwrite */ buf[0] = reg_address; buf[1] = new_value; err = lis3dh_acc_i2c_write(acc, buf, 1); if (err < 0) return err; return err; } #if 0 static int lis3dh_acc_register_read(struct lis3dh_acc_data *acc, u8 *buf, u8 reg_address) { int err = -1; buf[0] = (reg_address); err = lis3dh_acc_i2c_read(acc, buf, 1); return err; } static int lis3dh_acc_register_update(struct lis3dh_acc_data *acc, u8 *buf, u8 reg_address, u8 mask, u8 new_bit_values) { int err = -1; u8 init_val; u8 updated_val; err = lis3dh_acc_register_read(acc, buf, reg_address); if (!(err < 0)) { init_val = buf[1]; updated_val = ((mask & new_bit_values) | ((~mask) & init_val)); err = lis3dh_acc_register_write(acc, buf, reg_address, updated_val); } return err; } #endif static int lis3dh_acc_get_acceleration_data(struct lis3dh_acc_data *acc, int *xyz) { int err = -1; /* Data bytes from hardware xL, xH, yL, yH, zL, zH */ u8 acc_data[6]; /* x,y,z hardware data */ s16 hw_d[3] = { 0 }; acc_data[0] = (I2C_AUTO_INCREMENT | AXISDATA_REG); err = lis3dh_acc_i2c_read(acc, acc_data, 6); if (err < 0) return err; hw_d[0] = (((s16) ((acc_data[1] << 8) | acc_data[0])) >> 4); hw_d[1] = (((s16) ((acc_data[3] << 8) | acc_data[2])) >> 4); hw_d[2] = (((s16) ((acc_data[5] << 8) | acc_data[4])) >> 4); hw_d[0] = hw_d[0] * acc->sensitivity; hw_d[1] = hw_d[1] * acc->sensitivity; hw_d[2] = hw_d[2] * acc->sensitivity; xyz[0] = ((acc->pdata->negate_x) ? (-hw_d[acc->pdata->axis_map_x]) : (hw_d[acc->pdata->axis_map_x])); xyz[1] = ((acc->pdata->negate_y) ? (-hw_d[acc->pdata->axis_map_y]) : (hw_d[acc->pdata->axis_map_y])); xyz[2] = ((acc->pdata->negate_z) ? (-hw_d[acc->pdata->axis_map_z]) : (hw_d[acc->pdata->axis_map_z])); #ifdef DEBUG /* printk(KERN_INFO "%s read x=%d, y=%d, z=%d\n", LIS3DH_ACC_DEV_NAME, xyz[0], xyz[1], xyz[2]); */ #endif return err; } static void lis3dh_acc_report_values(struct lis3dh_acc_data *acc, int *xyz) { accl_data[0] = xyz[0]; accl_data[1] = xyz[1]; accl_data[2] = xyz[2]; input_report_abs(acc->input_dev, ABS_X, xyz[0]); input_report_abs(acc->input_dev, ABS_Y, xyz[1]); input_report_abs(acc->input_dev, ABS_Z, xyz[2]); input_sync(acc->input_dev); } static int lis3dh_acc_enable(struct lis3dh_acc_data *acc) { int err; if (!atomic_cmpxchg(&acc->enabled, 0, 1)) { err = lis3dh_acc_device_power_on(acc); if (err < 0) { atomic_set(&acc->enabled, 0); return err; } schedule_delayed_work(&acc->input_work, msecs_to_jiffies(acc->pdata->poll_interval)); } return 0; } static int lis3dh_acc_disable(struct lis3dh_acc_data *acc) { if (atomic_cmpxchg(&acc->enabled, 1, 0)) { cancel_delayed_work_sync(&acc->input_work); lis3dh_acc_device_power_off(acc); } return 0; } static ssize_t read_single_reg(struct device *dev, char *buf, u8 reg) { ssize_t ret; struct lis3dh_acc_data *acc = dev_get_drvdata(dev); int err; u8 data = reg; err = lis3dh_acc_i2c_read(acc, &data, 1); if (err < 0) return err; ret = sprintf(buf, "0x%02x\n", data); return ret; } static int write_reg(struct device *dev, const char *buf, u8 reg, u8 mask, int resumeIndex) { int err = -1; struct lis3dh_acc_data *acc = dev_get_drvdata(dev); u8 x[2]; u8 new_val; unsigned long val; if (strict_strtoul(buf, 16, &val)) return -EINVAL; new_val=((u8) val & mask); x[0] = reg; x[1] = new_val; err = lis3dh_acc_register_write(acc, x,reg,new_val); if (err < 0) return err; acc->resume_state[resumeIndex] = new_val; return err; } static ssize_t attr_get_polling_rate(struct device *dev, struct device_attribute *attr, char *buf) { int val; struct lis3dh_acc_data *acc = dev_get_drvdata(dev); mutex_lock(&acc->lock); val = acc->pdata->poll_interval; mutex_unlock(&acc->lock); return sprintf(buf, "%d\n", val); } static ssize_t attr_set_polling_rate(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct lis3dh_acc_data *acc = dev_get_drvdata(dev); unsigned long interval_ms; if (strict_strtoul(buf, 10, &interval_ms)) return -EINVAL; if (!interval_ms) return -EINVAL; mutex_lock(&acc->lock); acc->pdata->poll_interval = interval_ms; lis3dh_acc_update_odr(acc, interval_ms); mutex_unlock(&acc->lock); return size; } static ssize_t attr_get_range(struct device *dev, struct device_attribute *attr, char *buf) { char val; struct lis3dh_acc_data *acc = dev_get_drvdata(dev); char range = 2; mutex_lock(&acc->lock); val = acc->pdata->g_range ; switch (val) { case LIS3DH_ACC_G_2G: range = 2; break; case LIS3DH_ACC_G_4G: range = 4; break; case LIS3DH_ACC_G_8G: range = 8; break; case LIS3DH_ACC_G_16G: range = 16; break; } mutex_unlock(&acc->lock); return sprintf(buf, "%d\n", range); } static ssize_t attr_set_range(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct lis3dh_acc_data *acc = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 10, &val)) return -EINVAL; mutex_lock(&acc->lock); acc->pdata->g_range = val; lis3dh_acc_update_g_range(acc, val); mutex_unlock(&acc->lock); return size; } static ssize_t attr_get_enable(struct device *dev, struct device_attribute *attr, char *buf) { struct lis3dh_acc_data *acc = dev_get_drvdata(dev); int val = atomic_read(&acc->enabled); return sprintf(buf, "%d\n", val); } static ssize_t attr_set_enable(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct lis3dh_acc_data *acc = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 10, &val)) return -EINVAL; if (val) lis3dh_acc_enable(acc); else lis3dh_acc_disable(acc); return size; } static ssize_t attr_set_intconfig1(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { return write_reg(dev,buf,INT_CFG1,NO_MASK,RES_INT_CFG1); } static ssize_t attr_get_intconfig1(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,INT_CFG1); } static ssize_t attr_set_duration1(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { return write_reg(dev,buf,INT_DUR1,INT1_DURATION_MASK,RES_INT_DUR1); } static ssize_t attr_get_duration1(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,INT_DUR1); } static ssize_t attr_set_thresh1(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { return write_reg(dev,buf,INT_THS1,INT1_THRESHOLD_MASK,RES_INT_THS1); } static ssize_t attr_get_thresh1(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,INT_THS1); } static ssize_t attr_get_source1(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,INT_SRC1); } static ssize_t attr_set_click_cfg(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { return write_reg(dev,buf,TT_CFG,TAP_CFG_MASK,RES_TT_CFG); } static ssize_t attr_get_click_cfg(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,TT_CFG); } static ssize_t attr_get_click_source(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,TT_SRC); } static ssize_t attr_set_click_ths(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { return write_reg(dev,buf,TT_THS,TAP_THS_MASK,RES_TT_THS); } static ssize_t attr_get_click_ths(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,TT_THS); } static ssize_t attr_set_click_tlim(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { return write_reg(dev,buf,TT_LIM,TAP_TLIM_MASK,RES_TT_LIM); } static ssize_t attr_get_click_tlim(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,TT_LIM); } static ssize_t attr_set_click_tlat(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { return write_reg(dev,buf,TT_TLAT,TAP_TLAT_MASK,RES_TT_TLAT); } static ssize_t attr_get_click_tlat(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,TT_TLAT); } static ssize_t attr_set_click_tw(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { return write_reg(dev,buf,TT_TLAT,TAP_TW_MASK,RES_TT_TLAT); } static ssize_t attr_get_click_tw(struct device *dev, struct device_attribute *attr, char *buf) { return read_single_reg(dev,buf,TT_TLAT); } static ssize_t attr_get_accl_data(struct device *dev, struct device_attribute *attr, char *buf) { *((int16_t *)&buf[0]) = accl_data[0]; *((int16_t *)&buf[2]) = accl_data[1]; *((int16_t *)&buf[4]) = accl_data[2]; return ACCL_DATA_SIZE; } #ifdef DEBUG /* PAY ATTENTION: These DEBUG funtions don't manage resume_state */ static ssize_t attr_reg_set(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { int rc; struct lis3dh_acc_data *acc = dev_get_drvdata(dev); u8 x[2]; unsigned long val; if (strict_strtoul(buf, 16, &val)) return -EINVAL; mutex_lock(&acc->lock); x[0] = acc->reg_addr; mutex_unlock(&acc->lock); x[1] = val; rc = lis3dh_acc_i2c_write(acc, x, 1); /*TODO: error need to be managed */ return size; } static ssize_t attr_reg_get(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret; struct lis3dh_acc_data *acc = dev_get_drvdata(dev); int rc; u8 data; mutex_lock(&acc->lock); data = acc->reg_addr; mutex_unlock(&acc->lock); rc = lis3dh_acc_i2c_read(acc, &data, 1); /*TODO: error need to be managed */ ret = sprintf(buf, "0x%02x\n", data); return ret; } static ssize_t attr_addr_set(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct lis3dh_acc_data *acc = dev_get_drvdata(dev); unsigned long val; if (strict_strtoul(buf, 16, &val)) return -EINVAL; mutex_lock(&acc->lock); acc->reg_addr = val; mutex_unlock(&acc->lock); return size; } #endif static struct device_attribute attributes[] = { __ATTR(pollrate_ms, 0664, attr_get_polling_rate, attr_set_polling_rate), __ATTR(range, 0664, attr_get_range, attr_set_range), __ATTR(enable, 0664, attr_get_enable, attr_set_enable), __ATTR(int1_config, 0664, attr_get_intconfig1, attr_set_intconfig1), __ATTR(int1_duration, 0664, attr_get_duration1, attr_set_duration1), __ATTR(int1_threshold, 0664, attr_get_thresh1, attr_set_thresh1), __ATTR(int1_source, 0444, attr_get_source1, NULL), __ATTR(click_config, 0664, attr_get_click_cfg, attr_set_click_cfg), __ATTR(click_source, 0444, attr_get_click_source, NULL), __ATTR(click_threshold, 0664, attr_get_click_ths, attr_set_click_ths), __ATTR(click_timelimit, 0664, attr_get_click_tlim, attr_set_click_tlim), __ATTR(click_timelatency, 0664, attr_get_click_tlat, attr_set_click_tlat), __ATTR(click_timewindow, 0664, attr_get_click_tw, attr_set_click_tw), __ATTR(accl_data, 0664, attr_get_accl_data, NULL), #ifdef DEBUG __ATTR(reg_value, 0600, attr_reg_get, attr_reg_set), __ATTR(reg_addr, 0200, NULL, attr_addr_set), #endif }; static int create_sysfs_interfaces(struct device *dev) { int i; for (i = 0; i < ARRAY_SIZE(attributes); i++) if (device_create_file(dev, attributes + i)) goto error; return 0; error: for ( ; i >= 0; i--) device_remove_file(dev, attributes + i); dev_err(dev, "%s:Unable to create interface\n", __func__); return -1; } static int remove_sysfs_interfaces(struct device *dev) { int i; for (i = 0; i < ARRAY_SIZE(attributes); i++) device_remove_file(dev, attributes + i); return 0; } static void lis3dh_acc_input_work_func(struct work_struct *work) { struct lis3dh_acc_data *acc; int xyz[3] = { 0 }; int err; acc = container_of((struct delayed_work *)work, struct lis3dh_acc_data, input_work); mutex_lock(&acc->lock); err = lis3dh_acc_get_acceleration_data(acc, xyz); if (err < 0) dev_err(&acc->client->dev, "get_acceleration_data failed\n"); else lis3dh_acc_report_values(acc, xyz); schedule_delayed_work(&acc->input_work, msecs_to_jiffies( acc->pdata->poll_interval)); mutex_unlock(&acc->lock); } int lis3dh_acc_input_open(struct input_dev *input) { struct lis3dh_acc_data *acc = input_get_drvdata(input); return lis3dh_acc_enable(acc); } void lis3dh_acc_input_close(struct input_dev *dev) { struct lis3dh_acc_data *acc = input_get_drvdata(dev); lis3dh_acc_disable(acc); } static int lis3dh_acc_validate_pdata(struct lis3dh_acc_data *acc) { acc->pdata->poll_interval = max(acc->pdata->poll_interval, acc->pdata->min_interval); if (acc->pdata->axis_map_x > 2 || acc->pdata->axis_map_y > 2 || acc->pdata->axis_map_z > 2) { dev_err(&acc->client->dev, "invalid axis_map value " "x:%u y:%u z%u\n", acc->pdata->axis_map_x, acc->pdata->axis_map_y, acc->pdata->axis_map_z); return -EINVAL; } /* Only allow 0 and 1 for negation boolean flag */ if (acc->pdata->negate_x > 1 || acc->pdata->negate_y > 1 || acc->pdata->negate_z > 1) { dev_err(&acc->client->dev, "invalid negate value " "x:%u y:%u z:%u\n", acc->pdata->negate_x, acc->pdata->negate_y, acc->pdata->negate_z); return -EINVAL; } /* Enforce minimum polling interval */ if (acc->pdata->poll_interval < acc->pdata->min_interval) { dev_err(&acc->client->dev, "minimum poll interval violated\n"); return -EINVAL; } return 0; } static int lis3dh_acc_input_init(struct lis3dh_acc_data *acc) { int err; INIT_DELAYED_WORK(&acc->input_work, lis3dh_acc_input_work_func); acc->input_dev = input_allocate_device(); if (!acc->input_dev) { err = -ENOMEM; dev_err(&acc->client->dev, "input device allocation failed\n"); goto err0; } acc->input_dev->open = lis3dh_acc_input_open; acc->input_dev->close = lis3dh_acc_input_close; acc->input_dev->name = ACCL_INPUT_DEV_NAME; //acc->input_dev->name = "accelerometer"; acc->input_dev->id.bustype = BUS_I2C; acc->input_dev->dev.parent = &acc->client->dev; input_set_drvdata(acc->input_dev, acc); set_bit(EV_ABS, acc->input_dev->evbit); /* next is used for interruptA sources data if the case */ set_bit(ABS_MISC, acc->input_dev->absbit); /* next is used for interruptB sources data if the case */ set_bit(ABS_WHEEL, acc->input_dev->absbit); input_set_abs_params(acc->input_dev, ABS_X, -G_MAX, G_MAX, FUZZ, FLAT); input_set_abs_params(acc->input_dev, ABS_Y, -G_MAX, G_MAX, FUZZ, FLAT); input_set_abs_params(acc->input_dev, ABS_Z, -G_MAX, G_MAX, FUZZ, FLAT); /* next is used for interruptA sources data if the case */ input_set_abs_params(acc->input_dev, ABS_MISC, INT_MIN, INT_MAX, 0, 0); /* next is used for interruptB sources data if the case */ input_set_abs_params(acc->input_dev, ABS_WHEEL, INT_MIN, INT_MAX, 0, 0); err = input_register_device(acc->input_dev); if (err) { dev_err(&acc->client->dev, "unable to register input device %s\n", acc->input_dev->name); goto err1; } return 0; err1: input_free_device(acc->input_dev); err0: return err; } static void lis3dh_acc_input_cleanup(struct lis3dh_acc_data *acc) { input_unregister_device(acc->input_dev); input_free_device(acc->input_dev); } static int lis3dh_acc_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct lis3dh_acc_data *acc; int err = -1; pr_info("%s: probe start.\n", LIS3DH_ACC_DEV_NAME); enable_power_for_device(&client->dev,ST_ACCL_POWER_NAME,DEV_POWER); if (client->dev.platform_data == NULL) { dev_err(&client->dev, "platform data is NULL. exiting.\n"); err = -ENODEV; goto exit_check_functionality_failed; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "client not i2c capable\n"); err = -ENODEV; goto exit_check_functionality_failed; } /* if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE | I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA)) { dev_err(&client->dev, "client not smb-i2c capable:2\n"); err = -EIO; goto exit_check_functionality_failed; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_I2C_BLOCK)){ dev_err(&client->dev, "client not smb-i2c capable:3\n"); err = -EIO; goto exit_check_functionality_failed; } */ acc = kzalloc(sizeof(struct lis3dh_acc_data), GFP_KERNEL); if (acc == NULL) { err = -ENOMEM; dev_err(&client->dev, "failed to allocate memory for module data: " "%d\n", err); goto exit_check_functionality_failed; } mutex_init(&acc->lock); mutex_lock(&acc->lock); acc->client = client; i2c_set_clientdata(client, acc); acc->pdata = kmalloc(sizeof(*acc->pdata), GFP_KERNEL); if (acc->pdata == NULL) { err = -ENOMEM; dev_err(&client->dev, "failed to allocate memory for pdata: %d\n", err); goto err_mutexunlock; } memcpy(acc->pdata, client->dev.platform_data, sizeof(*acc->pdata)); err = lis3dh_acc_validate_pdata(acc); if (err < 0) { dev_err(&client->dev, "failed to validate platform data\n"); goto exit_kfree_pdata; } if (acc->pdata->init) { err = acc->pdata->init(); if (err < 0) { dev_err(&client->dev, "init failed: %d\n", err); goto err_pdata_init; } } if(acc->pdata->gpio_int1 >= 0){ acc->irq1 = gpio_to_irq(acc->pdata->gpio_int1); printk(KERN_INFO "%s: %s has set irq1 to irq: %d " "mapped on gpio:%d\n", LIS3DH_ACC_DEV_NAME, __func__, acc->irq1, acc->pdata->gpio_int1); } if(acc->pdata->gpio_int2 >= 0){ acc->irq2 = gpio_to_irq(acc->pdata->gpio_int2); printk(KERN_INFO "%s: %s has set irq2 to irq: %d " "mapped on gpio:%d\n", LIS3DH_ACC_DEV_NAME, __func__, acc->irq2, acc->pdata->gpio_int2); } memset(acc->resume_state, 0, ARRAY_SIZE(acc->resume_state)); acc->resume_state[RES_CTRL_REG1] = LIS3DH_ACC_ENABLE_ALL_AXES; acc->resume_state[RES_CTRL_REG2] = 0x00; acc->resume_state[RES_CTRL_REG3] = 0x00; acc->resume_state[RES_CTRL_REG4] = 0x00; acc->resume_state[RES_CTRL_REG5] = 0x00; acc->resume_state[RES_CTRL_REG6] = 0x00; acc->resume_state[RES_TEMP_CFG_REG] = 0x00; acc->resume_state[RES_FIFO_CTRL_REG] = 0x00; acc->resume_state[RES_INT_CFG1] = 0x00; acc->resume_state[RES_INT_THS1] = 0x00; acc->resume_state[RES_INT_DUR1] = 0x00; acc->resume_state[RES_TT_CFG] = 0x00; acc->resume_state[RES_TT_THS] = 0x00; acc->resume_state[RES_TT_LIM] = 0x00; acc->resume_state[RES_TT_TLAT] = 0x00; acc->resume_state[RES_TT_TW] = 0x00; err = lis3dh_acc_device_power_on(acc); if (err < 0) { dev_err(&client->dev, "power on failed: %d\n", err); goto err_pdata_init; } atomic_set(&acc->enabled, 1); err = lis3dh_acc_update_g_range(acc, acc->pdata->g_range); if (err < 0) { dev_err(&client->dev, "update_g_range failed\n"); goto err_power_off; } err = lis3dh_acc_update_odr(acc, acc->pdata->poll_interval); if (err < 0) { dev_err(&client->dev, "update_odr failed\n"); goto err_power_off; } err = lis3dh_acc_input_init(acc); if (err < 0) { dev_err(&client->dev, "input init failed\n"); goto err_power_off; } err = create_sysfs_interfaces(&client->dev); if (err < 0) { dev_err(&client->dev, "device LIS3DH_ACC_DEV_NAME sysfs register failed\n"); goto err_input_cleanup; } lis3dh_acc_device_power_off(acc); /* As default, do not report information */ atomic_set(&acc->enabled, 0); if(acc->pdata->gpio_int1 >= 0){ INIT_WORK(&acc->irq1_work, lis3dh_acc_irq1_work_func); acc->irq1_work_queue = create_singlethread_workqueue("lis3dh_acc_wq1"); if (!acc->irq1_work_queue) { err = -ENOMEM; dev_err(&client->dev, "cannot create work queue1: %d\n", err); goto err_remove_sysfs_int; } err = request_irq(acc->irq1, lis3dh_acc_isr1, IRQF_TRIGGER_RISING, "lis3dh_acc_irq1", acc); if (err < 0) { dev_err(&client->dev, "request irq1 failed: %d\n", err); goto err_destoyworkqueue1; } disable_irq_nosync(acc->irq1); } if(acc->pdata->gpio_int2 >= 0){ INIT_WORK(&acc->irq2_work, lis3dh_acc_irq2_work_func); acc->irq2_work_queue = create_singlethread_workqueue("lis3dh_acc_wq2"); if (!acc->irq2_work_queue) { err = -ENOMEM; dev_err(&client->dev, "cannot create work queue2: %d\n", err); goto err_free_irq1; } err = request_irq(acc->irq2, lis3dh_acc_isr2, IRQF_TRIGGER_RISING, "lis3dh_acc_irq2", acc); if (err < 0) { dev_err(&client->dev, "request irq2 failed: %d\n", err); goto err_destoyworkqueue2; } disable_irq_nosync(acc->irq2); } mutex_unlock(&acc->lock); dev_info(&client->dev, "%s: probed\n", LIS3DH_ACC_DEV_NAME); return 0; err_destoyworkqueue2: if(acc->pdata->gpio_int2 >= 0) destroy_workqueue(acc->irq2_work_queue); err_free_irq1: free_irq(acc->irq1, acc); err_destoyworkqueue1: if(acc->pdata->gpio_int1 >= 0) destroy_workqueue(acc->irq1_work_queue); err_remove_sysfs_int: remove_sysfs_interfaces(&client->dev); err_input_cleanup: lis3dh_acc_input_cleanup(acc); err_power_off: lis3dh_acc_device_power_off(acc); err_pdata_init: if (acc->pdata->exit) acc->pdata->exit(); exit_kfree_pdata: kfree(acc->pdata); err_mutexunlock: mutex_unlock(&acc->lock); //err_freedata: kfree(acc); exit_check_functionality_failed: printk(KERN_ERR "%s: Driver Init failed\n", LIS3DH_ACC_DEV_NAME); return err; } static int __devexit lis3dh_acc_remove(struct i2c_client *client) { struct lis3dh_acc_data *acc = i2c_get_clientdata(client); if(acc->pdata->gpio_int1 >= 0){ free_irq(acc->irq1, acc); gpio_free(acc->pdata->gpio_int1); destroy_workqueue(acc->irq1_work_queue); } if(acc->pdata->gpio_int2 >= 0){ free_irq(acc->irq2, acc); gpio_free(acc->pdata->gpio_int2); destroy_workqueue(acc->irq2_work_queue); } lis3dh_acc_input_cleanup(acc); lis3dh_acc_device_power_off(acc); remove_sysfs_interfaces(&client->dev); if (acc->pdata->exit) acc->pdata->exit(); kfree(acc->pdata); kfree(acc); return 0; } #ifdef CONFIG_PM static int lis3dh_acc_resume(struct i2c_client *client) { struct lis3dh_acc_data *acc = i2c_get_clientdata(client); if (acc->on_before_suspend) return lis3dh_acc_enable(acc); return 0; } static int lis3dh_acc_suspend(struct i2c_client *client, pm_message_t mesg) { struct lis3dh_acc_data *acc = i2c_get_clientdata(client); acc->on_before_suspend = atomic_read(&acc->enabled); return lis3dh_acc_disable(acc); } #else #define lis3dh_acc_suspend NULL #define lis3dh_acc_resume NULL #endif /* CONFIG_PM */ static const struct i2c_device_id lis3dh_acc_id[] = { { LIS3DH_ACC_DEV_NAME, 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, lis3dh_acc_id); static struct i2c_driver lis3dh_acc_driver = { .driver = { .owner = THIS_MODULE, .name = LIS3DH_ACC_DEV_NAME, }, .probe = lis3dh_acc_probe, .remove = __devexit_p(lis3dh_acc_remove), .suspend = lis3dh_acc_suspend, .resume = lis3dh_acc_resume, .id_table = lis3dh_acc_id, }; static int __init lis3dh_acc_init(void) { printk(KERN_INFO "%s accelerometer driver: init\n", LIS3DH_ACC_DEV_NAME); return i2c_add_driver(&lis3dh_acc_driver); } static void __exit lis3dh_acc_exit(void) { #ifdef DEBUG printk(KERN_INFO "%s accelerometer driver exit\n", LIS3DH_ACC_DEV_NAME); #endif /* DEBUG */ i2c_del_driver(&lis3dh_acc_driver); return; } module_init(lis3dh_acc_init); module_exit(lis3dh_acc_exit); MODULE_DESCRIPTION("lis3dh digital accelerometer sysfs driver"); MODULE_AUTHOR("Matteo Dameno, Carmine Iascone, STMicroelectronics"); MODULE_LICENSE("GPL");
ShevT/android_kernel_d1_p1
drivers/input/misc/lis3dh_acc.c
C
gpl-2.0
39,243
ace.define("ace/mode/csound_preprocessor_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CsoundPreprocessorHighlightRules = function(embeddedRulePrefix) { this.embeddedRulePrefix = embeddedRulePrefix === undefined ? "" : embeddedRulePrefix; this.semicolonComments = { token : "comment.line.semicolon.csound", regex : ";.*$" }; this.comments = [ { token : "punctuation.definition.comment.begin.csound", regex : "/\\*", push : [ { token : "punctuation.definition.comment.end.csound", regex : "\\*/", next : "pop" }, { defaultToken: "comment.block.csound" } ] }, { token : "comment.line.double-slash.csound", regex : "//.*$" }, this.semicolonComments ]; this.macroUses = [ { token : ["entity.name.function.preprocessor.csound", "punctuation.definition.macro-parameter-value-list.begin.csound"], regex : /(\$[A-Z_a-z]\w*\.?)(\()/, next : "macro parameter value list" }, { token : "entity.name.function.preprocessor.csound", regex : /\$[A-Z_a-z]\w*(?:\.|\b)/ } ]; this.numbers = [ { token : "constant.numeric.float.csound", regex : /(?:\d+[Ee][+-]?\d+)|(?:\d+\.\d*|\d*\.\d+)(?:[Ee][+-]?\d+)?/ }, { token : ["storage.type.number.csound", "constant.numeric.integer.hexadecimal.csound"], regex : /(0[Xx])([0-9A-Fa-f]+)/ }, { token : "constant.numeric.integer.decimal.csound", regex : /\d+/ } ]; this.bracedStringContents = [ { token : "constant.character.escape.csound", regex : /\\(?:[\\abnrt"]|[0-7]{1,3})/ }, { token : "constant.character.placeholder.csound", regex : /%[#0\- +]*\d*(?:\.\d+)?[diuoxXfFeEgGaAcs]/ }, { token : "constant.character.escape.csound", regex : /%%/ } ]; this.quotedStringContents = [ this.macroUses, this.bracedStringContents ]; var start = [ this.comments, { token : "keyword.preprocessor.csound", regex : /#(?:e(?:nd(?:if)?|lse)\b|##)|@@?[ \t]*\d+/ }, { token : "keyword.preprocessor.csound", regex : /#include/, push : [ this.comments, { token : "string.csound", regex : /([^ \t])(?:.*?\1)/, next : "pop" } ] }, { token : "keyword.preprocessor.csound", regex : /#includestr/, push : [ this.comments, { token : "string.csound", regex : /([^ \t])(?:.*?\1)/, next : "pop" } ] }, { token : "keyword.preprocessor.csound", regex : /#[ \t]*define/, next : "define directive" }, { token : "keyword.preprocessor.csound", regex : /#(?:ifn?def|undef)\b/, next : "macro directive" }, this.macroUses ]; this.$rules = { "start": start, "define directive": [ this.comments, { token : "entity.name.function.preprocessor.csound", regex : /[A-Z_a-z]\w*/ }, { token : "punctuation.definition.macro-parameter-name-list.begin.csound", regex : /\(/, next : "macro parameter name list" }, { token : "punctuation.definition.macro.begin.csound", regex : /#/, next : "macro body" } ], "macro parameter name list": [ { token : "variable.parameter.preprocessor.csound", regex : /[A-Z_a-z]\w*/ }, { token : "punctuation.definition.macro-parameter-name-list.end.csound", regex : /\)/, next : "define directive" } ], "macro body": [ { token : "constant.character.escape.csound", regex : /\\#/ }, { token : "punctuation.definition.macro.end.csound", regex : /#/, next : "start" }, start ], "macro directive": [ this.comments, { token : "entity.name.function.preprocessor.csound", regex : /[A-Z_a-z]\w*/, next : "start" } ], "macro parameter value list": [ { token : "punctuation.definition.macro-parameter-value-list.end.csound", regex : /\)/, next : "start" }, { token : "punctuation.definition.string.begin.csound", regex : /"/, next : "macro parameter value quoted string" }, this.pushRule({ token : "punctuation.macro-parameter-value-parenthetical.begin.csound", regex : /\(/, next : "macro parameter value parenthetical" }), { token : "punctuation.macro-parameter-value-separator.csound", regex : "[#']" } ], "macro parameter value quoted string": [ { token : "constant.character.escape.csound", regex : /\\[#'()]/ }, { token : "invalid.illegal.csound", regex : /[#'()]/ }, { token : "punctuation.definition.string.end.csound", regex : /"/, next : "macro parameter value list" }, this.quotedStringContents, { defaultToken: "string.quoted.csound" } ], "macro parameter value parenthetical": [ { token : "constant.character.escape.csound", regex : /\\\)/ }, this.popRule({ token : "punctuation.macro-parameter-value-parenthetical.end.csound", regex : /\)/ }), this.pushRule({ token : "punctuation.macro-parameter-value-parenthetical.begin.csound", regex : /\(/, next : "macro parameter value parenthetical" }), start ] }; }; oop.inherits(CsoundPreprocessorHighlightRules, TextHighlightRules); (function() { this.pushRule = function(params) { if (Array.isArray(params.next)) { for (var i = 0; i < params.next.length; i++) { params.next[i] = this.embeddedRulePrefix + params.next[i]; } } return { regex : params.regex, onMatch: function(value, currentState, stack, line) { if (stack.length === 0) stack.push(currentState); if (Array.isArray(params.next)) { for (var i = 0; i < params.next.length; i++) { stack.push(params.next[i]); } } else { stack.push(params.next); } this.next = stack[stack.length - 1]; return params.token; }, get next() { return Array.isArray(params.next) ? params.next[params.next.length - 1] : params.next; }, set next(next) { if (!Array.isArray(params.next)) { params.next = next; } }, get token() { return params.token; } }; }; this.popRule = function(params) { if (params.next) { params.next = this.embeddedRulePrefix + params.next; } return { regex : params.regex, onMatch: function(value, currentState, stack, line) { stack.pop(); if (params.next) { stack.push(params.next); this.next = stack[stack.length - 1]; } else { this.next = stack.length > 1 ? stack[stack.length - 1] : stack.pop(); } return params.token; } }; }; }).call(CsoundPreprocessorHighlightRules.prototype); exports.CsoundPreprocessorHighlightRules = CsoundPreprocessorHighlightRules; }); ace.define("ace/mode/csound_score_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/csound_preprocessor_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var CsoundPreprocessorHighlightRules = require("./csound_preprocessor_highlight_rules").CsoundPreprocessorHighlightRules; var CsoundScoreHighlightRules = function(embeddedRulePrefix) { CsoundPreprocessorHighlightRules.call(this, embeddedRulePrefix); this.quotedStringContents.push({ token : "invalid.illegal.csound-score", regex : /[^"]*$/ }); var start = this.$rules.start; start.push( { token : "keyword.control.csound-score", regex : /[abCdefiqstvxy]/ }, { token : "invalid.illegal.csound-score", regex : /w/ }, { token : "constant.numeric.language.csound-score", regex : /z/ }, { token : ["keyword.control.csound-score", "constant.numeric.integer.decimal.csound-score"], regex : /([nNpP][pP])(\d+)/ }, { token : "keyword.other.csound-score", regex : /[mn]/, push : [ { token : "empty", regex : /$/, next : "pop" }, this.comments, { token : "entity.name.label.csound-score", regex : /[A-Z_a-z]\w*/ } ] }, { token : "keyword.preprocessor.csound-score", regex : /r\b/, next : "repeat section" }, this.numbers, { token : "keyword.operator.csound-score", regex : "[!+\\-*/^%&|<>#~.]" }, this.pushRule({ token : "punctuation.definition.string.begin.csound-score", regex : /"/, next : "quoted string" }), this.pushRule({ token : "punctuation.braced-loop.begin.csound-score", regex : /{/, next : "loop after left brace" }) ); this.addRules({ "repeat section": [ { token : "empty", regex : /$/, next : "start" }, this.comments, { token : "constant.numeric.integer.decimal.csound-score", regex : /\d+/, next : "repeat section before label" } ], "repeat section before label": [ { token : "empty", regex : /$/, next : "start" }, this.comments, { token : "entity.name.label.csound-score", regex : /[A-Z_a-z]\w*/, next : "start" } ], "quoted string": [ this.popRule({ token : "punctuation.definition.string.end.csound-score", regex : /"/ }), this.quotedStringContents, { defaultToken: "string.quoted.csound-score" } ], "loop after left brace": [ this.popRule({ token : "constant.numeric.integer.decimal.csound-score", regex : /\d+/, next : "loop after repeat count" }), this.comments, { token : "invalid.illegal.csound", regex : /\S.*/ } ], "loop after repeat count": [ this.popRule({ token : "entity.name.function.preprocessor.csound-score", regex : /[A-Z_a-z]\w*\b/, next : "loop after macro name" }), this.comments, { token : "invalid.illegal.csound", regex : /\S.*/ } ], "loop after macro name": [ start, this.popRule({ token : "punctuation.braced-loop.end.csound-score", regex : /}/ }) ] }); this.normalizeRules(); }; oop.inherits(CsoundScoreHighlightRules, CsoundPreprocessorHighlightRules); exports.CsoundScoreHighlightRules = CsoundScoreHighlightRules; }); ace.define("ace/mode/csound_score",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/csound_score_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CsoundScoreHighlightRules = require("./csound_score_highlight_rules").CsoundScoreHighlightRules; var Mode = function() { this.HighlightRules = CsoundScoreHighlightRules; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = ";"; this.blockComment = {start: "/*", end: "*/"}; }).call(Mode.prototype); exports.Mode = Mode; }); (function() { ace.require(["ace/mode/csound_score"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
oat-sa/extension-tao-xmledit
views/js/lib/ace-1.4.5/mode-csound_score.js
JavaScript
gpl-2.0
14,369
/* * CINELERRA * Copyright (C) 2008 Adam Williams <broadcast at earthling dot 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef AEDITS_H #define AEDITS_H #include "atrack.inc" #include "edits.h" #include "edl.inc" #include "filexml.inc" #include "mwindow.inc" class AEdits : public Edits { public: AEdits(EDL *edl, Track *track); // Editing Edit* create_edit(); AEdits() {printf("default edits constructor called\n");}; ~AEdits() {}; // ======================================= editing Edit* append_new_edit(); Edit* insert_edit_after(Edit* previous_edit); int clone_derived(Edit* new_edit, Edit* old_edit); private: ATrack *atrack; }; #endif
petterreinholdtsen/cinelerra-cv
cinelerra/aedits.h
C
gpl-2.0
1,367
/* * Copyright (C) 2014, 2015 netblue30 ([email protected]) * * This file is part of firejail project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef FIREMON_H #define FIREMON_H #define _GNU_SOURCE #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <errno.h> #include <stdint.h> #include "../include/pid.h" #include "../include/common.h" // clear screen static inline void firemon_clrscr(void) { printf("\033[2J\033[1;1H"); fflush(0); } // firemon.c extern int arg_nowrap; int find_child(int id); void firemon_drop_privs(void); void firemon_sleep(int st); // procevent.c void procevent(pid_t pid); // usage.c void usage(void); // top.c void top(void); // list.c void list(void); // interface.c void interface(pid_t pid); // arp.c void arp(pid_t pid); // route.c void route(pid_t pid); // caps.c void caps(pid_t pid); // seccomp.c void seccomp(pid_t pid); // cpu.c void cpu(pid_t pid); // cgroup.c void cgroup(pid_t pid); // tree.c void tree(pid_t pid); // netstats.c void netstats(void); #endif
COLABORATI/firejail
src/firemon/firemon.h
C
gpl-2.0
1,738
/*************************************************************************** qgsrasterlayer.h - description ------------------- begin : Fri Jun 28 2002 copyright : (C) 2004 by T.Sutton, Gary E.Sherman, Steve Halasz email : [email protected] ***************************************************************************/ /* * Peter J. Ersts - contributed to the refactoring and maintenance of this class * B. Morley - added functions to convert this class to a data provider interface * Frank Warmerdam - contributed bug fixes and migrated class to use all GDAL_C_API calls */ /*************************************************************************** * * * 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 QGSRASTERLAYER_H #define QGSRASTERLAYER_H #include <QColor> #include <QDateTime> #include <QList> #include <QMap> #include <QPair> #include <QVector> #include "qgis.h" #include "qgsbrightnesscontrastfilter.h" #include "qgscolorrampshader.h" #include "qgscontrastenhancement.h" #include "qgshuesaturationfilter.h" #include "qgsmaplayer.h" #include "qgspoint.h" #include "qgsraster.h" #include "qgsrasterdataprovider.h" #include "qgsrasterinterface.h" #include "qgsrasterpipe.h" #include "qgsrasterresamplefilter.h" #include "qgsrastershaderfunction.h" #include "qgsrastershader.h" #include "qgsrastertransparency.h" #include "qgsrasterviewport.h" class QgsMapToPixel; class QgsRasterRenderer; class QgsRectangle; class QImage; class QLibrary; class QPixmap; class QSlider; typedef QList < QPair< QString, QColor > > QgsLegendColorList; /** \ingroup core * This class provides qgis with the ability to render raster datasets * onto the mapcanvas. * * The qgsrasterlayer class makes use of gdal for data io, and thus supports * any gdal supported format. The constructor attempts to infer what type of * file (LayerType) is being opened - not in terms of the file format (tif, ascii grid etc.) * but rather in terms of whether the image is a GRAYSCALE, PaletteD or Multiband, * * Within the three allowable raster layer types, there are 8 permutations of * how a layer can actually be rendered. These are defined in the DrawingStyle enum * and consist of: * * SingleBandGray -> a GRAYSCALE layer drawn as a range of gray colors (0-255) * SingleBandPseudoColor -> a GRAYSCALE layer drawn using a pseudocolor algorithm * PalettedSingleBandGray -> a PaletteD layer drawn in gray scale (using only one of the color components) * PalettedSingleBandPseudoColor -> a PaletteD layer having only one of its color components rendered as psuedo color * PalettedMultiBandColor -> a PaletteD image where the bands contains 24bit color info and 8 bits is pulled out per color * MultiBandSingleBandGray -> a layer containing 2 or more bands, but using only one band to produce a grayscale image * MultiBandSingleBandPseudoColor -> a layer containing 2 or more bands, but using only one band to produce a pseudocolor image * MultiBandColor -> a layer containing 2 or more bands, mapped to the three RGBcolors. In the case of a multiband with only two bands, one band will have to be mapped to more than one color * * Each of the above mentioned drawing styles is implemented in its own draw* function. * Some of the drawing styles listed above require statistics about the layer such * as the min / max / mean / stddev etc. statistics for a band can be gathered using the * bandStatistics function. Note that statistics gathering is a slow process and * every effort should be made to call this function as few times as possible. For this * reason, qgsraster has a vector class member to store stats for each band. The * constructor initialises this vector on startup, but only populates the band name and * number fields. * * Note that where bands are of gdal 'undefined' type, their values may exceed the * renderable range of 0-255. Because of this a linear scaling histogram enhanceContrast is * applied to undefined layers to normalise the data into the 0-255 range. * * A qgsrasterlayer band can be referred to either by name or by number (base=1). It * should be noted that band names as stored in datafiles may not be unique, and * so the rasterlayer class appends the band number in brackets behind each band name. * * Sample usage of the QgsRasterLayer class: * * \code * QString myFileNameQString = "/path/to/file"; * QFileInfo myFileInfo(myFileNameQString); * QString myBaseNameQString = myFileInfo.baseName(); * QgsRasterLayer *myRasterLayer = new QgsRasterLayer(myFileNameQString, myBaseNameQString); * * \endcode * * In order to automate redrawing of a raster layer, you should like it to a map canvas like this : * * \code * QObject::connect( myRasterLayer, SIGNAL(repaintRequested()), mapCanvas, SLOT(refresh()) ); * \endcode * * Once a layer has been created you can find out what type of layer it is (GrayOrUndefined, Palette or Multiband): * * \code * if (rasterLayer->rasterType()==QgsRasterLayer::Multiband) * { * //do something * } * else if (rasterLayer->rasterType()==QgsRasterLayer::Palette) * { * //do something * } * else // QgsRasterLayer::GrayOrUndefined * { * //do something. * } * \endcode * * You can combine layer type detection with the setDrawingStyle method to override the default drawing style assigned * when a layer is loaded: * * \code * if (rasterLayer->rasterType()==QgsRasterLayer::Multiband) * { * myRasterLayer->setDrawingStyle(QgsRasterLayer::MultiBandSingleBandPseudoColor); * } * else if (rasterLayer->rasterType()==QgsRasterLayer::Palette) * { * myRasterLayer->setDrawingStyle(QgsRasterLayer::PalettedSingleBandPseudoColor); * } * else // QgsRasterLayer::GrayOrUndefined * { * myRasterLayer->setDrawingStyle(QgsRasterLayer::SingleBandPseudoColor); * } * \endcode * * Raster layers can also have an arbitrary level of transparency defined, and have their * color palettes inverted using the setTransparency and setInvertHistogram methods. * * Pseudocolor images can have their output adjusted to a given number of standard * deviations using the setStandardDeviations method. * * The final area of functionality you may be interested in is band mapping. Band mapping * allows you to choose arbitrary band -> color mappings and is applicable only to Palette * and Multiband rasters, There are four mappings that can be made: red, green, blue and gray. * Mappings are non-exclusive. That is a given band can be assigned to no, some or all * color mappings. The constructor sets sensible defaults for band mappings but these can be * overridden at run time using the setRedBandName, setGreenBandName, setBlueBandName and setGrayBandName * methods. */ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer { Q_OBJECT public: /** \brief Default cumulative cut lower limit */ static const double CUMULATIVE_CUT_LOWER; /** \brief Default cumulative cut upper limit */ static const double CUMULATIVE_CUT_UPPER; /** \brief Default sample size (number of pixels) for estimated statistics/histogram calculation */ static const double SAMPLE_SIZE; /** \brief Constructor. Provider is not set. */ QgsRasterLayer(); /** \brief This is the constructor for the RasterLayer class. * * The main tasks carried out by the constructor are: * * -Load the rasters default style (.qml) file if it exists * * -Populate the RasterStatsVector with initial values for each band. * * -Calculate the layer extents * * -Determine whether the layer is gray, paletted or multiband. * * -Assign sensible defaults for the red, green, blue and gray bands. * * - * */ QgsRasterLayer( const QString &path, const QString &baseName = QString::null, bool loadDefaultStyleFlag = true ); //TODO - QGIS 3.0 //This constructor is confusing if used with string literals for providerKey, //as the previous constructor will be called with the literal for providerKey //implicitly converted to a bool. //for QGIS 3.0, make either constructor explicit or alter the signatures /** \brief [ data provider interface ] Constructor in provider mode */ QgsRasterLayer( const QString &uri, const QString &baseName, const QString &providerKey, bool loadDefaultStyleFlag = true ); /** \brief The destructor */ ~QgsRasterLayer(); /** \brief This enumerator describes the types of shading that can be used */ enum ColorShadingAlgorithm { UndefinedShader, PseudoColorShader, FreakOutShader, ColorRampShader, UserDefinedShader }; /** \brief This enumerator describes the type of raster layer */ enum LayerType { GrayOrUndefined, Palette, Multiband, ColorLayer }; /** This helper checks to see whether the file name appears to be a valid * raster file name. If the file name looks like it could be valid, * but some sort of error occurs in processing the file, the error is * returned in retError. */ static bool isValidRasterFileName( const QString & theFileNameQString, QString &retError ); static bool isValidRasterFileName( const QString & theFileNameQString ); /** Return time stamp for given file name */ static QDateTime lastModified( const QString & name ); /** [ data provider interface ] Set the data provider */ void setDataProvider( const QString & provider ); /** \brief Accessor for raster layer type (which is a read only property) */ LayerType rasterType() { return mRasterType; } /**Set raster renderer. Takes ownership of the renderer object*/ void setRenderer( QgsRasterRenderer* theRenderer ); QgsRasterRenderer* renderer() const { return mPipe.renderer(); } /**Set raster resample filter. Takes ownership of the resample filter object*/ QgsRasterResampleFilter * resampleFilter() const { return mPipe.resampleFilter(); } QgsBrightnessContrastFilter * brightnessFilter() const { return mPipe.brightnessFilter(); } QgsHueSaturationFilter * hueSaturationFilter() const { return mPipe.hueSaturationFilter(); } /** Get raster pipe */ QgsRasterPipe * pipe() { return &mPipe; } /** \brief Accessor that returns the width of the (unclipped) raster */ int width() const; /** \brief Accessor that returns the height of the (unclipped) raster */ int height() const; /** \brief Get the number of bands in this layer */ int bandCount() const; /** \brief Get the name of a band given its number */ const QString bandName( int theBandNoInt ); /** Returns the data provider */ QgsRasterDataProvider* dataProvider(); /** Returns the data provider in a const-correct manner @note available in python bindings as constDataProvider() */ const QgsRasterDataProvider* dataProvider() const; /**Synchronises with changes in the datasource */ virtual void reload() override; /** Return new instance of QgsMapLayerRenderer that will be used for rendering of given context * @note added in 2.4 */ virtual QgsMapLayerRenderer* createMapRenderer( QgsRenderContext& rendererContext ) override; /** \brief This is called when the view on the raster layer needs to be redrawn */ bool draw( QgsRenderContext& rendererContext ) override; /** \brief This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPixmap */ void draw( QPainter * theQPainter, QgsRasterViewPort * myRasterViewPort, const QgsMapToPixel* theQgsMapToPixel = 0 ); /**Returns a list with classification items (Text and color) */ QgsLegendColorList legendSymbologyItems() const; /** \brief Obtain GDAL Metadata for this layer */ QString metadata() override; /** \brief Get an 100x100 pixmap of the color palette. If the layer has no palette a white pixmap will be returned */ QPixmap paletteAsPixmap( int theBandNumber = 1 ); /** \brief [ data provider interface ] Which provider is being used for this Raster Layer? */ QString providerType() const; /** \brief Returns the number of raster units per each raster pixel. In a world file, this is normally the first row (without the sign) */ double rasterUnitsPerPixelX(); double rasterUnitsPerPixelY(); /** \brief Set contrast enhancement algorithm * @param theAlgorithm Contrast enhancement algorithm * @param theLimits Limits * @param theExtent Extent used to calculate limits, if empty, use full layer extent * @param theSampleSize Size of data sample to calculate limits, if 0, use full resolution * @param theGenerateLookupTableFlag Generate lookup table. */ void setContrastEnhancement( QgsContrastEnhancement::ContrastEnhancementAlgorithm theAlgorithm, QgsRaster::ContrastEnhancementLimits theLimits = QgsRaster::ContrastEnhancementMinMax, QgsRectangle theExtent = QgsRectangle(), int theSampleSize = SAMPLE_SIZE, bool theGenerateLookupTableFlag = true ); /** \brief Set default contrast enhancement */ void setDefaultContrastEnhancement(); /** \brief Overloaded version of the above function for convenience when restoring from xml */ void setDrawingStyle( const QString & theDrawingStyleQString ); /** \brief [ data provider interface ] A wrapper function to emit a progress update signal */ void showProgress( int theValue ); /** \brief Returns the sublayers of this layer - Useful for providers that manage their own layers, such as WMS */ virtual QStringList subLayers() const override; /** \brief Draws a preview of the rasterlayer into a pixmap @note - use previewAsImage() for rendering with QGIS>=2.4 */ Q_DECL_DEPRECATED QPixmap previewAsPixmap( QSize size, QColor bgColor = Qt::white ); /** \brief Draws a preview of the rasterlayer into a QImage @note added in 2.4 */ QImage previewAsImage( QSize size, QColor bgColor = Qt::white, QImage::Format format = QImage::Format_ARGB32_Premultiplied ); /** * Reorders the *previously selected* sublayers of this layer from bottom to top * * (Useful for providers that manage their own layers, such as WMS) * */ virtual void setLayerOrder( const QStringList &layers ) override; /** * Set the visibility of the given sublayer name */ virtual void setSubLayerVisibility( QString name, bool vis ) override; /** Time stamp of data source in the moment when data/metadata were loaded by provider */ virtual QDateTime timestamp() const override { return mDataProvider->timestamp() ; } public slots: void showStatusMessage( const QString & theMessage ); //! @deprecated in 2.4 - does nothing Q_DECL_DEPRECATED void updateProgress( int, int ); /** \brief receive progress signal from provider */ void onProgress( int, double, QString ); signals: /** \brief Signal for notifying listeners of long running processes */ void progressUpdate( int theValue ); /** * This is emitted whenever data or metadata (e.g. color table, extent) has changed */ void dataChanged(); protected: /** \brief Read the symbology for the current layer from the Dom node supplied */ bool readSymbology( const QDomNode& node, QString& errorMessage ) override; /** \brief Reads layer specific state from project file Dom node */ bool readXml( const QDomNode& layer_node ) override; /** \brief Write the symbology for the layer into the docment provided */ bool writeSymbology( QDomNode&, QDomDocument& doc, QString& errorMessage ) const override; /** \brief Write layer specific state to project file Dom node */ bool writeXml( QDomNode & layer_node, QDomDocument & doc ) override; private: /** \brief Initialize default values */ void init(); /** \brief Close data provider and clear related members */ void closeDataProvider(); /** \brief Update the layer if it is outdated */ bool update(); /**Sets corresponding renderer for style*/ void setRendererForDrawingStyle( const QgsRaster::DrawingStyle & theDrawingStyle ); /** \brief Constant defining flag for XML and a constant that signals property not used */ const QString QSTRING_NOT_SET; const QString TRSTRING_NOT_SET; /** Pointer to data provider */ QgsRasterDataProvider* mDataProvider; //DrawingStyle mDrawingStyle; /** [ data provider interface ] Timestamp, the last modified time of the data source when the layer was created */ QDateTime mLastModified; QgsRasterViewPort mLastViewPort; /** [ data provider interface ] Data provider key */ QString mProviderKey; LayerType mRasterType; QgsRasterPipe mPipe; }; #endif
herow/planning_qgis
src/core/raster/qgsrasterlayer.h
C
gpl-2.0
17,855
/* Texas Instruments Ethernet Switch Driver * * Copyright (C) 2013 Texas Instruments * * 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 "as is" WITHOUT ANY WARRANTY of any * kind, whether express or implied; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __CPSW_H__ #define __CPSW_H__ #include <linux/if_ether.h> #include <linux/phy.h> struct cpsw_slave_data { struct device_node *phy_node; char phy_id[MII_BUS_ID_SIZE]; int phy_if; u8 mac_addr[ETH_ALEN]; u16 dual_emac_res_vlan; /* Reserved VLAN for DualEMAC */ }; struct cpsw_platform_data { struct cpsw_slave_data *slave_data; u32 ss_reg_ofs; /* Subsystem control register offset */ u32 channels; /* number of cpdma channels (symmetric) */ u32 slaves; /* number of slave cpgmac ports */ u32 active_slave; /* time stamping, ethtool and SIOCGMIIPHY slave */ u32 ale_entries; /* ale table size */ u32 bd_ram_size; /*buffer descriptor ram size */ u32 mac_control; /* Mac control register */ u16 default_vlan; /* Def VLAN for ALE lookup in VLAN aware mode*/ bool dual_emac; /* Enable Dual EMAC mode */ u32 descs_pool_size; /* Number of Rx Descriptios */ }; void cpsw_phy_sel(struct device *dev, phy_interface_t phy_mode, int slave); int ti_cm_get_macid(struct device *dev, int slave, u8 *mac_addr); #endif /* __CPSW_H__ */
henrix/beagle-linux
drivers/net/ethernet/ti/cpsw.h
C
gpl-2.0
1,589
/* * Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* ACRNONYMS USED: * LSF - Low Secure Falcon (i.e. PMU and FECS) * LSFM- Low Secure Falcon Manager * ACR - Access Controlled Region * WPR - Write Protected Region * LSB Header - Low Secure Boot Header(For LS falocons i.e PMU and FECS) * BL - Bootloader * HS - High Secure * * ABOUT THIS FILE (Nouveau Secure Boot) * LS falcons in below description refers to PMU and FECS. * * For secure boot feature,there is a pre-requisite that, we need a ucode blob, * in which we copy each LS falon's ucode, BL and signatures to a particular * location and provide this location address and size to the HS (High Secure) * falcon ucode. * This High Secure(HS) ucode, called the ACR ucode,copies the entire ucode blob * to a pre-defined WPR and verifies the ucodes with their signatures for each * LS falcon. * If verification for a particular falcon goes well, ACR ucode loads memory of * that particular falcon with corresponding BL and other BL params. * */ #include "priv.h" #include "gk20a.h" #include <core/gpuobj.h> #include <core/device.h> #include <subdev/fb.h> #include <subdev/mc.h> #include <linux/firmware.h> #include <subdev/timer.h> struct gm20b_ctxsw_bootloader_desc { u32 start_offset; u32 size; u32 imem_offset; u32 entry_point; }; /*Defines*/ #define TEGRA_MC_BASE 0x70019000 #define MC_SECURITY_CARVEOUT2_BOM_0 0xc5c #define MC_SECURITY_CARVEOUT3_BOM_0 0xcac #define MC_ERR_GENERALIZED_CARVEOUT_STATUS_0 0xc00 /*chip specific defines*/ #define MAX_SUPPORTED_LSFM 2 /*PMU & FECS*/ #define LSF_UCODE_DATA_ALIGNMENT 4096 /*Firmware Names*/ #define GM20B_PMU_UCODE_IMAGE "gpmu_ucode_image.bin" #define GM20B_PMU_UCODE_DESC "gpmu_ucode_desc.bin" #define GM20B_PMU_UCODE_SIG "pmu_sig.bin" #define GM20B_FECS_UCODE_SIG "fecs_sig.bin" #define GK20A_FECS_UCODE_IMAGE "fecs.bin" #define GM20B_HSBIN_PMU_UCODE_IMAGE "acr_ucode.bin" #define GM20B_HSBIN_PMU_BL_UCODE_IMAGE "pmu_bl.bin" #define PMU_SECURE_MODE (0x1) #define PMU_LSFM_MANAGED (0x2) /* defined by pmu hw spec */ #define GK20A_PMU_VA_SIZE (512 * 1024 * 1024) #define GK20A_PMU_UCODE_SIZE_MAX (256 * 1024) /* idle timeout */ #define GK20A_IDLE_CHECK_DEFAULT 10000 /* usec */ #define GK20A_IDLE_CHECK_MAX 5000 /* usec */ #define GK20A_PMU_DMEM_BLKSIZE2 8 #define GK20A_PMU_UCODE_NB_MAX_OVERLAY 32 #define GK20A_PMU_UCODE_NB_MAX_DATE_LENGTH 64 #define T210_FLCN_ACR_MAX_REGIONS (2) #define LSF_BOOTSTRAP_OWNER_RESERVED_DMEM_SIZE (0x200) /* * Falcon Id Defines * Defines a common Light Secure Falcon identifier. */ #define LSF_FALCON_ID_PMU (0) #define LSF_FALCON_ID_FECS (2) #define LSF_FALCON_ID_INVALID (0xFFFFFFFF) /*Bootstrap Owner Defines*/ #define LSF_BOOTSTRAP_OWNER_DEFAULT (LSF_FALCON_ID_PMU) /*Image Status Defines*/ #define LSF_IMAGE_STATUS_NONE (0) #define LSF_IMAGE_STATUS_COPY (1) #define LSF_IMAGE_STATUS_VALIDATION_CODE_FAILED (2) #define LSF_IMAGE_STATUS_VALIDATION_DATA_FAILED (3) #define LSF_IMAGE_STATUS_VALIDATION_DONE (4) #define LSF_IMAGE_STATUS_VALIDATION_SKIPPED (5) #define LSF_IMAGE_STATUS_BOOTSTRAP_READY (6) /*LSB header related defines*/ #define NV_FLCN_ACR_LSF_FLAG_LOAD_CODE_AT_0_FALSE 0 #define NV_FLCN_ACR_LSF_FLAG_LOAD_CODE_AT_0_TRUE 1 #define NV_FLCN_ACR_LSF_FLAG_DMACTL_REQ_CTX_FALSE 0 #define NV_FLCN_ACR_LSF_FLAG_DMACTL_REQ_CTX_TRUE 4 /*Light Secure WPR Content Alignments*/ #define LSF_LSB_HEADER_ALIGNMENT 256 #define LSF_BL_DATA_ALIGNMENT 256 #define LSF_BL_DATA_SIZE_ALIGNMENT 256 #define LSF_BL_CODE_SIZE_ALIGNMENT 256 /*Falcon UCODE header index.*/ #define FLCN_NL_UCODE_HDR_OS_CODE_OFF_IND (0) #define FLCN_NL_UCODE_HDR_OS_CODE_SIZE_IND (1) #define FLCN_NL_UCODE_HDR_OS_DATA_OFF_IND (2) #define FLCN_NL_UCODE_HDR_OS_DATA_SIZE_IND (3) #define FLCN_NL_UCODE_HDR_NUM_APPS_IND (4) /* * There are total N number of Apps with code and offset defined in UCODE header * This macro provides the CODE and DATA offset and size of Ath application. */ #define FLCN_NL_UCODE_HDR_APP_CODE_START_IND (5) #define FLCN_NL_UCODE_HDR_APP_CODE_OFF_IND(N, A) \ (FLCN_NL_UCODE_HDR_APP_CODE_START_IND + (A*2)) #define FLCN_NL_UCODE_HDR_APP_CODE_SIZE_IND(N, A) \ (FLCN_NL_UCODE_HDR_APP_CODE_START_IND + (A*2) + 1) #define FLCN_NL_UCODE_HDR_APP_CODE_END_IND(N) \ (FLCN_NL_UCODE_HDR_APP_CODE_START_IND + (N*2) - 1) #define FLCN_NL_UCODE_HDR_APP_DATA_START_IND(N) \ (FLCN_NL_UCODE_HDR_APP_CODE_END_IND(N) + 1) #define FLCN_NL_UCODE_HDR_APP_DATA_OFF_IND(N, A) \ (FLCN_NL_UCODE_HDR_APP_DATA_START_IND(N) + (A*2)) #define FLCN_NL_UCODE_HDR_APP_DATA_SIZE_IND(N, A) \ (FLCN_NL_UCODE_HDR_APP_DATA_START_IND(N) + (A*2) + 1) #define FLCN_NL_UCODE_HDR_APP_DATA_END_IND(N) \ (FLCN_NL_UCODE_HDR_APP_DATA_START_IND(N) + (N*2) - 1) #define FLCN_NL_UCODE_HDR_OS_OVL_OFF_IND(N) \ (FLCN_NL_UCODE_HDR_APP_DATA_END_IND(N) + 1) #define FLCN_NL_UCODE_HDR_OS_OVL_SIZE_IND(N) \ (FLCN_NL_UCODE_HDR_APP_DATA_END_IND(N) + 2) struct lsf_ucode_desc { u8 prd_keys[2][16]; u8 dbg_keys[2][16]; u32 b_prd_present; u32 b_dbg_present; u32 falcon_id; }; /* * Light Secure WPR Header * Defines state allowing Light Secure Falcon bootstrapping. * * falcon_id - LS falcon ID * lsb_offset - Offset into WPR region holding LSB header * bootstrap_owner - Bootstrap OWNER * lazy_bootstrap - Skip bootstrapping by ACR * status - Bootstrapping status */ struct lsf_wpr_header { u32 falcon_id; u32 lsb_offset; u32 bootstrap_owner; u32 lazy_bootstrap; u32 status; }; struct pmu_mem_v1 { u32 dma_base; u8 dma_offset; u8 dma_idx; u16 fb_size; }; struct pmu_cmdline_args_v1 { u32 reserved; u32 cpu_freq_hz; /* Frequency of the clock driving PMU */ u32 falc_trace_size; /* falctrace buffer size (bytes) */ u32 falc_trace_dma_base; /* 256-byte block address */ u32 falc_trace_dma_idx; /* dmaIdx for DMA operations */ u8 secure_mode; u8 raise_priv_sec; struct pmu_mem_v1 gc6_ctx; /* dmem offset of gc6 context */ }; struct lsf_lsb_header { struct lsf_ucode_desc signature; u32 ucode_off; u32 ucode_size; u32 data_size; u32 bl_code_size; u32 bl_imem_off; u32 bl_data_off; u32 bl_data_size; u32 app_code_off; u32 app_code_size; u32 app_data_off; u32 app_data_size; u32 flags; }; static void __iomem *mc; /*Structure used by the bootloader*/ struct loader_config { u32 dma_idx; u32 code_dma_base; /*upper 32-bits of 40-bit dma address*/ u32 code_size_total; u32 code_size_to_load; u32 code_entry_point; u32 data_dma_base; /*upper 32-bits of 40-bit dma address*/ u32 data_size; /*initialized data of the application */ u32 overlay_dma_base; /*upper 32-bits of the 40-bit dma address*/ u32 argc; u32 argv; }; struct flcn_ucode_img { u32 *header; u32 *data; struct pmu_ucode_desc *desc; u32 data_size; void *fw_ver; u8 load_entire_os_data; struct lsf_ucode_desc *lsf_desc; u8 free_res_allocs; u32 flcn_inst; }; /*ACR related structs*/ /*! * start_addr - Starting address of region * end_addr - Ending address of region * region_id - Region ID * read_mask - Read Mask * write_mask - WriteMask * client_mask - Bit map of all clients currently using this region */ struct flcn_acr_region_prop { u32 start_addr; u32 end_addr; u32 region_id; u32 read_mask; u32 write_mask; u32 client_mask; }; /*! * no_regions - Number of regions used. * region_props - Region properties */ struct flcn_acr_regions { u32 no_regions; struct flcn_acr_region_prop region_props[T210_FLCN_ACR_MAX_REGIONS]; }; /*! * reserved_dmem-When the bootstrap owner has done bootstrapping other falcons, * and need to switch into LS mode, it needs to have its own * actual DMEM image copied into DMEM as part of LS setup. If * ACR desc is at location 0, it will definitely get overwritten * causing data corruption. Hence we are reserving 0x200 bytes * to give room for any loading data. NOTE: This has to be the * first member always * signature - Signature of ACR ucode. * wpr_region_id - Region ID holding the WPR header and its details * wpr_offset - Offset from the WPR region holding the wpr header * regions - Region descriptors * nonwpr_ucode_blob_start -stores non-WPR start where kernel stores ucode blob * nonwpr_ucode_blob_end -stores non-WPR end where kernel stores ucode blob */ struct flcn_acr_desc { union { u32 reserved_dmem[(LSF_BOOTSTRAP_OWNER_RESERVED_DMEM_SIZE/4)]; u32 signatures[4]; } ucode_reserved_space; /*Always 1st*/ u32 wpr_region_id; u32 wpr_offset; u32 mmu_mem_range; struct flcn_acr_regions regions; u32 nonwpr_ucode_blob_size; u64 nonwpr_ucode_blob_start; }; #define BLK_SIZE 256 /* Union of all supported structures used by bootloaders*/ union flcn_bl_generic_desc { struct flcn_bl_dmem_desc bl_dmem_desc; struct loader_config loader_cfg; }; /* * LSFM Managed Ucode Image * next : Next image in the list, NULL if last. * wpr_header : WPR header for this ucode image * lsb_header : LSB header for this ucode image * bl_gen_desc : Bootloader generic desc structure for this ucode image * bl_gen_desc_size : Sizeof bootloader desc structure for this ucode image * full_ucode_size : Surface size required for final ucode image * ucode_img : Ucode image info */ struct lsfm_managed_ucode_img { struct lsfm_managed_ucode_img *next; struct lsf_wpr_header wpr_header; struct lsf_lsb_header lsb_header; union flcn_bl_generic_desc bl_gen_desc; u32 bl_gen_desc_size; u32 full_ucode_size; struct flcn_ucode_img ucode_img; }; /*Structure to manage Low secure falcons*/ struct ls_flcn_mgr { u16 managed_flcn_cnt; u32 wpr_size; u32 disable_mask; /*Pointer to linked list of managed ucode images*/ struct lsfm_managed_ucode_img *ucode_img_list; }; /* * Structure/object which single register write need to be done during PG init * sequence to set PROD values. */ struct pg_init_sequence_list { u32 regaddr; u32 writeval; }; /* PROD settings for ELPG sequencing registers*/ static struct pg_init_sequence_list pg_init_seq_gm20b[] = { { 0x0010ab10, 0x00008180 }, { 0x0010e118, 0x83828180 }, { 0x0010e068, 0x00000000 }, { 0x0010e06c, 0x00000080 }, { 0x0010e06c, 0x00000081 }, { 0x0010e06c, 0x00000082 }, { 0x0010e06c, 0x00000083 }, { 0x0010e06c, 0x00000084 }, { 0x0010e06c, 0x00000085 }, { 0x0010e06c, 0x00000086 }, { 0x0010e06c, 0x00000087 }, { 0x0010e06c, 0x00000088 }, { 0x0010e06c, 0x00000089 }, { 0x0010e06c, 0x0000008a }, { 0x0010e06c, 0x0000008b }, { 0x0010e06c, 0x0000008c }, { 0x0010e06c, 0x0000008d }, { 0x0010e06c, 0x0000008e }, { 0x0010e06c, 0x0000008f }, { 0x0010e06c, 0x00000090 }, { 0x0010e06c, 0x00000091 }, { 0x0010e06c, 0x00000092 }, { 0x0010e06c, 0x00000093 }, { 0x0010e06c, 0x00000094 }, { 0x0010e06c, 0x00000095 }, { 0x0010e06c, 0x00000096 }, { 0x0010e06c, 0x00000097 }, { 0x0010e06c, 0x00000098 }, { 0x0010e06c, 0x00000099 }, { 0x0010e06c, 0x0000009a }, { 0x0010e06c, 0x0000009b }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010e06c, 0x00000000 }, { 0x0010ab14, 0x00000000 }, { 0x0010ab18, 0x00000000 }, { 0x0010e024, 0x00000000 }, { 0x0010e028, 0x00000000 }, { 0x0010e11c, 0x00000000 }, { 0x0010e120, 0x00000000 }, { 0x0010ab1c, 0x02010155 }, { 0x0010e020, 0x001b1b55 }, { 0x0010e124, 0x01030355 }, { 0x0010ab20, 0x89abcdef }, { 0x0010ab24, 0x00000000 }, { 0x0010e02c, 0x89abcdef }, { 0x0010e030, 0x00000000 }, { 0x0010e128, 0x89abcdef }, { 0x0010e12c, 0x00000000 }, { 0x0010ab28, 0x74444444 }, { 0x0010ab2c, 0x70000000 }, { 0x0010e034, 0x74444444 }, { 0x0010e038, 0x70000000 }, { 0x0010e130, 0x74444444 }, { 0x0010e134, 0x70000000 }, { 0x0010ab30, 0x00000000 }, { 0x0010ab34, 0x00000001 }, { 0x00020004, 0x00000000 }, { 0x0010e138, 0x00000000 }, { 0x0010e040, 0x00000000 }, }; static int gm20b_pmu_setup_elpg(struct nvkm_pmu *pmu) { int ret = 0; u32 reg_writes; u32 index; reg_writes = ARRAY_SIZE(pg_init_seq_gm20b); /* Initialize registers with production values*/ for (index = 0; index < reg_writes; index++) nv_wr32(pmu, pg_init_seq_gm20b[index].regaddr, pg_init_seq_gm20b[index].writeval); return ret; } /* slcg bus */ static const struct gating_desc gm20b_slcg_bus[] = { {.addr = 0x00001c04, .prod = 0x00000000, .disable = 0x000003fe}, }; /* slcg ce2 */ static const struct gating_desc gm20b_slcg_ce2[] = { {.addr = 0x00106f28, .prod = 0x00000000, .disable = 0x000007fe}, }; /* slcg chiplet */ static const struct gating_desc gm20b_slcg_chiplet[] = { {.addr = 0x0010c07c, .prod = 0x00000000, .disable = 0x00000007}, {.addr = 0x0010e07c, .prod = 0x00000000, .disable = 0x00000007}, {.addr = 0x0010d07c, .prod = 0x00000000, .disable = 0x00000007}, {.addr = 0x0010e17c, .prod = 0x00000000, .disable = 0x00000007}, }; /* slcg fb */ static const struct gating_desc gm20b_slcg_fb[] = { {.addr = 0x00100d14, .prod = 0x00000000, .disable = 0xfffffffe}, {.addr = 0x00100c9c, .prod = 0x00000000, .disable = 0x000001fe}, }; /* slcg fifo */ static const struct gating_desc gm20b_slcg_fifo[] = { {.addr = 0x000026ac, .prod = 0x00000100, .disable = 0x0001fffe}, }; /* slcg gr */ static const struct gating_desc gm20b_slcg_gr[] = { {.addr = 0x004041f4, .prod = 0x00000000, .disable = 0x03fffffe}, {.addr = 0x0040917c, .prod = 0x00020008, .disable = 0x0003fffe}, {.addr = 0x00409894, .prod = 0x00000040, .disable = 0x0003fffe}, {.addr = 0x004078c4, .prod = 0x00000000, .disable = 0x000001fe}, {.addr = 0x00406004, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00405864, .prod = 0x00000000, .disable = 0x000001fe}, {.addr = 0x00405910, .prod = 0xfffffff0, .disable = 0xfffffffe}, {.addr = 0x00408044, .prod = 0x00000000, .disable = 0x000007fe}, {.addr = 0x00407004, .prod = 0x00000000, .disable = 0x0000007e}, {.addr = 0x0041a17c, .prod = 0x00020008, .disable = 0x0003fffe}, {.addr = 0x0041a894, .prod = 0x00000040, .disable = 0x0003fffe}, {.addr = 0x00418504, .prod = 0x00000000, .disable = 0x0007fffe}, {.addr = 0x0041860c, .prod = 0x00000000, .disable = 0x000001fe}, {.addr = 0x0041868c, .prod = 0x00000000, .disable = 0x0000001e}, {.addr = 0x0041871c, .prod = 0x00000000, .disable = 0x0000003e}, {.addr = 0x00418388, .prod = 0x00000000, .disable = 0x00000001}, {.addr = 0x0041882c, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00418bc0, .prod = 0x00000000, .disable = 0x000001fe}, {.addr = 0x00418974, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00418c74, .prod = 0xffffffc0, .disable = 0xfffffffe}, {.addr = 0x00418cf4, .prod = 0xfffffffc, .disable = 0xfffffffe}, {.addr = 0x00418d74, .prod = 0xffffffe0, .disable = 0xfffffffe}, {.addr = 0x00418f10, .prod = 0xffffffe0, .disable = 0xfffffffe}, {.addr = 0x00418e10, .prod = 0xfffffffe, .disable = 0xfffffffe}, {.addr = 0x00419024, .prod = 0x000001fe, .disable = 0x000001fe}, {.addr = 0x0041889c, .prod = 0x00000000, .disable = 0x000001fe}, {.addr = 0x00419d64, .prod = 0x00000000, .disable = 0x000001ff}, {.addr = 0x00419a44, .prod = 0x00000000, .disable = 0x0000000e}, {.addr = 0x00419a4c, .prod = 0x00000000, .disable = 0x000001fe}, {.addr = 0x00419a54, .prod = 0x00000000, .disable = 0x0000003e}, {.addr = 0x00419a5c, .prod = 0x00000000, .disable = 0x0000000e}, {.addr = 0x00419a64, .prod = 0x00000000, .disable = 0x000001fe}, {.addr = 0x00419a6c, .prod = 0x00000000, .disable = 0x0000000e}, {.addr = 0x00419a74, .prod = 0x00000000, .disable = 0x0000000e}, {.addr = 0x00419a7c, .prod = 0x00000000, .disable = 0x0000003e}, {.addr = 0x00419a84, .prod = 0x00000000, .disable = 0x0000000e}, {.addr = 0x0041986c, .prod = 0x00000104, .disable = 0x00fffffe}, {.addr = 0x00419cd8, .prod = 0x00000000, .disable = 0x001ffffe}, {.addr = 0x00419ce0, .prod = 0x00000000, .disable = 0x001ffffe}, {.addr = 0x00419c74, .prod = 0x0000001e, .disable = 0x0000001e}, {.addr = 0x00419fd4, .prod = 0x00000000, .disable = 0x0003fffe}, {.addr = 0x00419fdc, .prod = 0xffedff00, .disable = 0xfffffffe}, {.addr = 0x00419fe4, .prod = 0x00001b00, .disable = 0x00001ffe}, {.addr = 0x00419ff4, .prod = 0x00000000, .disable = 0x00003ffe}, {.addr = 0x00419ffc, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x0041be2c, .prod = 0x04115fc0, .disable = 0xfffffffe}, {.addr = 0x0041bfec, .prod = 0xfffffff0, .disable = 0xfffffffe}, {.addr = 0x0041bed4, .prod = 0xfffffff6, .disable = 0xfffffffe}, {.addr = 0x00408814, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x0040881c, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00408a84, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00408a8c, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00408a94, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00408a9c, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00408aa4, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00408aac, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x004089ac, .prod = 0x00000000, .disable = 0x0001fffe}, {.addr = 0x00408a24, .prod = 0x00000000, .disable = 0x000001ff}, }; /* slcg ltc */ static const struct gating_desc gm20b_slcg_ltc[] = { {.addr = 0x0017e050, .prod = 0x00000000, .disable = 0xfffffffe}, {.addr = 0x0017e35c, .prod = 0x00000000, .disable = 0xfffffffe}, }; /* slcg perf */ static const struct gating_desc gm20b_slcg_perf[] = { {.addr = 0x001be018, .prod = 0x000001ff, .disable = 0x00000000}, {.addr = 0x001bc018, .prod = 0x000001ff, .disable = 0x00000000}, {.addr = 0x001b8018, .prod = 0x000001ff, .disable = 0x00000000}, {.addr = 0x001b4124, .prod = 0x00000001, .disable = 0x00000000}, }; /* slcg PriRing */ static const struct gating_desc gm20b_slcg_priring[] = { {.addr = 0x001200a8, .prod = 0x00000000, .disable = 0x00000001}, }; /* slcg pmu */ static const struct gating_desc gm20b_slcg_pmu[] = { {.addr = 0x0010a17c, .prod = 0x00020008, .disable = 0x0003fffe}, {.addr = 0x0010aa74, .prod = 0x00000000, .disable = 0x00007ffe}, {.addr = 0x0010ae74, .prod = 0x00000000, .disable = 0x0000000f}, }; /* slcg Xbar */ static const struct gating_desc gm20b_slcg_xbar[] = { {.addr = 0x0013cbe4, .prod = 0x00000000, .disable = 0x1ffffffe}, {.addr = 0x0013cc04, .prod = 0x00000000, .disable = 0x1ffffffe}, }; /* blcg bus */ static const struct gating_desc gm20b_blcg_bus[] = { {.addr = 0x00001c00, .prod = 0x00000042, .disable = 0x00000000}, }; /* blcg fb */ static const struct gating_desc gm20b_blcg_fb[] = { {.addr = 0x00100d10, .prod = 0x0000c242, .disable = 0x00000000}, {.addr = 0x00100d30, .prod = 0x0000c242, .disable = 0x00000000}, {.addr = 0x00100d3c, .prod = 0x00000242, .disable = 0x00000000}, {.addr = 0x00100d48, .prod = 0x0000c242, .disable = 0x00000000}, {.addr = 0x00100d1c, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x00100c98, .prod = 0x00000242, .disable = 0x00000000}, }; /* blcg fifo */ static const struct gating_desc gm20b_blcg_fifo[] = { {.addr = 0x000026a4, .prod = 0x0000c242, .disable = 0x00000000}, }; /* blcg gr */ static const struct gating_desc gm20b_blcg_gr[] = { {.addr = 0x004041f0, .prod = 0x00004046, .disable = 0x00000000}, {.addr = 0x00409890, .prod = 0x0000007f, .disable = 0x00000000}, {.addr = 0x004098b0, .prod = 0x0000007f, .disable = 0x00000000}, {.addr = 0x004078c0, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x00406000, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00405860, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x0040590c, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00408040, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00407000, .prod = 0x00004041, .disable = 0x00000000}, {.addr = 0x00405bf0, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x0041a890, .prod = 0x0000007f, .disable = 0x00000000}, {.addr = 0x0041a8b0, .prod = 0x0000007f, .disable = 0x00000000}, {.addr = 0x00418500, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00418608, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00418688, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00418718, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x00418828, .prod = 0x00000044, .disable = 0x00000000}, {.addr = 0x00418bbc, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00418970, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00418c70, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00418cf0, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00418d70, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00418f0c, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00418e0c, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00419020, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419038, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x00418898, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x00419a40, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x00419a48, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419a50, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419a58, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419a60, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419a68, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419a70, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419a78, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419a80, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00419868, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x00419cd4, .prod = 0x00000002, .disable = 0x00000000}, {.addr = 0x00419cdc, .prod = 0x00000002, .disable = 0x00000000}, {.addr = 0x00419c70, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00419fd0, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00419fd8, .prod = 0x00004046, .disable = 0x00000000}, {.addr = 0x00419fe0, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00419fe8, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x00419ff0, .prod = 0x00004045, .disable = 0x00000000}, {.addr = 0x00419ff8, .prod = 0x00000002, .disable = 0x00000000}, {.addr = 0x00419f90, .prod = 0x00000002, .disable = 0x00000000}, {.addr = 0x0041be28, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x0041bfe8, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x0041bed0, .prod = 0x00004044, .disable = 0x00000000}, {.addr = 0x00408810, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00408818, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00408a80, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00408a88, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00408a90, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00408a98, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00408aa0, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x00408aa8, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x004089a8, .prod = 0x00004042, .disable = 0x00000000}, {.addr = 0x004089b0, .prod = 0x00000042, .disable = 0x00000000}, {.addr = 0x004089b8, .prod = 0x00004042, .disable = 0x00000000}, }; /* blcg ltc */ static const struct gating_desc gm20b_blcg_ltc[] = { {.addr = 0x0017e030, .prod = 0x00000044, .disable = 0x00000000}, {.addr = 0x0017e040, .prod = 0x00000044, .disable = 0x00000000}, {.addr = 0x0017e3e0, .prod = 0x00000044, .disable = 0x00000000}, {.addr = 0x0017e3c8, .prod = 0x00000044, .disable = 0x00000000}, }; /* blcg pmu */ static const struct gating_desc gm20b_blcg_pmu[] = { {.addr = 0x0010aa70, .prod = 0x00000045, .disable = 0x00000000}, }; static int gm20b_pmu_disable_clk_gating(struct nvkm_pmu *pmu) { struct gk20a_pmu_priv *priv = to_gk20a_priv(pmu); int ret; mutex_lock(&priv->clk_gating_mutex); if (priv->clk_gating_disable_depth++ > 0) { ret = 0; goto do_nothing; } gk20a_init_elcg_mode(pmu, ELCG_RUN, ENGINE_CE2_GK20A); gk20a_init_elcg_mode(pmu, ELCG_RUN, ENGINE_CE2_GK20A); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_bus, ARRAY_SIZE(gm20b_slcg_bus)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_ce2, ARRAY_SIZE(gm20b_slcg_ce2)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_chiplet, ARRAY_SIZE(gm20b_slcg_chiplet)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_fb, ARRAY_SIZE(gm20b_slcg_fb)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_fifo, ARRAY_SIZE(gm20b_slcg_fifo)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_gr, ARRAY_SIZE(gm20b_slcg_gr)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_ltc, ARRAY_SIZE(gm20b_slcg_ltc)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_perf, ARRAY_SIZE(gm20b_slcg_perf)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_priring, ARRAY_SIZE(gm20b_slcg_priring)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_pmu, ARRAY_SIZE(gm20b_slcg_pmu)); gk20a_disable_load_gating_prod(pmu, gm20b_slcg_xbar, ARRAY_SIZE(gm20b_slcg_xbar)); gk20a_disable_load_gating_prod(pmu, gm20b_blcg_bus, ARRAY_SIZE(gm20b_blcg_bus)); gk20a_disable_load_gating_prod(pmu, gm20b_blcg_fb, ARRAY_SIZE(gm20b_blcg_fb)); gk20a_disable_load_gating_prod(pmu, gm20b_blcg_fifo, ARRAY_SIZE(gm20b_blcg_fifo)); gk20a_disable_load_gating_prod(pmu, gm20b_blcg_gr, ARRAY_SIZE(gm20b_blcg_gr)); gk20a_disable_load_gating_prod(pmu, gm20b_blcg_ltc, ARRAY_SIZE(gm20b_blcg_ltc)); gk20a_disable_load_gating_prod(pmu, gm20b_blcg_pmu, ARRAY_SIZE(gm20b_blcg_pmu)); do_nothing: mutex_unlock(&priv->clk_gating_mutex); return 0; } static int gm20b_pmu_enable_clk_gating(struct nvkm_pmu *pmu) { struct gk20a_pmu_priv *priv = to_gk20a_priv(pmu); int ret; mutex_lock(&priv->clk_gating_mutex); if (--priv->clk_gating_disable_depth > 0) { ret = 0; goto do_nothing; } if (pmu->elcg_enabled) { gk20a_init_elcg_mode(pmu, ELCG_AUTO, ENGINE_CE2_GK20A); gk20a_init_elcg_mode(pmu, ELCG_AUTO, ENGINE_GR_GK20A); } if (pmu->slcg_enabled) { gk20a_enable_load_gating_prod(pmu, gm20b_slcg_bus, ARRAY_SIZE(gm20b_slcg_bus)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_ce2, ARRAY_SIZE(gm20b_slcg_ce2)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_chiplet, ARRAY_SIZE(gm20b_slcg_chiplet)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_fb, ARRAY_SIZE(gm20b_slcg_fb)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_fifo, ARRAY_SIZE(gm20b_slcg_fifo)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_gr, ARRAY_SIZE(gm20b_slcg_gr)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_ltc, ARRAY_SIZE(gm20b_slcg_ltc)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_perf, ARRAY_SIZE(gm20b_slcg_perf)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_priring, ARRAY_SIZE(gm20b_slcg_priring)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_pmu, ARRAY_SIZE(gm20b_slcg_pmu)); gk20a_enable_load_gating_prod(pmu, gm20b_slcg_xbar, ARRAY_SIZE(gm20b_slcg_xbar)); } if (pmu->blcg_enabled) { gk20a_enable_load_gating_prod(pmu, gm20b_blcg_bus, ARRAY_SIZE(gm20b_blcg_bus)); gk20a_enable_load_gating_prod(pmu, gm20b_blcg_fb, ARRAY_SIZE(gm20b_blcg_fb)); gk20a_enable_load_gating_prod(pmu, gm20b_blcg_fifo, ARRAY_SIZE(gm20b_blcg_fifo)); gk20a_enable_load_gating_prod(pmu, gm20b_blcg_gr, ARRAY_SIZE(gm20b_blcg_gr)); gk20a_enable_load_gating_prod(pmu, gm20b_blcg_ltc, ARRAY_SIZE(gm20b_blcg_ltc)); gk20a_enable_load_gating_prod(pmu, gm20b_blcg_pmu, ARRAY_SIZE(gm20b_blcg_pmu)); } do_nothing: mutex_unlock(&priv->clk_gating_mutex); return 0; } int pmu_reset(struct nvkm_pmu *ppmu, struct nvkm_mc *pmc) { int err; struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); err = gk20a_pmu_idle(pmu); if (err) return err; /* TBD: release pmu hw mutex */ err = gk20a_pmu_enable(pmu, pmc, false); if (err) return err; err = gk20a_pmu_enable(pmu, pmc, true); if (err) return err; return 0; } static int gm20b_pmu_init_vm(struct nvkm_pmu *ppmu) { int ret = 0; struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); struct nvkm_pmu_priv_vm *pmuvm = &pmu->pmuvm; struct nvkm_device *device = nv_device(&ppmu->base); struct nvkm_vm *vm; struct nvkm_mmu *mmu = nvkm_mmu(pmu); const u64 pmu_area_len = 600*1024; /* allocate inst blk */ ret = nvkm_gpuobj_new(nv_object(ppmu), NULL, 0x1000, 0, 0, &pmuvm->mem); if (ret) return ret; /* allocate pgd and initialize inst blk */ ret = mmu->create_pgd(mmu, nv_object(ppmu), pmuvm->mem, pmu_area_len, &pmuvm->pgd); if (ret) goto err_pgd; /* allocate virtual memory range */ ret = nvkm_vm_new(device, 0, pmu_area_len, 0, &vm); if (ret) goto err_vm; atomic_inc(&vm->engref[NVDEV_SUBDEV_PMU]); /* update VM with pgd */ ret = nvkm_vm_ref(vm, &pmuvm->vm, pmuvm->pgd); if (ret) goto err_ref; ppmu->pmu_vm = pmuvm; return 0; err_ref: nvkm_vm_ref(NULL, &vm, NULL); err_vm: nvkm_gpuobj_destroy(pmuvm->pgd); pmuvm->pgd = NULL; err_pgd: nvkm_gpuobj_destroy(pmuvm->mem); pmuvm->mem = NULL; return ret; } typedef int (*get_ucode_details)(struct nvkm_pmu *ppmu, struct flcn_ucode_img *udata); static void gm20b_copy_ctxsw_ucode_segments( u8 *buf, struct gm20b_ctxsw_ucode_segments *segments, u32 *bootimage, u32 *code, u32 *data) { memcpy(buf + segments->boot.offset, bootimage, segments->boot.size); memcpy(buf + segments->code.offset, code, segments->code.size); memcpy(buf + segments->data.offset, data, segments->data.size); } static void gm20b_init_ctxsw_ucode_segment( struct gm20b_ctxsw_ucode_segment *p_seg, u32 *offset, u32 size) { p_seg->offset = *offset; p_seg->size = size; *offset = ALIGN(*offset + size, BLK_SIZE); } static u8 gm20b_lsfm_falcon_disabled(struct nvkm_pmu *ppmu, struct ls_flcn_mgr *plsfm, u32 falcon_id) { return (plsfm->disable_mask >> falcon_id) & 0x1; } /* Free any ucode image structure resources*/ static void gm20b_lsfm_free_ucode_img_res(struct flcn_ucode_img *p_img) { if (p_img->lsf_desc != NULL) { kfree(p_img->lsf_desc); p_img->lsf_desc = NULL; } } /* Free any ucode image structure resources*/ static void gm20b_lsfm_free_nonpmu_ucode_img_res(struct flcn_ucode_img *p_img) { if (p_img->lsf_desc != NULL) { kfree(p_img->lsf_desc); p_img->lsf_desc = NULL; } if (p_img->desc != NULL) { kfree(p_img->desc); p_img->desc = NULL; } if (p_img->data != NULL) { kfree(p_img->data); p_img->data = NULL; p_img->data_size = 0; } } /* * Calculates PHY and VIRT addresses for various portions of the ucode image. * like: application code, application data, and bootloader code. * Return if ucode image is header based. * BL desc will be used by HS bin to boot corresponding LS(Low secure) falcon. */ static int gm20b_flcn_populate_bl_dmem_desc(struct nvkm_pmu *ppmu, struct lsfm_managed_ucode_img *lsfm, union flcn_bl_generic_desc *p_bl_gen_desc, u32 *p_bl_gen_desc_size) { struct flcn_ucode_img *p_img = &(lsfm->ucode_img); struct flcn_bl_dmem_desc *ldr_cfg = (struct flcn_bl_dmem_desc *)(&p_bl_gen_desc->bl_dmem_desc); u64 addr_base; struct pmu_ucode_desc *desc; u64 addr_code, addr_data; if (p_img->desc == NULL) return -EINVAL; desc = p_img->desc; addr_base = lsfm->lsb_header.ucode_off; addr_base += ioread32_native(mc + MC_SECURITY_CARVEOUT2_BOM_0); nv_debug(ppmu, "gen loader cfg %x u32 addrbase %x ID\n", (u32)addr_base, lsfm->wpr_header.falcon_id); addr_code = lower_32_bits((addr_base + desc->app_start_offset + desc->app_resident_code_offset) >> 8); addr_data = lower_32_bits((addr_base + desc->app_start_offset + desc->app_resident_data_offset) >> 8); nv_debug(ppmu, "gen cfg %x u32 addrcode %x & data %x load offst %xID\n", (u32)addr_code, (u32)addr_data, desc->bootloader_start_offset, lsfm->wpr_header.falcon_id); memset((void *) ldr_cfg, 0, sizeof(struct flcn_bl_dmem_desc)); ldr_cfg->ctx_dma = GK20A_PMU_DMAIDX_UCODE; ldr_cfg->code_dma_base = addr_code; ldr_cfg->non_sec_code_size = desc->app_resident_code_size; ldr_cfg->data_dma_base = addr_data; ldr_cfg->data_size = desc->app_resident_data_size; ldr_cfg->code_entry_point = desc->app_imem_entry; *p_bl_gen_desc_size = sizeof(p_bl_gen_desc->bl_dmem_desc); return 0; } static u8 pmu_is_debug_mode_en(struct nvkm_pmu *pmu) { u32 ctl_stat = nv_rd32(pmu, 0x0010ac08); return (ctl_stat >> 20) & 0x1; } /* * @brief Patch signatures into ucode image */ static int acr_ucode_patch_sig(struct nvkm_pmu *pmu, unsigned int *p_img, unsigned int *p_prod_sig, unsigned int *p_dbg_sig, unsigned int *p_patch_loc, unsigned int *p_patch_ind) { int i, *p_sig; if (!pmu_is_debug_mode_en(pmu)) { p_sig = p_prod_sig; nv_debug(pmu, "PRODUCTION MODE\n"); } else { p_sig = p_dbg_sig; nv_debug(pmu, "DEBUG MODE\n"); } /*Patching logic:*/ for (i = 0; i < sizeof(*p_patch_loc)>>2; i++) { p_img[(p_patch_loc[i]>>2)] = p_sig[(p_patch_ind[i]<<2)]; p_img[(p_patch_loc[i]>>2)+1] = p_sig[(p_patch_ind[i]<<2)+1]; p_img[(p_patch_loc[i]>>2)+2] = p_sig[(p_patch_ind[i]<<2)+2]; p_img[(p_patch_loc[i]>>2)+3] = p_sig[(p_patch_ind[i]<<2)+3]; } return 0; } /*Once is LS mode, cpuctl_alias is only accessible*/ static void start_gm20b_pmu(struct nvkm_pmu *ppmu) { struct nvkm_mc *pmc = nvkm_mc(ppmu); struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); mutex_lock(&pmu->isr_mutex); gk20a_pmu_enable_irq(pmu, pmc, true); pmu->isr_enabled = true; mutex_unlock(&pmu->isr_mutex); nv_wr32(ppmu, 0x0010a130, 0x2); } /*Parses UCODE header of falcon to fill respective LSB header*/ static int gm20b_lsfm_parse_no_loader_ucode(u32 *p_ucodehdr, struct lsf_lsb_header *lsb_hdr) { u32 code_size = 0; u32 data_size = 0; u32 i = 0; u32 total_apps = p_ucodehdr[FLCN_NL_UCODE_HDR_NUM_APPS_IND]; /* Lets calculate code size*/ code_size += p_ucodehdr[FLCN_NL_UCODE_HDR_OS_CODE_SIZE_IND]; for (i = 0; i < total_apps; i++) { code_size += p_ucodehdr[FLCN_NL_UCODE_HDR_APP_CODE_SIZE_IND (total_apps, i)]; } code_size += p_ucodehdr[FLCN_NL_UCODE_HDR_OS_OVL_SIZE_IND(total_apps)]; /* Calculate data size*/ data_size += p_ucodehdr[FLCN_NL_UCODE_HDR_OS_DATA_SIZE_IND]; for (i = 0; i < total_apps; i++) { data_size += p_ucodehdr[FLCN_NL_UCODE_HDR_APP_DATA_SIZE_IND (total_apps, i)]; } lsb_hdr->ucode_size = code_size; lsb_hdr->data_size = data_size; lsb_hdr->bl_code_size = p_ucodehdr[FLCN_NL_UCODE_HDR_OS_CODE_SIZE_IND]; lsb_hdr->bl_imem_off = 0; lsb_hdr->bl_data_off = p_ucodehdr[FLCN_NL_UCODE_HDR_OS_DATA_OFF_IND]; lsb_hdr->bl_data_size = p_ucodehdr[FLCN_NL_UCODE_HDR_OS_DATA_SIZE_IND]; return 0; } static void gm20b_free_acr_resources(struct nvkm_pmu *ppmu, struct ls_flcn_mgr *plsfm) { u32 cnt = plsfm->managed_flcn_cnt; struct lsfm_managed_ucode_img *mg_ucode_img; while (cnt) { mg_ucode_img = plsfm->ucode_img_list; if (mg_ucode_img->ucode_img.lsf_desc->falcon_id == LSF_FALCON_ID_PMU) gm20b_lsfm_free_ucode_img_res(&mg_ucode_img->ucode_img); else gm20b_lsfm_free_nonpmu_ucode_img_res( &mg_ucode_img->ucode_img); plsfm->ucode_img_list = mg_ucode_img->next; kfree(mg_ucode_img); cnt--; } } /* * Calculates PHY and VIRT addresses for various portions of the PMU ucode. * e.g. application code, application data, and bootloader code. * Return -EINVAL if ucode image is header based. * HS bin will use BL desc to boot PMU LS(Low secure) falcon. */ static int gm20b_pmu_populate_loader_cfg(struct nvkm_pmu *ppmu, struct lsfm_managed_ucode_img *lsfm, union flcn_bl_generic_desc *p_bl_gen_desc, u32 *p_bl_gen_desc_size) { struct gk20a_pmu_priv *priv = to_gk20a_priv(ppmu); struct gm20b_acr *acr = &priv->acr; struct flcn_ucode_img *p_img = &(lsfm->ucode_img); struct loader_config *ldr_cfg = (struct loader_config *)(&p_bl_gen_desc->loader_cfg); u64 addr_base; struct pmu_ucode_desc *desc; u64 addr_code, addr_data; u32 addr_args; struct pmu_cmdline_args_v1 cmdline_args; if (p_img->desc == NULL) return -EINVAL; desc = p_img->desc; addr_base = lsfm->lsb_header.ucode_off; addr_base += ioread32_native(mc + MC_SECURITY_CARVEOUT2_BOM_0); nv_debug(ppmu, "pmu loader cfg u32 addrbase %x\n", (u32)addr_base); addr_code = lower_32_bits((addr_base + desc->app_start_offset + desc->app_resident_code_offset) >> 8); nv_debug(ppmu, "app start %d app res code off %d\n", desc->app_start_offset, desc->app_resident_code_offset); addr_data = lower_32_bits((addr_base + desc->app_start_offset + desc->app_resident_data_offset) >> 8); nv_debug(ppmu, "app res data offset%d\n", desc->app_resident_data_offset); nv_debug(ppmu, "bl start off %d\n", desc->bootloader_start_offset); addr_args = ((nv_rd32(ppmu, 0x0010a108) >> 9) & 0x1ff) << GK20A_PMU_DMEM_BLKSIZE2; addr_args -= sizeof(cmdline_args); nv_debug(ppmu, "addr_args %x\n", addr_args); ldr_cfg->dma_idx = GK20A_PMU_DMAIDX_UCODE; ldr_cfg->code_dma_base = addr_code; ldr_cfg->code_size_total = desc->app_size; ldr_cfg->code_size_to_load = desc->app_resident_code_size; ldr_cfg->code_entry_point = desc->app_imem_entry; ldr_cfg->data_dma_base = addr_data; ldr_cfg->data_size = desc->app_resident_data_size; ldr_cfg->overlay_dma_base = addr_code; ldr_cfg->argc = 1; ldr_cfg->argv = addr_args; *p_bl_gen_desc_size = sizeof(p_bl_gen_desc->loader_cfg); acr->pmu_args = addr_args; return 0; } static void gm20b_init_ctxsw_ucode_segments( struct gm20b_ctxsw_ucode_segments *segments, u32 *offset, struct gm20b_ctxsw_bootloader_desc *bootdesc, u32 code_size, u32 data_size) { u32 boot_size = ALIGN(bootdesc->size, sizeof(u32)); segments->boot_entry = bootdesc->entry_point; segments->boot_imem_offset = bootdesc->imem_offset; gm20b_init_ctxsw_ucode_segment(&segments->boot, offset, boot_size); gm20b_init_ctxsw_ucode_segment(&segments->code, offset, code_size); gm20b_init_ctxsw_ucode_segment(&segments->data, offset, data_size); } /*Get PMU ucode details & fill flcn_ucode_img struct with these details*/ static int gm20b_pmu_ucode_details(struct nvkm_pmu *ppmu, struct flcn_ucode_img *p_img) { const struct firmware *pmu_fw, *pmu_desc, *pmu_sig; struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); struct gm20b_acr *acr = &pmu->acr; struct lsf_ucode_desc *lsf_desc; int err; nv_debug(ppmu, "requesting PMU ucode in GM20B\n"); err = gk20a_load_firmware(ppmu, &pmu_fw, GM20B_PMU_UCODE_IMAGE); if (err) { nv_error(ppmu, "failed to load pmu ucode!!\n"); return -ENOENT; } acr->pmu_fw = pmu_fw; nv_debug(ppmu, "Loaded PMU ucode in for blob preparation\n"); nv_debug(ppmu, "requesting PMU ucode desc in GM20B\n"); err = gk20a_load_firmware(ppmu, &pmu_desc, GM20B_PMU_UCODE_DESC); if (err) { nv_error(ppmu, "failed to load pmu ucode desc!!\n"); err = -ENOENT; goto release_img_fw; } nv_debug(ppmu, "requesting PMU ucode signature in GM20B\n"); err = gk20a_load_firmware(ppmu, &pmu_sig, GM20B_PMU_UCODE_SIG); if (err) { nv_error(ppmu, "failed to load pmu sig!!\n"); err = -ENOENT; goto release_desc; } pmu->desc = (struct pmu_ucode_desc *)pmu_desc->data; pmu->ucode_image = (u32 *)pmu_fw->data; acr->pmu_desc = pmu_desc; lsf_desc = kzalloc(sizeof(struct lsf_ucode_desc), GFP_KERNEL); if (!lsf_desc) { err = -ENOMEM; nv_error(ppmu, "lsf_desc alloc failed\n"); goto release_sig; } memcpy(lsf_desc, (void *)pmu_sig->data, sizeof(struct lsf_ucode_desc)); lsf_desc->falcon_id = LSF_FALCON_ID_PMU; p_img->desc = pmu->desc; p_img->data = pmu->ucode_image; p_img->data_size = pmu->desc->image_size; nv_debug(ppmu, "pmu ucode img loc %p & size %d\n", p_img->data, p_img->data_size); p_img->fw_ver = NULL; p_img->header = NULL; p_img->lsf_desc = (struct lsf_ucode_desc *)lsf_desc; gk20a_release_firmware(ppmu, pmu_sig); return 0; release_sig: gk20a_release_firmware(ppmu, pmu_sig); release_desc: gk20a_release_firmware(ppmu, pmu_desc); release_img_fw: gk20a_release_firmware(ppmu, pmu_fw); return err; } /*Populate static LSB header information using the provided ucode image*/ static void gm20b_lsfm_fill_static_lsb_hdr(struct nvkm_pmu *ppmu, u32 falcon_id, struct lsfm_managed_ucode_img *pnode) { struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); u32 full_app_size = 0; u32 data = 0; if (pnode->ucode_img.lsf_desc) memcpy(&pnode->lsb_header.signature, pnode->ucode_img.lsf_desc, sizeof(struct lsf_ucode_desc)); pnode->lsb_header.ucode_size = pnode->ucode_img.data_size; /* The remainder of the LSB depends on the loader usage */ if (pnode->ucode_img.header) { /* Does not use a loader */ pnode->lsb_header.data_size = 0; pnode->lsb_header.bl_code_size = 0; pnode->lsb_header.bl_data_off = 0; pnode->lsb_header.bl_data_size = 0; gm20b_lsfm_parse_no_loader_ucode(pnode->ucode_img.header, &(pnode->lsb_header)); /* Load the first 256 bytes of IMEM. */ /* Set LOAD_CODE_AT_0 and DMACTL_REQ_CTX. True for all method based falcons */ data = NV_FLCN_ACR_LSF_FLAG_LOAD_CODE_AT_0_TRUE | NV_FLCN_ACR_LSF_FLAG_DMACTL_REQ_CTX_TRUE; pnode->lsb_header.flags = data; } else { /* Uses a loader. that is has a desc */ pnode->lsb_header.data_size = 0; /* The loader code size is already aligned (padded) such that the code following it is aligned, but the size in the image desc is not, bloat it up to be on a 256 byte alignment. */ pnode->lsb_header.bl_code_size = ALIGN( pnode->ucode_img.desc->bootloader_size, LSF_BL_CODE_SIZE_ALIGNMENT); full_app_size = ALIGN(pnode->ucode_img.desc->app_size, LSF_BL_CODE_SIZE_ALIGNMENT) + pnode->lsb_header.bl_code_size; pnode->lsb_header.ucode_size = ALIGN( pnode->ucode_img.desc->app_resident_data_offset, LSF_BL_CODE_SIZE_ALIGNMENT) + pnode->lsb_header.bl_code_size; pnode->lsb_header.data_size = full_app_size - pnode->lsb_header.ucode_size; /* Though the BL is located at 0th offset of the image, the VA is different to make sure that it doesnt collide the actual OS VA range */ pnode->lsb_header.bl_imem_off = pnode->ucode_img.desc->bootloader_imem_offset; pnode->lsb_header.app_code_off = pnode->ucode_img.desc->app_start_offset + pnode->ucode_img.desc->app_resident_code_offset; pnode->lsb_header.app_code_size = pnode->ucode_img.desc->app_resident_code_size; pnode->lsb_header.app_data_off = pnode->ucode_img.desc->app_start_offset + pnode->ucode_img.desc->app_resident_data_offset; pnode->lsb_header.app_data_size = pnode->ucode_img.desc->app_resident_data_size; pnode->lsb_header.flags = 0; if (falcon_id == pmu->falcon_id) { data = NV_FLCN_ACR_LSF_FLAG_DMACTL_REQ_CTX_TRUE; pnode->lsb_header.flags = data; } } } /*Adds a ucode image to the list of managed ucode images managed*/ static int gm20b_lsfm_add_ucode_img(struct nvkm_pmu *ppmu, struct ls_flcn_mgr *plsfm, struct flcn_ucode_img *ucode_image, u32 falcon_id) { struct lsfm_managed_ucode_img *pnode; pnode = kzalloc(sizeof(struct lsfm_managed_ucode_img), GFP_KERNEL); if (pnode == NULL) return -ENOMEM; nv_debug(ppmu, "created pnode\n"); /*Keep a copy of the ucode image info locally*/ memcpy(&pnode->ucode_img, ucode_image, sizeof(struct flcn_ucode_img)); /*Fill in static WPR header info*/ pnode->wpr_header.falcon_id = falcon_id; pnode->wpr_header.bootstrap_owner = LSF_BOOTSTRAP_OWNER_DEFAULT; pnode->wpr_header.status = LSF_IMAGE_STATUS_COPY; /*Fill in static LSB header info elsewhere*/ gm20b_lsfm_fill_static_lsb_hdr(ppmu, falcon_id, pnode); nv_debug(ppmu, "filled lsb header\n"); pnode->next = plsfm->ucode_img_list; plsfm->ucode_img_list = pnode; return 0; } /*Get FECS ucode details & fill flcn_ucode_img struct with these details*/ static int gm20b_fecs_ucode_details(struct nvkm_pmu *ppmu, struct flcn_ucode_img *p_img) { struct lsf_ucode_desc *lsf_desc; const struct firmware *fecs_sig, *fecs_blfw, *fecs_cfw, *fecs_dfw; int err; u32 ucode_size; u8 *buf; struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); struct gm20b_ctxsw_bootloader_desc *fecs_boot_desc; struct gm20b_ctxsw_ucode_info *ucode_info = &pmu->ucode_info; u32 *fecs_boot_image; err = gk20a_load_firmware(ppmu, &fecs_blfw, GK20A_FECS_UCODE_IMAGE); if (err) { nv_error(ppmu, "failed to load fecs ucode image\n"); return -ENOENT; } err = gk20a_load_firmware(ppmu, &fecs_cfw, "nv12b_fuc409c"); if (err) { nv_error(ppmu, "failed to load fecs ucode image\n"); goto rel_fecs_blfw; } err = gk20a_load_firmware(ppmu, &fecs_dfw, "nv12b_fuc409d"); if (err) { nv_error(ppmu, "failed to load fecs data image\n"); goto rel_fecs_cfw; } err = gk20a_load_firmware(ppmu, &fecs_sig, GM20B_FECS_UCODE_SIG); if (err) { nv_error(ppmu, "failed to load fecs ucode sig\n"); goto rel_fecs_dfw; } lsf_desc = kzalloc(sizeof(struct lsf_ucode_desc), GFP_KERNEL); if (!lsf_desc) { err = -ENOMEM; goto rel_fecs_sig; } nv_debug(ppmu, "fecs related fws loaded\n"); memcpy(lsf_desc, (void *)fecs_sig->data, sizeof(struct lsf_ucode_desc)); lsf_desc->falcon_id = LSF_FALCON_ID_FECS; fecs_boot_desc = (void *)fecs_blfw->data; fecs_boot_image = (void *)(fecs_blfw->data + sizeof(struct gm20b_ctxsw_bootloader_desc)); ucode_size = 0; nv_debug(ppmu, "fecs related size calculation\n"); gm20b_init_ctxsw_ucode_segments(&ucode_info->fecs, &ucode_size, fecs_boot_desc, fecs_cfw->size, fecs_dfw->size); buf = kzalloc(ucode_size, GFP_KERNEL); if (buf == NULL) { err = -ENOMEM; goto free_lsf_desc; } p_img->desc = kzalloc(sizeof(struct pmu_ucode_desc), GFP_KERNEL); if (p_img->desc == NULL) { err = -ENOMEM; goto free_ucode_buf; } gm20b_copy_ctxsw_ucode_segments(buf, &ucode_info->fecs, fecs_boot_image, (u32 *)fecs_cfw->data, (u32 *)fecs_dfw->data); nv_debug(ppmu, "fecs related p_img allocated\n"); p_img->desc->bootloader_start_offset = pmu->ucode_info.fecs.boot.offset; p_img->desc->bootloader_size = ALIGN(pmu->ucode_info.fecs.boot.size, 256); p_img->desc->bootloader_imem_offset = pmu->ucode_info.fecs.boot_imem_offset; p_img->desc->bootloader_entry_point = pmu->ucode_info.fecs.boot_entry; p_img->desc->image_size = ALIGN(pmu->ucode_info.fecs.boot.size, 256) + ALIGN(pmu->ucode_info.fecs.code.size, 256) + ALIGN(pmu->ucode_info.fecs.data.size, 256); p_img->desc->app_size = ALIGN(pmu->ucode_info.fecs.code.size, 256) + ALIGN(pmu->ucode_info.fecs.data.size, 256); p_img->desc->app_start_offset = pmu->ucode_info.fecs.code.offset; p_img->desc->app_imem_offset = 0; p_img->desc->app_imem_entry = 0; p_img->desc->app_dmem_offset = 0; p_img->desc->app_resident_code_offset = 0; p_img->desc->app_resident_code_size = pmu->ucode_info.fecs.code.size; p_img->desc->app_resident_data_offset = pmu->ucode_info.fecs.data.offset - pmu->ucode_info.fecs.code.offset; p_img->desc->app_resident_data_size = pmu->ucode_info.fecs.data.size; p_img->data = (u32 *)buf; p_img->data_size = p_img->desc->image_size; nv_debug(ppmu, "fecs ucode image location %p and size %d\n", p_img->data, p_img->data_size); p_img->fw_ver = NULL; p_img->header = NULL; p_img->lsf_desc = (struct lsf_ucode_desc *)lsf_desc; nv_debug(ppmu, "fecs fw loaded\n"); gk20a_release_firmware(ppmu, fecs_sig); gk20a_release_firmware(ppmu, fecs_blfw); gk20a_release_firmware(ppmu, fecs_cfw); gk20a_release_firmware(ppmu, fecs_dfw); return 0; free_ucode_buf: kfree(buf); free_lsf_desc: kfree(lsf_desc); rel_fecs_sig: gk20a_release_firmware(ppmu, fecs_sig); rel_fecs_dfw: gk20a_release_firmware(ppmu, fecs_dfw); rel_fecs_cfw: gk20a_release_firmware(ppmu, fecs_cfw); rel_fecs_blfw: gk20a_release_firmware(ppmu, fecs_blfw); return err; } /* Populate falcon boot loader generic desc.*/ static int gm20b_lsfm_fill_flcn_bl_gen_desc(struct nvkm_pmu *ppmu, struct lsfm_managed_ucode_img *pnode) { struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); if (pnode->wpr_header.falcon_id != pmu->falcon_id) { nv_debug(ppmu, "non pmu. write flcn bl gen desc\n"); gm20b_flcn_populate_bl_dmem_desc(ppmu, pnode, &pnode->bl_gen_desc, &pnode->bl_gen_desc_size); return 0; } if (pmu->pmu_mode & PMU_LSFM_MANAGED) { nv_debug(ppmu, "pmu write flcn bl gen desc\n"); if (pnode->wpr_header.falcon_id == pmu->falcon_id) return gm20b_pmu_populate_loader_cfg(ppmu, pnode, &pnode->bl_gen_desc, &pnode->bl_gen_desc_size); } /* Failed to find the falcon requested. */ return -ENOENT; } /*writes memory allocated to nvgpu object*/ void gpu_obj_memrd(struct nvkm_gpuobj *ucodeobj, int offset, void *read, int size) { int temp = size; u32 *source32; u16 *source16; u8 *source8; u32 red; int four_bytes_cnt, two_bytes_cnt, one_bytes_cnt; four_bytes_cnt = temp / 4; temp = temp % 4; two_bytes_cnt = temp / 2; temp = temp % 2; one_bytes_cnt = temp; source32 = (u32 *)read; for (temp = 0; temp < four_bytes_cnt; temp++) { source32 = (u32 *)read + temp; red = nv_ro32(ucodeobj, offset); memcpy(source32, &red, sizeof(u32)); offset += 4; } source16 = (u16 *)source32; for (temp = 0; temp < two_bytes_cnt; temp++) { source16 = (u16 *)source32 + temp; *source16 = nv_ro16(ucodeobj, offset); offset += 2; } source8 = (u8 *)source16; for (temp = 0; temp < one_bytes_cnt; temp++) { source8 = (u8 *)source16 + temp; *source8 = nv_ro08(ucodeobj, offset); offset += 1; } } /* * Initialize ucodeblob/WPR contents i.e. * Walk the managed falcons, copy WPR and LSB headers to ucodeblob created. * flush any bl args to the storage area relative to the * ucode image (appended on the end as a DMEM area). */ static int gm20b_lsfm_init_wpr_contents(struct nvkm_pmu *ppmu, struct ls_flcn_mgr *plsfm, struct nvkm_gpuobj *ucodebufobj) { int status = 0; if (!ucodebufobj) { nv_error(ppmu, "ucode blob gpuboj is NULL\n"); status = -EINVAL; } else { struct lsfm_managed_ucode_img *pnode = plsfm->ucode_img_list; struct lsf_wpr_header wpr_hdr; struct lsf_lsb_header lsb_hdr; u32 i, offset; /* The WPR array is at the base of the ucode blob (WPR)*/ pnode = plsfm->ucode_img_list; i = 0; nv_debug(ppmu, "iterate all managed falcons\n"); while (pnode) { nv_debug(ppmu, "falconid :%d\n", pnode->wpr_header.falcon_id); nv_debug(ppmu, "lsb_offset :%x\n", pnode->wpr_header.lsb_offset); nv_debug(ppmu, "bootstrap_owner : %d\n", pnode->wpr_header.bootstrap_owner); gpu_obj_memwr(ucodebufobj, 0 + (i * sizeof(struct lsf_wpr_header)), &pnode->wpr_header, sizeof(struct lsf_wpr_header)); /*Copying of WPR header*/ gpu_obj_memrd(ucodebufobj, 0 + i * sizeof(struct lsf_wpr_header), &wpr_hdr, sizeof(struct lsf_wpr_header)); nv_debug(ppmu, "wpr header as in memory and pnode\n"); nv_debug(ppmu, "falconid :%d %d\n", pnode->wpr_header.falcon_id, wpr_hdr.falcon_id); nv_debug(ppmu, "lsb_offset :%x %x\n", pnode->wpr_header.lsb_offset, wpr_hdr.lsb_offset); nv_debug(ppmu, "bootstrap_owner :%d %d\n", pnode->wpr_header.bootstrap_owner, wpr_hdr.bootstrap_owner); nv_debug(ppmu, "lazy_bootstrap :%d %d\n", pnode->wpr_header.lazy_bootstrap, wpr_hdr.lazy_bootstrap); nv_debug(ppmu, "status :%d %d\n", pnode->wpr_header.status, wpr_hdr.status); offset = pnode->wpr_header.lsb_offset; nv_debug(ppmu, "writing lsb header @ offset = %d\n", offset); /*Copying of LSB header*/ gpu_obj_memwr(ucodebufobj, offset, &pnode->lsb_header, sizeof(struct lsf_lsb_header)); gpu_obj_memrd(ucodebufobj, offset, &lsb_hdr, sizeof(struct lsf_lsb_header)); nv_debug(ppmu, "lsb header as in memory and pnode\n"); nv_debug(ppmu, "ucode_off :%x %x\n", pnode->lsb_header.ucode_off, lsb_hdr.ucode_off); nv_debug(ppmu, "ucode_size :%x %x\n", pnode->lsb_header.ucode_size, lsb_hdr.ucode_size); nv_debug(ppmu, "data_size :%x %x\n", pnode->lsb_header.data_size, lsb_hdr.data_size); nv_debug(ppmu, "bl_code_size :%x %x\n", pnode->lsb_header.bl_code_size, lsb_hdr.bl_code_size); nv_debug(ppmu, "bl_imem_off :%x %x\n", pnode->lsb_header.bl_imem_off, lsb_hdr.bl_imem_off); nv_debug(ppmu, "bl_data_off :%x %x\n", pnode->lsb_header.bl_data_off, lsb_hdr.bl_data_off); nv_debug(ppmu, "bl_data_size :%x %x\n", pnode->lsb_header.bl_data_size, lsb_hdr.bl_data_size); nv_debug(ppmu, "flags :%x %x\n", pnode->lsb_header.flags, lsb_hdr.flags); if (!pnode->ucode_img.header) { offset = pnode->lsb_header.bl_data_off; /*Copying of generic bootloader*/ gm20b_lsfm_fill_flcn_bl_gen_desc(ppmu, pnode); nv_debug(ppmu, "writing bl header @ offset = %d\n", offset); gpu_obj_memwr(ucodebufobj, offset, &pnode->bl_gen_desc, pnode->bl_gen_desc_size); } offset = (pnode->lsb_header.ucode_off); nv_debug(ppmu, "writing ucode @ offset = %d\n", offset); /*Copying of ucode*/ nv_debug(ppmu, "ucode start from loc %p & size = %d\n", pnode->ucode_img.data, pnode->ucode_img.data_size); gpu_obj_memwr(ucodebufobj, offset, pnode->ucode_img.data, pnode->ucode_img.data_size); pnode = pnode->next; i++; } nv_wo32(ucodebufobj, 0 + i * sizeof(struct lsf_wpr_header), LSF_FALCON_ID_INVALID); } return status; } static get_ucode_details pmu_acr_supp_ucode_list[] = { gm20b_pmu_ucode_details, gm20b_fecs_ucode_details, }; /* Discover all managed falcon ucode images */ static int gm20b_lsfm_discover_ucode_images(struct nvkm_pmu *ppmu, struct ls_flcn_mgr *plsfm) { struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); struct flcn_ucode_img ucode_img; u32 falcon_id; u32 i; int status; /* LSFM requires a secure PMU, discover it first.*/ /* Obtain the PMU ucode image and add it to the list if required*/ memset(&ucode_img, 0, sizeof(ucode_img)); status = gm20b_pmu_ucode_details(ppmu, &ucode_img); if (status == 0) { if (ucode_img.lsf_desc != NULL) { /* The falon_id is formed by grabbing the static base * falon_id from the image and adding the * engine-designated falcon instance.*/ pmu->pmu_mode |= PMU_SECURE_MODE; falcon_id = ucode_img.lsf_desc->falcon_id + ucode_img.flcn_inst; if (!gm20b_lsfm_falcon_disabled(ppmu, plsfm, falcon_id)) { pmu->falcon_id = falcon_id; if (gm20b_lsfm_add_ucode_img(ppmu, plsfm, &ucode_img, pmu->falcon_id) == 0) pmu->pmu_mode |= PMU_LSFM_MANAGED; plsfm->managed_flcn_cnt++; } else { nv_debug(ppmu, "id not managed %d\n", ucode_img.lsf_desc->falcon_id); } } /*Free any ucode image resources if not managing this falcon*/ if (!(pmu->pmu_mode & PMU_LSFM_MANAGED)) { nv_debug(ppmu, "pmu is not LSFM managed\n"); gm20b_lsfm_free_ucode_img_res(&ucode_img); } } /* Enumerate all constructed falcon objects, as we need the ucode image info and total falcon count.*/ /*0th index is always PMU which is already handled in earlier if condition*/ for (i = 1; i < (MAX_SUPPORTED_LSFM); i++) { memset(&ucode_img, 0, sizeof(ucode_img)); if (pmu_acr_supp_ucode_list[i](ppmu, &ucode_img) == 0) { if (ucode_img.lsf_desc != NULL) { /* We have engine sigs, ensure that this falcon is aware of the secure mode expectations (ACR status)*/ nv_debug(ppmu, "iterated fecs ucode details\n"); /* falon_id is formed by grabbing the static base falonId from the image and adding the engine-designated falcon instance. */ falcon_id = ucode_img.lsf_desc->falcon_id + ucode_img.flcn_inst; if (!gm20b_lsfm_falcon_disabled(ppmu, plsfm, falcon_id)) { /* Do not manage non-FB ucode*/ if (gm20b_lsfm_add_ucode_img(ppmu, plsfm, &ucode_img, falcon_id) == 0) plsfm->managed_flcn_cnt++; } else { nv_debug(ppmu, "not managed %d\n", ucode_img.lsf_desc->falcon_id); gm20b_lsfm_free_nonpmu_ucode_img_res( &ucode_img); } } } else { /* Consumed all available falcon objects */ nv_debug(ppmu, "Done checking for ucodes %d\n", i); break; } } return 0; } /*Calculate size required for UCODE BLOB*/ static int gm20b_lsf_gen_wpr_requirements(struct nvkm_pmu *ppmu, struct ls_flcn_mgr *plsfm) { struct lsfm_managed_ucode_img *pnode = plsfm->ucode_img_list; u32 wpr_offset; /* Calculate WPR size required */ /* Start with an array of WPR headers at the base of the WPR. The expectation here is that the secure falcon will do a single DMA read of this array and cache it internally so it's OK to pack these. Also, we add 1 to the falcon count to indicate the end of the array.*/ wpr_offset = sizeof(struct lsf_wpr_header) * (plsfm->managed_flcn_cnt+1); /* Walk the managed falcons, accounting for the LSB structs as well as the ucode images. */ while (pnode) { /* Align, save off, and include an LSB header size */ wpr_offset = ALIGN(wpr_offset, LSF_LSB_HEADER_ALIGNMENT); nv_debug(ppmu, "LSB header offset %d\n", wpr_offset); pnode->wpr_header.lsb_offset = wpr_offset; wpr_offset += sizeof(struct lsf_lsb_header); /* Align, save off, and include the original (static) ucode image size */ wpr_offset = ALIGN(wpr_offset, LSF_UCODE_DATA_ALIGNMENT); pnode->lsb_header.ucode_off = wpr_offset; nv_debug(ppmu, "UCODE offset %d and size %d\n", wpr_offset, pnode->ucode_img.data_size); wpr_offset += pnode->ucode_img.data_size; /* For falcons that use a boot loader (BL), we append a loader desc structure on the end of the ucode image and consider this the boot loader data. The host will then copy the loader desc args to this space within the WPR region (before locking down) and the HS bin will then copy them to DMEM 0 for the loader. */ if (!pnode->ucode_img.header) { /* Track the size for LSB details filled in later Note that at this point we don't know what kind of i boot loader desc, so we just take the size of the generic one, which is the largest it will will ever be. */ /* Align (size bloat) and save off generic descriptor size*/ pnode->lsb_header.bl_data_size = ALIGN( sizeof(pnode->bl_gen_desc), LSF_BL_DATA_SIZE_ALIGNMENT); /*Align, save off, and include the additional BL data*/ wpr_offset = ALIGN(wpr_offset, LSF_BL_DATA_ALIGNMENT); pnode->lsb_header.bl_data_off = wpr_offset; nv_debug(ppmu, "BL desc offset %d\n", wpr_offset); wpr_offset += pnode->lsb_header.bl_data_size; } else { /* bl_data_off is already assigned in static information. But that is from start of the image */ pnode->lsb_header.bl_data_off += (wpr_offset - pnode->ucode_img.data_size); } /* Finally, update ucode surface size to include updates */ pnode->full_ucode_size = wpr_offset - pnode->lsb_header.ucode_off; pnode = pnode->next; } plsfm->wpr_size = wpr_offset; return 0; } static int gm20b_prepare_ucode_blob(struct nvkm_pmu *ppmu) { u32 status; struct ls_flcn_mgr lsfm_l, *plsfm; int ret; struct gk20a_pmu_priv *priv = to_gk20a_priv(ppmu); struct gm20b_acr *acr = &priv->acr; if (priv->pmuvm.vm) return 0; plsfm = &lsfm_l; memset((void *)plsfm, 0, sizeof(struct ls_flcn_mgr)); status = gm20b_lsfm_discover_ucode_images(ppmu, plsfm); if (status != 0) return status; nv_debug(ppmu, "All ucode images discovered\n"); nv_debug(ppmu, " Managed Falcon cnt %d\n", plsfm->managed_flcn_cnt); if (plsfm->managed_flcn_cnt) { /* Generate WPR requirements*/ status = gm20b_lsf_gen_wpr_requirements(ppmu, plsfm); if (status != 0) return status; ret = gm20b_pmu_init_vm(ppmu); if (ret) { nv_error(ppmu, "gm20b_init_vm failed\n"); return ret; } ret = nvkm_gpuobj_new(nv_object(ppmu), NULL, plsfm->wpr_size, 0x1000, 0, &acr->ucode_blob.obj); if (ret) { nv_error(ppmu, "alloc for ucode blob failed\n"); return ret; } nv_debug(ppmu, "managed LS falcon %d, WPR size %d bytes.\n", plsfm->managed_flcn_cnt, plsfm->wpr_size); gm20b_lsfm_init_wpr_contents(ppmu, plsfm, acr->ucode_blob.obj); nv_debug(ppmu, "base reg carveout 2:%x\n", ioread32_native(mc + MC_SECURITY_CARVEOUT2_BOM_0)); nv_debug(ppmu, "base reg carveout 3:%x\n", ioread32_native(mc + MC_SECURITY_CARVEOUT3_BOM_0)); nv_debug(ppmu, "wpr init success\n"); ret = nvkm_gpuobj_map_vm(nv_gpuobj(acr->ucode_blob.obj), priv->pmuvm.vm, NV_MEM_ACCESS_RW, &acr->ucode_blob.vma); if (ret) { nv_error(ppmu, "mapping of ucode blob failed\n"); return ret; } nv_debug(ppmu, "acr->ucode_blob.vma.offset is: 0x%llx\n", acr->ucode_blob.vma.offset); acr->ucode_blob_start = acr->ucode_blob.obj->addr; acr->ucode_blob_size = plsfm->wpr_size; } else { nv_error(ppmu, "LSFM is managing no falcons.\n"); } nv_debug(ppmu, "prepare ucode blob success\n"); gm20b_free_acr_resources(ppmu, plsfm); gk20a_release_firmware(ppmu, priv->acr.pmu_fw); gk20a_release_firmware(ppmu, priv->acr.pmu_desc); return 0; } /*! * Wait for PMU halt interrupt status to be cleared * @param[in] g GPU object pointer * @param[in] timeout_us Timeout in Us for PMU to halt * @return '0' if PMU halt irq status is clear */ int clear_halt_interrupt_status(struct nvkm_pmu *pmu, unsigned int timeout) { u32 data = 0; while (timeout != 0) { nv_mask(pmu, 0x0010a004, 0x10, 0x10); data = nv_rd32(pmu, 0x0010a008); if ((data & 0x10) != 0x10) break; timeout--; udelay(1); } if (timeout == 0) return -EBUSY; return 0; } /*! * Wait for PMU to halt * @param[in] g GPU object pointer * @param[in] timeout_us Timeout in Us for PMU to halt * @return '0' if PMU halts */ int pmu_wait_for_halt(struct nvkm_pmu *pmu, unsigned int timeout) { u32 data = 0; udelay(10); data = nv_rd32(pmu, 0x0010a100); nv_debug(pmu, "cpuctl %x, timeout %d\n", data, timeout); while (timeout != 0) { data = nv_rd32(pmu, 0x0010a100); if (data & (0x1 << 4)) break; timeout--; udelay(1); } if (timeout == 0) { nv_error(pmu, "Timeout happens in pmu_wait_for_halt.\n"); return -EBUSY; } data = nv_rd32(pmu, 0x0010a040); if (data) { nv_error(pmu, "ACR boot failed, err %x\n", data); return -EAGAIN; } return 0; } static int bl_bootstrap(struct nvkm_pmu *ppmu, struct flcn_bl_dmem_desc *pbl_desc, u32 bl_sz) { struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); struct gm20b_acr *acr = &pmu->acr; u32 imem_dst_blk = 0; u32 virt_addr = 0; u32 tag = 0; u32 index = 0; struct hsflcn_bl_desc *pmu_bl_gm10x_desc = &acr->pmu_hsbl_desc; nv_mask(ppmu, 0x0010a048, 0x1, 0x1); nv_wr32(ppmu, 0x0010a480, (0xfffffff & pmu->pmuvm.mem->addr >> 12) | ((0x1) << 30) | 0x20000000); /*copy bootloader interface structure to dmem*/ nv_wr32(ppmu, 0x0010a1c0, (0 | (0x1 << 24))); gk20a_pmu_copy_to_dmem(pmu, 0, (u8 *)pbl_desc, sizeof(struct flcn_bl_dmem_desc), 0); /* Now copy bootloader to TOP of IMEM */ imem_dst_blk = (nv_rd32(ppmu, 0x0010a108) & 0x1ff) - bl_sz/256; /* Set Auto-Increment on write */ nv_wr32(ppmu, 0x0010a180, ((imem_dst_blk & 0xff) << 8) | (0x1 << 24)); virt_addr = pmu_bl_gm10x_desc->bl_start_tag << 8; tag = virt_addr >> 8; /* tag is always 256B aligned */ for (index = 0; index < bl_sz/4; index++) { if ((index % 64) == 0) { nv_wr32(ppmu, 0x0010a188, (tag & 0xffff) << 0); tag++; } nv_wr32(ppmu, 0x0010a184, nv_ro32(acr->hsbl_ucode.obj, index * 4)); } nv_wr32(ppmu, 0x0010a188, (0 & 0xffff) << 0); nv_debug(ppmu, "Before starting falcon with BL\n"); nv_wr32(ppmu, 0x0010a104, (virt_addr & 0xffffffff)); nv_wr32(ppmu, 0x0010a100, 0x2); return 0; } static int gm20b_init_pmu_setup_hw1(struct nvkm_pmu *ppmu, struct flcn_bl_dmem_desc *desc, u32 bl_sz) { struct nvkm_mc *pmc = nvkm_mc(ppmu); struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); struct gm20b_acr *acr = &pmu->acr; int err; struct pmu_cmdline_args_v1 args; /* TODO remove this when perfmon is used for pstate/dvfs scaling */ pmu->perfmon_sampling_enabled = false; if (!pmu->trace_buf.size) { err = nvkm_gpuobj_new(nv_object(ppmu), NULL, GK20A_PMU_TRACE_BUFSIZE, 0x1000, 0, &pmu->trace_buf.obj); if (err) { nv_error(ppmu, "alloc for trace buf failed\n"); return err; } err = nvkm_gpuobj_map_vm(nv_gpuobj(pmu->trace_buf.obj), pmu->pmuvm.vm, NV_MEM_ACCESS_RW, &pmu->trace_buf.vma); if (err) { nv_error(ppmu, "mapping of trace buf failed\n"); return err; } pmu->trace_buf.size = GK20A_PMU_TRACE_BUFSIZE; } if (!pmu->seq_buf.size) { err = nvkm_gpuobj_new(nv_object(ppmu), NULL, GK20A_PMU_SEQ_BUFSIZE, 0x1000, 0, &pmu->seq_buf.obj); if (err) { nv_error(ppmu, "alloc for seq buf failed\n"); return err; } err = nvkm_gpuobj_map_vm(nv_gpuobj(pmu->seq_buf.obj), pmu->pmuvm.vm, NV_MEM_ACCESS_RW, &pmu->seq_buf.vma); if (err) { nv_error(ppmu, "mapping of seq buf failed\n"); return err; } pmu->seq_buf.size = GK20A_PMU_SEQ_BUFSIZE; } memset(&args, 0x00, sizeof(struct pmu_cmdline_args_v1)); gk20a_pmu_seq_init(pmu); INIT_WORK(&pmu->pg_init, gk20a_pmu_setup_hw); reinit_completion(&pmu->lspmu_completion); reinit_completion(&ppmu->gr_init); mutex_lock(&pmu->isr_mutex); pmu_reset(ppmu, pmc); pmu->isr_enabled = true; mutex_unlock(&pmu->isr_mutex); INIT_WORK(&pmu->base.recv.work, gk20a_pmu_process_message); /* setup apertures - virtual */ nv_wr32(ppmu, 0x0010ae00 + 4 * (GK20A_PMU_DMAIDX_UCODE), 0x4 | 0x0); nv_wr32(ppmu, 0x0010ae00 + 4 * (GK20A_PMU_DMAIDX_VIRT), 0x0); /* setup apertures - physical */ nv_wr32(ppmu, 0x0010ae00 + 4 * (GK20A_PMU_DMAIDX_PHYS_VID), 0x4); nv_wr32(ppmu, 0x0010ae00 + 4 * (GK20A_PMU_DMAIDX_PHYS_SYS_COH), 0x4 | 0x1); nv_wr32(ppmu, 0x0010ae00 + 4 * (GK20A_PMU_DMAIDX_PHYS_SYS_NCOH), 0x4 | 0x2); args.cpu_freq_hz = 0; args.secure_mode = 1; args.falc_trace_size = GK20A_PMU_TRACE_BUFSIZE; args.falc_trace_dma_base = ((u32)pmu->trace_buf.vma.offset) >> 8; args.falc_trace_dma_idx = GK20A_PMU_DMAIDX_VIRT; gk20a_pmu_copy_to_dmem(pmu, acr->pmu_args, (u8 *)(&args), sizeof(args), 0); /*disable irqs for hs falcon booting as we will poll for halt*/ mutex_lock(&pmu->isr_mutex); gk20a_pmu_enable_irq(pmu, pmc, false); pmu->isr_enabled = false; mutex_unlock(&pmu->isr_mutex); return bl_bootstrap(ppmu, desc, bl_sz); } /* * Executes a generic bootloader and wait for PMU to halt. * This BL will be used for those binaries that are loaded * and executed at times other than RM PMU Binary execution. * * @param[in] g gk20a pointer * @param[in] desc Bootloader descriptor * @param[in] dma_idx DMA Index * @param[in] b_wait_for_halt Wait for PMU to HALT */ int pmu_exec_gen_bl(struct nvkm_pmu *pmu, void *desc, u8 b_wait_for_halt) { int i, err = 0; struct gk20a_pmu_priv *priv = to_gk20a_priv(pmu); struct gm20b_acr *acr = &priv->acr; u32 bl_sz; const struct firmware *hsbl_fw = acr->hsbl_fw; struct hsflcn_bl_desc *pmu_bl_desc = &acr->pmu_hsbl_desc; struct hsflcn_bl_desc *pmu_hsbl_desc; u32 *pmu_bl = NULL; if (!acr->hsbl_ucode.size) { err = gk20a_load_firmware(pmu, &hsbl_fw, GM20B_HSBIN_PMU_BL_UCODE_IMAGE); if (err) { nv_error(pmu, "HSbin BL ucode load failed\n"); return -ENOENT; } acr->hsbl_fw = hsbl_fw; acr->bl_bin_hdr = (struct bin_hdr *)hsbl_fw->data; pmu_hsbl_desc = (struct hsflcn_bl_desc *)(hsbl_fw->data + acr->bl_bin_hdr->header_offset); *pmu_bl_desc = *pmu_hsbl_desc; pmu_bl = (u32 *)(hsbl_fw->data + acr->bl_bin_hdr->data_offset); bl_sz = ALIGN(pmu_bl_desc->bl_img_hdr.bl_code_size, 256); acr->hsbl_ucode.size = bl_sz; nv_debug(pmu, "Executing Generic Bootloader\n"); err = nvkm_gpuobj_new(nv_object(pmu), NULL, bl_sz, 0x1000, 0, &acr->hsbl_ucode.obj); if (err) { nv_error(pmu, "acr bl ucode alloc failed\n"); gk20a_release_firmware(pmu, hsbl_fw); acr->hsbl_fw = NULL; return -ENOMEM; } err = nvkm_gpuobj_map_vm(nv_gpuobj(acr->hsbl_ucode.obj), priv->pmuvm.vm, NV_MEM_ACCESS_RW, &acr->hsbl_ucode.vma); if (err) { nv_error(pmu, "acr bl ucode mapping to vm failed\n"); gk20a_release_firmware(pmu, hsbl_fw); acr->hsbl_fw = NULL; goto err_free_gpuobj; } nv_debug(pmu, "acr->hsbl_ucode.vma.offset is: 0x%llx\n", acr->hsbl_ucode.vma.offset); for (i = 0; i < (bl_sz) >> 2; i++) nv_wo32(acr->hsbl_ucode.obj, i * 4, pmu_bl[i]); nv_debug(pmu, "Copied HSBL ucode to iova\n"); gk20a_release_firmware(pmu, hsbl_fw); acr->hsbl_fw = NULL; } /* * Disable interrupts to avoid kernel hitting breakpoint due * to PMU halt */ if (clear_halt_interrupt_status(pmu, GK20A_IDLE_CHECK_DEFAULT)) goto err_unmap_bl; nv_debug(pmu, "err reg :%x\n", ioread32_native(mc + MC_ERR_GENERALIZED_CARVEOUT_STATUS_0)); nv_debug(pmu, "phys sec reg %x\n", nv_rd32(pmu, 0x00100ce4)); nv_debug(pmu, "before ACR exec sctl %x\n", nv_rd32(pmu, 0x0010a240)); err = gm20b_init_pmu_setup_hw1(pmu, desc, acr->hsbl_ucode.size); if (err) { nv_error(pmu, "gm20b_init_pmu_setup_hw1 failed\n"); goto err_unmap_bl; } /* Poll for HALT */ if (b_wait_for_halt) { err = pmu_wait_for_halt(pmu, GK20A_IDLE_CHECK_DEFAULT); if (err == 0) { /* Clear the HALT interrupt */ if (clear_halt_interrupt_status(pmu, GK20A_IDLE_CHECK_DEFAULT)) goto err_unmap_bl; } else goto err_unmap_bl; } nv_debug(pmu, "after waiting for halt, err %x\n", err); nv_debug(pmu, "MC_ERR_GENERALIZED_CARVEOUT_STATUS_0: 0x%X\n", ioread32_native(mc + MC_ERR_GENERALIZED_CARVEOUT_STATUS_0)); nv_debug(pmu, "MC_ERR_GENERALIZED_CARVEOUT_ADR_0: 0x%X\n", ioread32_native(mc + 0xc04)); nv_debug(pmu, "phys sec reg %x\n", nv_rd32(pmu, 0x00100ce4)); nv_debug(pmu, "sctl reg %x\n", nv_rd32(pmu, 0x0010a240)); priv->pmu_state = PMU_STATE_STARTING; start_gm20b_pmu(pmu); return 0; err_unmap_bl: nvkm_gpuobj_unmap(&priv->acr.hsbl_ucode.vma); err_free_gpuobj: nvkm_gpuobj_ref(NULL, &priv->acr.hsbl_ucode.obj); return err; } /*Loads ACR bin to FB mem and bootstraps PMU with bootloader code * start and end are addresses of ucode blob in non-WPR region*/ int gm20b_bootstrap_hs_flcn(struct nvkm_pmu *ppmu) { int i, err = 0, offset = 0; u64 *acr_dmem; u32 img_size_in_bytes = 0; u32 size; u64 start; struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); struct gm20b_acr *acr = &pmu->acr; const struct firmware *acr_fw = acr->acr_fw; struct flcn_bl_dmem_desc *bl_dmem_desc = &acr->bl_dmem_desc; u32 *acr_ucode_header_t210_load; u32 *acr_ucode_data_t210_load; start = acr->ucode_blob_start; size = acr->ucode_blob_size; if (!acr->acr_ucode.size) { /*First time init case*/ err = gk20a_load_firmware(ppmu, &acr_fw, GM20B_HSBIN_PMU_UCODE_IMAGE); if (err) { nv_error(ppmu, "pmu ucode get fail\n"); return -ENOENT; } acr->acr_fw = acr_fw; acr->hsbin_hdr = (struct bin_hdr *)acr_fw->data; acr->fw_hdr = (struct acr_fw_header *)(acr_fw->data + acr->hsbin_hdr->header_offset); acr_ucode_data_t210_load = (u32 *)(acr_fw->data + acr->hsbin_hdr->data_offset); acr_ucode_header_t210_load = (u32 *)(acr_fw->data + acr->fw_hdr->hdr_offset); img_size_in_bytes = ALIGN((acr->hsbin_hdr->data_size), 256); /*Lets patch the signatures first..*/ if (acr_ucode_patch_sig(ppmu, acr_ucode_data_t210_load, (u32 *)(acr_fw->data + acr->fw_hdr->sig_prod_offset), (u32 *)(acr_fw->data + acr->fw_hdr->sig_dbg_offset), (u32 *)(acr_fw->data + acr->fw_hdr->patch_loc), (u32 *)(acr_fw->data + acr->fw_hdr->patch_sig)) < 0) { nv_error(ppmu, "patch signatures fail\n"); err = -1; gk20a_release_firmware(ppmu, acr_fw); acr->acr_fw = NULL; return err; } err = nvkm_gpuobj_new(nv_object(ppmu), NULL, img_size_in_bytes, 0x1000, 0, &acr->acr_ucode.obj); if (err) { nv_error(ppmu, "alloc for acr ucode failed\n"); gk20a_release_firmware(ppmu, acr_fw); acr->acr_fw = NULL; return -ENOMEM; } err = nvkm_gpuobj_map_vm(nv_gpuobj(acr->acr_ucode.obj), pmu->pmuvm.vm, NV_MEM_ACCESS_RW, &acr->acr_ucode.vma); if (err) { nv_error(ppmu, "alloc for acr ucode failed\n"); gk20a_release_firmware(ppmu, acr_fw); acr->acr_fw = NULL; goto err_map_acr_gpuobj; } nv_debug(ppmu, "acr_ucode.vma.offset is: 0x%llX\n", acr->acr_ucode.vma.offset); acr_dmem = (u64 *) &(((u8 *)acr_ucode_data_t210_load)[ acr_ucode_header_t210_load[2]]); ((struct flcn_acr_desc *)acr_dmem)->nonwpr_ucode_blob_start = start; ((struct flcn_acr_desc *)acr_dmem)->nonwpr_ucode_blob_size = size; ((struct flcn_acr_desc *)acr_dmem)->regions.no_regions = 2; ((struct flcn_acr_desc *)acr_dmem)->wpr_offset = 0; for (i = 0; i < (img_size_in_bytes/4); i++) { nv_wo32(acr->acr_ucode.obj, offset , acr_ucode_data_t210_load[i]); offset += 4; } acr->acr_ucode.size = img_size_in_bytes; /* * In order to execute this binary, we will be using * a bootloader which will load this image into PMU IMEM/DMEM. * Fill up the bootloader descriptor for PMU HAL to use..*/ bl_dmem_desc->signature[0] = 0; bl_dmem_desc->signature[1] = 0; bl_dmem_desc->signature[2] = 0; bl_dmem_desc->signature[3] = 0; bl_dmem_desc->ctx_dma = GK20A_PMU_DMAIDX_VIRT; bl_dmem_desc->code_dma_base = lower_32_bits(((u64)acr->acr_ucode.vma.offset >> 8)); bl_dmem_desc->non_sec_code_off = acr_ucode_header_t210_load[0]; bl_dmem_desc->non_sec_code_size = acr_ucode_header_t210_load[1]; bl_dmem_desc->sec_code_off = acr_ucode_header_t210_load[5]; bl_dmem_desc->sec_code_size = acr_ucode_header_t210_load[6]; bl_dmem_desc->code_entry_point = 0; bl_dmem_desc->data_dma_base = bl_dmem_desc->code_dma_base + ((acr_ucode_header_t210_load[2]) >> 8); bl_dmem_desc->data_size = acr_ucode_header_t210_load[3]; gk20a_release_firmware(ppmu, acr_fw); acr->acr_fw = NULL; } err = pmu_exec_gen_bl(ppmu, bl_dmem_desc, 1); if (err) goto err_acr_exec; return 0; err_acr_exec: nvkm_gpuobj_unmap(&pmu->acr.acr_ucode.vma); err_map_acr_gpuobj: nvkm_gpuobj_ref(NULL, &pmu->acr.acr_ucode.obj); return err; } static void pmu_handle_acr_init_wpr_msg(struct nvkm_pmu *pmu, struct pmu_msg *msg, void *param, u32 handle, u32 status) { struct gk20a_pmu_priv *priv = param; if (msg->msg.acr.acrmsg.error_code == PMU_ACR_SUCCESS) { nv_debug(pmu, "reply PMU_ACR_CMD_ID_INIT_WPR_REGION done\n"); priv->lspmu_wpr_init_done = true; complete(&priv->lspmu_completion); } } int gm20b_pmu_init_acr(struct nvkm_pmu *pmu) { struct gk20a_pmu_priv *priv = to_gk20a_priv(pmu); struct pmu_cmd cmd; u32 seq; /* init ACR */ memset(&cmd, 0, sizeof(cmd)); cmd.hdr.unit_id = PMU_UNIT_ACR; cmd.hdr.size = PMU_CMD_HDR_SIZE + sizeof(struct pmu_acr_cmd_init_wpr_details); cmd.cmd.acr.init_wpr.cmd_type = PMU_ACR_CMD_ID_INIT_WPR_REGION; cmd.cmd.acr.init_wpr.region_id = 0x01; cmd.cmd.acr.init_wpr.wpr_offset = 0x00; nv_debug(pmu, "cmd post PMU_ACR_CMD_ID_INIT_WPR_REGION\n"); gk20a_pmu_cmd_post(pmu, &cmd, NULL, NULL, PMU_COMMAND_QUEUE_HPQ, pmu_handle_acr_init_wpr_msg, priv, &seq, ~0); return 0; } static void pmu_handle_fecs_boot_acr_msg(struct nvkm_pmu *pmu, struct pmu_msg *msg, void *param, u32 handle, u32 status) { struct gk20a_pmu_priv *priv = param; if (msg->msg.acr.acrmsg.falcon_id == LSF_FALCON_ID_FECS) { nv_debug(pmu, "reply PMU_ACR_CMD_ID_BOOTSTRAP_FALCON\n"); priv->recovery_in_progress = false; complete(&priv->lspmu_completion); } nv_debug(pmu, "response code = %x\n", msg->msg.acr.acrmsg.falcon_id); } int gm20b_pmu_load_lsf(struct nvkm_pmu *pmu, u8 falcon_id) { struct gk20a_pmu_priv *priv = to_gk20a_priv(pmu); struct pmu_cmd cmd; u32 seq; nv_debug(pmu, "wprinit status = %x\n", priv->lspmu_wpr_init_done); if (!priv->lspmu_wpr_init_done) { nv_error(pmu, "lspmu WPR init not done\n"); return -EAGAIN; } /* send message to load FECS falcon */ memset(&cmd, 0, sizeof(struct pmu_cmd)); cmd.hdr.unit_id = PMU_UNIT_ACR; cmd.hdr.size = PMU_CMD_HDR_SIZE + sizeof(struct pmu_acr_cmd_bootstrap_falcon); cmd.cmd.acr.bootstrap_falcon.cmd_type = PMU_ACR_CMD_ID_BOOTSTRAP_FALCON; cmd.cmd.acr.bootstrap_falcon.flags = PMU_ACR_CMD_BOOTSTRAP_FALCON_FLAGS_RESET_YES; cmd.cmd.acr.bootstrap_falcon.falcon_id = falcon_id; nv_debug(pmu, "cmd post PMU_ACR_CMD_ID_BOOTSTRAP_FALCON\n"); gk20a_pmu_cmd_post(pmu, &cmd, NULL, NULL, PMU_COMMAND_QUEUE_HPQ, pmu_handle_fecs_boot_acr_msg, priv, &seq, ~0); return 0; } int gm20b_boot_fecs(struct nvkm_pmu *pmu) { struct gk20a_pmu_priv *priv = to_gk20a_priv(pmu); int ret; priv->recovery_in_progress = true; wait_for_completion_timeout(&priv->lspmu_completion, usecs_to_jiffies(50)); if (!priv->lspmu_wpr_init_done) { nv_error(pmu, "lspmu wpr init not completed, timeout\n"); return -ETIMEDOUT; } reinit_completion(&priv->lspmu_completion); ret = gm20b_pmu_load_lsf(pmu, LSF_FALCON_ID_FECS); if (ret) { nv_error(pmu, "loading/booting LSF falcon failed\n"); return ret; } wait_for_completion_timeout(&priv->lspmu_completion, msecs_to_jiffies(100)); if (priv->recovery_in_progress) { nv_error(pmu, "recovery not completed, timeout\n"); return -ETIMEDOUT; } return 0; } int gm20b_boot_secure(struct nvkm_pmu *ppmu) { struct gk20a_pmu_priv *priv = to_gk20a_priv(ppmu); int ret; ret = gm20b_bootstrap_hs_flcn(ppmu); if (ret) { nv_error(ppmu, "%s failed\n", __func__); goto error; } ppmu->cold_boot = false; /* Have to re-init the idle count ctrl after secure boot */ gk20a_pmu_dvfs_init(priv); return ret; error: nvkm_gpuobj_unmap(&priv->seq_buf.vma); nvkm_gpuobj_ref(NULL, &priv->seq_buf.obj); nvkm_gpuobj_unmap(&priv->trace_buf.vma); nvkm_gpuobj_ref(NULL, &priv->trace_buf.obj); nvkm_gpuobj_unmap(&priv->acr.acr_ucode.vma); nvkm_gpuobj_ref(NULL, &priv->acr.acr_ucode.obj); nvkm_gpuobj_unmap(&priv->acr.hsbl_ucode.vma); nvkm_gpuobj_ref(NULL, &priv->acr.hsbl_ucode.obj); return ret; } extern struct gk20a_pmu_dvfs_data gk20a_dvfs_data; static int gm20b_pmu_ctor(struct nvkm_object *parent, struct nvkm_object *engine, struct nvkm_oclass *oclass, void *data, u32 size, struct nvkm_object **pobject) { struct gk20a_pmu_priv *priv; int ret, i; struct nvkm_pmu *ppmu; ret = nvkm_pmu_create(parent, engine, oclass, &priv); *pobject = nv_object(priv); if (ret) return ret; priv->pmu_chip_data = kzalloc(sizeof(struct pmu_gk20a_data), GFP_KERNEL); if (!priv->pmu_chip_data) { nv_error(priv, "failed to allocate mem for chip data\n"); return -ENOMEM; } priv->mutex_cnt = MUTEX_CNT; priv->mutex = kzalloc(priv->mutex_cnt * sizeof(struct pmu_mutex), GFP_KERNEL); if (!priv->mutex) { nv_error(priv, "alloc for pmu_mutexes failed\n"); return -ENOMEM; } for (i = 0; i < priv->mutex_cnt; i++) priv->mutex[i].index = i; priv->seq = kzalloc(PMU_MAX_NUM_SEQUENCES * sizeof(struct pmu_sequence), GFP_KERNEL); if (!priv->seq) { nv_error(priv, "alloc for sequences failed\n"); kfree(priv->mutex); return -ENOMEM; } ppmu = &priv->base; mc = ioremap(TEGRA_MC_BASE, 0x00000d00); ppmu->cold_boot = true; priv->allow_elpg = true; nv_subdev(ppmu)->intr = gk20a_pmu_intr; priv->data = &gk20a_dvfs_data; nvkm_alarm_init(&priv->alarm, gk20a_pmu_dvfs_work); mutex_init(&priv->isr_mutex); mutex_init(&priv->allow_elpg_mutex); init_completion(&priv->lspmu_completion); init_completion(&priv->elpg_off_completion); init_completion(&priv->elpg_on_completion); init_completion(&ppmu->gr_init); init_completion(&priv->zbc_save_done); ret = gm20b_prepare_ucode_blob(ppmu); if (ret) nv_error(ppmu, "prepare ucode failed\n"); ret = gk20a_pmu_debugfs_register(priv); if (ret) nv_error(ppmu, "debugfs register failed\n"); return ret; } static int gm20b_pmu_fini(struct nvkm_object *object, bool suspend) { struct gk20a_pmu_priv *priv = (void *)object; struct nvkm_mc *pmc = nvkm_mc(object); struct nvkm_pmu *pmu = &priv->base; nvkm_timer_alarm_cancel(priv, &priv->alarm); if (suspend) { cancel_work_sync(&priv->base.recv.work); cancel_work_sync(&priv->pg_init); mutex_lock(&priv->isr_mutex); gk20a_pmu_enable(priv, pmc, false); priv->isr_enabled = false; mutex_unlock(&priv->isr_mutex); mutex_lock(&priv->elpg_mutex); priv->elpg_disable_depth = 0; mutex_unlock(&priv->elpg_mutex); priv->pmu_state = PMU_STATE_OFF; mutex_lock(&priv->clk_gating_mutex); priv->clk_gating_disable_depth = 0; mutex_unlock(&priv->clk_gating_mutex); pmu->elcg_enabled = false; pmu->slcg_enabled = false; pmu->blcg_enabled = false; priv->pmu_ready = false; priv->out_of_reset = false; pmu->cold_boot = true; priv->lspmu_wpr_init_done = false; nv_wr32(priv, 0x10a014, 0x00000060); } else { mutex_lock(&priv->isr_mutex); gk20a_pmu_enable(priv, pmc, true); pmu_reset(pmu, pmc); mutex_unlock(&priv->isr_mutex); } return nvkm_subdev_fini(&priv->base.base, suspend); } static void gm20b_pmu_dtor(struct nvkm_object *object) { struct nvkm_pmu *ppmu = (void *)object; struct gk20a_pmu_priv *pmu = to_gk20a_priv(ppmu); nvkm_gpuobj_unmap(&pmu->acr.ucode_blob.vma); nvkm_gpuobj_ref(NULL, &pmu->acr.ucode_blob.obj); nvkm_vm_ref(NULL, &pmu->pmuvm.vm, pmu->pmuvm.pgd); nvkm_gpuobj_ref(NULL, &pmu->pmuvm.pgd); nvkm_gpuobj_ref(NULL, &pmu->pmuvm.mem); nvkm_gpuobj_unmap(&pmu->acr.acr_ucode.vma); nvkm_gpuobj_ref(NULL, &pmu->acr.acr_ucode.obj); nvkm_gpuobj_unmap(&pmu->acr.hsbl_ucode.vma); nvkm_gpuobj_ref(NULL, &pmu->acr.hsbl_ucode.obj); ppmu->cold_boot = true; gk20a_pmu_allocator_destroy(&pmu->dmem); gk20a_pmu_debugfs_unregister(pmu); mutex_destroy(&pmu->allow_elpg_mutex); kfree(pmu->mutex); kfree(pmu->seq); kfree(pmu->pmu_chip_data); } static int gm20b_pmu_init(struct nvkm_object *object) { struct nvkm_pmu *ppmu = (void *)object; struct gk20a_pmu_priv *priv = to_gk20a_priv(ppmu); int ret; ret = nvkm_subdev_init(&ppmu->base); if (ret) { nv_error(ppmu, "subdev init failed\n"); return ret; } mutex_init(&priv->pmu_copy_lock); mutex_init(&priv->pmu_seq_lock); mutex_init(&priv->elpg_mutex); mutex_init(&priv->clk_gating_mutex); reinit_completion(&priv->zbc_save_done); ppmu->secure_bootstrap = gm20b_boot_secure; ppmu->boot_fecs = gm20b_boot_fecs; ppmu->enable_elpg = gk20a_pmu_enable_elpg; ppmu->disable_elpg = gk20a_pmu_disable_elpg; ppmu->enable_clk_gating = gm20b_pmu_enable_clk_gating; ppmu->disable_clk_gating = gm20b_pmu_disable_clk_gating; ppmu->fecs_secure_boot = true; ppmu->gpccs_secure_boot = false; ppmu->elcg_enabled = true; ppmu->slcg_enabled = true; ppmu->blcg_enabled = true; priv->out_of_reset = true; priv->pmu_setup_elpg = gm20b_pmu_setup_elpg; mutex_lock(&priv->elpg_mutex); priv->elpg_disable_depth = 0; mutex_unlock(&priv->elpg_mutex); mutex_lock(&priv->clk_gating_mutex); priv->clk_gating_disable_depth = 0; mutex_unlock(&priv->clk_gating_mutex); gk20a_pmu_dvfs_init(priv); nvkm_timer_alarm(priv, PMU_DVFS_INTERVAL, &priv->alarm); return ret; } struct nvkm_oclass * gm20b_pmu_oclass = &(struct nvkm_pmu_impl) { .base.handle = NV_SUBDEV(PMU, 0x12b), .base.ofuncs = &(struct nvkm_ofuncs) { .ctor = gm20b_pmu_ctor, .dtor = gm20b_pmu_dtor, .init = gm20b_pmu_init, .fini = gm20b_pmu_fini, }, .base.handle = NV_SUBDEV(PMU, 0x12b), .acquire_mutex = gk20a_pmu_mutex_acquire, .release_mutex = gk20a_pmu_mutex_release, .save_zbc = gk20a_pmu_save_zbc, } .base;
kendling/android_kernel_google_dragon
drivers/gpu/drm/nouveau/nvkm/subdev/pmu/gm20b.c
C
gpl-2.0
85,421
<?php /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ namespace TYPO3\CMS\Extbase\Persistence\Generic\Qom; /** * Performs a logical negation of another constraint. * * To satisfy the Not constraint, the node-tuple must not satisfy constraint. * @internal only to be used within Extbase, not part of TYPO3 Core API. */ class LogicalNot implements NotInterface { /** * @var ConstraintInterface */ protected $constraint; /** * @param ConstraintInterface $constraint */ public function __construct(ConstraintInterface $constraint) { $this->constraint = $constraint; } /** * Fills an array with the names of all bound variables in the constraint * * @param array $boundVariables */ public function collectBoundVariableNames(&$boundVariables) { $this->constraint->collectBoundVariableNames($boundVariables); } /** * Gets the constraint negated by this Not constraint. * * @return ConstraintInterface the constraint; non-null */ public function getConstraint() { return $this->constraint; } }
maddy2101/TYPO3.CMS
typo3/sysext/extbase/Classes/Persistence/Generic/Qom/LogicalNot.php
PHP
gpl-2.0
1,510
@charset "utf-8"; /* CSS Document */ .datepicker { border-collapse: collapse; border: 2px solid #999; position: absolute; z-index:10;} .datepicker tr.controls th { height: 22px; font-size: 11px; } .datepicker select { font-size: 11px; } .datepicker tr.days th { height: 18px; } .datepicker tfoot td { height: 18px; text-align: center; text-transform: capitalize; } .datepicker th, .datepicker tfoot td { background: #eee; font: 10px/18px Verdana, Arial, Helvetica, sans-serif; } .datepicker th span, .datepicker tfoot td span { font-weight: bold; } .datepicker tbody td { width: 24px; height: 24px; border: 1px solid #ccc; font: 11px/22px Arial, Helvetica, sans-serif; text-align: center; background: #fff; } .datepicker tbody td.date { cursor: pointer; } .datepicker tbody td.date.over { background-color: #99ffff; } .datepicker tbody td.date.chosen { font-weight: bold; background-color: #ccffcc; }
Deanish/YUVA
wp-content/plugins/portfolio/datepicker/datepicker.css
CSS
gpl-2.0
902
/*****************************************************************************/ /* */ /* Copyright (c) 1990-2008 Morgan Stanley All rights reserved.*/ /* See .../src/LICENSE for terms of distribution. */ /* */ /* */ /*****************************************************************************/ /* * This file contains the FSA machine parser for Steve's "d" system. */ #include <a/development.h> #include <stdio.h> #include <string.h> #include <a/k.h> #include <a/fncdcls.h> #include <a/x.h> #include <a/fir.h> #undef ENTRYPOINT #define ENTRYPOINT static SUBROUTINE int VetteMachine (machine) A machine; { int i, j, len; A aobj, element, subelement, tokens; if (Et != machine->t || 1 != machine->r || 4 != machine->n ) return 1; for (i=0; i<machine->n; ++i) { if (!QA(machine->p[i])) return 2; } /* names */ aobj=(A) machine->p[0]; if (0==(len=aobj->n)) return 3; if (Et != aobj->t || 1 < aobj->r ) return 4; for (i=0; i<aobj->n; ++i) { if (!QS(aobj->p[i])) return 5; } /* tokens */ aobj=tokens=(A) machine->p[1]; if (Et != aobj->t || 1 < aobj->r || len != aobj->n ) return 6; for (i=0; i<aobj->n; ++i) { if (!QA(element=(A) aobj->p[i])) return 7; if (Et != element->t || 0 == element->n ) return 8; for (j=0; j<element->n; ++j) { if (!QA(subelement=(A) element->p[j])) return 81; if (Ct != subelement->t || 0 == subelement->n ) return 82; } } /* states */ aobj=(A) machine->p[2]; if (Et != aobj->t || 1 < aobj->r || len != aobj->n ) return 9; for (i=0; i<aobj->n; ++i) { if (!QA(element=(A) aobj->p[i])) return 10; if (It != element->t || 2 != element->r || 0 == element->n || element->d[1] != 1+((A)tokens->p[i])->n) return 11; } /* statenames */ /* Who cares? They aren't used. */ return 0; } /* gst * Cover for A entrypoint gsv() that *always* returns a vector. */ SUBROUTINE A gst( x, s) I x; C *s; { A r=(A) gsv(x,s); r->r=1; return(r); } SUBROUTINE A MakeEmptyResult( machine) A machine; { A result; result = gv(Et,3); result->p[0] = ((A)(machine->p[0]))->p[0]; result->p[1] = (I)gv(It, 0); result->p[2] = 0; return(result); } static char buffer[512]; SUBROUTINE A MakeResult( sym, s, toktype, len) I sym; char *s; I *toktype, len; { I nparts, curtype, i, idx=0, bufidx; A result, aobj, typeobj; result=gv(Et, 3); aobj = gs(Et); aobj->p[0] = sym; result->p[0] = (I) aobj; nparts=0; curtype=-1; for (i=0; i<len; ++i ) if (toktype[i] != curtype) { curtype=toktype[i]; ++nparts; } typeobj=gv(It,nparts); aobj=gv(Et,nparts); bufidx = 0; curtype=-1; for (i=0; i<=len; ++i) { if ( i == len || toktype[i] != curtype ) if (i == len || -1 != curtype) { buffer[bufidx++]='\0'; aobj->p[idx++] = (I) gst(0, buffer); bufidx=0; } typeobj->p[idx]=curtype=toktype[i]; buffer[bufidx++] = s[i]; } result->p[1] = (I) typeobj; result->p[2] = (I) aobj; return(result); } static char tokenstr[512]; static int tokentype[512]; static int tokencount; SUBROUTINE A RunMachine( s, forms, tokenobj, statesobj) char *s; A forms, tokenobj, statesobj; { A result=NULL, curtoken; I *tokens, *statemat, slen, tklen, formno, i, j, idx, nr, nc, state; char *tokes, *s1; slen = strlen((DEV_STRARG)s); tokens = ma(slen); for (formno=0; NULL == result && formno<forms->n ; ++formno) { curtoken=(A) tokenobj->p[formno]; statemat=((A) statesobj->p[formno])->p; nr=((A) statesobj->p[formno])->d[0]; nc=((A) statesobj->p[formno])->d[1]; tokencount=curtoken->n; tokenstr[0]='\0'; idx=0; for (i=0; i<tokencount ; ++i ) { tokes = (char *) ((A) curtoken->p[i])->p; tklen=strlen((DEV_STRARG)tokes); for (j=0; j<tklen; ++j) tokentype[idx++]=i; strcat( (DEV_STRARG)tokenstr, (DEV_STRARG)tokes); } state=0; for (i=0; -1 != state && i<slen; ++i) { if (NULL==(s1=(char *)strchr((DEV_STRARG)tokenstr, s[i]))) state=-1; else { tokens[i] = tokentype[s1-tokenstr]; state = statemat[tokens[i]+state*nc]; if (nr<=state) state=-1; } } if ( -1 != state && -1 != statemat[state*nc+nc-1]) result=MakeResult( forms->p[formno], s, tokens, slen); } if (NULL==result) { result=gv(Et,3); result->p[0]=(I) gv(Et,0); result->p[1]=(I) gv(Et,0); result->p[2]=(I) gv(Et,0); } mf(tokens); return(result); } ENTRYPOINT A ep_cform(s, machine) char *s; A machine; { A result; if (VetteMachine( machine)) ERRMSG("machine"); if (0==strlen((DEV_STRARG)s)) result=MakeEmptyResult(machine); else result=RunMachine(s,(A)machine->p[0],(A)machine->p[1],(A)machine->p[2]); return(result); } void cformInstall() { CX saveCx=Cx; Cx=cx("c"); install((PFI)ep_cform, "form", A_, 2, CP, A_,0,0,0,0,0,0); Cx=saveCx; return; }
dbremner/aplusdev
src/cxc/cform.c
C
gpl-2.0
5,093
#ifndef NO_STREAM #define Uses_TMenuView #define Uses_TStreamableClass #include <tv.h> __link( RView ) TStreamableClass CLY_EXPORT RMenuView( TMenuView::name, TMenuView::build, __DELTA(TMenuView) ); #endif
qunying/tvision
stream/smenuvie.cc
C++
gpl-2.0
292
# Rowley CrossWorks ARM Project for wolfSSL and wolfCrypt This directory contains a CrossWorks solution named wolfssl.hzp. Inside are three projects: 1. libwolfssl: This generates a library file named "libwolfssl_ARM_Debug/libwolfssl_v7em_t_le_eabi.a" 2. benchmark: This is a sample benchmark application. It runs the "benchmark_test" suite repeatedly until a failure occurs. 3. test: This is a sample test application. It runs "wolfcrypt_test" suite suite repeatedly until a failure occurs. # Prerequisites +You will need to install the "Freescale Kinetis CPU Support Package" and "ARM CPU Support Package" in the Rowley Package Manager under Tools -> Package Manager. # Hardware Support All hardware functions are defined in `kinetis_hw.c` and are currently setup for a Freescale Kinetis K64 Coretx-M4 microcontroller. This file can be customized to work with other Kinetis microcontrollers by editing the top part of the file. Testing for this project was done with the Freescale Kinetis `MK64FN1M0xxx12` using the `TWR-K64F120M`. To build for the `TWR-K64F120M` or `FRDM-K64F`, define `WOLFSSL_FRDM_K64` in the Preprocessor Definitions section of CrossStudio, or define it in "user_settings.h". To create support for a new ARM microcontroller the functions in `hw.h` will need to be implemented. Also you will need to configure the ARM Architecture and ARM Core Type in the "Solution Properties" -> "ARM". Also the "Target Processor" in each of the projects ("Project Properties" -> "Target Processor") ## Hardware Crypto Acceleration To enable NXP/Freescale MMCAU: 1. [Download the MMCAU library](http://www.freescale.com/products/arm-processors/kinetis-cortex-m/k-series/k7x-glcd-mcus/crypto-acceleration-unit-cau-and-mmcau-software-library:CAUAP). 2. Copy the `lib_mmcau.a` and `cau_api.h` files into the project. 3. Define `USE_NXP_MMCAU` to enable in `user_settings.h`. 4. Add the `lib_mmcau.a` file to `Source Files` in the application project. 5. Open the wolfssl_ltc.hzp CrossWorks project 6. Build and run To enable the NXP/Freescale MMCAU and/or LTC: 1. [Download the NXP KSDK 2.0](https://nxp.flexnetoperations.com/control/frse/download?agree=Accept&element=7353807) 2. Copy the following folders into IDE/ROWLEY-CROSSWORKS-ARM: drivers, mmcau_2.0.0 and CMSIS. 3. Copy the following files into IDE/ROWLEY-CROSSWORKS-ARM: clock_config.c, clock_config.h, fsl_debug_console.c, fsl_debug_console.h, fsl_device_registers.h, system_MK82F25615.c, system_MK82F25615.h, MK82F25615.h and MK82F25615_features.h. 4. Define `USE_NXP_LTX` to enable in `user_settings.h`. 5. Open the wolfssl_ltc.hzp CrossWorks project 6. Build and run # Project Files * `arm_startup.c`: Handles startup from `reset_handler`. Disabled watchdog, initializes sections, initializes heap, starts hardware and starts main. * `benchmark_main.c`: The main function entrypoint for benchmark application. * `hw.h`: The hardware API interface. These hardware interface functions are required for all platforms. * `kinetis_hw.c`: The most basic hardware implementation required for Kinetis. * `test_main.c`: The main function entrypoint for test application. * `user_libc.c`: Defines stubs for functions required by libc. It also wraps hardware functions for UART, RTC and Random Number Generator (RNG). * `user_settings.h`: This is the custom user configuration file for WolfSSL. # Functions required by the WolfSSL Library If you are writing your own application, the following functions need to be implemented to support the WolfSSL library: * `double current_time(int reset)`: Returns a double as seconds.milliseconds. * `int custom_rand_generate(void)`: Returns a 32-bit randomly generated number.
kaleb-himes/wolfssl
IDE/ROWLEY-CROSSWORKS-ARM/README.md
Markdown
gpl-2.0
3,699
/* * jQuery One Page Nav Plugin * http://github.com/davist11/jQuery-One-Page-Nav * * Copyright (c) 2010 Trevor Davis (http://trevordavis.net) * Dual licensed under the MIT and GPL licenses. * Uses the same license as jQuery, see: * http://jquery.org/license * * @version 0.6 */ (function(e){e.fn.onePageNav=function(j){var g=e.extend({},e.fn.onePageNav.defaults,j),c={};c.sections={};c.bindNav=function(b,d,a){var f=b.parent(),h=b.attr("href"),i=e(window);if(!f.hasClass(a.currentClass)){a.begin&&a.begin();c.adjustNav(d,f,a.currentClass);i.unbind(".onePageNav");e.scrollTo(h,a.scrollSpeed,{onAfter:function(){if(a.changeHash)window.location.hash=h;i.bind("scroll.onePageNav",function(){c.scrollChange(d,a.currentClass)});a.end&&a.end()}})}};c.adjustNav=function(b,d,a){b.find("."+ a).removeClass(a);d.addClass(a)};c.getPositions=function(b){b.find("a").each(function(){var d=e(this).attr("href"),a=e(d).offset();a=a.top;c.sections[d.substr(1)]=Math.round(a)})};c.getSection=function(b){var d="",a=Math.round(e(window).height()/2);for(var f in c.sections)if(c.sections[f]-a<b)d=f;return d};c.scrollChange=function(b,d){c.getPositions(b);var a=e(window).scrollTop();a=c.getSection(a);a!==""&&c.adjustNav(b,b.find("a[href=#"+a+"]").parent(),d)};c.init=function(b,d){b.find("a").bind("click", function(f){c.bindNav(e(this),b,d);f.preventDefault()});c.getPositions(b);var a=false;e(window).bind("scroll.onePageNav",function(){a=true});setInterval(function(){if(a){a=false;c.scrollChange(b,d.currentClass)}},250)};return this.each(function(){var b=e(this),d=e.meta?e.extend({},g,b.data()):g;c.init(b,d)})};e.fn.onePageNav.defaults={currentClass:"current",changeHash:false,scrollSpeed:750,begin:false,end:false}})(jQuery);
alvarpoon/tti_ar_2013
wp-content/themes/twentyten/js/jquery.nav.min.js
JavaScript
gpl-2.0
1,727
<?php //if ( ! defined( 'ABSPATH' ) ) exit; // ///** // * Class NF_Field_File // */ //class NF_Fields_File extends NF_Abstracts_Field //{ // protected $_name = 'file'; // // protected $_nicename = 'File'; // // protected $_section = ''; // // protected $_type = 'file'; // // protected $_templates = array( 'file', 'textbox', 'input' ); // // public function __construct() // { // parent::__construct(); // // $this->_nicename = __( 'File', 'ninja-forms' ); // } //}
KESBS/accelerate
wp-content/plugins/ninja-forms/includes/Fields/File.php
PHP
gpl-2.0
505
<?php /** * CacheTable * * This class has been auto-generated by the Doctrine ORM Framework */ class CacheTable extends PluginCacheTable { /** * Returns an instance of this class. * * @return object CacheTable */ public static function getInstance() { return Doctrine_Core::getTable('Cache'); } }
gwenaelCF/eveGCF
lib/model/doctrine/generic/CacheTable.class.php
PHP
gpl-2.0
346
class View_conference_rating < Momomoto::Table end
gaudenz/pentabarf-dc13
rails/app/models/view_conference_rating.rb
Ruby
gpl-2.0
52
/*----------------------------------------------------------------------------------*/ //This code is part of a larger project whose main purpose is to entretain either // //by working on it and helping it be better or by playing it in it's actual state // // // //Copyright (C) 2011 Three Legged Studio // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2, or (at your option) // // any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software Foundation, // // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // // // You can contact us at projectpgz.blogspot.com // /*----------------------------------------------------------------------------------*/ #pragma once #ifndef __TOOLMENU_H__ #define __TOOLMENU_H__ #include "GameMenuController.h" #include "GameMenuTextItemS.h" #include "GameMenuItemS.h" #include "Stamp.h" #include "PGZGame.h" #include <vector> //Centro real 112,96 //Centro para que se dibuje bien 112 - 16/2 , 96 -16/2 //Radio 60 #define Pi 3.1415f class ToolMenu : public GameMenuController { protected: vector<GameMenuItemS*>* iTools; GameMenuTextItem * iText; vector<int> idTools; TileFont* menuFont; int centroX; int centroY; int radio; public: ToolMenu(int x, int y, Game* game, GameState* gstate,int centroX = 104, int centroY = 88, int radio = 60); ~ToolMenu(); void launch(); void onStep(); void onRender(); void onChosen(iSelectable* selectable); void onCancelled(iSelectable* selectable); void onStartPressed(iSelectable* selectable); iSelectable* getMandatorySelectable(iSelectable* slc, Direction dir); iSelectable* getAlternativeSelectable(iSelectable* slc, Direction dir); }; #endif __TOOLMENU_H__
rafadelahoz/projectpgz-dev
interprete/source/include/ToolMenu.h
C
gpl-2.0
2,496
/* * fs/cifs/connect.c * * Copyright (C) International Business Machines Corp., 2002,2005 * Author(s): Steve French ([email protected]) * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/fs.h> #include <linux/net.h> #include <linux/string.h> #include <linux/list.h> #include <linux/wait.h> #include <linux/ipv6.h> #include <linux/pagemap.h> #include <linux/ctype.h> #include <linux/utsname.h> #include <linux/mempool.h> #include <linux/delay.h> #include <asm/uaccess.h> #include <asm/processor.h> #include "cifspdu.h" #include "cifsglob.h" #include "cifsproto.h" #include "cifs_unicode.h" #include "cifs_debug.h" #include "cifs_fs_sb.h" #include "ntlmssp.h" #include "nterr.h" #include "rfc1002pdu.h" #define CIFS_PORT 445 #define RFC1001_PORT 139 extern void SMBencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24); extern void SMBNTencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24); extern mempool_t *cifs_req_poolp; struct smb_vol { char *username; char *password; char *domainname; char *UNC; char *UNCip; char *in6_addr; /* ipv6 address as human readable form of in6_addr */ char *iocharset; /* local code page for mapping to and from Unicode */ char source_rfc1001_name[16]; /* netbios name of client */ uid_t linux_uid; gid_t linux_gid; mode_t file_mode; mode_t dir_mode; unsigned rw:1; unsigned retry:1; unsigned intr:1; unsigned setuids:1; unsigned noperm:1; unsigned no_psx_acl:1; /* set if posix acl support should be disabled */ unsigned no_xattr:1; /* set if xattr (EA) support should be disabled*/ unsigned server_ino:1; /* use inode numbers from server ie UniqueId */ unsigned direct_io:1; unsigned remap:1; /* set to remap seven reserved chars in filenames */ unsigned int rsize; unsigned int wsize; unsigned int sockopt; unsigned short int port; }; static int ipv4_connect(struct sockaddr_in *psin_server, struct socket **csocket, char * netb_name); static int ipv6_connect(struct sockaddr_in6 *psin_server, struct socket **csocket); /* * cifs tcp session reconnection * * mark tcp session as reconnecting so temporarily locked * mark all smb sessions as reconnecting for tcp session * reconnect tcp session * wake up waiters on reconnection? - (not needed currently) */ int cifs_reconnect(struct TCP_Server_Info *server) { int rc = 0; struct list_head *tmp; struct cifsSesInfo *ses; struct cifsTconInfo *tcon; struct mid_q_entry * mid_entry; spin_lock(&GlobalMid_Lock); if(server->tcpStatus == CifsExiting) { /* the demux thread will exit normally next time through the loop */ spin_unlock(&GlobalMid_Lock); return rc; } else server->tcpStatus = CifsNeedReconnect; spin_unlock(&GlobalMid_Lock); server->maxBuf = 0; cFYI(1, ("Reconnecting tcp session")); /* before reconnecting the tcp session, mark the smb session (uid) and the tid bad so they are not used until reconnected */ read_lock(&GlobalSMBSeslock); list_for_each(tmp, &GlobalSMBSessionList) { ses = list_entry(tmp, struct cifsSesInfo, cifsSessionList); if (ses->server) { if (ses->server == server) { ses->status = CifsNeedReconnect; ses->ipc_tid = 0; } } /* else tcp and smb sessions need reconnection */ } list_for_each(tmp, &GlobalTreeConnectionList) { tcon = list_entry(tmp, struct cifsTconInfo, cifsConnectionList); if((tcon) && (tcon->ses) && (tcon->ses->server == server)) { tcon->tidStatus = CifsNeedReconnect; } } read_unlock(&GlobalSMBSeslock); /* do not want to be sending data on a socket we are freeing */ down(&server->tcpSem); if(server->ssocket) { cFYI(1,("State: 0x%x Flags: 0x%lx", server->ssocket->state, server->ssocket->flags)); server->ssocket->ops->shutdown(server->ssocket,SEND_SHUTDOWN); cFYI(1,("Post shutdown state: 0x%x Flags: 0x%lx", server->ssocket->state, server->ssocket->flags)); sock_release(server->ssocket); server->ssocket = NULL; } spin_lock(&GlobalMid_Lock); list_for_each(tmp, &server->pending_mid_q) { mid_entry = list_entry(tmp, struct mid_q_entry, qhead); if(mid_entry) { if(mid_entry->midState == MID_REQUEST_SUBMITTED) { /* Mark other intransit requests as needing retry so we do not immediately mark the session bad again (ie after we reconnect below) as they timeout too */ mid_entry->midState = MID_RETRY_NEEDED; } } } spin_unlock(&GlobalMid_Lock); up(&server->tcpSem); while ((server->tcpStatus != CifsExiting) && (server->tcpStatus != CifsGood)) { if(server->protocolType == IPV6) { rc = ipv6_connect(&server->addr.sockAddr6,&server->ssocket); } else { rc = ipv4_connect(&server->addr.sockAddr, &server->ssocket, server->workstation_RFC1001_name); } if(rc) { msleep(3000); } else { atomic_inc(&tcpSesReconnectCount); spin_lock(&GlobalMid_Lock); if(server->tcpStatus != CifsExiting) server->tcpStatus = CifsGood; server->sequence_number = 0; spin_unlock(&GlobalMid_Lock); /* atomic_set(&server->inFlight,0);*/ wake_up(&server->response_q); } } return rc; } /* return codes: 0 not a transact2, or all data present >0 transact2 with that much data missing -EINVAL = invalid transact2 */ static int check2ndT2(struct smb_hdr * pSMB, unsigned int maxBufSize) { struct smb_t2_rsp * pSMBt; int total_data_size; int data_in_this_rsp; int remaining; if(pSMB->Command != SMB_COM_TRANSACTION2) return 0; /* check for plausible wct, bcc and t2 data and parm sizes */ /* check for parm and data offset going beyond end of smb */ if(pSMB->WordCount != 10) { /* coalesce_t2 depends on this */ cFYI(1,("invalid transact2 word count")); return -EINVAL; } pSMBt = (struct smb_t2_rsp *)pSMB; total_data_size = le16_to_cpu(pSMBt->t2_rsp.TotalDataCount); data_in_this_rsp = le16_to_cpu(pSMBt->t2_rsp.DataCount); remaining = total_data_size - data_in_this_rsp; if(remaining == 0) return 0; else if(remaining < 0) { cFYI(1,("total data %d smaller than data in frame %d", total_data_size, data_in_this_rsp)); return -EINVAL; } else { cFYI(1,("missing %d bytes from transact2, check next response", remaining)); if(total_data_size > maxBufSize) { cERROR(1,("TotalDataSize %d is over maximum buffer %d", total_data_size,maxBufSize)); return -EINVAL; } return remaining; } } static int coalesce_t2(struct smb_hdr * psecond, struct smb_hdr *pTargetSMB) { struct smb_t2_rsp *pSMB2 = (struct smb_t2_rsp *)psecond; struct smb_t2_rsp *pSMBt = (struct smb_t2_rsp *)pTargetSMB; int total_data_size; int total_in_buf; int remaining; int total_in_buf2; char * data_area_of_target; char * data_area_of_buf2; __u16 byte_count; total_data_size = le16_to_cpu(pSMBt->t2_rsp.TotalDataCount); if(total_data_size != le16_to_cpu(pSMB2->t2_rsp.TotalDataCount)) { cFYI(1,("total data sizes of primary and secondary t2 differ")); } total_in_buf = le16_to_cpu(pSMBt->t2_rsp.DataCount); remaining = total_data_size - total_in_buf; if(remaining < 0) return -EINVAL; if(remaining == 0) /* nothing to do, ignore */ return 0; total_in_buf2 = le16_to_cpu(pSMB2->t2_rsp.DataCount); if(remaining < total_in_buf2) { cFYI(1,("transact2 2nd response contains too much data")); } /* find end of first SMB data area */ data_area_of_target = (char *)&pSMBt->hdr.Protocol + le16_to_cpu(pSMBt->t2_rsp.DataOffset); /* validate target area */ data_area_of_buf2 = (char *) &pSMB2->hdr.Protocol + le16_to_cpu(pSMB2->t2_rsp.DataOffset); data_area_of_target += total_in_buf; /* copy second buffer into end of first buffer */ memcpy(data_area_of_target,data_area_of_buf2,total_in_buf2); total_in_buf += total_in_buf2; pSMBt->t2_rsp.DataCount = cpu_to_le16(total_in_buf); byte_count = le16_to_cpu(BCC_LE(pTargetSMB)); byte_count += total_in_buf2; BCC_LE(pTargetSMB) = cpu_to_le16(byte_count); byte_count = be32_to_cpu(pTargetSMB->smb_buf_length); byte_count += total_in_buf2; /* BB also add check that we are not beyond maximum buffer size */ pTargetSMB->smb_buf_length = cpu_to_be32(byte_count); if(remaining == total_in_buf2) { cFYI(1,("found the last secondary response")); return 0; /* we are done */ } else /* more responses to go */ return 1; } static int cifs_demultiplex_thread(struct TCP_Server_Info *server) { int length; unsigned int pdu_length, total_read; struct smb_hdr *smb_buffer = NULL; struct smb_hdr *bigbuf = NULL; struct smb_hdr *smallbuf = NULL; struct msghdr smb_msg; struct kvec iov; struct socket *csocket = server->ssocket; struct list_head *tmp; struct cifsSesInfo *ses; struct task_struct *task_to_wake = NULL; struct mid_q_entry *mid_entry; char *temp; int isLargeBuf = FALSE; int isMultiRsp; int reconnect; daemonize("cifsd"); allow_signal(SIGKILL); current->flags |= PF_MEMALLOC; server->tsk = current; /* save process info to wake at shutdown */ cFYI(1, ("Demultiplex PID: %d", current->pid)); write_lock(&GlobalSMBSeslock); atomic_inc(&tcpSesAllocCount); length = tcpSesAllocCount.counter; write_unlock(&GlobalSMBSeslock); if(length > 1) { mempool_resize(cifs_req_poolp, length + cifs_min_rcv, GFP_KERNEL); } while (server->tcpStatus != CifsExiting) { if (bigbuf == NULL) { bigbuf = cifs_buf_get(); if(bigbuf == NULL) { cERROR(1,("No memory for large SMB response")); msleep(3000); /* retry will check if exiting */ continue; } } else if(isLargeBuf) { /* we are reusing a dirtry large buf, clear its start */ memset(bigbuf, 0, sizeof (struct smb_hdr)); } if (smallbuf == NULL) { smallbuf = cifs_small_buf_get(); if(smallbuf == NULL) { cERROR(1,("No memory for SMB response")); msleep(1000); /* retry will check if exiting */ continue; } /* beginning of smb buffer is cleared in our buf_get */ } else /* if existing small buf clear beginning */ memset(smallbuf, 0, sizeof (struct smb_hdr)); isLargeBuf = FALSE; isMultiRsp = FALSE; smb_buffer = smallbuf; iov.iov_base = smb_buffer; iov.iov_len = 4; smb_msg.msg_control = NULL; smb_msg.msg_controllen = 0; length = kernel_recvmsg(csocket, &smb_msg, &iov, 1, 4, 0 /* BB see socket.h flags */); if(server->tcpStatus == CifsExiting) { break; } else if (server->tcpStatus == CifsNeedReconnect) { cFYI(1,("Reconnect after server stopped responding")); cifs_reconnect(server); cFYI(1,("call to reconnect done")); csocket = server->ssocket; continue; } else if ((length == -ERESTARTSYS) || (length == -EAGAIN)) { msleep(1); /* minimum sleep to prevent looping allowing socket to clear and app threads to set tcpStatus CifsNeedReconnect if server hung */ continue; } else if (length <= 0) { if(server->tcpStatus == CifsNew) { cFYI(1,("tcp session abend after SMBnegprot")); /* some servers kill the TCP session rather than returning an SMB negprot error, in which case reconnecting here is not going to help, and so simply return error to mount */ break; } if(length == -EINTR) { cFYI(1,("cifsd thread killed")); break; } cFYI(1,("Reconnect after unexpected peek error %d", length)); cifs_reconnect(server); csocket = server->ssocket; wake_up(&server->response_q); continue; } else if (length < 4) { cFYI(1, ("Frame under four bytes received (%d bytes long)", length)); cifs_reconnect(server); csocket = server->ssocket; wake_up(&server->response_q); continue; } /* the right amount was read from socket - 4 bytes */ pdu_length = ntohl(smb_buffer->smb_buf_length); cFYI(1,("rfc1002 length(big endian)0x%x)", pdu_length+4)); temp = (char *) smb_buffer; if (temp[0] == (char) RFC1002_SESSION_KEEP_ALIVE) { continue; } else if (temp[0] == (char)RFC1002_POSITIVE_SESSION_RESPONSE) { cFYI(1,("Good RFC 1002 session rsp")); continue; } else if (temp[0] == (char)RFC1002_NEGATIVE_SESSION_RESPONSE) { /* we get this from Windows 98 instead of an error on SMB negprot response */ cFYI(1,("Negative RFC1002 Session Response Error 0x%x)", temp[4])); if(server->tcpStatus == CifsNew) { /* if nack on negprot (rather than ret of smb negprot error) reconnecting not going to help, ret error to mount */ break; } else { /* give server a second to clean up before reconnect attempt */ msleep(1000); /* always try 445 first on reconnect since we get NACK on some if we ever connected to port 139 (the NACK is since we do not begin with RFC1001 session initialize frame) */ server->addr.sockAddr.sin_port = htons(CIFS_PORT); cifs_reconnect(server); csocket = server->ssocket; wake_up(&server->response_q); continue; } } else if (temp[0] != (char) 0) { cERROR(1,("Unknown RFC 1002 frame")); cifs_dump_mem(" Received Data: ", temp, length); cifs_reconnect(server); csocket = server->ssocket; continue; } /* else we have an SMB response */ if((pdu_length > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4) || (pdu_length < sizeof (struct smb_hdr) - 1 - 4)) { cERROR(1, ("Invalid size SMB length %d pdu_length %d", length, pdu_length+4)); cifs_reconnect(server); csocket = server->ssocket; wake_up(&server->response_q); continue; } /* else length ok */ reconnect = 0; if(pdu_length > MAX_CIFS_HDR_SIZE - 4) { isLargeBuf = TRUE; memcpy(bigbuf, smallbuf, 4); smb_buffer = bigbuf; } length = 0; iov.iov_base = 4 + (char *)smb_buffer; iov.iov_len = pdu_length; for (total_read = 0; total_read < pdu_length; total_read += length) { length = kernel_recvmsg(csocket, &smb_msg, &iov, 1, pdu_length - total_read, 0); if((server->tcpStatus == CifsExiting) || (length == -EINTR)) { /* then will exit */ reconnect = 2; break; } else if (server->tcpStatus == CifsNeedReconnect) { cifs_reconnect(server); csocket = server->ssocket; /* Reconnect wakes up rspns q */ /* Now we will reread sock */ reconnect = 1; break; } else if ((length == -ERESTARTSYS) || (length == -EAGAIN)) { msleep(1); /* minimum sleep to prevent looping, allowing socket to clear and app threads to set tcpStatus CifsNeedReconnect if server hung*/ continue; } else if (length <= 0) { cERROR(1,("Received no data, expecting %d", pdu_length - total_read)); cifs_reconnect(server); csocket = server->ssocket; reconnect = 1; break; } } if(reconnect == 2) break; else if(reconnect == 1) continue; length += 4; /* account for rfc1002 hdr */ dump_smb(smb_buffer, length); if (checkSMB (smb_buffer, smb_buffer->Mid, total_read+4)) { cERROR(1, ("Bad SMB Received ")); continue; } task_to_wake = NULL; spin_lock(&GlobalMid_Lock); list_for_each(tmp, &server->pending_mid_q) { mid_entry = list_entry(tmp, struct mid_q_entry, qhead); if ((mid_entry->mid == smb_buffer->Mid) && (mid_entry->midState == MID_REQUEST_SUBMITTED) && (mid_entry->command == smb_buffer->Command)) { if(check2ndT2(smb_buffer,server->maxBuf) > 0) { /* We have a multipart transact2 resp */ isMultiRsp = TRUE; if(mid_entry->resp_buf) { /* merge response - fix up 1st*/ if(coalesce_t2(smb_buffer, mid_entry->resp_buf)) { break; } else { /* all parts received */ goto multi_t2_fnd; } } else { if(!isLargeBuf) { cERROR(1,("1st trans2 resp needs bigbuf")); /* BB maybe we can fix this up, switch to already allocated large buffer? */ } else { /* Have first buffer */ mid_entry->resp_buf = smb_buffer; mid_entry->largeBuf = 1; bigbuf = NULL; } } break; } mid_entry->resp_buf = smb_buffer; if(isLargeBuf) mid_entry->largeBuf = 1; else mid_entry->largeBuf = 0; multi_t2_fnd: task_to_wake = mid_entry->tsk; mid_entry->midState = MID_RESPONSE_RECEIVED; break; } } spin_unlock(&GlobalMid_Lock); if (task_to_wake) { /* Was previous buf put in mpx struct for multi-rsp? */ if(!isMultiRsp) { /* smb buffer will be freed by user thread */ if(isLargeBuf) { bigbuf = NULL; } else smallbuf = NULL; } wake_up_process(task_to_wake); } else if ((is_valid_oplock_break(smb_buffer) == FALSE) && (isMultiRsp == FALSE)) { cERROR(1, ("No task to wake, unknown frame rcvd!")); cifs_dump_mem("Received Data is: ",temp,sizeof(struct smb_hdr)); } } /* end while !EXITING */ spin_lock(&GlobalMid_Lock); server->tcpStatus = CifsExiting; server->tsk = NULL; /* check if we have blocked requests that need to free */ /* Note that cifs_max_pending is normally 50, but can be set at module install time to as little as two */ if(atomic_read(&server->inFlight) >= cifs_max_pending) atomic_set(&server->inFlight, cifs_max_pending - 1); /* We do not want to set the max_pending too low or we could end up with the counter going negative */ spin_unlock(&GlobalMid_Lock); /* Although there should not be any requests blocked on this queue it can not hurt to be paranoid and try to wake up requests that may haven been blocked when more than 50 at time were on the wire to the same server - they now will see the session is in exit state and get out of SendReceive. */ wake_up_all(&server->request_q); /* give those requests time to exit */ msleep(125); if(server->ssocket) { sock_release(csocket); server->ssocket = NULL; } /* buffer usuallly freed in free_mid - need to free it here on exit */ if (bigbuf != NULL) cifs_buf_release(bigbuf); if (smallbuf != NULL) cifs_small_buf_release(smallbuf); read_lock(&GlobalSMBSeslock); if (list_empty(&server->pending_mid_q)) { /* loop through server session structures attached to this and mark them dead */ list_for_each(tmp, &GlobalSMBSessionList) { ses = list_entry(tmp, struct cifsSesInfo, cifsSessionList); if (ses->server == server) { ses->status = CifsExiting; ses->server = NULL; } } read_unlock(&GlobalSMBSeslock); } else { /* although we can not zero the server struct pointer yet, since there are active requests which may depnd on them, mark the corresponding SMB sessions as exiting too */ list_for_each(tmp, &GlobalSMBSessionList) { ses = list_entry(tmp, struct cifsSesInfo, cifsSessionList); if (ses->server == server) { ses->status = CifsExiting; } } spin_lock(&GlobalMid_Lock); list_for_each(tmp, &server->pending_mid_q) { mid_entry = list_entry(tmp, struct mid_q_entry, qhead); if (mid_entry->midState == MID_REQUEST_SUBMITTED) { cFYI(1, ("Clearing Mid 0x%x - waking up ",mid_entry->mid)); task_to_wake = mid_entry->tsk; if(task_to_wake) { wake_up_process(task_to_wake); } } } spin_unlock(&GlobalMid_Lock); read_unlock(&GlobalSMBSeslock); /* 1/8th of sec is more than enough time for them to exit */ msleep(125); } if (list_empty(&server->pending_mid_q)) { /* mpx threads have not exited yet give them at least the smb send timeout time for long ops */ /* due to delays on oplock break requests, we need to wait at least 45 seconds before giving up on a request getting a response and going ahead and killing cifsd */ cFYI(1, ("Wait for exit from demultiplex thread")); msleep(46000); /* if threads still have not exited they are probably never coming home not much else we can do but free the memory */ } write_lock(&GlobalSMBSeslock); atomic_dec(&tcpSesAllocCount); length = tcpSesAllocCount.counter; /* last chance to mark ses pointers invalid if there are any pointing to this (e.g if a crazy root user tried to kill cifsd kernel thread explicitly this might happen) */ list_for_each(tmp, &GlobalSMBSessionList) { ses = list_entry(tmp, struct cifsSesInfo, cifsSessionList); if (ses->server == server) { ses->server = NULL; } } write_unlock(&GlobalSMBSeslock); kfree(server); if(length > 0) { mempool_resize(cifs_req_poolp, length + cifs_min_rcv, GFP_KERNEL); } msleep(250); return 0; } static int cifs_parse_mount_options(char *options, const char *devname,struct smb_vol *vol) { char *value; char *data; unsigned int temp_len, i, j; char separator[2]; separator[0] = ','; separator[1] = 0; memset(vol->source_rfc1001_name,0x20,15); for(i=0;i < strnlen(system_utsname.nodename,15);i++) { /* does not have to be a perfect mapping since the field is informational, only used for servers that do not support port 445 and it can be overridden at mount time */ vol->source_rfc1001_name[i] = toupper(system_utsname.nodename[i]); } vol->source_rfc1001_name[15] = 0; vol->linux_uid = current->uid; /* current->euid instead? */ vol->linux_gid = current->gid; vol->dir_mode = S_IRWXUGO; /* 2767 perms indicate mandatory locking support */ vol->file_mode = S_IALLUGO & ~(S_ISUID | S_IXGRP); /* vol->retry default is 0 (i.e. "soft" limited retry not hard retry) */ vol->rw = TRUE; if (!options) return 1; if(strncmp(options,"sep=",4) == 0) { if(options[4] != 0) { separator[0] = options[4]; options += 5; } else { cFYI(1,("Null separator not allowed")); } } while ((data = strsep(&options, separator)) != NULL) { if (!*data) continue; if ((value = strchr(data, '=')) != NULL) *value++ = '\0'; if (strnicmp(data, "user_xattr",10) == 0) {/*parse before user*/ vol->no_xattr = 0; } else if (strnicmp(data, "nouser_xattr",12) == 0) { vol->no_xattr = 1; } else if (strnicmp(data, "user", 4) == 0) { if (!value || !*value) { printk(KERN_WARNING "CIFS: invalid or missing username\n"); return 1; /* needs_arg; */ } if (strnlen(value, 200) < 200) { vol->username = value; } else { printk(KERN_WARNING "CIFS: username too long\n"); return 1; } } else if (strnicmp(data, "pass", 4) == 0) { if (!value) { vol->password = NULL; continue; } else if(value[0] == 0) { /* check if string begins with double comma since that would mean the password really does start with a comma, and would not indicate an empty string */ if(value[1] != separator[0]) { vol->password = NULL; continue; } } temp_len = strlen(value); /* removed password length check, NTLM passwords can be arbitrarily long */ /* if comma in password, the string will be prematurely null terminated. Commas in password are specified across the cifs mount interface by a double comma ie ,, and a comma used as in other cases ie ',' as a parameter delimiter/separator is single and due to the strsep above is temporarily zeroed. */ /* NB: password legally can have multiple commas and the only illegal character in a password is null */ if ((value[temp_len] == 0) && (value[temp_len+1] == separator[0])) { /* reinsert comma */ value[temp_len] = separator[0]; temp_len+=2; /* move after the second comma */ while(value[temp_len] != 0) { if (value[temp_len] == separator[0]) { if (value[temp_len+1] == separator[0]) { /* skip second comma */ temp_len++; } else { /* single comma indicating start of next parm */ break; } } temp_len++; } if(value[temp_len] == 0) { options = NULL; } else { value[temp_len] = 0; /* point option to start of next parm */ options = value + temp_len + 1; } /* go from value to value + temp_len condensing double commas to singles. Note that this ends up allocating a few bytes too many, which is ok */ vol->password = kcalloc(1, temp_len, GFP_KERNEL); if(vol->password == NULL) { printk("CIFS: no memory for pass\n"); return 1; } for(i=0,j=0;i<temp_len;i++,j++) { vol->password[j] = value[i]; if(value[i] == separator[0] && value[i+1] == separator[0]) { /* skip second comma */ i++; } } vol->password[j] = 0; } else { vol->password = kcalloc(1, temp_len+1, GFP_KERNEL); if(vol->password == NULL) { printk("CIFS: no memory for pass\n"); return 1; } strcpy(vol->password, value); } } else if (strnicmp(data, "ip", 2) == 0) { if (!value || !*value) { vol->UNCip = NULL; } else if (strnlen(value, 35) < 35) { vol->UNCip = value; } else { printk(KERN_WARNING "CIFS: ip address too long\n"); return 1; } } else if ((strnicmp(data, "unc", 3) == 0) || (strnicmp(data, "target", 6) == 0) || (strnicmp(data, "path", 4) == 0)) { if (!value || !*value) { printk(KERN_WARNING "CIFS: invalid path to network resource\n"); return 1; /* needs_arg; */ } if ((temp_len = strnlen(value, 300)) < 300) { vol->UNC = kmalloc(temp_len+1,GFP_KERNEL); if(vol->UNC == NULL) return 1; strcpy(vol->UNC,value); if (strncmp(vol->UNC, "//", 2) == 0) { vol->UNC[0] = '\\'; vol->UNC[1] = '\\'; } else if (strncmp(vol->UNC, "\\\\", 2) != 0) { printk(KERN_WARNING "CIFS: UNC Path does not begin with // or \\\\ \n"); return 1; } } else { printk(KERN_WARNING "CIFS: UNC name too long\n"); return 1; } } else if ((strnicmp(data, "domain", 3) == 0) || (strnicmp(data, "workgroup", 5) == 0)) { if (!value || !*value) { printk(KERN_WARNING "CIFS: invalid domain name\n"); return 1; /* needs_arg; */ } /* BB are there cases in which a comma can be valid in a domain name and need special handling? */ if (strnlen(value, 65) < 65) { vol->domainname = value; cFYI(1, ("Domain name set")); } else { printk(KERN_WARNING "CIFS: domain name too long\n"); return 1; } } else if (strnicmp(data, "iocharset", 9) == 0) { if (!value || !*value) { printk(KERN_WARNING "CIFS: invalid iocharset specified\n"); return 1; /* needs_arg; */ } if (strnlen(value, 65) < 65) { if(strnicmp(value,"default",7)) vol->iocharset = value; /* if iocharset not set load_nls_default used by caller */ cFYI(1, ("iocharset set to %s",value)); } else { printk(KERN_WARNING "CIFS: iocharset name too long.\n"); return 1; } } else if (strnicmp(data, "uid", 3) == 0) { if (value && *value) { vol->linux_uid = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "gid", 3) == 0) { if (value && *value) { vol->linux_gid = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "file_mode", 4) == 0) { if (value && *value) { vol->file_mode = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "dir_mode", 4) == 0) { if (value && *value) { vol->dir_mode = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "dirmode", 4) == 0) { if (value && *value) { vol->dir_mode = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "port", 4) == 0) { if (value && *value) { vol->port = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "rsize", 5) == 0) { if (value && *value) { vol->rsize = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "wsize", 5) == 0) { if (value && *value) { vol->wsize = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "sockopt", 5) == 0) { if (value && *value) { vol->sockopt = simple_strtoul(value, &value, 0); } } else if (strnicmp(data, "netbiosname", 4) == 0) { if (!value || !*value || (*value == ' ')) { cFYI(1,("invalid (empty) netbiosname specified")); } else { memset(vol->source_rfc1001_name,0x20,15); for(i=0;i<15;i++) { /* BB are there cases in which a comma can be valid in this workstation netbios name (and need special handling)? */ /* We do not uppercase netbiosname for user */ if (value[i]==0) break; else vol->source_rfc1001_name[i] = value[i]; } /* The string has 16th byte zero still from set at top of the function */ if((i==15) && (value[i] != 0)) printk(KERN_WARNING "CIFS: netbiosname longer than 15 and was truncated.\n"); } } else if (strnicmp(data, "credentials", 4) == 0) { /* ignore */ } else if (strnicmp(data, "version", 3) == 0) { /* ignore */ } else if (strnicmp(data, "guest",5) == 0) { /* ignore */ } else if (strnicmp(data, "rw", 2) == 0) { vol->rw = TRUE; } else if ((strnicmp(data, "suid", 4) == 0) || (strnicmp(data, "nosuid", 6) == 0) || (strnicmp(data, "exec", 4) == 0) || (strnicmp(data, "noexec", 6) == 0) || (strnicmp(data, "nodev", 5) == 0) || (strnicmp(data, "noauto", 6) == 0) || (strnicmp(data, "dev", 3) == 0)) { /* The mount tool or mount.cifs helper (if present) uses these opts to set flags, and the flags are read by the kernel vfs layer before we get here (ie before read super) so there is no point trying to parse these options again and set anything and it is ok to just ignore them */ continue; } else if (strnicmp(data, "ro", 2) == 0) { vol->rw = FALSE; } else if (strnicmp(data, "hard", 4) == 0) { vol->retry = 1; } else if (strnicmp(data, "soft", 4) == 0) { vol->retry = 0; } else if (strnicmp(data, "perm", 4) == 0) { vol->noperm = 0; } else if (strnicmp(data, "noperm", 6) == 0) { vol->noperm = 1; } else if (strnicmp(data, "mapchars", 8) == 0) { vol->remap = 1; } else if (strnicmp(data, "nomapchars", 10) == 0) { vol->remap = 0; } else if (strnicmp(data, "setuids", 7) == 0) { vol->setuids = 1; } else if (strnicmp(data, "nosetuids", 9) == 0) { vol->setuids = 0; } else if (strnicmp(data, "nohard", 6) == 0) { vol->retry = 0; } else if (strnicmp(data, "nosoft", 6) == 0) { vol->retry = 1; } else if (strnicmp(data, "nointr", 6) == 0) { vol->intr = 0; } else if (strnicmp(data, "intr", 4) == 0) { vol->intr = 1; } else if (strnicmp(data, "serverino",7) == 0) { vol->server_ino = 1; } else if (strnicmp(data, "noserverino",9) == 0) { vol->server_ino = 0; } else if (strnicmp(data, "acl",3) == 0) { vol->no_psx_acl = 0; } else if (strnicmp(data, "noacl",5) == 0) { vol->no_psx_acl = 1; } else if (strnicmp(data, "direct",6) == 0) { vol->direct_io = 1; } else if (strnicmp(data, "forcedirectio",13) == 0) { vol->direct_io = 1; } else if (strnicmp(data, "in6_addr",8) == 0) { if (!value || !*value) { vol->in6_addr = NULL; } else if (strnlen(value, 49) == 48) { vol->in6_addr = value; } else { printk(KERN_WARNING "CIFS: ip v6 address not 48 characters long\n"); return 1; } } else if (strnicmp(data, "noac", 4) == 0) { printk(KERN_WARNING "CIFS: Mount option noac not supported. Instead set /proc/fs/cifs/LookupCacheEnabled to 0\n"); } else printk(KERN_WARNING "CIFS: Unknown mount option %s\n",data); } if (vol->UNC == NULL) { if(devname == NULL) { printk(KERN_WARNING "CIFS: Missing UNC name for mount target\n"); return 1; } if ((temp_len = strnlen(devname, 300)) < 300) { vol->UNC = kmalloc(temp_len+1,GFP_KERNEL); if(vol->UNC == NULL) return 1; strcpy(vol->UNC,devname); if (strncmp(vol->UNC, "//", 2) == 0) { vol->UNC[0] = '\\'; vol->UNC[1] = '\\'; } else if (strncmp(vol->UNC, "\\\\", 2) != 0) { printk(KERN_WARNING "CIFS: UNC Path does not begin with // or \\\\ \n"); return 1; } } else { printk(KERN_WARNING "CIFS: UNC name too long\n"); return 1; } } if(vol->UNCip == NULL) vol->UNCip = &vol->UNC[2]; return 0; } static struct cifsSesInfo * cifs_find_tcp_session(struct in_addr * target_ip_addr, struct in6_addr *target_ip6_addr, char *userName, struct TCP_Server_Info **psrvTcp) { struct list_head *tmp; struct cifsSesInfo *ses; *psrvTcp = NULL; read_lock(&GlobalSMBSeslock); list_for_each(tmp, &GlobalSMBSessionList) { ses = list_entry(tmp, struct cifsSesInfo, cifsSessionList); if (ses->server) { if((target_ip_addr && (ses->server->addr.sockAddr.sin_addr.s_addr == target_ip_addr->s_addr)) || (target_ip6_addr && memcmp(&ses->server->addr.sockAddr6.sin6_addr, target_ip6_addr,sizeof(*target_ip6_addr)))){ /* BB lock server and tcp session and increment use count here?? */ *psrvTcp = ses->server; /* found a match on the TCP session */ /* BB check if reconnection needed */ if (strncmp (ses->userName, userName, MAX_USERNAME_SIZE) == 0){ read_unlock(&GlobalSMBSeslock); return ses; /* found exact match on both tcp and SMB sessions */ } } } /* else tcp and smb sessions need reconnection */ } read_unlock(&GlobalSMBSeslock); return NULL; } static struct cifsTconInfo * find_unc(__be32 new_target_ip_addr, char *uncName, char *userName) { struct list_head *tmp; struct cifsTconInfo *tcon; read_lock(&GlobalSMBSeslock); list_for_each(tmp, &GlobalTreeConnectionList) { cFYI(1, ("Next tcon - ")); tcon = list_entry(tmp, struct cifsTconInfo, cifsConnectionList); if (tcon->ses) { if (tcon->ses->server) { cFYI(1, (" old ip addr: %x == new ip %x ?", tcon->ses->server->addr.sockAddr.sin_addr. s_addr, new_target_ip_addr)); if (tcon->ses->server->addr.sockAddr.sin_addr. s_addr == new_target_ip_addr) { /* BB lock tcon and server and tcp session and increment use count here? */ /* found a match on the TCP session */ /* BB check if reconnection needed */ cFYI(1,("Matched ip, old UNC: %s == new: %s ?", tcon->treeName, uncName)); if (strncmp (tcon->treeName, uncName, MAX_TREE_SIZE) == 0) { cFYI(1, ("Matched UNC, old user: %s == new: %s ?", tcon->treeName, uncName)); if (strncmp (tcon->ses->userName, userName, MAX_USERNAME_SIZE) == 0) { read_unlock(&GlobalSMBSeslock); return tcon;/* also matched user (smb session)*/ } } } } } } read_unlock(&GlobalSMBSeslock); return NULL; } int connect_to_dfs_path(int xid, struct cifsSesInfo *pSesInfo, const char *old_path, const struct nls_table *nls_codepage, int remap) { unsigned char *referrals = NULL; unsigned int num_referrals; int rc = 0; rc = get_dfs_path(xid, pSesInfo,old_path, nls_codepage, &num_referrals, &referrals, remap); /* BB Add in code to: if valid refrl, if not ip address contact the helper that resolves tcp names, mount to it, try to tcon to it unmount it if fail */ if(referrals) kfree(referrals); return rc; } int get_dfs_path(int xid, struct cifsSesInfo *pSesInfo, const char *old_path, const struct nls_table *nls_codepage, unsigned int *pnum_referrals, unsigned char ** preferrals, int remap) { char *temp_unc; int rc = 0; *pnum_referrals = 0; if (pSesInfo->ipc_tid == 0) { temp_unc = kmalloc(2 /* for slashes */ + strnlen(pSesInfo->serverName,SERVER_NAME_LEN_WITH_NULL * 2) + 1 + 4 /* slash IPC$ */ + 2, GFP_KERNEL); if (temp_unc == NULL) return -ENOMEM; temp_unc[0] = '\\'; temp_unc[1] = '\\'; strcpy(temp_unc + 2, pSesInfo->serverName); strcpy(temp_unc + 2 + strlen(pSesInfo->serverName), "\\IPC$"); rc = CIFSTCon(xid, pSesInfo, temp_unc, NULL, nls_codepage); cFYI(1, ("CIFS Tcon rc = %d ipc_tid = %d", rc,pSesInfo->ipc_tid)); kfree(temp_unc); } if (rc == 0) rc = CIFSGetDFSRefer(xid, pSesInfo, old_path, preferrals, pnum_referrals, nls_codepage, remap); return rc; } /* See RFC1001 section 14 on representation of Netbios names */ static void rfc1002mangle(char * target,char * source, unsigned int length) { unsigned int i,j; for(i=0,j=0;i<(length);i++) { /* mask a nibble at a time and encode */ target[j] = 'A' + (0x0F & (source[i] >> 4)); target[j+1] = 'A' + (0x0F & source[i]); j+=2; } } static int ipv4_connect(struct sockaddr_in *psin_server, struct socket **csocket, char * netbios_name) { int rc = 0; int connected = 0; __be16 orig_port = 0; if(*csocket == NULL) { rc = sock_create_kern(PF_INET, SOCK_STREAM, IPPROTO_TCP, csocket); if (rc < 0) { cERROR(1, ("Error %d creating socket",rc)); *csocket = NULL; return rc; } else { /* BB other socket options to set KEEPALIVE, NODELAY? */ cFYI(1,("Socket created")); (*csocket)->sk->sk_allocation = GFP_NOFS; } } psin_server->sin_family = AF_INET; if(psin_server->sin_port) { /* user overrode default port */ rc = (*csocket)->ops->connect(*csocket, (struct sockaddr *) psin_server, sizeof (struct sockaddr_in),0); if (rc >= 0) connected = 1; } if(!connected) { /* save original port so we can retry user specified port later if fall back ports fail this time */ orig_port = psin_server->sin_port; /* do not retry on the same port we just failed on */ if(psin_server->sin_port != htons(CIFS_PORT)) { psin_server->sin_port = htons(CIFS_PORT); rc = (*csocket)->ops->connect(*csocket, (struct sockaddr *) psin_server, sizeof (struct sockaddr_in),0); if (rc >= 0) connected = 1; } } if (!connected) { psin_server->sin_port = htons(RFC1001_PORT); rc = (*csocket)->ops->connect(*csocket, (struct sockaddr *) psin_server, sizeof (struct sockaddr_in),0); if (rc >= 0) connected = 1; } /* give up here - unless we want to retry on different protocol families some day */ if (!connected) { if(orig_port) psin_server->sin_port = orig_port; cFYI(1,("Error %d connecting to server via ipv4",rc)); sock_release(*csocket); *csocket = NULL; return rc; } /* Eventually check for other socket options to change from the default. sock_setsockopt not used because it expects user space buffer */ (*csocket)->sk->sk_rcvtimeo = 7 * HZ; /* send RFC1001 sessinit */ if(psin_server->sin_port == htons(RFC1001_PORT)) { /* some servers require RFC1001 sessinit before sending negprot - BB check reconnection in case where second sessinit is sent but no second negprot */ struct rfc1002_session_packet * ses_init_buf; struct smb_hdr * smb_buf; ses_init_buf = kcalloc(1, sizeof(struct rfc1002_session_packet), GFP_KERNEL); if(ses_init_buf) { ses_init_buf->trailer.session_req.called_len = 32; rfc1002mangle(ses_init_buf->trailer.session_req.called_name, DEFAULT_CIFS_CALLED_NAME,16); ses_init_buf->trailer.session_req.calling_len = 32; /* calling name ends in null (byte 16) from old smb convention. */ if(netbios_name && (netbios_name[0] !=0)) { rfc1002mangle(ses_init_buf->trailer.session_req.calling_name, netbios_name,16); } else { rfc1002mangle(ses_init_buf->trailer.session_req.calling_name, "LINUX_CIFS_CLNT",16); } ses_init_buf->trailer.session_req.scope1 = 0; ses_init_buf->trailer.session_req.scope2 = 0; smb_buf = (struct smb_hdr *)ses_init_buf; /* sizeof RFC1002_SESSION_REQUEST with no scope */ smb_buf->smb_buf_length = 0x81000044; rc = smb_send(*csocket, smb_buf, 0x44, (struct sockaddr *)psin_server); kfree(ses_init_buf); } /* else the negprot may still work without this even though malloc failed */ } return rc; } static int ipv6_connect(struct sockaddr_in6 *psin_server, struct socket **csocket) { int rc = 0; int connected = 0; __be16 orig_port = 0; if(*csocket == NULL) { rc = sock_create_kern(PF_INET6, SOCK_STREAM, IPPROTO_TCP, csocket); if (rc < 0) { cERROR(1, ("Error %d creating ipv6 socket",rc)); *csocket = NULL; return rc; } else { /* BB other socket options to set KEEPALIVE, NODELAY? */ cFYI(1,("ipv6 Socket created")); (*csocket)->sk->sk_allocation = GFP_NOFS; } } psin_server->sin6_family = AF_INET6; if(psin_server->sin6_port) { /* user overrode default port */ rc = (*csocket)->ops->connect(*csocket, (struct sockaddr *) psin_server, sizeof (struct sockaddr_in6),0); if (rc >= 0) connected = 1; } if(!connected) { /* save original port so we can retry user specified port later if fall back ports fail this time */ orig_port = psin_server->sin6_port; /* do not retry on the same port we just failed on */ if(psin_server->sin6_port != htons(CIFS_PORT)) { psin_server->sin6_port = htons(CIFS_PORT); rc = (*csocket)->ops->connect(*csocket, (struct sockaddr *) psin_server, sizeof (struct sockaddr_in6),0); if (rc >= 0) connected = 1; } } if (!connected) { psin_server->sin6_port = htons(RFC1001_PORT); rc = (*csocket)->ops->connect(*csocket, (struct sockaddr *) psin_server, sizeof (struct sockaddr_in6),0); if (rc >= 0) connected = 1; } /* give up here - unless we want to retry on different protocol families some day */ if (!connected) { if(orig_port) psin_server->sin6_port = orig_port; cFYI(1,("Error %d connecting to server via ipv6",rc)); sock_release(*csocket); *csocket = NULL; return rc; } /* Eventually check for other socket options to change from the default. sock_setsockopt not used because it expects user space buffer */ (*csocket)->sk->sk_rcvtimeo = 7 * HZ; return rc; } int cifs_mount(struct super_block *sb, struct cifs_sb_info *cifs_sb, char *mount_data, const char *devname) { int rc = 0; int xid; int address_type = AF_INET; struct socket *csocket = NULL; struct sockaddr_in sin_server; struct sockaddr_in6 sin_server6; struct smb_vol volume_info; struct cifsSesInfo *pSesInfo = NULL; struct cifsSesInfo *existingCifsSes = NULL; struct cifsTconInfo *tcon = NULL; struct TCP_Server_Info *srvTcp = NULL; xid = GetXid(); /* cFYI(1, ("Entering cifs_mount. Xid: %d with: %s", xid, mount_data)); */ memset(&volume_info,0,sizeof(struct smb_vol)); if (cifs_parse_mount_options(mount_data, devname, &volume_info)) { if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return -EINVAL; } if (volume_info.username) { /* BB fixme parse for domain name here */ cFYI(1, ("Username: %s ", volume_info.username)); } else { cifserror("No username specified "); /* In userspace mount helper we can get user name from alternate locations such as env variables and files on disk */ if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return -EINVAL; } if (volume_info.UNCip && volume_info.UNC) { rc = cifs_inet_pton(AF_INET, volume_info.UNCip,&sin_server.sin_addr.s_addr); if(rc <= 0) { /* not ipv4 address, try ipv6 */ rc = cifs_inet_pton(AF_INET6,volume_info.UNCip,&sin_server6.sin6_addr.in6_u); if(rc > 0) address_type = AF_INET6; } else { address_type = AF_INET; } if(rc <= 0) { /* we failed translating address */ if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return -EINVAL; } cFYI(1, ("UNC: %s ip: %s", volume_info.UNC, volume_info.UNCip)); /* success */ rc = 0; } else if (volume_info.UNCip){ /* BB using ip addr as server name connect to the DFS root below */ cERROR(1,("Connecting to DFS root not implemented yet")); if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return -EINVAL; } else /* which servers DFS root would we conect to */ { cERROR(1, ("CIFS mount error: No UNC path (e.g. -o unc=//192.168.1.100/public) specified ")); if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return -EINVAL; } /* this is needed for ASCII cp to Unicode converts */ if(volume_info.iocharset == NULL) { cifs_sb->local_nls = load_nls_default(); /* load_nls_default can not return null */ } else { cifs_sb->local_nls = load_nls(volume_info.iocharset); if(cifs_sb->local_nls == NULL) { cERROR(1,("CIFS mount error: iocharset %s not found",volume_info.iocharset)); if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return -ELIBACC; } } if(address_type == AF_INET) existingCifsSes = cifs_find_tcp_session(&sin_server.sin_addr, NULL /* no ipv6 addr */, volume_info.username, &srvTcp); else if(address_type == AF_INET6) existingCifsSes = cifs_find_tcp_session(NULL /* no ipv4 addr */, &sin_server6.sin6_addr, volume_info.username, &srvTcp); else { if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return -EINVAL; } if (srvTcp) { cFYI(1, ("Existing tcp session with server found ")); } else { /* create socket */ if(volume_info.port) sin_server.sin_port = htons(volume_info.port); else sin_server.sin_port = 0; rc = ipv4_connect(&sin_server,&csocket,volume_info.source_rfc1001_name); if (rc < 0) { cERROR(1, ("Error connecting to IPv4 socket. Aborting operation")); if(csocket != NULL) sock_release(csocket); if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return rc; } srvTcp = kmalloc(sizeof (struct TCP_Server_Info), GFP_KERNEL); if (srvTcp == NULL) { rc = -ENOMEM; sock_release(csocket); if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return rc; } else { memset(srvTcp, 0, sizeof (struct TCP_Server_Info)); memcpy(&srvTcp->addr.sockAddr, &sin_server, sizeof (struct sockaddr_in)); atomic_set(&srvTcp->inFlight,0); /* BB Add code for ipv6 case too */ srvTcp->ssocket = csocket; srvTcp->protocolType = IPV4; init_waitqueue_head(&srvTcp->response_q); init_waitqueue_head(&srvTcp->request_q); INIT_LIST_HEAD(&srvTcp->pending_mid_q); /* at this point we are the only ones with the pointer to the struct since the kernel thread not created yet so no need to spinlock this init of tcpStatus */ srvTcp->tcpStatus = CifsNew; init_MUTEX(&srvTcp->tcpSem); rc = (int)kernel_thread((void *)(void *)cifs_demultiplex_thread, srvTcp, CLONE_FS | CLONE_FILES | CLONE_VM); if(rc < 0) { rc = -ENOMEM; sock_release(csocket); if(volume_info.UNC) kfree(volume_info.UNC); if(volume_info.password) kfree(volume_info.password); FreeXid(xid); return rc; } else rc = 0; memcpy(srvTcp->workstation_RFC1001_name, volume_info.source_rfc1001_name,16); srvTcp->sequence_number = 0; } } if (existingCifsSes) { pSesInfo = existingCifsSes; cFYI(1, ("Existing smb sess found ")); if(volume_info.password) kfree(volume_info.password); /* volume_info.UNC freed at end of function */ } else if (!rc) { cFYI(1, ("Existing smb sess not found ")); pSesInfo = sesInfoAlloc(); if (pSesInfo == NULL) rc = -ENOMEM; else { pSesInfo->server = srvTcp; sprintf(pSesInfo->serverName, "%u.%u.%u.%u", NIPQUAD(sin_server.sin_addr.s_addr)); } if (!rc){ /* volume_info.password freed at unmount */ if (volume_info.password) pSesInfo->password = volume_info.password; if (volume_info.username) strncpy(pSesInfo->userName, volume_info.username,MAX_USERNAME_SIZE); if (volume_info.domainname) strncpy(pSesInfo->domainName, volume_info.domainname,MAX_USERNAME_SIZE); pSesInfo->linux_uid = volume_info.linux_uid; down(&pSesInfo->sesSem); rc = cifs_setup_session(xid,pSesInfo, cifs_sb->local_nls); up(&pSesInfo->sesSem); if(!rc) atomic_inc(&srvTcp->socketUseCount); } else if(volume_info.password) kfree(volume_info.password); } /* search for existing tcon to this server share */ if (!rc) { if((volume_info.rsize) && (volume_info.rsize <= CIFSMaxBufSize)) cifs_sb->rsize = volume_info.rsize; else cifs_sb->rsize = srvTcp->maxBuf - MAX_CIFS_HDR_SIZE; /* default */ if((volume_info.wsize) && (volume_info.wsize <= CIFSMaxBufSize)) cifs_sb->wsize = volume_info.wsize; else cifs_sb->wsize = CIFSMaxBufSize; /* default */ if(cifs_sb->rsize < PAGE_CACHE_SIZE) { cifs_sb->rsize = PAGE_CACHE_SIZE; cERROR(1,("Attempt to set readsize for mount to less than one page (4096)")); } cifs_sb->mnt_uid = volume_info.linux_uid; cifs_sb->mnt_gid = volume_info.linux_gid; cifs_sb->mnt_file_mode = volume_info.file_mode; cifs_sb->mnt_dir_mode = volume_info.dir_mode; cFYI(1,("file mode: 0x%x dir mode: 0x%x",cifs_sb->mnt_file_mode,cifs_sb->mnt_dir_mode)); if(volume_info.noperm) cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_PERM; if(volume_info.setuids) cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SET_UID; if(volume_info.server_ino) cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SERVER_INUM; if(volume_info.remap) cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SPECIAL_CHR; if(volume_info.no_xattr) cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_XATTR; if(volume_info.direct_io) { cERROR(1,("mounting share using direct i/o")); cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DIRECT_IO; } tcon = find_unc(sin_server.sin_addr.s_addr, volume_info.UNC, volume_info.username); if (tcon) { cFYI(1, ("Found match on UNC path ")); /* we can have only one retry value for a connection to a share so for resources mounted more than once to the same server share the last value passed in for the retry flag is used */ tcon->retry = volume_info.retry; } else { tcon = tconInfoAlloc(); if (tcon == NULL) rc = -ENOMEM; else { /* check for null share name ie connect to dfs root */ /* BB check if this works for exactly length three strings */ if ((strchr(volume_info.UNC + 3, '\\') == NULL) && (strchr(volume_info.UNC + 3, '/') == NULL)) { rc = connect_to_dfs_path(xid, pSesInfo, "", cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if(volume_info.UNC) kfree(volume_info.UNC); FreeXid(xid); return -ENODEV; } else { rc = CIFSTCon(xid, pSesInfo, volume_info.UNC, tcon, cifs_sb->local_nls); cFYI(1, ("CIFS Tcon rc = %d", rc)); } if (!rc) { atomic_inc(&pSesInfo->inUse); tcon->retry = volume_info.retry; } } } } if(pSesInfo) { if (pSesInfo->capabilities & CAP_LARGE_FILES) { sb->s_maxbytes = (u64) 1 << 63; } else sb->s_maxbytes = (u64) 1 << 31; /* 2 GB */ } sb->s_time_gran = 100; /* on error free sesinfo and tcon struct if needed */ if (rc) { /* if session setup failed, use count is zero but we still need to free cifsd thread */ if(atomic_read(&srvTcp->socketUseCount) == 0) { spin_lock(&GlobalMid_Lock); srvTcp->tcpStatus = CifsExiting; spin_unlock(&GlobalMid_Lock); if(srvTcp->tsk) send_sig(SIGKILL,srvTcp->tsk,1); } /* If find_unc succeeded then rc == 0 so we can not end */ if (tcon) /* up accidently freeing someone elses tcon struct */ tconInfoFree(tcon); if (existingCifsSes == NULL) { if (pSesInfo) { if ((pSesInfo->server) && (pSesInfo->status == CifsGood)) { int temp_rc; temp_rc = CIFSSMBLogoff(xid, pSesInfo); /* if the socketUseCount is now zero */ if((temp_rc == -ESHUTDOWN) && (pSesInfo->server->tsk)) send_sig(SIGKILL,pSesInfo->server->tsk,1); } else cFYI(1, ("No session or bad tcon")); sesInfoFree(pSesInfo); /* pSesInfo = NULL; */ } } } else { atomic_inc(&tcon->useCount); cifs_sb->tcon = tcon; tcon->ses = pSesInfo; /* do not care if following two calls succeed - informational only */ CIFSSMBQFSDeviceInfo(xid, tcon); CIFSSMBQFSAttributeInfo(xid, tcon); if (tcon->ses->capabilities & CAP_UNIX) { if(!CIFSSMBQFSUnixInfo(xid, tcon)) { if(!volume_info.no_psx_acl) { if(CIFS_UNIX_POSIX_ACL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) cFYI(1,("server negotiated posix acl support")); sb->s_flags |= MS_POSIXACL; } } } } /* volume_info.password is freed above when existing session found (in which case it is not needed anymore) but when new sesion is created the password ptr is put in the new session structure (in which case the password will be freed at unmount time) */ if(volume_info.UNC) kfree(volume_info.UNC); FreeXid(xid); return rc; } static int CIFSSessSetup(unsigned int xid, struct cifsSesInfo *ses, char session_key[CIFS_SESSION_KEY_SIZE], const struct nls_table *nls_codepage) { struct smb_hdr *smb_buffer; struct smb_hdr *smb_buffer_response; SESSION_SETUP_ANDX *pSMB; SESSION_SETUP_ANDX *pSMBr; char *bcc_ptr; char *user; char *domain; int rc = 0; int remaining_words = 0; int bytes_returned = 0; int len; __u32 capabilities; __u16 count; cFYI(1, ("In sesssetup ")); if(ses == NULL) return -EINVAL; user = ses->userName; domain = ses->domainName; smb_buffer = cifs_buf_get(); if (smb_buffer == NULL) { return -ENOMEM; } smb_buffer_response = smb_buffer; pSMBr = pSMB = (SESSION_SETUP_ANDX *) smb_buffer; /* send SMBsessionSetup here */ header_assemble(smb_buffer, SMB_COM_SESSION_SETUP_ANDX, NULL /* no tCon exists yet */ , 13 /* wct */ ); pSMB->req_no_secext.AndXCommand = 0xFF; pSMB->req_no_secext.MaxBufferSize = cpu_to_le16(ses->server->maxBuf); pSMB->req_no_secext.MaxMpxCount = cpu_to_le16(ses->server->maxReq); if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE; capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS | CAP_LARGE_WRITE_X | CAP_LARGE_READ_X; if (ses->capabilities & CAP_UNICODE) { smb_buffer->Flags2 |= SMBFLG2_UNICODE; capabilities |= CAP_UNICODE; } if (ses->capabilities & CAP_STATUS32) { smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS; capabilities |= CAP_STATUS32; } if (ses->capabilities & CAP_DFS) { smb_buffer->Flags2 |= SMBFLG2_DFS; capabilities |= CAP_DFS; } pSMB->req_no_secext.Capabilities = cpu_to_le32(capabilities); pSMB->req_no_secext.CaseInsensitivePasswordLength = cpu_to_le16(CIFS_SESSION_KEY_SIZE); pSMB->req_no_secext.CaseSensitivePasswordLength = cpu_to_le16(CIFS_SESSION_KEY_SIZE); bcc_ptr = pByteArea(smb_buffer); memcpy(bcc_ptr, (char *) session_key, CIFS_SESSION_KEY_SIZE); bcc_ptr += CIFS_SESSION_KEY_SIZE; memcpy(bcc_ptr, (char *) session_key, CIFS_SESSION_KEY_SIZE); bcc_ptr += CIFS_SESSION_KEY_SIZE; if (ses->capabilities & CAP_UNICODE) { if ((long) bcc_ptr % 2) { /* must be word aligned for Unicode */ *bcc_ptr = 0; bcc_ptr++; } if(user == NULL) bytes_returned = 0; /* skill null user */ else bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, user, 100, nls_codepage); /* convert number of 16 bit words to bytes */ bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; /* trailing null */ if (domain == NULL) bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, "CIFS_LINUX_DOM", 32, nls_codepage); else bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, domain, 64, nls_codepage); bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, "Linux version ", 32, nls_codepage); bcc_ptr += 2 * bytes_returned; bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, system_utsname.release, 32, nls_codepage); bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, CIFS_NETWORK_OPSYS, 64, nls_codepage); bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; } else { if(user != NULL) { strncpy(bcc_ptr, user, 200); bcc_ptr += strnlen(user, 200); } *bcc_ptr = 0; bcc_ptr++; if (domain == NULL) { strcpy(bcc_ptr, "CIFS_LINUX_DOM"); bcc_ptr += strlen("CIFS_LINUX_DOM") + 1; } else { strncpy(bcc_ptr, domain, 64); bcc_ptr += strnlen(domain, 64); *bcc_ptr = 0; bcc_ptr++; } strcpy(bcc_ptr, "Linux version "); bcc_ptr += strlen("Linux version "); strcpy(bcc_ptr, system_utsname.release); bcc_ptr += strlen(system_utsname.release) + 1; strcpy(bcc_ptr, CIFS_NETWORK_OPSYS); bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1; } count = (long) bcc_ptr - (long) pByteArea(smb_buffer); smb_buffer->smb_buf_length += count; pSMB->req_no_secext.ByteCount = cpu_to_le16(count); rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &bytes_returned, 1); if (rc) { /* rc = map_smb_to_linux_error(smb_buffer_response); now done in SendReceive */ } else if ((smb_buffer_response->WordCount == 3) || (smb_buffer_response->WordCount == 4)) { __u16 action = le16_to_cpu(pSMBr->resp.Action); __u16 blob_len = le16_to_cpu(pSMBr->resp.SecurityBlobLength); if (action & GUEST_LOGIN) cFYI(1, (" Guest login")); /* do we want to mark SesInfo struct ? */ ses->Suid = smb_buffer_response->Uid; /* UID left in wire format (le) */ cFYI(1, ("UID = %d ", ses->Suid)); /* response can have either 3 or 4 word count - Samba sends 3 */ bcc_ptr = pByteArea(smb_buffer_response); if ((pSMBr->resp.hdr.WordCount == 3) || ((pSMBr->resp.hdr.WordCount == 4) && (blob_len < pSMBr->resp.ByteCount))) { if (pSMBr->resp.hdr.WordCount == 4) bcc_ptr += blob_len; if (smb_buffer->Flags2 & SMBFLG2_UNICODE) { if ((long) (bcc_ptr) % 2) { remaining_words = (BCC(smb_buffer_response) - 1) /2; bcc_ptr++; /* Unicode strings must be word aligned */ } else { remaining_words = BCC(smb_buffer_response) / 2; } len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words - 1); /* We look for obvious messed up bcc or strings in response so we do not go off the end since (at least) WIN2K and Windows XP have a major bug in not null terminating last Unicode string in response */ ses->serverOS = kcalloc(1, 2 * (len + 1), GFP_KERNEL); if(ses->serverOS == NULL) goto sesssetup_nomem; cifs_strfromUCS_le(ses->serverOS, (wchar_t *)bcc_ptr, len,nls_codepage); bcc_ptr += 2 * (len + 1); remaining_words -= len + 1; ses->serverOS[2 * len] = 0; ses->serverOS[1 + (2 * len)] = 0; if (remaining_words > 0) { len = UniStrnlen((wchar_t *)bcc_ptr, remaining_words-1); ses->serverNOS = kcalloc(1, 2 * (len + 1),GFP_KERNEL); if(ses->serverNOS == NULL) goto sesssetup_nomem; cifs_strfromUCS_le(ses->serverNOS, (wchar_t *)bcc_ptr,len,nls_codepage); bcc_ptr += 2 * (len + 1); ses->serverNOS[2 * len] = 0; ses->serverNOS[1 + (2 * len)] = 0; if(strncmp(ses->serverNOS, "NT LAN Manager 4",16) == 0) { cFYI(1,("NT4 server")); ses->flags |= CIFS_SES_NT4; } remaining_words -= len + 1; if (remaining_words > 0) { len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words); /* last string is not always null terminated (for e.g. for Windows XP & 2000) */ ses->serverDomain = kcalloc(1, 2*(len+1),GFP_KERNEL); if(ses->serverDomain == NULL) goto sesssetup_nomem; cifs_strfromUCS_le(ses->serverDomain, (wchar_t *)bcc_ptr,len,nls_codepage); bcc_ptr += 2 * (len + 1); ses->serverDomain[2*len] = 0; ses->serverDomain[1+(2*len)] = 0; } /* else no more room so create dummy domain string */ else ses->serverDomain = kcalloc(1, 2, GFP_KERNEL); } else { /* no room so create dummy domain and NOS string */ /* if these kcallocs fail not much we can do, but better to not fail the sesssetup itself */ ses->serverDomain = kcalloc(1, 2, GFP_KERNEL); ses->serverNOS = kcalloc(1, 2, GFP_KERNEL); } } else { /* ASCII */ len = strnlen(bcc_ptr, 1024); if (((long) bcc_ptr + len) - (long) pByteArea(smb_buffer_response) <= BCC(smb_buffer_response)) { ses->serverOS = kcalloc(1, len + 1,GFP_KERNEL); if(ses->serverOS == NULL) goto sesssetup_nomem; strncpy(ses->serverOS,bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; /* null terminate the string */ bcc_ptr++; len = strnlen(bcc_ptr, 1024); ses->serverNOS = kcalloc(1, len + 1,GFP_KERNEL); if(ses->serverNOS == NULL) goto sesssetup_nomem; strncpy(ses->serverNOS, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; bcc_ptr++; len = strnlen(bcc_ptr, 1024); ses->serverDomain = kcalloc(1, len + 1,GFP_KERNEL); if(ses->serverDomain == NULL) goto sesssetup_nomem; strncpy(ses->serverDomain, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; bcc_ptr++; } else cFYI(1, ("Variable field of length %d extends beyond end of smb ", len)); } } else { cERROR(1, (" Security Blob Length extends beyond end of SMB")); } } else { cERROR(1, (" Invalid Word count %d: ", smb_buffer_response->WordCount)); rc = -EIO; } sesssetup_nomem: /* do not return an error on nomem for the info strings, since that could make reconnection harder, and reconnection might be needed to free memory */ if (smb_buffer) cifs_buf_release(smb_buffer); return rc; } static int CIFSSpnegoSessSetup(unsigned int xid, struct cifsSesInfo *ses, char *SecurityBlob,int SecurityBlobLength, const struct nls_table *nls_codepage) { struct smb_hdr *smb_buffer; struct smb_hdr *smb_buffer_response; SESSION_SETUP_ANDX *pSMB; SESSION_SETUP_ANDX *pSMBr; char *bcc_ptr; char *user; char *domain; int rc = 0; int remaining_words = 0; int bytes_returned = 0; int len; __u32 capabilities; __u16 count; cFYI(1, ("In spnego sesssetup ")); if(ses == NULL) return -EINVAL; user = ses->userName; domain = ses->domainName; smb_buffer = cifs_buf_get(); if (smb_buffer == NULL) { return -ENOMEM; } smb_buffer_response = smb_buffer; pSMBr = pSMB = (SESSION_SETUP_ANDX *) smb_buffer; /* send SMBsessionSetup here */ header_assemble(smb_buffer, SMB_COM_SESSION_SETUP_ANDX, NULL /* no tCon exists yet */ , 12 /* wct */ ); pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC; pSMB->req.AndXCommand = 0xFF; pSMB->req.MaxBufferSize = cpu_to_le16(ses->server->maxBuf); pSMB->req.MaxMpxCount = cpu_to_le16(ses->server->maxReq); if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE; capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS | CAP_EXTENDED_SECURITY; if (ses->capabilities & CAP_UNICODE) { smb_buffer->Flags2 |= SMBFLG2_UNICODE; capabilities |= CAP_UNICODE; } if (ses->capabilities & CAP_STATUS32) { smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS; capabilities |= CAP_STATUS32; } if (ses->capabilities & CAP_DFS) { smb_buffer->Flags2 |= SMBFLG2_DFS; capabilities |= CAP_DFS; } pSMB->req.Capabilities = cpu_to_le32(capabilities); pSMB->req.SecurityBlobLength = cpu_to_le16(SecurityBlobLength); bcc_ptr = pByteArea(smb_buffer); memcpy(bcc_ptr, SecurityBlob, SecurityBlobLength); bcc_ptr += SecurityBlobLength; if (ses->capabilities & CAP_UNICODE) { if ((long) bcc_ptr % 2) { /* must be word aligned for Unicode strings */ *bcc_ptr = 0; bcc_ptr++; } bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, user, 100, nls_codepage); bcc_ptr += 2 * bytes_returned; /* convert num of 16 bit words to bytes */ bcc_ptr += 2; /* trailing null */ if (domain == NULL) bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, "CIFS_LINUX_DOM", 32, nls_codepage); else bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, domain, 64, nls_codepage); bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, "Linux version ", 32, nls_codepage); bcc_ptr += 2 * bytes_returned; bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, system_utsname.release, 32, nls_codepage); bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, CIFS_NETWORK_OPSYS, 64, nls_codepage); bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; } else { strncpy(bcc_ptr, user, 200); bcc_ptr += strnlen(user, 200); *bcc_ptr = 0; bcc_ptr++; if (domain == NULL) { strcpy(bcc_ptr, "CIFS_LINUX_DOM"); bcc_ptr += strlen("CIFS_LINUX_DOM") + 1; } else { strncpy(bcc_ptr, domain, 64); bcc_ptr += strnlen(domain, 64); *bcc_ptr = 0; bcc_ptr++; } strcpy(bcc_ptr, "Linux version "); bcc_ptr += strlen("Linux version "); strcpy(bcc_ptr, system_utsname.release); bcc_ptr += strlen(system_utsname.release) + 1; strcpy(bcc_ptr, CIFS_NETWORK_OPSYS); bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1; } count = (long) bcc_ptr - (long) pByteArea(smb_buffer); smb_buffer->smb_buf_length += count; pSMB->req.ByteCount = cpu_to_le16(count); rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &bytes_returned, 1); if (rc) { /* rc = map_smb_to_linux_error(smb_buffer_response); *//* done in SendReceive now */ } else if ((smb_buffer_response->WordCount == 3) || (smb_buffer_response->WordCount == 4)) { __u16 action = le16_to_cpu(pSMBr->resp.Action); __u16 blob_len = le16_to_cpu(pSMBr->resp.SecurityBlobLength); if (action & GUEST_LOGIN) cFYI(1, (" Guest login")); /* BB do we want to set anything in SesInfo struct ? */ if (ses) { ses->Suid = smb_buffer_response->Uid; /* UID left in wire format (le) */ cFYI(1, ("UID = %d ", ses->Suid)); bcc_ptr = pByteArea(smb_buffer_response); /* response can have either 3 or 4 word count - Samba sends 3 */ /* BB Fix below to make endian neutral !! */ if ((pSMBr->resp.hdr.WordCount == 3) || ((pSMBr->resp.hdr.WordCount == 4) && (blob_len < pSMBr->resp.ByteCount))) { if (pSMBr->resp.hdr.WordCount == 4) { bcc_ptr += blob_len; cFYI(1, ("Security Blob Length %d ", blob_len)); } if (smb_buffer->Flags2 & SMBFLG2_UNICODE) { if ((long) (bcc_ptr) % 2) { remaining_words = (BCC(smb_buffer_response) - 1) / 2; bcc_ptr++; /* Unicode strings must be word aligned */ } else { remaining_words = BCC (smb_buffer_response) / 2; } len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words - 1); /* We look for obvious messed up bcc or strings in response so we do not go off the end since (at least) WIN2K and Windows XP have a major bug in not null terminating last Unicode string in response */ ses->serverOS = kcalloc(1, 2 * (len + 1), GFP_KERNEL); cifs_strfromUCS_le(ses->serverOS, (wchar_t *) bcc_ptr, len, nls_codepage); bcc_ptr += 2 * (len + 1); remaining_words -= len + 1; ses->serverOS[2 * len] = 0; ses->serverOS[1 + (2 * len)] = 0; if (remaining_words > 0) { len = UniStrnlen((wchar_t *)bcc_ptr, remaining_words - 1); ses->serverNOS = kcalloc(1, 2 * (len + 1), GFP_KERNEL); cifs_strfromUCS_le(ses->serverNOS, (wchar_t *)bcc_ptr, len, nls_codepage); bcc_ptr += 2 * (len + 1); ses->serverNOS[2 * len] = 0; ses->serverNOS[1 + (2 * len)] = 0; remaining_words -= len + 1; if (remaining_words > 0) { len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words); /* last string is not always null terminated (for e.g. for Windows XP & 2000) */ ses->serverDomain = kcalloc(1, 2*(len+1),GFP_KERNEL); cifs_strfromUCS_le(ses->serverDomain, (wchar_t *)bcc_ptr, len, nls_codepage); bcc_ptr += 2*(len+1); ses->serverDomain[2*len] = 0; ses->serverDomain[1+(2*len)] = 0; } /* else no more room so create dummy domain string */ else ses->serverDomain = kcalloc(1, 2,GFP_KERNEL); } else { /* no room so create dummy domain and NOS string */ ses->serverDomain = kcalloc(1, 2, GFP_KERNEL); ses->serverNOS = kcalloc(1, 2, GFP_KERNEL); } } else { /* ASCII */ len = strnlen(bcc_ptr, 1024); if (((long) bcc_ptr + len) - (long) pByteArea(smb_buffer_response) <= BCC(smb_buffer_response)) { ses->serverOS = kcalloc(1, len + 1, GFP_KERNEL); strncpy(ses->serverOS, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; /* null terminate the string */ bcc_ptr++; len = strnlen(bcc_ptr, 1024); ses->serverNOS = kcalloc(1, len + 1,GFP_KERNEL); strncpy(ses->serverNOS, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; bcc_ptr++; len = strnlen(bcc_ptr, 1024); ses->serverDomain = kcalloc(1, len + 1, GFP_KERNEL); strncpy(ses->serverDomain, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; bcc_ptr++; } else cFYI(1, ("Variable field of length %d extends beyond end of smb ", len)); } } else { cERROR(1, (" Security Blob Length extends beyond end of SMB")); } } else { cERROR(1, ("No session structure passed in.")); } } else { cERROR(1, (" Invalid Word count %d: ", smb_buffer_response->WordCount)); rc = -EIO; } if (smb_buffer) cifs_buf_release(smb_buffer); return rc; } static int CIFSNTLMSSPNegotiateSessSetup(unsigned int xid, struct cifsSesInfo *ses, int * pNTLMv2_flag, const struct nls_table *nls_codepage) { struct smb_hdr *smb_buffer; struct smb_hdr *smb_buffer_response; SESSION_SETUP_ANDX *pSMB; SESSION_SETUP_ANDX *pSMBr; char *bcc_ptr; char *domain; int rc = 0; int remaining_words = 0; int bytes_returned = 0; int len; int SecurityBlobLength = sizeof (NEGOTIATE_MESSAGE); PNEGOTIATE_MESSAGE SecurityBlob; PCHALLENGE_MESSAGE SecurityBlob2; __u32 negotiate_flags, capabilities; __u16 count; cFYI(1, ("In NTLMSSP sesssetup (negotiate) ")); if(ses == NULL) return -EINVAL; domain = ses->domainName; *pNTLMv2_flag = FALSE; smb_buffer = cifs_buf_get(); if (smb_buffer == NULL) { return -ENOMEM; } smb_buffer_response = smb_buffer; pSMB = (SESSION_SETUP_ANDX *) smb_buffer; pSMBr = (SESSION_SETUP_ANDX *) smb_buffer_response; /* send SMBsessionSetup here */ header_assemble(smb_buffer, SMB_COM_SESSION_SETUP_ANDX, NULL /* no tCon exists yet */ , 12 /* wct */ ); pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC; pSMB->req.hdr.Flags |= (SMBFLG_CASELESS | SMBFLG_CANONICAL_PATH_FORMAT); pSMB->req.AndXCommand = 0xFF; pSMB->req.MaxBufferSize = cpu_to_le16(ses->server->maxBuf); pSMB->req.MaxMpxCount = cpu_to_le16(ses->server->maxReq); if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE; capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS | CAP_EXTENDED_SECURITY; if (ses->capabilities & CAP_UNICODE) { smb_buffer->Flags2 |= SMBFLG2_UNICODE; capabilities |= CAP_UNICODE; } if (ses->capabilities & CAP_STATUS32) { smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS; capabilities |= CAP_STATUS32; } if (ses->capabilities & CAP_DFS) { smb_buffer->Flags2 |= SMBFLG2_DFS; capabilities |= CAP_DFS; } pSMB->req.Capabilities = cpu_to_le32(capabilities); bcc_ptr = (char *) &pSMB->req.SecurityBlob; SecurityBlob = (PNEGOTIATE_MESSAGE) bcc_ptr; strncpy(SecurityBlob->Signature, NTLMSSP_SIGNATURE, 8); SecurityBlob->MessageType = NtLmNegotiate; negotiate_flags = NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_OEM | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_NTLM | 0x80000000 | /* NTLMSSP_NEGOTIATE_ALWAYS_SIGN | */ NTLMSSP_NEGOTIATE_128; if(sign_CIFS_PDUs) negotiate_flags |= NTLMSSP_NEGOTIATE_SIGN; if(ntlmv2_support) negotiate_flags |= NTLMSSP_NEGOTIATE_NTLMV2; /* setup pointers to domain name and workstation name */ bcc_ptr += SecurityBlobLength; SecurityBlob->WorkstationName.Buffer = 0; SecurityBlob->WorkstationName.Length = 0; SecurityBlob->WorkstationName.MaximumLength = 0; if (domain == NULL) { SecurityBlob->DomainName.Buffer = 0; SecurityBlob->DomainName.Length = 0; SecurityBlob->DomainName.MaximumLength = 0; } else { __u16 len; negotiate_flags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED; strncpy(bcc_ptr, domain, 63); len = strnlen(domain, 64); SecurityBlob->DomainName.MaximumLength = cpu_to_le16(len); SecurityBlob->DomainName.Buffer = cpu_to_le32((long) &SecurityBlob-> DomainString - (long) &SecurityBlob->Signature); bcc_ptr += len; SecurityBlobLength += len; SecurityBlob->DomainName.Length = cpu_to_le16(len); } if (ses->capabilities & CAP_UNICODE) { if ((long) bcc_ptr % 2) { *bcc_ptr = 0; bcc_ptr++; } bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, "Linux version ", 32, nls_codepage); bcc_ptr += 2 * bytes_returned; bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, system_utsname.release, 32, nls_codepage); bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; /* null terminate Linux version */ bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, CIFS_NETWORK_OPSYS, 64, nls_codepage); bcc_ptr += 2 * bytes_returned; *(bcc_ptr + 1) = 0; *(bcc_ptr + 2) = 0; bcc_ptr += 2; /* null terminate network opsys string */ *(bcc_ptr + 1) = 0; *(bcc_ptr + 2) = 0; bcc_ptr += 2; /* null domain */ } else { /* ASCII */ strcpy(bcc_ptr, "Linux version "); bcc_ptr += strlen("Linux version "); strcpy(bcc_ptr, system_utsname.release); bcc_ptr += strlen(system_utsname.release) + 1; strcpy(bcc_ptr, CIFS_NETWORK_OPSYS); bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1; bcc_ptr++; /* empty domain field */ *bcc_ptr = 0; } SecurityBlob->NegotiateFlags = cpu_to_le32(negotiate_flags); pSMB->req.SecurityBlobLength = cpu_to_le16(SecurityBlobLength); count = (long) bcc_ptr - (long) pByteArea(smb_buffer); smb_buffer->smb_buf_length += count; pSMB->req.ByteCount = cpu_to_le16(count); rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &bytes_returned, 1); if (smb_buffer_response->Status.CifsError == cpu_to_le32(NT_STATUS_MORE_PROCESSING_REQUIRED)) rc = 0; if (rc) { /* rc = map_smb_to_linux_error(smb_buffer_response); *//* done in SendReceive now */ } else if ((smb_buffer_response->WordCount == 3) || (smb_buffer_response->WordCount == 4)) { __u16 action = le16_to_cpu(pSMBr->resp.Action); __u16 blob_len = le16_to_cpu(pSMBr->resp.SecurityBlobLength); if (action & GUEST_LOGIN) cFYI(1, (" Guest login")); /* Do we want to set anything in SesInfo struct when guest login? */ bcc_ptr = pByteArea(smb_buffer_response); /* response can have either 3 or 4 word count - Samba sends 3 */ SecurityBlob2 = (PCHALLENGE_MESSAGE) bcc_ptr; if (SecurityBlob2->MessageType != NtLmChallenge) { cFYI(1, ("Unexpected NTLMSSP message type received %d", SecurityBlob2->MessageType)); } else if (ses) { ses->Suid = smb_buffer_response->Uid; /* UID left in le format */ cFYI(1, ("UID = %d ", ses->Suid)); if ((pSMBr->resp.hdr.WordCount == 3) || ((pSMBr->resp.hdr.WordCount == 4) && (blob_len < pSMBr->resp.ByteCount))) { if (pSMBr->resp.hdr.WordCount == 4) { bcc_ptr += blob_len; cFYI(1, ("Security Blob Length %d ", blob_len)); } cFYI(1, ("NTLMSSP Challenge rcvd ")); memcpy(ses->server->cryptKey, SecurityBlob2->Challenge, CIFS_CRYPTO_KEY_SIZE); if(SecurityBlob2->NegotiateFlags & cpu_to_le32(NTLMSSP_NEGOTIATE_NTLMV2)) *pNTLMv2_flag = TRUE; if((SecurityBlob2->NegotiateFlags & cpu_to_le32(NTLMSSP_NEGOTIATE_ALWAYS_SIGN)) || (sign_CIFS_PDUs > 1)) ses->server->secMode |= SECMODE_SIGN_REQUIRED; if ((SecurityBlob2->NegotiateFlags & cpu_to_le32(NTLMSSP_NEGOTIATE_SIGN)) && (sign_CIFS_PDUs)) ses->server->secMode |= SECMODE_SIGN_ENABLED; if (smb_buffer->Flags2 & SMBFLG2_UNICODE) { if ((long) (bcc_ptr) % 2) { remaining_words = (BCC(smb_buffer_response) - 1) / 2; bcc_ptr++; /* Unicode strings must be word aligned */ } else { remaining_words = BCC (smb_buffer_response) / 2; } len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words - 1); /* We look for obvious messed up bcc or strings in response so we do not go off the end since (at least) WIN2K and Windows XP have a major bug in not null terminating last Unicode string in response */ ses->serverOS = kcalloc(1, 2 * (len + 1), GFP_KERNEL); cifs_strfromUCS_le(ses->serverOS, (wchar_t *) bcc_ptr, len, nls_codepage); bcc_ptr += 2 * (len + 1); remaining_words -= len + 1; ses->serverOS[2 * len] = 0; ses->serverOS[1 + (2 * len)] = 0; if (remaining_words > 0) { len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words - 1); ses->serverNOS = kcalloc(1, 2 * (len + 1), GFP_KERNEL); cifs_strfromUCS_le(ses-> serverNOS, (wchar_t *) bcc_ptr, len, nls_codepage); bcc_ptr += 2 * (len + 1); ses->serverNOS[2 * len] = 0; ses->serverNOS[1 + (2 * len)] = 0; remaining_words -= len + 1; if (remaining_words > 0) { len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words); /* last string is not always null terminated (for e.g. for Windows XP & 2000) */ ses->serverDomain = kcalloc(1, 2 * (len + 1), GFP_KERNEL); cifs_strfromUCS_le (ses-> serverDomain, (wchar_t *) bcc_ptr, len, nls_codepage); bcc_ptr += 2 * (len + 1); ses-> serverDomain[2 * len] = 0; ses-> serverDomain[1 + (2 * len)] = 0; } /* else no more room so create dummy domain string */ else ses->serverDomain = kcalloc(1, 2, GFP_KERNEL); } else { /* no room so create dummy domain and NOS string */ ses->serverDomain = kcalloc(1, 2, GFP_KERNEL); ses->serverNOS = kcalloc(1, 2, GFP_KERNEL); } } else { /* ASCII */ len = strnlen(bcc_ptr, 1024); if (((long) bcc_ptr + len) - (long) pByteArea(smb_buffer_response) <= BCC(smb_buffer_response)) { ses->serverOS = kcalloc(1, len + 1, GFP_KERNEL); strncpy(ses->serverOS, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; /* null terminate string */ bcc_ptr++; len = strnlen(bcc_ptr, 1024); ses->serverNOS = kcalloc(1, len + 1, GFP_KERNEL); strncpy(ses->serverNOS, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; bcc_ptr++; len = strnlen(bcc_ptr, 1024); ses->serverDomain = kcalloc(1, len + 1, GFP_KERNEL); strncpy(ses->serverDomain, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; bcc_ptr++; } else cFYI(1, ("Variable field of length %d extends beyond end of smb ", len)); } } else { cERROR(1, (" Security Blob Length extends beyond end of SMB")); } } else { cERROR(1, ("No session structure passed in.")); } } else { cERROR(1, (" Invalid Word count %d: ", smb_buffer_response->WordCount)); rc = -EIO; } if (smb_buffer) cifs_buf_release(smb_buffer); return rc; } static int CIFSNTLMSSPAuthSessSetup(unsigned int xid, struct cifsSesInfo *ses, char *ntlm_session_key, int ntlmv2_flag, const struct nls_table *nls_codepage) { struct smb_hdr *smb_buffer; struct smb_hdr *smb_buffer_response; SESSION_SETUP_ANDX *pSMB; SESSION_SETUP_ANDX *pSMBr; char *bcc_ptr; char *user; char *domain; int rc = 0; int remaining_words = 0; int bytes_returned = 0; int len; int SecurityBlobLength = sizeof (AUTHENTICATE_MESSAGE); PAUTHENTICATE_MESSAGE SecurityBlob; __u32 negotiate_flags, capabilities; __u16 count; cFYI(1, ("In NTLMSSPSessSetup (Authenticate)")); if(ses == NULL) return -EINVAL; user = ses->userName; domain = ses->domainName; smb_buffer = cifs_buf_get(); if (smb_buffer == NULL) { return -ENOMEM; } smb_buffer_response = smb_buffer; pSMB = (SESSION_SETUP_ANDX *) smb_buffer; pSMBr = (SESSION_SETUP_ANDX *) smb_buffer_response; /* send SMBsessionSetup here */ header_assemble(smb_buffer, SMB_COM_SESSION_SETUP_ANDX, NULL /* no tCon exists yet */ , 12 /* wct */ ); pSMB->req.hdr.Flags |= (SMBFLG_CASELESS | SMBFLG_CANONICAL_PATH_FORMAT); pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC; pSMB->req.AndXCommand = 0xFF; pSMB->req.MaxBufferSize = cpu_to_le16(ses->server->maxBuf); pSMB->req.MaxMpxCount = cpu_to_le16(ses->server->maxReq); pSMB->req.hdr.Uid = ses->Suid; if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE; capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS | CAP_EXTENDED_SECURITY; if (ses->capabilities & CAP_UNICODE) { smb_buffer->Flags2 |= SMBFLG2_UNICODE; capabilities |= CAP_UNICODE; } if (ses->capabilities & CAP_STATUS32) { smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS; capabilities |= CAP_STATUS32; } if (ses->capabilities & CAP_DFS) { smb_buffer->Flags2 |= SMBFLG2_DFS; capabilities |= CAP_DFS; } pSMB->req.Capabilities = cpu_to_le32(capabilities); bcc_ptr = (char *) &pSMB->req.SecurityBlob; SecurityBlob = (PAUTHENTICATE_MESSAGE) bcc_ptr; strncpy(SecurityBlob->Signature, NTLMSSP_SIGNATURE, 8); SecurityBlob->MessageType = NtLmAuthenticate; bcc_ptr += SecurityBlobLength; negotiate_flags = NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_TARGET_INFO | 0x80000000 | NTLMSSP_NEGOTIATE_128; if(sign_CIFS_PDUs) negotiate_flags |= /* NTLMSSP_NEGOTIATE_ALWAYS_SIGN |*/ NTLMSSP_NEGOTIATE_SIGN; if(ntlmv2_flag) negotiate_flags |= NTLMSSP_NEGOTIATE_NTLMV2; /* setup pointers to domain name and workstation name */ SecurityBlob->WorkstationName.Buffer = 0; SecurityBlob->WorkstationName.Length = 0; SecurityBlob->WorkstationName.MaximumLength = 0; SecurityBlob->SessionKey.Length = 0; SecurityBlob->SessionKey.MaximumLength = 0; SecurityBlob->SessionKey.Buffer = 0; SecurityBlob->LmChallengeResponse.Length = 0; SecurityBlob->LmChallengeResponse.MaximumLength = 0; SecurityBlob->LmChallengeResponse.Buffer = 0; SecurityBlob->NtChallengeResponse.Length = cpu_to_le16(CIFS_SESSION_KEY_SIZE); SecurityBlob->NtChallengeResponse.MaximumLength = cpu_to_le16(CIFS_SESSION_KEY_SIZE); memcpy(bcc_ptr, ntlm_session_key, CIFS_SESSION_KEY_SIZE); SecurityBlob->NtChallengeResponse.Buffer = cpu_to_le32(SecurityBlobLength); SecurityBlobLength += CIFS_SESSION_KEY_SIZE; bcc_ptr += CIFS_SESSION_KEY_SIZE; if (ses->capabilities & CAP_UNICODE) { if (domain == NULL) { SecurityBlob->DomainName.Buffer = 0; SecurityBlob->DomainName.Length = 0; SecurityBlob->DomainName.MaximumLength = 0; } else { __u16 len = cifs_strtoUCS((wchar_t *) bcc_ptr, domain, 64, nls_codepage); len *= 2; SecurityBlob->DomainName.MaximumLength = cpu_to_le16(len); SecurityBlob->DomainName.Buffer = cpu_to_le32(SecurityBlobLength); bcc_ptr += len; SecurityBlobLength += len; SecurityBlob->DomainName.Length = cpu_to_le16(len); } if (user == NULL) { SecurityBlob->UserName.Buffer = 0; SecurityBlob->UserName.Length = 0; SecurityBlob->UserName.MaximumLength = 0; } else { __u16 len = cifs_strtoUCS((wchar_t *) bcc_ptr, user, 64, nls_codepage); len *= 2; SecurityBlob->UserName.MaximumLength = cpu_to_le16(len); SecurityBlob->UserName.Buffer = cpu_to_le32(SecurityBlobLength); bcc_ptr += len; SecurityBlobLength += len; SecurityBlob->UserName.Length = cpu_to_le16(len); } /* SecurityBlob->WorkstationName.Length = cifs_strtoUCS((wchar_t *) bcc_ptr, "AMACHINE",64, nls_codepage); SecurityBlob->WorkstationName.Length *= 2; SecurityBlob->WorkstationName.MaximumLength = cpu_to_le16(SecurityBlob->WorkstationName.Length); SecurityBlob->WorkstationName.Buffer = cpu_to_le32(SecurityBlobLength); bcc_ptr += SecurityBlob->WorkstationName.Length; SecurityBlobLength += SecurityBlob->WorkstationName.Length; SecurityBlob->WorkstationName.Length = cpu_to_le16(SecurityBlob->WorkstationName.Length); */ if ((long) bcc_ptr % 2) { *bcc_ptr = 0; bcc_ptr++; } bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, "Linux version ", 32, nls_codepage); bcc_ptr += 2 * bytes_returned; bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, system_utsname.release, 32, nls_codepage); bcc_ptr += 2 * bytes_returned; bcc_ptr += 2; /* null term version string */ bytes_returned = cifs_strtoUCS((wchar_t *) bcc_ptr, CIFS_NETWORK_OPSYS, 64, nls_codepage); bcc_ptr += 2 * bytes_returned; *(bcc_ptr + 1) = 0; *(bcc_ptr + 2) = 0; bcc_ptr += 2; /* null terminate network opsys string */ *(bcc_ptr + 1) = 0; *(bcc_ptr + 2) = 0; bcc_ptr += 2; /* null domain */ } else { /* ASCII */ if (domain == NULL) { SecurityBlob->DomainName.Buffer = 0; SecurityBlob->DomainName.Length = 0; SecurityBlob->DomainName.MaximumLength = 0; } else { __u16 len; negotiate_flags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED; strncpy(bcc_ptr, domain, 63); len = strnlen(domain, 64); SecurityBlob->DomainName.MaximumLength = cpu_to_le16(len); SecurityBlob->DomainName.Buffer = cpu_to_le32(SecurityBlobLength); bcc_ptr += len; SecurityBlobLength += len; SecurityBlob->DomainName.Length = cpu_to_le16(len); } if (user == NULL) { SecurityBlob->UserName.Buffer = 0; SecurityBlob->UserName.Length = 0; SecurityBlob->UserName.MaximumLength = 0; } else { __u16 len; strncpy(bcc_ptr, user, 63); len = strnlen(user, 64); SecurityBlob->UserName.MaximumLength = cpu_to_le16(len); SecurityBlob->UserName.Buffer = cpu_to_le32(SecurityBlobLength); bcc_ptr += len; SecurityBlobLength += len; SecurityBlob->UserName.Length = cpu_to_le16(len); } /* BB fill in our workstation name if known BB */ strcpy(bcc_ptr, "Linux version "); bcc_ptr += strlen("Linux version "); strcpy(bcc_ptr, system_utsname.release); bcc_ptr += strlen(system_utsname.release) + 1; strcpy(bcc_ptr, CIFS_NETWORK_OPSYS); bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1; bcc_ptr++; /* null domain */ *bcc_ptr = 0; } SecurityBlob->NegotiateFlags = cpu_to_le32(negotiate_flags); pSMB->req.SecurityBlobLength = cpu_to_le16(SecurityBlobLength); count = (long) bcc_ptr - (long) pByteArea(smb_buffer); smb_buffer->smb_buf_length += count; pSMB->req.ByteCount = cpu_to_le16(count); rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &bytes_returned, 1); if (rc) { /* rc = map_smb_to_linux_error(smb_buffer_response); *//* done in SendReceive now */ } else if ((smb_buffer_response->WordCount == 3) || (smb_buffer_response->WordCount == 4)) { __u16 action = le16_to_cpu(pSMBr->resp.Action); __u16 blob_len = le16_to_cpu(pSMBr->resp.SecurityBlobLength); if (action & GUEST_LOGIN) cFYI(1, (" Guest login")); /* BB do we want to set anything in SesInfo struct ? */ /* if(SecurityBlob2->MessageType != NtLm??){ cFYI("Unexpected message type on auth response is %d ")); } */ if (ses) { cFYI(1, ("Does UID on challenge %d match auth response UID %d ", ses->Suid, smb_buffer_response->Uid)); ses->Suid = smb_buffer_response->Uid; /* UID left in wire format */ bcc_ptr = pByteArea(smb_buffer_response); /* response can have either 3 or 4 word count - Samba sends 3 */ if ((pSMBr->resp.hdr.WordCount == 3) || ((pSMBr->resp.hdr.WordCount == 4) && (blob_len < pSMBr->resp.ByteCount))) { if (pSMBr->resp.hdr.WordCount == 4) { bcc_ptr += blob_len; cFYI(1, ("Security Blob Length %d ", blob_len)); } cFYI(1, ("NTLMSSP response to Authenticate ")); if (smb_buffer->Flags2 & SMBFLG2_UNICODE) { if ((long) (bcc_ptr) % 2) { remaining_words = (BCC(smb_buffer_response) - 1) / 2; bcc_ptr++; /* Unicode strings must be word aligned */ } else { remaining_words = BCC(smb_buffer_response) / 2; } len = UniStrnlen((wchar_t *) bcc_ptr,remaining_words - 1); /* We look for obvious messed up bcc or strings in response so we do not go off the end since (at least) WIN2K and Windows XP have a major bug in not null terminating last Unicode string in response */ ses->serverOS = kcalloc(1, 2 * (len + 1), GFP_KERNEL); cifs_strfromUCS_le(ses->serverOS, (wchar_t *) bcc_ptr, len, nls_codepage); bcc_ptr += 2 * (len + 1); remaining_words -= len + 1; ses->serverOS[2 * len] = 0; ses->serverOS[1 + (2 * len)] = 0; if (remaining_words > 0) { len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words - 1); ses->serverNOS = kcalloc(1, 2 * (len + 1), GFP_KERNEL); cifs_strfromUCS_le(ses-> serverNOS, (wchar_t *) bcc_ptr, len, nls_codepage); bcc_ptr += 2 * (len + 1); ses->serverNOS[2 * len] = 0; ses->serverNOS[1+(2*len)] = 0; remaining_words -= len + 1; if (remaining_words > 0) { len = UniStrnlen((wchar_t *) bcc_ptr, remaining_words); /* last string not always null terminated (e.g. for Windows XP & 2000) */ ses->serverDomain = kcalloc(1, 2 * (len + 1), GFP_KERNEL); cifs_strfromUCS_le (ses-> serverDomain, (wchar_t *) bcc_ptr, len, nls_codepage); bcc_ptr += 2 * (len + 1); ses-> serverDomain[2 * len] = 0; ses-> serverDomain[1 + (2 * len)] = 0; } /* else no more room so create dummy domain string */ else ses->serverDomain = kcalloc(1, 2,GFP_KERNEL); } else { /* no room so create dummy domain and NOS string */ ses->serverDomain = kcalloc(1, 2, GFP_KERNEL); ses->serverNOS = kcalloc(1, 2, GFP_KERNEL); } } else { /* ASCII */ len = strnlen(bcc_ptr, 1024); if (((long) bcc_ptr + len) - (long) pByteArea(smb_buffer_response) <= BCC(smb_buffer_response)) { ses->serverOS = kcalloc(1, len + 1,GFP_KERNEL); strncpy(ses->serverOS,bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; /* null terminate the string */ bcc_ptr++; len = strnlen(bcc_ptr, 1024); ses->serverNOS = kcalloc(1, len+1,GFP_KERNEL); strncpy(ses->serverNOS, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; bcc_ptr++; len = strnlen(bcc_ptr, 1024); ses->serverDomain = kcalloc(1, len+1,GFP_KERNEL); strncpy(ses->serverDomain, bcc_ptr, len); bcc_ptr += len; bcc_ptr[0] = 0; bcc_ptr++; } else cFYI(1, ("Variable field of length %d extends beyond end of smb ", len)); } } else { cERROR(1, (" Security Blob Length extends beyond end of SMB")); } } else { cERROR(1, ("No session structure passed in.")); } } else { cERROR(1, (" Invalid Word count %d: ", smb_buffer_response->WordCount)); rc = -EIO; } if (smb_buffer) cifs_buf_release(smb_buffer); return rc; } int CIFSTCon(unsigned int xid, struct cifsSesInfo *ses, const char *tree, struct cifsTconInfo *tcon, const struct nls_table *nls_codepage) { struct smb_hdr *smb_buffer; struct smb_hdr *smb_buffer_response; TCONX_REQ *pSMB; TCONX_RSP *pSMBr; unsigned char *bcc_ptr; int rc = 0; int length; __u16 count; if (ses == NULL) return -EIO; smb_buffer = cifs_buf_get(); if (smb_buffer == NULL) { return -ENOMEM; } smb_buffer_response = smb_buffer; header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX, NULL /*no tid */ , 4 /*wct */ ); smb_buffer->Uid = ses->Suid; pSMB = (TCONX_REQ *) smb_buffer; pSMBr = (TCONX_RSP *) smb_buffer_response; pSMB->AndXCommand = 0xFF; pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO); pSMB->PasswordLength = cpu_to_le16(1); /* minimum */ bcc_ptr = &pSMB->Password[0]; bcc_ptr++; /* skip password */ if(ses->server->secMode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE; if (ses->capabilities & CAP_STATUS32) { smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS; } if (ses->capabilities & CAP_DFS) { smb_buffer->Flags2 |= SMBFLG2_DFS; } if (ses->capabilities & CAP_UNICODE) { smb_buffer->Flags2 |= SMBFLG2_UNICODE; length = cifs_strtoUCS((wchar_t *) bcc_ptr, tree, 100, nls_codepage); bcc_ptr += 2 * length; /* convert num of 16 bit words to bytes */ bcc_ptr += 2; /* skip trailing null */ } else { /* ASCII */ strcpy(bcc_ptr, tree); bcc_ptr += strlen(tree) + 1; } strcpy(bcc_ptr, "?????"); bcc_ptr += strlen("?????"); bcc_ptr += 1; count = bcc_ptr - &pSMB->Password[0]; pSMB->hdr.smb_buf_length += count; pSMB->ByteCount = cpu_to_le16(count); rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length, 0); /* if (rc) rc = map_smb_to_linux_error(smb_buffer_response); */ /* above now done in SendReceive */ if ((rc == 0) && (tcon != NULL)) { tcon->tidStatus = CifsGood; tcon->tid = smb_buffer_response->Tid; bcc_ptr = pByteArea(smb_buffer_response); length = strnlen(bcc_ptr, BCC(smb_buffer_response) - 2); /* skip service field (NB: this field is always ASCII) */ bcc_ptr += length + 1; strncpy(tcon->treeName, tree, MAX_TREE_SIZE); if (smb_buffer->Flags2 & SMBFLG2_UNICODE) { length = UniStrnlen((wchar_t *) bcc_ptr, 512); if ((bcc_ptr + (2 * length)) - pByteArea(smb_buffer_response) <= BCC(smb_buffer_response)) { if(tcon->nativeFileSystem) kfree(tcon->nativeFileSystem); tcon->nativeFileSystem = kcalloc(1, length + 2, GFP_KERNEL); cifs_strfromUCS_le(tcon->nativeFileSystem, (wchar_t *) bcc_ptr, length, nls_codepage); bcc_ptr += 2 * length; bcc_ptr[0] = 0; /* null terminate the string */ bcc_ptr[1] = 0; bcc_ptr += 2; } /* else do not bother copying these informational fields */ } else { length = strnlen(bcc_ptr, 1024); if ((bcc_ptr + length) - pByteArea(smb_buffer_response) <= BCC(smb_buffer_response)) { if(tcon->nativeFileSystem) kfree(tcon->nativeFileSystem); tcon->nativeFileSystem = kcalloc(1, length + 1, GFP_KERNEL); strncpy(tcon->nativeFileSystem, bcc_ptr, length); } /* else do not bother copying these informational fields */ } tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport); cFYI(1, ("Tcon flags: 0x%x ", tcon->Flags)); } else if ((rc == 0) && tcon == NULL) { /* all we need to save for IPC$ connection */ ses->ipc_tid = smb_buffer_response->Tid; } if (smb_buffer) cifs_buf_release(smb_buffer); return rc; } int cifs_umount(struct super_block *sb, struct cifs_sb_info *cifs_sb) { int rc = 0; int xid; struct cifsSesInfo *ses = NULL; struct task_struct *cifsd_task; xid = GetXid(); if (cifs_sb->tcon) { ses = cifs_sb->tcon->ses; /* save ptr to ses before delete tcon!*/ rc = CIFSSMBTDis(xid, cifs_sb->tcon); if (rc == -EBUSY) { FreeXid(xid); return 0; } tconInfoFree(cifs_sb->tcon); if ((ses) && (ses->server)) { /* save off task so we do not refer to ses later */ cifsd_task = ses->server->tsk; cFYI(1, ("About to do SMBLogoff ")); rc = CIFSSMBLogoff(xid, ses); if (rc == -EBUSY) { FreeXid(xid); return 0; } else if (rc == -ESHUTDOWN) { cFYI(1,("Waking up socket by sending it signal")); if(cifsd_task) send_sig(SIGKILL,cifsd_task,1); rc = 0; } /* else - we have an smb session left on this socket do not kill cifsd */ } else cFYI(1, ("No session or bad tcon")); } cifs_sb->tcon = NULL; if (ses) { set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(HZ / 2); } if (ses) sesInfoFree(ses); FreeXid(xid); return rc; /* BB check if we should always return zero here */ } int cifs_setup_session(unsigned int xid, struct cifsSesInfo *pSesInfo, struct nls_table * nls_info) { int rc = 0; char ntlm_session_key[CIFS_SESSION_KEY_SIZE]; int ntlmv2_flag = FALSE; int first_time = 0; /* what if server changes its buffer size after dropping the session? */ if(pSesInfo->server->maxBuf == 0) /* no need to send on reconnect */ { rc = CIFSSMBNegotiate(xid, pSesInfo); if(rc == -EAGAIN) /* retry only once on 1st time connection */ { rc = CIFSSMBNegotiate(xid, pSesInfo); if(rc == -EAGAIN) rc = -EHOSTDOWN; } if(rc == 0) { spin_lock(&GlobalMid_Lock); if(pSesInfo->server->tcpStatus != CifsExiting) pSesInfo->server->tcpStatus = CifsGood; else rc = -EHOSTDOWN; spin_unlock(&GlobalMid_Lock); } first_time = 1; } if (!rc) { pSesInfo->capabilities = pSesInfo->server->capabilities; if(linuxExtEnabled == 0) pSesInfo->capabilities &= (~CAP_UNIX); /* pSesInfo->sequence_number = 0;*/ cFYI(1,("Security Mode: 0x%x Capabilities: 0x%x Time Zone: %d", pSesInfo->server->secMode, pSesInfo->server->capabilities, pSesInfo->server->timeZone)); if (extended_security && (pSesInfo->capabilities & CAP_EXTENDED_SECURITY) && (pSesInfo->server->secType == NTLMSSP)) { cFYI(1, ("New style sesssetup ")); rc = CIFSSpnegoSessSetup(xid, pSesInfo, NULL /* security blob */, 0 /* blob length */, nls_info); } else if (extended_security && (pSesInfo->capabilities & CAP_EXTENDED_SECURITY) && (pSesInfo->server->secType == RawNTLMSSP)) { cFYI(1, ("NTLMSSP sesssetup ")); rc = CIFSNTLMSSPNegotiateSessSetup(xid, pSesInfo, &ntlmv2_flag, nls_info); if (!rc) { if(ntlmv2_flag) { char * v2_response; cFYI(1,("Can use more secure NTLM version 2 password hash")); if(CalcNTLMv2_partial_mac_key(pSesInfo, nls_info)) { rc = -ENOMEM; goto ss_err_exit; } else v2_response = kmalloc(16 + 64 /* blob */, GFP_KERNEL); if(v2_response) { CalcNTLMv2_response(pSesInfo,v2_response); /* if(first_time) cifs_calculate_ntlmv2_mac_key( pSesInfo->server->mac_signing_key, response, ntlm_session_key, */ kfree(v2_response); /* BB Put dummy sig in SessSetup PDU? */ } else { rc = -ENOMEM; goto ss_err_exit; } } else { SMBNTencrypt(pSesInfo->password, pSesInfo->server->cryptKey, ntlm_session_key); if(first_time) cifs_calculate_mac_key( pSesInfo->server->mac_signing_key, ntlm_session_key, pSesInfo->password); } /* for better security the weaker lanman hash not sent in AuthSessSetup so we no longer calculate it */ rc = CIFSNTLMSSPAuthSessSetup(xid, pSesInfo, ntlm_session_key, ntlmv2_flag, nls_info); } } else { /* old style NTLM 0.12 session setup */ SMBNTencrypt(pSesInfo->password, pSesInfo->server->cryptKey, ntlm_session_key); if(first_time) cifs_calculate_mac_key( pSesInfo->server->mac_signing_key, ntlm_session_key, pSesInfo->password); rc = CIFSSessSetup(xid, pSesInfo, ntlm_session_key, nls_info); } if (rc) { cERROR(1,("Send error in SessSetup = %d",rc)); } else { cFYI(1,("CIFS Session Established successfully")); pSesInfo->status = CifsGood; } } ss_err_exit: return rc; }
kzlin129/tt-gpl
go9/linux-s3c24xx/fs/cifs/connect.c
C
gpl-2.0
101,660
<?php if ( ! class_exists( 'WPBakeryVisualComposerCssEditor' ) ) { class WPBakeryVisualComposerCssEditor { protected $js_script_appended = false; protected $settings = array(); protected $value = ''; protected $layers = array( 'margin', 'border', 'padding', 'content' ); protected $positions = array( 'top', 'right', 'bottom', 'left' ); function __construct() { } /** * Setters/Getters {{ */ function settings( $settings = null ) { if ( is_array( $settings ) ) $this->settings = $settings; return $this->settings; } function setting( $key ) { return isset( $this->settings[$key] ) ? $this->settings[$key] : ''; } function value( $value = null ) { if ( is_string( $value ) ) { $this->value = $value; } return $this->value; } function params( $values = null ) { if ( is_array( $values ) ) $this->params = $values; return $this->params; } // }} function render() { $output = '<div class="vc_css-editor vc_row" data-css-editor="true">'; $output .= $this->onionLayout(); $output .= '<div class="vc_col-xs-5 vc_settings">' . ' <label>' . __( 'Border', LANGUAGE_ZONE ) . '</label> ' . ' <div class="color-group"><input type="text" name="border_color" value="" class="vc_color-control"></div>' . ' <div class="vc_border-style"><select name="border_style" class="vc_border-style">' . $this->getBorderStyleOptions() . '</select></div>' . ' <label>' . __( 'Background', LANGUAGE_ZONE ) . '</label>' . ' <div class="color-group"><input type="text" name="background_color" value="" class="vc_color-control"></div>' . ' <div class="vc_background-image">' . $this->getBackgroundImageControl() . '<div class="vc_clearfix"></div></div>' . ' <div class="vc_background-style"><select name="background_style" class="vc_background-style">' . $this->getBackgroundStyleOptions() . '</select></div>' . ' <label>' . __( 'Box controls', LANGUAGE_ZONE ) . '</label>' . ' <label class="vc_checkbox"><input type="checkbox" name="simply" class="vc_simplify" value=""> ' . __( 'Simplify controls', LANGUAGE_ZONE ) . '</label>' . '</div>'; $output .= '<input name="' . $this->setting( 'param_name' ) . '" class="wpb_vc_param_value ' . $this->setting( 'param_name' ) . ' ' . $this->setting( 'type' ) . '_field" type="hidden" value="' . esc_attr( $this->value() ) . '"/>'; $output .= '</div><div class="vc_clearfix"></div>'; $output .= '<script type="text/html" id="vc_css-editor-image-block">' . '<li class="added">' . ' <div class="inner" style="width: 75px; height: 75px; overflow: hidden;text-align: center;">' . ' <img src="{{ img.url }}?id={{ img.id }}" data-image-id="{{ img.id }}" class="vc_ce-image<# if(!_.isUndefined(img.css_class)) {#> {{ img.css_class }}<# }#>">' . ' </div>' . ' <a href="#" class="icon-remove"></a>' . '</li>' . '</script>'; if(!$this->js_script_appended) { $output .= '<script type="text/javascript" src="' . vc_asset_url( 'js/params/css_editor.js' ) . '"></script>'; $this->js_script_appended = true; } return apply_filters( 'vc_css_editor', $output ); } function getBackgroundImageControl() { return '<ul class="vc_image">' . '</ul>' . '<a href="#" class="vc_add-image">' . __( 'Add image', LANGUAGE_ZONE ) . '</a>'; } function getBorderStyleOptions() { $output = '<option value="">' . __( 'Theme defaults', LANGUAGE_ZONE ) . '</option>'; $styles = array( 'solid', 'dotted', 'dashed', 'none', 'hidden', 'double', 'groove', 'ridge', 'inset', 'outset', 'initial', 'inherit' ); foreach ( $styles as $style ) { $output .= '<option value="' . $style . '">' . __( ucfirst( $style ), LANGUAGE_ZONE ) . '</option>'; } return $output; } function getBackgroundStyleOptions() { $output = '<option value="">' . __( 'Theme defaults', LANGUAGE_ZONE ) . '</option>'; $styles = array( __( "Cover", LANGUAGE_ZONE ) => 'cover', __( 'Contain', LANGUAGE_ZONE ) => 'contain', __( 'No Repeat', LANGUAGE_ZONE ) => 'no-repeat', __( 'Repeat', LANGUAGE_ZONE ) => 'repeat' ); foreach ( $styles as $name => $style ) { $output .= '<option value="' . $style . '">' . $name . '</option>'; } return $output; } function onionLayout() { $output = '<div class="vc_layout-onion vc_col-xs-7">' . ' <div class="vc_margin">' . $this->layerControls( 'margin' ) . ' <div class="vc_border">' . $this->layerControls( 'border', 'width' ) . ' <div class="vc_padding">' . $this->layerControls( 'padding' ) . ' <div class="vc_content"><i></i></div>' . ' </div>' . ' </div>' . ' </div>' . '</div>'; return $output; } protected function layerControls( $name, $prefix = '' ) { $output = '<label>' . __( $name, LANGUAGE_ZONE ) . '</label>'; foreach ( $this->positions as $pos ) { $output .= '<input type="text" name="' . $name . '_' . $pos . ( $prefix != '' ? '_' . $prefix : '' ) . '" data-name="' . $name . ( $prefix != '' ? '-' . $prefix : '' ) . '-' . $pos . '" class="vc_' . $pos . '" placeholder="-" data-attribute="' . $name . '" value="">'; } return $output; } } } function vc_css_editor_form_field( $settings, $value ) { $css_editor = new WPBakeryVisualComposerCssEditor(); $css_editor->settings( $settings ); $css_editor->value( $value ); return $css_editor->render(); }
proj-2014/vlan247-test-wp
wp-content/themes/dt-the7/wpbakery/js_composer/include/params/css_editor/css_editor.php
PHP
gpl-2.0
5,474
#include "driver.h" #include "vidhrdw/generic.h" static struct tilemap *bg_layer,*fg_layer,*tx_layer; unsigned char *dynduke_back_data,*dynduke_fore_data,*dynduke_scroll_ram,*dynduke_control_ram; static int flipscreen,back_bankbase,fore_bankbase,back_palbase; static int back_enable,fore_enable,sprite_enable; /******************************************************************************/ WRITE_HANDLER( dynduke_paletteram_w ) { int r,g,b; paletteram[offset]=data; data=paletteram[offset&0xffe]|(paletteram[offset|1]<<8); r = (data >> 0) & 0x0f; g = (data >> 4) & 0x0f; b = (data >> 8) & 0x0f; r = (r << 4) | r; g = (g << 4) | g; b = (b << 4) | b; palette_change_color(offset/2,r,g,b); /* This is a kludge to handle 5bpp graphics but 4bpp palette data */ if (offset<1024) { palette_change_color(((offset&0x1f)/2) | (offset&0xffe0) | 2048,r,g,b); palette_change_color(((offset&0x1f)/2) | (offset&0xffe0) | 2048 | 16,r,g,b); } } READ_HANDLER( dynduke_background_r ) { return dynduke_back_data[offset]; } READ_HANDLER( dynduke_foreground_r ) { return dynduke_fore_data[offset]; } WRITE_HANDLER( dynduke_background_w ) { dynduke_back_data[offset]=data; tilemap_mark_tile_dirty(bg_layer,offset/2); } WRITE_HANDLER( dynduke_foreground_w ) { dynduke_fore_data[offset]=data; tilemap_mark_tile_dirty(fg_layer,offset/2); } WRITE_HANDLER( dynduke_text_w ) { videoram[offset]=data; tilemap_mark_tile_dirty(tx_layer,offset/2); } static void get_bg_tile_info(int tile_index) { int tile=dynduke_back_data[2*tile_index]+(dynduke_back_data[2*tile_index+1]<<8); int color=tile >> 12; tile=tile&0xfff; SET_TILE_INFO(1,tile+back_bankbase,color+back_palbase) } static void get_fg_tile_info(int tile_index) { int tile=dynduke_fore_data[2*tile_index]+(dynduke_fore_data[2*tile_index+1]<<8); int color=tile >> 12; tile=tile&0xfff; SET_TILE_INFO(2,tile+fore_bankbase,color) } static void get_tx_tile_info(int tile_index) { int tile=videoram[2*tile_index]+((videoram[2*tile_index+1]&0xc0)<<2); int color=videoram[2*tile_index+1]&0xf; SET_TILE_INFO(0,tile,color) } int dynduke_vh_start(void) { bg_layer = tilemap_create(get_bg_tile_info,tilemap_scan_cols,TILEMAP_SPLIT, 16,16,32,32); fg_layer = tilemap_create(get_fg_tile_info,tilemap_scan_cols,TILEMAP_TRANSPARENT,16,16,32,32); tx_layer = tilemap_create(get_tx_tile_info,tilemap_scan_rows,TILEMAP_TRANSPARENT, 8, 8,32,32); bg_layer->transmask[0] = 0x0000ffff; /* 4bpp */ bg_layer->transmask[1] = 0xffff0000; /* The rest - 1bpp */ fg_layer->transparent_pen = 15; tx_layer->transparent_pen = 15; return 0; } WRITE_HANDLER( dynduke_gfxbank_w ) { static int old_back,old_fore; if (data&0x01) back_bankbase=0x1000; else back_bankbase=0; if (data&0x10) fore_bankbase=0x1000; else fore_bankbase=0; if (back_bankbase!=old_back) tilemap_mark_all_tiles_dirty(bg_layer); if (fore_bankbase!=old_fore) tilemap_mark_all_tiles_dirty(fg_layer); old_back=back_bankbase; old_fore=fore_bankbase; } WRITE_HANDLER( dynduke_control_w ) { static int old_bpal; dynduke_control_ram[offset]=data; if (offset!=6) return; if (data&0x1) back_enable=0; else back_enable=1; if (data&0x2) back_palbase=16; else back_palbase=0; if (data&0x4) fore_enable=0; else fore_enable=1; if (data&0x8) sprite_enable=0; else sprite_enable=1; if (back_palbase!=old_bpal) tilemap_mark_all_tiles_dirty(bg_layer); old_bpal=back_palbase; flipscreen=data&0x40; tilemap_set_flip(ALL_TILEMAPS,flipscreen ? (TILEMAP_FLIPY | TILEMAP_FLIPX) : 0); } static void draw_sprites(struct osd_bitmap *bitmap,int pri) { int offs,fx,fy,x,y,color,sprite; if (!sprite_enable) return; for (offs = 0x1000-8;offs >= 0;offs -= 8) { /* Don't draw empty sprite table entries */ if (buffered_spriteram[offs+7]!=0xf) continue; if (buffered_spriteram[offs+0]==0xf0f) continue; if (((buffered_spriteram[offs+5]>>5)&3)!=pri) continue; fx= buffered_spriteram[offs+1]&0x20; fy= buffered_spriteram[offs+1]&0x40; y = buffered_spriteram[offs+0]; x = buffered_spriteram[offs+4]; if (buffered_spriteram[offs+5]&1) x=0-(0x100-x); color = buffered_spriteram[offs+1]&0x1f; sprite = buffered_spriteram[offs+2]+(buffered_spriteram[offs+3]<<8); sprite &= 0x3fff; if (flipscreen) { x=240-x; y=240-y; if (fx) fx=0; else fx=1; if (fy) fy=0; else fy=1; } drawgfx(bitmap,Machine->gfx[3], sprite, color,fx,fy,x,y, &Machine->visible_area,TRANSPARENCY_PEN,15); } } void dynduke_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh) { int color,offs,sprite; int colmask[32],i,pal_base; /* Setup the tilemaps */ tilemap_set_scrolly( bg_layer,0, ((dynduke_scroll_ram[0x02]&0x30)<<4)+((dynduke_scroll_ram[0x04]&0x7f)<<1)+((dynduke_scroll_ram[0x04]&0x80)>>7) ); tilemap_set_scrollx( bg_layer,0, ((dynduke_scroll_ram[0x12]&0x30)<<4)+((dynduke_scroll_ram[0x14]&0x7f)<<1)+((dynduke_scroll_ram[0x14]&0x80)>>7) ); tilemap_set_scrolly( fg_layer,0, ((dynduke_scroll_ram[0x22]&0x30)<<4)+((dynduke_scroll_ram[0x24]&0x7f)<<1)+((dynduke_scroll_ram[0x24]&0x80)>>7) ); tilemap_set_scrollx( fg_layer,0, ((dynduke_scroll_ram[0x32]&0x30)<<4)+((dynduke_scroll_ram[0x34]&0x7f)<<1)+((dynduke_scroll_ram[0x34]&0x80)>>7) ); tilemap_set_enable( bg_layer,back_enable); tilemap_set_enable( fg_layer,fore_enable); tilemap_update(ALL_TILEMAPS); /* Build the dynamic palette */ palette_init_used_colors(); /* Sprites */ pal_base = Machine->drv->gfxdecodeinfo[3].color_codes_start; for (color = 0;color < 32;color++) colmask[color] = 0; for (offs = 0;offs <0x1000;offs += 8) { color = spriteram[offs+1]&0x1f; sprite = buffered_spriteram[offs+2]+(buffered_spriteram[offs+3]<<8); sprite &= 0x3fff; colmask[color] |= Machine->gfx[3]->pen_usage[sprite]; } for (color = 0;color < 32;color++) { for (i = 0;i < 15;i++) { if (colmask[color] & (1 << i)) palette_used_colors[pal_base + 16 * color + i] = PALETTE_COLOR_USED; } } if (palette_recalc()) tilemap_mark_all_pixels_dirty(ALL_TILEMAPS); tilemap_render(ALL_TILEMAPS); if (back_enable) tilemap_draw(bitmap,bg_layer,TILEMAP_BACK); else fillbitmap(bitmap,palette_transparent_pen,&Machine->visible_area); draw_sprites(bitmap,0); /* Untested: does anything use it? Could be behind background */ draw_sprites(bitmap,1); tilemap_draw(bitmap,bg_layer,TILEMAP_FRONT); draw_sprites(bitmap,2); tilemap_draw(bitmap,fg_layer,0); draw_sprites(bitmap,3); tilemap_draw(bitmap,tx_layer,0); }
skeezix/compo4all
stevem/mame4all/src/vidhrdw/dynduke.cpp
C++
gpl-2.0
6,702
Plugin Version ============== Displays the plugin and wordpress version as well as any updates that need to happen to the plugin. #### How to use: ```js var PluginVersion = require( 'my-sites/plugins/plugin-version' ); render: function() { return ( <div className="your-plugins-list"> <PluginVersion plugin={ plugin } site={ site } notices={ notices } /> </div> ); } ``` #### Props * `plugin`: a plugin object. * `site`: a site object. * `notices`: notices.
mmmavis/mofo-calypso
client/my-sites/plugins/plugin-version/README.md
Markdown
gpl-2.0
489
DROP TABLE IF EXISTS `#__helloworld`; CREATE TABLE `#__helloworld` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `greeting` VARCHAR(25) NOT NULL, PRIMARY KEY (`id`) ) ENGINE =MyISAM AUTO_INCREMENT =0 DEFAULT CHARSET =utf8; INSERT INTO `#__helloworld` (`greeting`) VALUES ('Hello World!'), ('Good bye World!');
PrepETNA2015/Joomla_Up
tmp/install_533d5a8af0749/Joomla-3.2-Hello-World-Component-step-7-basic-backend/admin/sql/updates/mysql/0.0.6.sql
SQL
gpl-2.0
321
<?php /** * @file * Definition of Drupal\system\Tests\Menu\BreadcrumbTest. */ namespace Drupal\system\Tests\Menu; use Drupal\Component\Utility\String; use Drupal\Component\Utility\Unicode; use Drupal\node\Entity\NodeType; /** * Tests breadcrumbs functionality. * * @group Menu */ class BreadcrumbTest extends MenuTestBase { /** * Modules to enable. * * @var array */ public static $modules = array('menu_test', 'block'); /** * Test paths in the Standard profile. */ protected $profile = 'standard'; protected function setUp() { parent::setUp(); $perms = array_keys(\Drupal::service('user.permissions')->getPermissions()); $this->admin_user = $this->drupalCreateUser($perms); $this->drupalLogin($this->admin_user); // This test puts menu links in the Tools menu and then tests for their // presence on the page, so we need to ensure that the Tools block will be // displayed in the admin theme. $this->drupalPlaceBlock('system_menu_block:tools', array( 'region' => 'content', 'theme' => $this->config('system.theme')->get('admin'), )); } /** * Tests breadcrumbs on node and administrative paths. */ function testBreadCrumbs() { // Prepare common base breadcrumb elements. $home = array('' => 'Home'); $admin = $home + array('admin' => t('Administration')); $config = $admin + array('admin/config' => t('Configuration')); $type = 'article'; // Verify Taxonomy administration breadcrumbs. $trail = $admin + array( 'admin/structure' => t('Structure'), ); $this->assertBreadcrumb('admin/structure/taxonomy', $trail); $trail += array( 'admin/structure/taxonomy' => t('Taxonomy'), ); $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags', $trail); $trail += array( 'admin/structure/taxonomy/manage/tags' => t('Tags'), ); $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags/overview', $trail); $this->assertBreadcrumb('admin/structure/taxonomy/manage/tags/add', $trail); // Verify Menu administration breadcrumbs. $trail = $admin + array( 'admin/structure' => t('Structure'), ); $this->assertBreadcrumb('admin/structure/menu', $trail); $trail += array( 'admin/structure/menu' => t('Menus'), ); $this->assertBreadcrumb('admin/structure/menu/manage/tools', $trail); $trail += array( 'admin/structure/menu/manage/tools' => t('Tools'), ); $this->assertBreadcrumb("admin/structure/menu/link/node.add_page/edit", $trail); $this->assertBreadcrumb('admin/structure/menu/manage/tools/add', $trail); // Verify Node administration breadcrumbs. $trail = $admin + array( 'admin/structure' => t('Structure'), 'admin/structure/types' => t('Content types'), ); $this->assertBreadcrumb('admin/structure/types/add', $trail); $this->assertBreadcrumb("admin/structure/types/manage/$type", $trail); $trail += array( "admin/structure/types/manage/$type" => t('Article'), ); $this->assertBreadcrumb("admin/structure/types/manage/$type/fields", $trail); $this->assertBreadcrumb("admin/structure/types/manage/$type/display", $trail); $trail_teaser = $trail + array( "admin/structure/types/manage/$type/display" => t('Manage display'), ); $this->assertBreadcrumb("admin/structure/types/manage/$type/display/teaser", $trail_teaser); $this->assertBreadcrumb("admin/structure/types/manage/$type/delete", $trail); $trail += array( "admin/structure/types/manage/$type/fields" => t('Manage fields'), ); $this->assertBreadcrumb("admin/structure/types/manage/$type/fields/node.$type.body", $trail); // Verify Filter text format administration breadcrumbs. $filter_formats = filter_formats(); $format = reset($filter_formats); $format_id = $format->id(); $trail = $config + array( 'admin/config/content' => t('Content authoring'), ); $this->assertBreadcrumb('admin/config/content/formats', $trail); $trail += array( 'admin/config/content/formats' => t('Text formats and editors'), ); $this->assertBreadcrumb('admin/config/content/formats/add', $trail); $this->assertBreadcrumb("admin/config/content/formats/manage/$format_id", $trail); // @todo Remove this part once we have a _title_callback, see // https://drupal.org/node/2076085. $trail += array( "admin/config/content/formats/manage/$format_id" => $format->label(), ); $this->assertBreadcrumb("admin/config/content/formats/manage/$format_id/disable", $trail); // Verify node breadcrumbs (without menu link). $node1 = $this->drupalCreateNode(); $nid1 = $node1->id(); $trail = $home; $this->assertBreadcrumb("node/$nid1", $trail); // Also verify that the node does not appear elsewhere (e.g., menu trees). $this->assertNoLink($node1->getTitle()); // Also verify that the node does not appear elsewhere (e.g., menu trees). $this->assertNoLink($node1->getTitle()); $trail += array( "node/$nid1" => $node1->getTitle(), ); $this->assertBreadcrumb("node/$nid1/edit", $trail); // Verify that breadcrumb on node listing page contains "Home" only. $trail = array(); $this->assertBreadcrumb('node', $trail); // Verify node breadcrumbs (in menu). // Do this separately for Main menu and Tools menu, since only the // latter is a preferred menu by default. // @todo Also test all themes? Manually testing led to the suspicion that // breadcrumbs may differ, possibly due to theme overrides. $menus = array('main', 'tools'); // Alter node type menu settings. $node_type = NodeType::load($type); $node_type->setThirdPartySetting('menu_ui', 'available_menus', $menus); $node_type->setThirdPartySetting('menu_ui', 'parent', 'tools:'); $node_type->save(); foreach ($menus as $menu) { // Create a parent node in the current menu. $title = $this->randomMachineName(); $node2 = $this->drupalCreateNode(array( 'type' => $type, 'title' => $title, 'menu' => array( 'enabled' => 1, 'title' => 'Parent ' . $title, 'description' => '', 'menu_name' => $menu, 'parent' => '', ), )); if ($menu == 'tools') { $parent = $node2; } } // Create a Tools menu link for 'node', move the last parent node menu // link below it, and verify a full breadcrumb for the last child node. $menu = 'tools'; $edit = array( 'title[0][value]' => 'Root', 'url' => 'node', ); $this->drupalPostForm("admin/structure/menu/manage/$menu/add", $edit, t('Save')); $menu_links = entity_load_multiple_by_properties('menu_link_content', array('title' => 'Root')); $link = reset($menu_links); $edit = array( 'menu[menu_parent]' => $link->getMenuName() . ':' . $link->getPluginId(), ); $this->drupalPostForm('node/' . $parent->id() . '/edit', $edit, t('Save and keep published')); $expected = array( "node" => $link->getTitle(), ); $trail = $home + $expected; $tree = $expected + array( 'node/' . $parent->id() => $parent->menu['title'], ); $trail += array( 'node/' . $parent->id() => $parent->menu['title'], ); // Add a taxonomy term/tag to last node, and add a link for that term to the // Tools menu. $tags = array( 'Drupal' => array(), 'Breadcrumbs' => array(), ); $edit = array( 'field_tags' => implode(',', array_keys($tags)), ); $this->drupalPostForm('node/' . $parent->id() . '/edit', $edit, t('Save and keep published')); // Put both terms into a hierarchy Drupal » Breadcrumbs. Required for both // the menu links and the terms itself, since taxonomy_term_page() resets // the breadcrumb based on taxonomy term hierarchy. $parent_tid = 0; foreach ($tags as $name => $null) { $terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $name)); $term = reset($terms); $tags[$name]['term'] = $term; if ($parent_tid) { $edit = array( 'parent[]' => array($parent_tid), ); $this->drupalPostForm("taxonomy/term/{$term->id()}/edit", $edit, t('Save')); } $parent_tid = $term->id(); } $parent_mlid = ''; foreach ($tags as $name => $data) { $term = $data['term']; $edit = array( 'title[0][value]' => "$name link", 'url' => "taxonomy/term/{$term->id()}", 'menu_parent' => "$menu:{$parent_mlid}", 'enabled[value]' => 1, ); $this->drupalPostForm("admin/structure/menu/manage/$menu/add", $edit, t('Save')); $menu_links = entity_load_multiple_by_properties('menu_link_content', array( 'title' => $edit['title[0][value]'], 'route_name' => 'entity.taxonomy_term.canonical', 'route_parameters' => serialize(array('taxonomy_term' => $term->id())), )); $tags[$name]['link'] = reset($menu_links); $parent_mlid = $tags[$name]['link']->getPluginId(); } // Verify expected breadcrumbs for menu links. $trail = $home; $tree = array(); // Logout the user because we want to check the active class as well, which // is just rendered as anonymous user. $this->drupalLogout(); foreach ($tags as $name => $data) { $term = $data['term']; /** @var \Drupal\menu_link_content\MenuLinkContentInterface $link */ $link = $data['link']; $link_path = $link->getUrlObject()->getInternalPath(); $tree += array( $link_path => $link->getTitle(), ); $this->assertBreadcrumb($link_path, $trail, $term->getName(), $tree); $this->assertEscaped($parent->getTitle(), 'Tagged node found.'); // Additionally make sure that this link appears only once; i.e., the // untranslated menu links automatically generated from menu router items // ('taxonomy/term/%') should never be translated and appear in any menu // other than the breadcrumb trail. $elements = $this->xpath('//nav[@id=:menu]/descendant::a[@href=:href]', array( ':menu' => 'block-bartik-tools', ':href' => _url($link_path), )); $this->assertTrue(count($elements) == 1, "Link to {$link_path} appears only once."); // Next iteration should expect this tag as parent link. // Note: Term name, not link name, due to taxonomy_term_page(). $trail += array( $link_path => $term->getName(), ); } // Verify breadcrumbs on user and user/%. // We need to log back in and out below, and cannot simply grant the // 'administer users' permission, since user_page() makes your head explode. user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array( 'access user profiles', )); // Verify breadcrumb on front page. $this->assertBreadcrumb('<front>', array()); // Verify breadcrumb on user pages (without menu link) for anonymous user. $trail = $home; $this->assertBreadcrumb('user', $trail, t('Log in')); $this->assertBreadcrumb('user/' . $this->admin_user->id(), $trail, $this->admin_user->getUsername()); // Verify breadcrumb on user pages (without menu link) for registered users. $this->drupalLogin($this->admin_user); $trail = $home; $this->assertBreadcrumb('user', $trail, $this->admin_user->getUsername()); $this->assertBreadcrumb('user/' . $this->admin_user->id(), $trail, $this->admin_user->getUsername()); $trail += array( 'user/' . $this->admin_user->id() => $this->admin_user->getUsername(), ); $this->assertBreadcrumb('user/' . $this->admin_user->id() . '/edit', $trail, $this->admin_user->getUsername()); // Create a second user to verify breadcrumb on user pages again. $this->web_user = $this->drupalCreateUser(array( 'administer users', 'access user profiles', )); $this->drupalLogin($this->web_user); // Verify correct breadcrumb and page title on another user's account pages. $trail = $home; $this->assertBreadcrumb('user/' . $this->admin_user->id(), $trail, $this->admin_user->getUsername()); $trail += array( 'user/' . $this->admin_user->id() => $this->admin_user->getUsername(), ); $this->assertBreadcrumb('user/' . $this->admin_user->id() . '/edit', $trail, $this->admin_user->getUsername()); // Verify correct breadcrumb and page title when viewing own user account. $trail = $home; $this->assertBreadcrumb('user/' . $this->web_user->id(), $trail, $this->web_user->getUsername()); $trail += array( 'user/' . $this->web_user->id() => $this->web_user->getUsername(), ); $this->assertBreadcrumb('user/' . $this->web_user->id() . '/edit', $trail, $this->web_user->getUsername()); // Create an only slightly privileged user being able to access site reports // but not administration pages. $this->web_user = $this->drupalCreateUser(array( 'access site reports', )); $this->drupalLogin($this->web_user); // Verify that we can access recent log entries, there is a corresponding // page title, and that the breadcrumb is just the Home link (because the // user is not able to access "Administer". $trail = $home; $this->assertBreadcrumb('admin', $trail, t('Access denied')); $this->assertResponse(403); // Since the 'admin' path is not accessible, we still expect only the Home // link. $this->assertBreadcrumb('admin/reports', $trail, t('Reports')); $this->assertNoResponse(403); // Since the Reports page is accessible, that will show. $trail += array('admin/reports' => t('Reports')); $this->assertBreadcrumb('admin/reports/dblog', $trail, t('Recent log messages')); $this->assertNoResponse(403); // Ensure that the breadcrumb is safe against XSS. $this->drupalGet('menu-test/breadcrumb1/breadcrumb2/breadcrumb3'); $this->assertRaw('<script>alert(12);</script>'); $this->assertEscaped('<script>alert(123);</script>'); } }
webflo/d8-core
modules/system/src/Tests/Menu/BreadcrumbTest.php
PHP
gpl-2.0
14,159
oilsRptSetSubClass('oilsRptParamEditor','oilsRptObject'); function oilsRptParamEditor(report, tbody) { this.tbody = tbody; this.report = report; } oilsRptParamEditor.prototype.recur = function() { //var cb = $n(DOM.oils_rpt_recur_editor_table,'oils_rpt_recur'); var cb = DOM.oils_rpt_recur; return (cb.checked) ? 't' : 'f'; } oilsRptParamEditor.prototype.recurInterval = function() { /* var count = getSelectorVal($n(DOM.oils_rpt_recur_editor_table,'oils_rpt_recur_count')); var intvl = getSelectorVal($n(DOM.oils_rpt_recur_editor_table,'oils_rpt_recur_interval_type')); */ var count = getSelectorVal(DOM.oils_rpt_recur_count); var intvl = getSelectorVal(DOM.oils_rpt_recur_interval_type); return count+''+intvl; } oilsRptParamEditor.prototype.draw = function() { var params = this.report.gatherParams(); this.params = params; if(!oilsRptParamEditor.row) oilsRptParamEditor.row = DOM.oils_rpt_param_editor_tbody.removeChild( $n(DOM.oils_rpt_param_editor_tbody, 'tr')); removeChildren(this.tbody); _debug(formatJSON(js2JSON(params))); for( var p = 0; p < params.length; p++ ) { var par = params[p]; var row = oilsRptParamEditor.row.cloneNode(true); this.tbody.appendChild(row); $n(row, 'column').appendChild(text(oilsRptMakeLabel(par.path))); $n(row, 'transform').appendChild(text(OILS_RPT_TRANSFORMS[par.column.transform].label)); $n(row, 'action').appendChild(text(OILS_RPT_FILTERS[par.op].label)); par.widget = this.buildWidget(par, $n(row, 'widget')); par.widget.draw(); } /** draw the pre-defined template params so the user will know what params are already set */ var tparams = this.report.gatherTemplateParams(); for( var p = 0; p < tparams.length; p++ ) { var par = tparams[p]; var row = oilsRptParamEditor.row.cloneNode(true); this.tbody.appendChild(row); $n(row, 'column').appendChild(text(oilsRptMakeLabel(par.path))); $n(row, 'transform').appendChild(text(OILS_RPT_TRANSFORMS[par.column.transform].label)); $n(row, 'action').appendChild(text(OILS_RPT_FILTERS[par.op].label)); par.widget = this.buildWidget(par, $n(row, 'widget')); par.widget.draw(); } } oilsRptParamEditor.prototype.buildWidget = function(param, node) { var transform = param.column.transform; var cls = oilsRptPathClass(param.path); var field = oilsRptFindField(oilsIDL[cls], oilsRptPathCol(param.path)); var dtype = field.datatype; _debug("building widget with param class:" + cls + ' col: '+param.column.colname + ' op: '+ param.op); /* get the atomic widget from the datatype */ var atomicWidget = oilsRptTextWidget; var widgetArgs = {node:node}; widgetArgs.calFormat = OILS_RPT_TRANSFORMS[transform].cal_format; widgetArgs.inputSize = OILS_RPT_TRANSFORMS[transform].input_size; widgetArgs.regex = OILS_RPT_TRANSFORMS[transform].regex; widgetArgs.value = param.value; switch(transform) { case 'date': widgetArgs.type = 'date'; atomicWidget = oilsRptTruncPicker; break; case 'hour_trunc': widgetArgs.type = 'hour'; atomicWidget = oilsRptTruncPicker; break; case 'month_trunc': widgetArgs.type = 'month'; atomicWidget = oilsRptTruncPicker; break; case 'year_trunc': widgetArgs.type = 'year'; atomicWidget = oilsRptTruncPicker; break; case 'date': atomicWidget = oilsRptCalWidget; break; case 'age': atomicWidget = oilsRptAgeWidget; break; case 'days_ago': widgetArgs.size = 7; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'months_ago': widgetArgs.size = 12; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'quarters_ago': widgetArgs.size = 4; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'years_ago': widgetArgs.size = 20; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'dow': widgetArgs.size = 7; widgetArgs.start = 0; atomicWidget = oilsRptNumberWidget break; case 'dom': widgetArgs.size = 31; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'doy': widgetArgs.size = 365; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'woy': widgetArgs.size = 52; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'moy': widgetArgs.size = 12; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'qoy': widgetArgs.size = 4; widgetArgs.start = 1; atomicWidget = oilsRptNumberWidget break; case 'hod': widgetArgs.size = 24; widgetArgs.start = 0; atomicWidget = oilsRptNumberWidget break; case 'substring': atomicWidget = oilsRptSubstrWidget break; } if( field.selector ) { atomicWidget = oilsRptRemoteWidget; widgetArgs.class = cls; widgetArgs.field = field; widgetArgs.column = param.column.colname; } switch(cls) { case 'aou': atomicWidget = oilsRptOrgSelector; break; } switch(dtype) { case 'bool': atomicWidget = oilsRptBoolWidget; break; case "org_unit": atomicWidget = oilsRptOrgSelector; break; } if(widgetArgs.value != undefined) return new oilsRptTemplateWidget(widgetArgs); switch(param.op) { case 'in': case 'not in': widgetArgs.inputWidget = atomicWidget; return new oilsRptSetWidget(widgetArgs); case 'is': case 'is not': case 'is blank': case 'is not blank': return new oilsRptNullWidget(widgetArgs); case 'between': case 'not between': widgetArgs.startWidget = atomicWidget; widgetArgs.endWidget = atomicWidget; return new oilsRptBetweenWidget(widgetArgs); default: return new atomicWidget(widgetArgs); } }
atz/OpenILS-Evergreen
Open-ILS/web/reports/oils_rpt_param_editor.js
JavaScript
gpl-2.0
5,756
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>XED2: XED2 User Guide - Tue Nov 22 12:27:53 2011 </title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.6 --> <div class="tabs"> <ul> <li><a href="main.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="classes.html"><span>Data&nbsp;Structures</span></a></li> <li id="current"><a href="files.html"><span>Files</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul></div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul></div> <h1>xed-exception-enum.h File Reference</h1><code>#include &quot;<a class="el" href="xed-common-hdrs_8h-source.html">xed-common-hdrs.h</a>&quot;</code><br> <p> <a href="xed-exception-enum_8h-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Defines</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">#define&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="xed-exception-enum_8h.html#455289dadd0e6c4440b972f37542eaaa">_XED_EXCEPTION_ENUM_H_</a></td></tr> <tr><td colspan="2"><br><h2>Enumerations</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">enum &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696">xed_exception_enum_t</a> { <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac86969a4f2e9dcfddaf981dd1528b0e7ed933">XED_EXCEPTION_INVALID</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696e8ab9bb619215a2178b869cea65a6247">XED_EXCEPTION_AVX_TYPE_1</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696362044715007b259d1c4ad080b4e2d10">XED_EXCEPTION_AVX_TYPE_2</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696dd4094989212ff4c3bfe00ca39d08041">XED_EXCEPTION_AVX_TYPE_2D</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696ac454125215efc926beded3d8327a6bd">XED_EXCEPTION_AVX_TYPE_3</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac869603c8f1844946e42215977eadcad52e2d">XED_EXCEPTION_AVX_TYPE_4</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac86960ded3a111fb7061dad49079eed84ef19">XED_EXCEPTION_AVX_TYPE_4M</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696b11ecb486f34ecf1ca8df0a4d1846cd8">XED_EXCEPTION_AVX_TYPE_5</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac86962c0c3ba78a3856fea3c4646b6079674b">XED_EXCEPTION_AVX_TYPE_6</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac86968aa34cd01cde1c8cce08695d43bdf8f8">XED_EXCEPTION_AVX_TYPE_7</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac86963edd69bed36814c744fb1d7c0abb55f5">XED_EXCEPTION_AVX_TYPE_8</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac869690c1434099af3ce23a75afab54eb2fa9">XED_EXCEPTION_AVX_TYPE_9</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac86960e428ad8193ed2f4cd31c7ef8af04269">XED_EXCEPTION_AVX_TYPE_9L</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696be4e6c3c02f55470790a982a4a7699b4">XED_EXCEPTION_SSE_TYPE_1</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696747e1e52b5445c7e86710c4cef6b37d6">XED_EXCEPTION_SSE_TYPE_2</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696b3d75aebea81736f6cae7e1c863a03fc">XED_EXCEPTION_SSE_TYPE_2D</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696099514e205b4f3831aaeed306e85f142">XED_EXCEPTION_SSE_TYPE_3</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696ce3e28771a0d490d284e886e926c71f6">XED_EXCEPTION_SSE_TYPE_4</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696dd45c1d763b5c0fcb0937ca7cbe81860">XED_EXCEPTION_SSE_TYPE_4M</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696800879d863cba55f12f44a49a94b4301">XED_EXCEPTION_SSE_TYPE_5</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696e8f866f17b03d82b9309eed409f0cf4f">XED_EXCEPTION_SSE_TYPE_7</a>, <br> &nbsp;&nbsp;<a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac86967dd602327066406b440b4c81a9e0d638">XED_EXCEPTION_LAST</a> <br> }</td></tr> <tr><td colspan="2"><br><h2>Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">XED_DLL_EXPORT <a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696">xed_exception_enum_t</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="xed-exception-enum_8h.html#32a991d8a6a53c5ec8ee03bea3f174df">str2xed_exception_enum_t</a> (const char *s)</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">XED_DLL_EXPORT const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="xed-exception-enum_8h.html#b6ad341fc08e6c94a2507b45d65e0422">xed_exception_enum_t2str</a> (const <a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696">xed_exception_enum_t</a> p)</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">XED_DLL_EXPORT <a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696">xed_exception_enum_t</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="xed-exception-enum_8h.html#22da1e7a9610587a7569ff4540bf0a1c">xed_exception_enum_t_last</a> (void)</td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> <p> Definition in file <a class="el" href="xed-exception-enum_8h-source.html">xed-exception-enum.h</a>.<hr><h2>Define Documentation</h2> <a class="anchor" name="455289dadd0e6c4440b972f37542eaaa"></a><!-- doxytag: member="xed-exception-enum.h::_XED_EXCEPTION_ENUM_H_" ref="455289dadd0e6c4440b972f37542eaaa" args="" --><p> <table class="mdTable" cellpadding="2" cellspacing="0"> <tr> <td class="mdRow"> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td class="md" nowrap valign="top">#define _XED_EXCEPTION_ENUM_H_ </td> </tr> </table> </td> </tr> </table> <table cellspacing="5" cellpadding="0" border="0"> <tr> <td> &nbsp; </td> <td> <p> <p> Definition at line <a class="el" href="xed-exception-enum_8h-source.html#l00037">37</a> of file <a class="el" href="xed-exception-enum_8h-source.html">xed-exception-enum.h</a>. </td> </tr> </table> <hr><h2>Enumeration Type Documentation</h2> <a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696"></a><!-- doxytag: member="xed-exception-enum.h::xed_exception_enum_t" ref="cb049bf132a31addd90d09d7e3ac8696" args="" --><p> <table class="mdTable" cellpadding="2" cellspacing="0"> <tr> <td class="mdRow"> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td class="md" nowrap valign="top">enum <a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696">xed_exception_enum_t</a> </td> </tr> </table> </td> </tr> </table> <table cellspacing="5" cellpadding="0" border="0"> <tr> <td> &nbsp; </td> <td> <p> <dl compact><dt><b>Enumerator: </b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac86969a4f2e9dcfddaf981dd1528b0e7ed933"></a><!-- doxytag: member="XED_EXCEPTION_INVALID" ref="cb049bf132a31addd90d09d7e3ac86969a4f2e9dcfddaf981dd1528b0e7ed933" args="" -->XED_EXCEPTION_INVALID</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696e8ab9bb619215a2178b869cea65a6247"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_1" ref="cb049bf132a31addd90d09d7e3ac8696e8ab9bb619215a2178b869cea65a6247" args="" -->XED_EXCEPTION_AVX_TYPE_1</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696362044715007b259d1c4ad080b4e2d10"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_2" ref="cb049bf132a31addd90d09d7e3ac8696362044715007b259d1c4ad080b4e2d10" args="" -->XED_EXCEPTION_AVX_TYPE_2</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696dd4094989212ff4c3bfe00ca39d08041"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_2D" ref="cb049bf132a31addd90d09d7e3ac8696dd4094989212ff4c3bfe00ca39d08041" args="" -->XED_EXCEPTION_AVX_TYPE_2D</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696ac454125215efc926beded3d8327a6bd"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_3" ref="cb049bf132a31addd90d09d7e3ac8696ac454125215efc926beded3d8327a6bd" args="" -->XED_EXCEPTION_AVX_TYPE_3</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac869603c8f1844946e42215977eadcad52e2d"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_4" ref="cb049bf132a31addd90d09d7e3ac869603c8f1844946e42215977eadcad52e2d" args="" -->XED_EXCEPTION_AVX_TYPE_4</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac86960ded3a111fb7061dad49079eed84ef19"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_4M" ref="cb049bf132a31addd90d09d7e3ac86960ded3a111fb7061dad49079eed84ef19" args="" -->XED_EXCEPTION_AVX_TYPE_4M</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696b11ecb486f34ecf1ca8df0a4d1846cd8"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_5" ref="cb049bf132a31addd90d09d7e3ac8696b11ecb486f34ecf1ca8df0a4d1846cd8" args="" -->XED_EXCEPTION_AVX_TYPE_5</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac86962c0c3ba78a3856fea3c4646b6079674b"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_6" ref="cb049bf132a31addd90d09d7e3ac86962c0c3ba78a3856fea3c4646b6079674b" args="" -->XED_EXCEPTION_AVX_TYPE_6</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac86968aa34cd01cde1c8cce08695d43bdf8f8"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_7" ref="cb049bf132a31addd90d09d7e3ac86968aa34cd01cde1c8cce08695d43bdf8f8" args="" -->XED_EXCEPTION_AVX_TYPE_7</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac86963edd69bed36814c744fb1d7c0abb55f5"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_8" ref="cb049bf132a31addd90d09d7e3ac86963edd69bed36814c744fb1d7c0abb55f5" args="" -->XED_EXCEPTION_AVX_TYPE_8</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac869690c1434099af3ce23a75afab54eb2fa9"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_9" ref="cb049bf132a31addd90d09d7e3ac869690c1434099af3ce23a75afab54eb2fa9" args="" -->XED_EXCEPTION_AVX_TYPE_9</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac86960e428ad8193ed2f4cd31c7ef8af04269"></a><!-- doxytag: member="XED_EXCEPTION_AVX_TYPE_9L" ref="cb049bf132a31addd90d09d7e3ac86960e428ad8193ed2f4cd31c7ef8af04269" args="" -->XED_EXCEPTION_AVX_TYPE_9L</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696be4e6c3c02f55470790a982a4a7699b4"></a><!-- doxytag: member="XED_EXCEPTION_SSE_TYPE_1" ref="cb049bf132a31addd90d09d7e3ac8696be4e6c3c02f55470790a982a4a7699b4" args="" -->XED_EXCEPTION_SSE_TYPE_1</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696747e1e52b5445c7e86710c4cef6b37d6"></a><!-- doxytag: member="XED_EXCEPTION_SSE_TYPE_2" ref="cb049bf132a31addd90d09d7e3ac8696747e1e52b5445c7e86710c4cef6b37d6" args="" -->XED_EXCEPTION_SSE_TYPE_2</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696b3d75aebea81736f6cae7e1c863a03fc"></a><!-- doxytag: member="XED_EXCEPTION_SSE_TYPE_2D" ref="cb049bf132a31addd90d09d7e3ac8696b3d75aebea81736f6cae7e1c863a03fc" args="" -->XED_EXCEPTION_SSE_TYPE_2D</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696099514e205b4f3831aaeed306e85f142"></a><!-- doxytag: member="XED_EXCEPTION_SSE_TYPE_3" ref="cb049bf132a31addd90d09d7e3ac8696099514e205b4f3831aaeed306e85f142" args="" -->XED_EXCEPTION_SSE_TYPE_3</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696ce3e28771a0d490d284e886e926c71f6"></a><!-- doxytag: member="XED_EXCEPTION_SSE_TYPE_4" ref="cb049bf132a31addd90d09d7e3ac8696ce3e28771a0d490d284e886e926c71f6" args="" -->XED_EXCEPTION_SSE_TYPE_4</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696dd45c1d763b5c0fcb0937ca7cbe81860"></a><!-- doxytag: member="XED_EXCEPTION_SSE_TYPE_4M" ref="cb049bf132a31addd90d09d7e3ac8696dd45c1d763b5c0fcb0937ca7cbe81860" args="" -->XED_EXCEPTION_SSE_TYPE_4M</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696800879d863cba55f12f44a49a94b4301"></a><!-- doxytag: member="XED_EXCEPTION_SSE_TYPE_5" ref="cb049bf132a31addd90d09d7e3ac8696800879d863cba55f12f44a49a94b4301" args="" -->XED_EXCEPTION_SSE_TYPE_5</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac8696e8f866f17b03d82b9309eed409f0cf4f"></a><!-- doxytag: member="XED_EXCEPTION_SSE_TYPE_7" ref="cb049bf132a31addd90d09d7e3ac8696e8f866f17b03d82b9309eed409f0cf4f" args="" -->XED_EXCEPTION_SSE_TYPE_7</em>&nbsp;</td><td> </td></tr> <tr><td valign="top"><em><a class="anchor" name="cb049bf132a31addd90d09d7e3ac86967dd602327066406b440b4c81a9e0d638"></a><!-- doxytag: member="XED_EXCEPTION_LAST" ref="cb049bf132a31addd90d09d7e3ac86967dd602327066406b440b4c81a9e0d638" args="" -->XED_EXCEPTION_LAST</em>&nbsp;</td><td> </td></tr> </table> </dl> <p> Definition at line <a class="el" href="xed-exception-enum_8h-source.html#l00039">39</a> of file <a class="el" href="xed-exception-enum_8h-source.html">xed-exception-enum.h</a>. </td> </tr> </table> <hr><h2>Function Documentation</h2> <a class="anchor" name="32a991d8a6a53c5ec8ee03bea3f174df"></a><!-- doxytag: member="xed-exception-enum.h::str2xed_exception_enum_t" ref="32a991d8a6a53c5ec8ee03bea3f174df" args="(const char *s)" --><p> <table class="mdTable" cellpadding="2" cellspacing="0"> <tr> <td class="mdRow"> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td class="md" nowrap valign="top">XED_DLL_EXPORT <a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696">xed_exception_enum_t</a> str2xed_exception_enum_t </td> <td class="md" valign="top">(&nbsp;</td> <td class="md" nowrap valign="top">const char *&nbsp;</td> <td class="mdname1" valign="top" nowrap> <em>s</em> </td> <td class="md" valign="top">&nbsp;)&nbsp;</td> <td class="md" nowrap></td> </tr> </table> </td> </tr> </table> <table cellspacing="5" cellpadding="0" border="0"> <tr> <td> &nbsp; </td> <td> <p> </td> </tr> </table> <a class="anchor" name="b6ad341fc08e6c94a2507b45d65e0422"></a><!-- doxytag: member="xed-exception-enum.h::xed_exception_enum_t2str" ref="b6ad341fc08e6c94a2507b45d65e0422" args="(const xed_exception_enum_t p)" --><p> <table class="mdTable" cellpadding="2" cellspacing="0"> <tr> <td class="mdRow"> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td class="md" nowrap valign="top">XED_DLL_EXPORT const char* xed_exception_enum_t2str </td> <td class="md" valign="top">(&nbsp;</td> <td class="md" nowrap valign="top">const <a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696">xed_exception_enum_t</a>&nbsp;</td> <td class="mdname1" valign="top" nowrap> <em>p</em> </td> <td class="md" valign="top">&nbsp;)&nbsp;</td> <td class="md" nowrap></td> </tr> </table> </td> </tr> </table> <table cellspacing="5" cellpadding="0" border="0"> <tr> <td> &nbsp; </td> <td> <p> </td> </tr> </table> <a class="anchor" name="22da1e7a9610587a7569ff4540bf0a1c"></a><!-- doxytag: member="xed-exception-enum.h::xed_exception_enum_t_last" ref="22da1e7a9610587a7569ff4540bf0a1c" args="(void)" --><p> <table class="mdTable" cellpadding="2" cellspacing="0"> <tr> <td class="mdRow"> <table cellpadding="0" cellspacing="0" border="0"> <tr> <td class="md" nowrap valign="top">XED_DLL_EXPORT <a class="el" href="xed-exception-enum_8h.html#cb049bf132a31addd90d09d7e3ac8696">xed_exception_enum_t</a> xed_exception_enum_t_last </td> <td class="md" valign="top">(&nbsp;</td> <td class="md" nowrap valign="top">void&nbsp;</td> <td class="mdname1" valign="top" nowrap> </td> <td class="md" valign="top">&nbsp;)&nbsp;</td> <td class="md" nowrap></td> </tr> </table> </td> </tr> </table> <table cellspacing="5" cellpadding="0" border="0"> <tr> <td> &nbsp; </td> <td> <p> </td> </tr> </table> <hr size="1"><address style="align: right;"><small>Generated on Tue Nov 22 12:27:53 2011 for XED2 by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.6 </small></address> </body> </html>
jzeng4/trace_syscall_obj
xed2/xed2-intel64/doc/html/xed-exception-enum_8h.html
HTML
gpl-2.0
18,965
//-------------------------------------------------------------------------- // Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved. // Copyright (C) 2005-2013 Sourcefire, 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. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- #include "port_var_table.h" //------------------------------------------------------------------------- // PortVarTable //------------------------------------------------------------------------- /* * Create a PortVar Table * * The PortVar table used to store and lookup Named PortObjects */ PortVarTable* PortVarTableCreate(void) { PortObject* po; SFGHASH* h; /* * This is used during parsing of config, * so 1000 entries is ok, worst that happens is somewhat slower * config/rule processing. */ h = sfghash_new(1000,0,0,PortObjectFree); if ( !h ) return 0; /* Create default port objects */ po = PortObjectNew(); if ( !po ) return 0; /* Default has an ANY port */ PortObjectAddPortAny(po); /* Add ANY to the table */ PortVarTableAdd(h, po); return h; } /* This deletes the table, the PortObjects and PortObjectItems, and rule list. */ int PortVarTableFree(PortVarTable* pvt) { if ( pvt ) { sfghash_delete(pvt); } return 0; } /* * PortVarTableAdd() * * returns * -1 : error, no memory... * 0 : added * 1 : in table */ int PortVarTableAdd(PortVarTable* h, PortObject* po) { int stat; stat = sfghash_add(h,po->name,po); if ( stat == SFGHASH_INTABLE ) return 1; if ( stat == SFGHASH_OK ) return 0; return -1; } PortObject* PortVarTableFind(PortVarTable* h, const char* name) { if (!h || !name) return NULL; return (PortObject*)sfghash_find(h,name); }
gavares/snort3
src/ports/port_var_table.cc
C++
gpl-2.0
2,606
#ifndef __GIWAVE_H_ #define __GIWAVE_H_ #include "iwave.h" /* included to enable access to MAXPATHLEN */ #include <sys/param.h> /*---------------*/ #ifdef __cplusplus extern "C" { #endif /** generalized update function - returns true if field ia is updated at substep iv */ typedef int (*GEN_UPDATE_FUN)(int ia, int iv, const IMODEL * m); /** zero receive buffers in preparation for adjoint accumulation. Should be called before giwave_dmod, and update called before giwave_synch CONCRETE: defined by reference to GFD_MODEL data members @param pstate - perturbation IWAVE object @param ud - update rule (for adjoint) @param stream - verbose output @return - 0 on success */ int giwave_zero_recv(IWAVE * pstate, GEN_UPDATE_FUN ud, FILE * stream); /** synchronize perturbation fields after update CONCRETE: defined by reference to GFD_MODEL data members @param[out] pstate - perturbation IWAVE object @param[in] ud - flags fields updated in current substep @param[in] fwd - 1 for fwd lin, 0 for adj lin @param[out] stream - verbose output @return - 0 on success, else error code. */ int giwave_synch(IWAVE * pstate, GEN_UPDATE_FUN ud, int fwd, FILE * stream); /** initialize dynamic fields at time(it) from data files or zero out dynamic fields at time(itstart) CONCRETE: defined by reference to GFD_MODEL data members */ int giwave_dynamic_init(IWAVE * state, int it, /* time to initialize dynamic fields*/ int itoff); /* it - itstart */ /** store dynamic fields at time (itcheck = itstart + itoff) to data files, such as $DATAPATH/statecheckpoint_itcheck_proc_?_array_?.bin CONCRETE: defined by reference to GFD_MODEL data members */ int iwave_dynamic_takeshot(IWAVE * state, int itoff ); /* itoff = itcheck - itstart */ /** remove unused data files hoding dynamic fields at time (itcheck = itstart + itoff), such as $DATAPATH/statecheckpoint_itcheck_proc_?_array_?.bin CONCRETE: defined by reference to GFD_MODEL data members */ int iwave_remove_checkfile(IWAVE * state, int itoff); /** generate checkfile names at time (itcheck = itstart + itoff) for array (iarr) CONCRETE: defined by reference to GFD_MODEL data members */ char * iwave_get_a_checkfilename(int iarr,int itoff); #ifdef __cplusplus } #endif #endif
zxtstarry/src
trip/iwave/core/include/archive/giwave.h
C
gpl-2.0
2,524
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009 Zuza Software Foundation # # This file is part of Pootle. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from pootle_app.management.commands import PootleCommand class Command(PootleCommand): help = "Allow stats and text indices to be refreshed manually." def handle_translation_project(self, translation_project, **options): # This will force the indexer of a TranslationProject to be # initialized. The indexer will update the text index of the # TranslationProject if it is out of date. translation_project.indexer def handle_all_stores(self, translation_project, **options): translation_project.getcompletestats() translation_project.getquickstats() def handle_store(self, store, **options): store.getcompletestats() store.getquickstats()
tzabian/fuego-pootle
local_apps/pootle_app/management/commands/refresh_stats.py
Python
gpl-2.0
1,550
\section{Wave-mode separation for 2D TI media} %how does separation for VTI work \subsection{Wave-mode separation for symmetry planes of VTI media} \cite{GEO55-07-09140919} separate {\it quasi-}P and {\it quasi-}SV modes in 2D VTI media by projecting the wavefields onto the directions in which P and S modes are polarized. For example, in the wavenumber domain, one can project the wavefields onto the P-wave polarization vectors $\UU_P$ to obtain {\it quasi-}P ({\it q}P) waves: \beq\label{AniDivK} \widetilde{{\it q}P}=i\, \UU_P(\kk) \cdot \WWK =i\, U_x\,\WK_x+i\, U_z\,\WK_z\, , \eeq where $\widetilde{{\it q}P}$ is the P-wave mode in the wavenumber domain, $\kk=\{k_x,k_z\}$ is the wavenumber vector, $\WWK$ is the elastic wavefield in the wavenumber domain, and $\UU_P(\kk)$ is the P-wave polarization vector as a function of the wavenumber $\kk$. %Christoffel equation % what is different about TTI and VTI The polarization vectors $\UU(\kk)$ of plane waves for VTI media in the symmetry planes can be found by solving the Christoffel equation ~\cite[]{akirichards.2002,Tsvankin}: \beq\label{3dChristoffel}\lb {\bf G} - \rho V^2 {\bf I} \rb \UU = 0 \, , \eeq where {\textbf G} is the Christoffel matrix with $G_{ij}=c_{ijkl}n_jn_l$, in which $c_{ijkl}$ is the stiffness tensor. The vector $\mathbf n=\frac{\kk}{\left|\kk\right|}$ is the unit vector orthogonal to the plane wavefront, with $n_j$ and $n_l$ being the components in the $j$ and $l$ directions, $i,j,k,l=1,2,3$. The eigenvalues $V$ of this system correspond to the phase velocities of different wave-modes and are dependent on the plane wave propagation direction $\mathbf k$. For plane waves in the vertical symmetry plane of a TTI medium, since {\it q}P and {\it q}SV modes are decoupled from the SH-mode and polarized in the symmetry planes, one can set $n_y=0$ and obtain \def\c11{c_{11}} \def\c55{c_{55}} \def\c13{c_{13}} \def\c33{c_{33}} \beq\label{VtiChristoffel} \lb \mtrx{ G_{11}-\rho V^2 & G_{12}\\ G_{12} & G_{22} -\rho V^2 } \rb \lb\mtrx{ U_x\\U_z} \rb =0 \, , \eeq where \begin{eqnarray} G_{11}&=&c_{11} n_x^2 +c_{55} n_z^2 \, ,\\ G_{12}&=&\lp c_{13}+c_{55}\rp n_xn_z\, ,\\ G_{22}&=&c_{55} n_x^2 +c_{33} n_z^2\, . \end{eqnarray} \rEq{VtiChristoffel} allows one to compute the polarization vectors $\UU_P=\{U_x,U_z\}$ and $\UU_{SV}=\{-U_z,U_x\}$ (the eigenvectors of the matrix {\textbf G}) given the stiffness tensor at every location of the medium. \rEq{AniDivK} represents the separation process for the P-mode in 2D homogeneous VTI media. To separate wave-modes for heterogeneous models, one needs to use different polarization vectors at every location of the model~\cite[]{yan:WB19}, because the polarization vectors change spatially with medium parameters. In the space domain, an expression equivalent to \req{AniDivK} at each grid point is \beq\label{AniDivX} {\it q}P=\nabla_a\cdot \WW = L_x[W_x] + L_z[W_z] \, , \eeq where $L\lb\,\cdot\,\rb$ indicates spatial filtering, and $L_x$ and $L_z$ are the filters to separate P waves representing the inverse Fourier transforms of $i\, U_x$ and $i\, U_z$, respectively. The terms $L_x$ and $L_z$ define the ``pseudo-derivative operators'' in the $x$ and $z$ directions for a VTI medium, respectively, and they change according to the material parameters, $V_{P0}$, $V_{S0}$ ($V_{P0}$ and $V_{S0}$ are the P and S velocities along the symmetry axis, respectively), $\epsilon$, and $\delta$~\cite[]{thomsen:1954}. \subsection{Wave-mode separation for symmetry planes of TTI media} My separation algorithm for TTI models is similar to the approach used for VTI models. The main difference is that for VTI media, the wavefields consist of P- and SV-modes, and \reqs{AniDivK} and \ren{AniDivX} can be used for separation in all vertical planes of a VTI medium. However, for TTI media, this separation only works in the plane containing the dip of the reflector, where P- and SV-waves are polarized, while other vertical planes contain SH-waves as well. To obtain the polarization vectors for P and S modes in the symmetry planes of TTI media, one needs to solve for the Christoffel \req{VtiChristoffel} with \begin{eqnarray} G_{11}&=&c_{11} n_x^2 +2c_{15}n_xn_z+c_{55} n_z^2 \, ,\\ G_{12}&=&c_{15} n_x^2+\lp c_{13}+c_{55}\rp n_xn_z+c_{35} n_z^2\, ,\\ G_{22}&=&c_{55} n_x^2 +2c_{35}n_xn_z+c_{33} n_z^2\, . \end{eqnarray} Here, since the symmetry axis of the TTI medium does not align with the vertical axis $k_z$, the TTI Christoffel matrix is different from its VTI equivalent. The stiffness tensor is determined by the parameters $V_{P0}$, $V_{S0}$ , $\epsilon$, $\delta$, and the tilt angle $\nu$. In anisotropic media, $\UU_P$ generally deviates from the wave vector direction $\kk=\frac{\omega}{V}\nn$, where $\omega$ is the angular frequency, $V$ is the phase vector. \rFgs{VTIpolar} and \subrfn{TTIpolar} show the P-mode polarization in the wavenumber domain for a VTI medium and a TTI medium with a 30$^\circ$ tilt angle, respectively. The polarization vectors for the VTI medium deviate from radial directions, which represent the isotropic polarization vectors $\kk$. The polarization vectors of the TTI medium are rotated 30$^\circ$ about the origin from the vectors of the VTI medium. \rFgs{dK_notaper_VTI} and \subrfn{dK_notaper_TTI} show the components of the P-wave polarization of a VTI medium and a TTI medium with a 30{$^\circ$} tilt angle, respectively. \rFg{dK_notaper_rot_TTI} shows that the polarization vectors in \rfg{dK_notaper_TTI} rotated to the symmetry axis and its orthogonal direction of the TTI medium. Comparing \rFgs{dK_notaper_VTI} and \subrfn{dK_notaper_rot_TTI}, we see that within the circle of radius $\pi$~radians, the components of this TTI medium are rotated 30{$^\circ$} from those of the VTI medium. However, note that the $z$ and $x$ components of the polarization vectors for the VTI medium (\rFg{dK_notaper_VTI}) are symmetric with respect to the $x$ and $z$ axes, respectively; in contrast, the vectors of the TTI medium (\rFg{dK_notaper_rot_TTI}) are not symmetric because of the non-alignment of the TTI symmetry with the Cartesian coordinates. \def\sk#1{\sin\lp #1 k\rp} \def\done#1#2{\frac{\partial#1}{\partial#2}} To maintain continuity at the negative and positive Nyquist wavenumbers for Fourier transform to obtain space-domain filters, i.e. at $k_x,k_z=\pm\pi$~radians, one needs to apply tapers to the vector components. For VTI media, a taper corresponding to the function~\cite[]{yan:WB19} \beq\label{sintaper} f(k)= -\frac{8\sk{}}{5k} + \frac{2\sk{2}}{5k} -\frac{8\sk{3}}{105k} + \frac{\sk{4}}{140k} \eeq can be applied to the $x$ and $z$ components of the polarization vectors (\rFg{dK_notaper_VTI}), where $k$ represent the components $k_x$ and $k_z$ of the vector $\kk$. This taper ensures that $U_x$ and $U_z$ are zero at $k_z=\pm\pi$~radians and $k_x=\pm\pi$~radians, respectively. The components $U_x$ and $U_z$ are continuous in the $z$ and $x$ directions across the Nyquist wave numbers, respectively, due to the symmetry of the VTI media. Moreover, the application of this taper transforms polarization vector components to 8$^{th}$ order derivatives. If the components of the isotropic polarization vectors $\kk$ are tapered by the function in \req{sintaper} and then transformed to the space domain, one obtains the conventional 8$^{th}$ order finite difference derivative operators $\done{}{x}$ and $\done{}{z}$~\cite[]{yan:WB19}. Therefore, the VTI separators reduce to conventional derivatives---the components of the divergence and curl operators---when the medium is isotropic. For TTI media, due to the asymmetry of the Fourier domain derivatives (\rFg{dK_notaper_TTI}), one needs to apply a rotational symmetric taper to the polarization vector components to obtain continuity across Nyquist wavenumbers. A simple Gaussian taper % \beq\label{gaussiantaper} g(\kk)=C \, exp\lb-\frac{\left|\kk\right|^2}{2\sigma^2}\rb \eeq % can be used, where C is a normalizing constant. When one chooses a standard deviation of $\sigma=1$ radian, the magnitude of this taper at $\left|\kk\right|=\pi$~radians is about 0.7\% of the peak value, and therefore the TTI components can be safely assumed to be continuous across the Nyquist wavenumbers. Tapering the polarization vector components in \rFg{kdomain.notaper} with the function in \req{gaussiantaper}, one obtains the plots in \rFg{kdomain.tapered}. The panels in \rFg{kdomain.tapered}, which exhibits circular continuity across the Nyquist wavenumbers, transform to the space-domain separators in \rFg{xdomain.tapered}. The space-domain filters for TTI media is rotated from the VTI filters, also by the tilt angle $\nu$. %With the application of %this taper, even for isotropic media, the operators constructed this %way are 2D stencils instead of the conventional 1D finite difference %operators. The value of $\sigma$ determines the size of the operators in the space domain and also affects the frequency content of the separated wave-modes. For example, \rfg{gauss.sigma} shows the component $U_z$ and operator $L_z$ for $\sigma$ values of $0.25$, $1.00$, and $1.25$ radians. A larger value of $\sigma$ results in more concentrated operators in the space domain and better preserved frequency of the separated wave-modes. However, one needs to ensure that the function $g(\kk)$ at $\left|\kk\right|=\pi$~radians is small enough to assume continuity of the value function across Nyquist wavenumbers. When one chooses $\sigma=1$ radian, the TTI components can be safely assumed to be continuous across the Nyquist wavenumbers. %discuss different sigma For heterogeneous models, I can pre-compute the polarization vectors at each grid point as a function of the $V_{P0}/ V_{S0}$ ratio, the Thomsen parameters $\epsilon$ and $\delta$, and tilt angle $\nu$. I then transform the tapered polarization vector components to the space domain to obtain the spatially-varying separators $L_x$ and $L_z$. The separators for the entire model are stored and used to separate P- and S-modes from reconstructed elastic wavefields at different time steps. Thus, wavefield separation in TI media can be achieved simply by non-stationary filtering with spatially varying operators. I assume that the medium parameters vary slowly in space and that they are locally homogeneous. For complex media, the localized operators behave similarly to the long finite difference operators used for finite difference modeling at locations where medium parameters change rapidly. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \inputdir{Matlab} \multiplot{2}{VTIpolar,TTIpolar}{width=.48\textwidth} {The polarization vectors of P-mode as a function of normalized wavenumbers $k_x$ and $k_z$ ranging from $-\pi$~radians to $+\pi$~radians, for (a) a VTI model with $V_{P0}=3.0$~km/s, $V_{S0}=1.5$~km/s, $\epsilon=0.25$ and $\delta=-0.29$, and for (b) a TTI model with the same model parameters as (a) and a symmetry axis tilt $\nu=30^\circ$. The vectors in (b) are rotated 30$^\circ$ with respect to the vectors in (a) around $k_x=0$ and $k_z=0$.} \inputdir{operator} \multiplot{1}{dK-notaper-VTI,dK-notaper-TTI,dK-notaper-rot-TTI} {width=.7\textwidth} {The $z$ and $x$ components of the polarization vectors for P-mode in the Fourier domain for (a) a VTI medium with $\epsilon=0.25$ and $\delta=-0.29$, and for (b) a TTI medium with $\epsilon=0.25$, $\delta=-0.29$, and $\nu=30^\circ$. Panel (c) represents the projection of the polarization vectors shown in (b) onto the tilt axis and its orthogonal direction. \label{fig:kdomain.notaper} } \multiplot{1}{dK-VTI,dK-TTI,dK-rot-TTI}{width=.7\textwidth} {The wavenumber-domain vectors in \rFg{dK-notaper-VTI,dK-notaper-TTI,dK-notaper-rot-TTI} are tapered by the function in \req{gaussiantaper} to avoid Nyquist discontinuity. Panel (a) corresponds to \rFg{dK-notaper-VTI}, panel (b) corresponds to \rfg{dK-notaper-TTI}, and panel (c) corresponds to \rFg{dK-notaper-rot-TTI}. \label{fig:kdomain.tapered}} \multiplot{1}{dX-VTI,dX-TTI,dX-rot-TTI}{width=.7\textwidth} {The space-domain wave-mode separators for the medium shown in \rFg{VTIpolar,TTIpolar}. They are the Fourier transformation of the polarization vectors shown in \rFg{kdomain.tapered}. Panel (a) corresponds to \rFg{dK-VTI}, panel (b) corresponds to \rfg{dK-TTI}, and panel (c) corresponds to \rFg{dK-rot-TTI}. The zoomed views show $24\times24$ samples out of the original $64\times64$ samples around the center of the filters. \label{fig:xdomain.tapered}} \multiplot{1}{dzKX-sig0-TTI,dzKX-sig1-TTI,dzKX-sig2-TTI} {width=.7\textwidth} {Panels (a)--(c) correspond to component $U_z$ (left) and operator $L_z$ (right) for $\sigma$ values of $0.25$, $1.00$, and $1.25$ radians in \req{gaussiantaper}, respectively. A larger value of $\sigma$ results in more spread components in the wavenumber domain and more concentrated operators in the space domain. \label{fig:gauss.sigma}} \section{Wave-mode separation for 3D TI media} In order to separate all three modes---P, SV, and SH---in a 3D TI medium, one needs to construct 3D separators. \cite{dellinger.thesis} shows that P-waves can be separated from two shear modes by a straightforward extension of the 2D algorithm. Indeed, for 3D TI media, one can always obtain the P-mode by constructing P-wave separators represented by the polarization vector $\UU_P=\{U_x, U_y, U_z \}$ and then projecting the 3D elastic wavefields onto the vector $\UU_P$. The P-wave polarization vector with components $\{U_x, U_y, U_z\}$ is obtained by solving the 3D Christoffel matrix~\cite[]{akirichards.2002,Tsvankin}: \beq\label{VtiChristoffel3d.ch3} \lb \mtrx{ G_{11}-\rho V^2 & G_{12} & G_{13}\\ G_{12} & G_{22} -\rho V^2 & G_{23} \\ G_{13} & G_{23} & G_{33} -\rho V^2 } \rb \lb\mtrx{ U_x\\U_y\\U_z} \rb =0 \, . \eeq The notations in this equation have the same definitions as in \req{3dChristoffel}. For TTI media, the matrix ${\mathbf G}$ has the elements \begin{eqnarray} G_{11}&=&c_{11}n_x^2+c_{66}n_y^2+c_{55}n_z^2 +2 c_{16}n_xn_y+2 c_{15}n_xn_z+2c_{56}n_yn_z \, ,\\ G_{22}&=&c_{66}n_x^2+c_{22}n_y^2+c_{44}n_z^2 +2 c_{26}n_xn_y+ (c_{45}+c_{46})n_xn_z+2c_{24}n_yn_z \, ,\\ G_{33}&=&c_{55}n_x^2+c_{44}n_y^2+c_{33}n_z^2 +2 c_{45}n_xn_y+2 c_{35}n_xn_z+2c_{34}n_yn_z \, ,\\ G_{12}&=&c_{16}n_x^2+c_{26}n_y^2+c_{45}n_z^2 + (c_{12}+c_{66})n_xn_y+ (c_{14}+c_{56})n_xn_z+(c_{25}+c_{46})n_yn_z \, ,\nonumber\\ \\ G_{13}&=&c_{15}n_x^2+c_{46}n_y^2+c_{35}n_z^2 + (c_{14}+c_{56})n_xn_y+ (c_{13}+c_{55})n_xn_z+(c_{36}+c_{45})n_yn_z \, ,\nonumber\\\\ G_{23}&=&c_{56}n_x^2+c_{24}n_y^2+c_{34}n_z^2 + (c_{25}+c_{46})n_xn_y+ (c_{36}+c_{45})n_xn_z+(c_{23}+c_{44})n_yn_z \, .\nonumber\\ \end{eqnarray} When constructing shear mode separators, one faces an additional complication: SV- and SH-waves have the same velocity along the symmetry axis of a 3D TI medium, and this singularity prevents one from obtaining polarization vectors for shear modes in this particular direction by solving the Christoffel equation~\cite[]{Tsvankin}. In 3D TI media, the polarization of the shear modes around the singular directions are non-linear and cannot be characterized by a plane-wave solution. Consequently, constructing 3D global separators for fast and slow shear modes is difficult. % how does S-wave-mode separaton work To mitigate the effects of the shear wave-mode singularity, I use the mutual orthogonality among the P, SV, and SH modes depicted in \rFg{polar3d}. In this figure, vector $\nn=\{\sin\nu\cos\alpha,\sin\nu\sin\alpha,\cos\nu\}$ represents the symmetry axis of a TTI medium, with $\nu$ and $\alpha$ being the tilt and azimuth of the symmetry axis, respectively. The wave vector $\kk$ characterizes the propagation direction of a plane wave. Vectors ${\mathbf P}$, ${\mathbf {SV}}$, and ${\mathbf {SH}}$ symbolize the compressional, and fast and slow shear polarization directions, respectively. For TI media, plane waves propagate in symmetry planes, and the symmetry axis $\nn$ and any wave vector $\kk$ form a symmetry plane. For a plane wave propagating in the direction $\kk$, the P-wave is polarized in this symmetry plane and deviates from the vector $\kk$; the SV- and SH-waves are polarized perpendicular to the P-mode, in and out of the symmetry plane, respectively. Using this mutual orthogonality among all three modes, I first obtain the SH-wave polarization vector $\UU_{SH}$ by cross multiplying vectors $\nn$ and $\kk$, which ensures that the SH mode is polarized orthogonal to symmetry planes: \bea\label{ShPolar} \UU_{SH} &=&\nn\times\kk \nonumber \\ &=&\{ k_z n_y-k_y n_z, \nonumber \\ &&~\, k_x n_z- k_z n_x, \nonumber \\ &&~\, k_y n_x - k_x n_y \} \, . \eea Then I calculate the SV polarization vector $\UU_{SV}$ by cross multiplying polarization vectors P and SH modes, which ensures the orthogonality between SV and P modes and SV and SH modes: \bea\label{SvPolar} \UU_{SV} &=&\UU_{P}\times\UU_{SH} \, , \nonumber \\ &=&\{ k_y n_x U_y - k_x n_y U_y+k_z n_x U_z - k_x n_z U_z, \nonumber \\ &&~\, k_z n_y U_z - k_y n_z U_z+k_x n_y U_x - k_y n_x U_x, \nonumber \\ &&~\, k_x n_z U_x - k_z n_x U_x+k_y n_z U_y - k_z n_y U_y \} \, . \eea Here, the magnitude of the P-wave polarization vectors for a certain wavenumber $|\kk|$ is a constant: \beq \left| U_{P} \right| = \sqrt{U_x^2+U_y^2+U_z^2}=c \, . \eeq This ensures that for a certain wavenumber, P-waves obtained by projecting the elastic wavefields onto the polarization vectors are uniformly scaled. For comparison, the magnitudes of all three modes are respectively \bea \left| U_{P} \right| &=&c \, , \\ \left| U_{SV}\right| &=&c\sin\phi \, , \\ \left| U_{SH}\right| &=&c\sin\phi \, , \eea where $\phi$ is the polar angle of the propagating plane wave, i.e., the angle between vectors $\kk$ and $\nn$. \rFg{polar3dP,polar3dS2,polar3dS1} shows the polarization vectors of P-, SH-, and SV-modes computed using \reqs{VtiChristoffel3d.ch3}, \ren{ShPolar}, and \ren{SvPolar}, respectively. The P-wave polarization vectors in \rfg{polar3dP} all have the same magnitude, but the SV and SH polarization vectors in \rfgs{polar3dS1} and \subrfn{polar3dS2} vary in magnitude. In the symmetry axis direction, they become zero. The zero amplitude of the shear modes in the symmetry axis direction is not an abrupt but a continuous change over nearby propagation angles. Using separators represented by solutions to \req{VtiChristoffel3d.ch3} and expressions \ren{ShPolar} and \ren{SvPolar} to filter the wavefields, I obtain separated shear modes that are scaled differently than the P-mode. For a certain wavenumber, the shear modes are scaled by $\sin\phi$, with $\phi$ being the polar angle, which increases from zero in the symmetry axis to unity in the orthogonal propagation directions. Therefore, the separated SV- and SH-waves have zero amplitude in the symmetry axis direction, and the amplitudes of the shear modes are just kinematically correct. The components of the polarization vectors for P-, SV-, and SH-waves can be transformed back to the space domain to construct spatial filters for 3D heterogeneous TI media. For example, \rfg{filters3d} illustrates nine spatial filters transformed from the Cartesian components of the polarization vectors shown in \rfg{polar3dP,polar3dS2,polar3dS1}. All these filters can be spatially varying when the medium is heterogeneous. Therefore, in principle, wave-mode separation in 3D would perform well even for models that have complex structures and arbitrary tilts and azimuths of TI symmetry. \inputdir{XFig} \plot{polar3d} {width=\textwidth}{A schematic showing the elastic wave-modes polarization in a 3D TI medium. The three parallel planes represent the isotropy planes of the medium. The vector $\nn$ represents the symmetry axis, which is orthogonal to the isotropy plane. The vector $\kk$ is the propagation direction of a plane wave. The wave-modes P, SV, and SH are polarized in the direction ${\mathbf P}$, ${\mathbf {SV}}$, and ${\mathbf {SH}}$, respectively. The three modes are polarized orthogonal to each other.} \inputdir{Matlab} \multiplot{2}{polar3dP,polar3dS2,polar3dS1}{width=.45\textwidth} {The wave-mode polarization for P-, SH-, and SV-mode for a VTI medium with parameters $V_{P0}=4.95$~km/s, $V_{S0}=2.48$~km/s, $\epsilon=0.4$, and $\delta=0.1$. The P-mode polarization is computed using the 3D Christoffel equation, and SV and SH polarizations are computed using \rEqs{SvPolar} and~\ren{ShPolar}. Note that the SV- and SH-wave polarization vectors have zero amplitude in the vertical direction.} \inputdir{vti3} \plot{filters3d}{width=\textwidth}{The separation filters $L_x$, $L_y$, and $L_z$ for the P, SV, and SH modes for a VTI medium. The corresponding wavenumber-domain polarization vectors are shown in \rFg{polar3dP,polar3dS2,polar3dS1}. Note that the filter $L_z$ for the SH mode is blank because the $z$ component of the polarization vector is zero. The zoomed views show $24\times24$ samples out of the original $64\times64$ samples around the center of the filters. }
zxtstarry/src
book/cwp/geo2009TTIModeSeparation/methodology.tex
TeX
gpl-2.0
21,226
/* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/slab.h> #include <linux/kthread.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/uaccess.h> #include <linux/wait.h> #include <linux/mutex.h> #include <asm/mach-types.h> #include <mach/qdsp6v2/audio_acdb.h> #include <mach/qdsp6v2/rtac.h> #include "sound/apr_audio.h" #include "sound/q6afe.h" #include "q6voice.h" #define TIMEOUT_MS 3000 #define CMD_STATUS_SUCCESS 0 #define CMD_STATUS_FAIL 1 #define CAL_BUFFER_SIZE 4096 #define NUM_CVP_CAL_BLOCKS 75 #define NUM_CVS_CAL_BLOCKS 15 #define CVP_CAL_SIZE (NUM_CVP_CAL_BLOCKS * CAL_BUFFER_SIZE) #define CVS_CAL_SIZE (NUM_CVS_CAL_BLOCKS * CAL_BUFFER_SIZE) #define VOICE_CAL_BUFFER_SIZE (CVP_CAL_SIZE + CVS_CAL_SIZE) /* Total cal needed to support concurrent VOIP & VOLTE sessions */ /* Due to memory map issue on Q6 separate memory has to be used */ /* for VOIP & VOLTE */ #define TOTAL_VOICE_CAL_SIZE (NUM_VOICE_CAL_BUFFERS * VOICE_CAL_BUFFER_SIZE) static struct common_data common; static int voice_send_enable_vocproc_cmd(struct voice_data *v); static int voice_send_netid_timing_cmd(struct voice_data *v); static int voice_send_attach_vocproc_cmd(struct voice_data *v); static int voice_send_set_device_cmd(struct voice_data *v); static int voice_send_disable_vocproc_cmd(struct voice_data *v); static int voice_send_vol_index_cmd(struct voice_data *v); static int voice_send_cvp_map_memory_cmd(struct voice_data *v); static int voice_send_cvp_unmap_memory_cmd(struct voice_data *v); static int voice_send_cvs_map_memory_cmd(struct voice_data *v); static int voice_send_cvs_unmap_memory_cmd(struct voice_data *v); static int voice_send_cvs_register_cal_cmd(struct voice_data *v); static int voice_send_cvs_deregister_cal_cmd(struct voice_data *v); static int voice_send_cvp_register_cal_cmd(struct voice_data *v); static int voice_send_cvp_deregister_cal_cmd(struct voice_data *v); static int voice_send_cvp_register_vol_cal_table_cmd(struct voice_data *v); static int voice_send_cvp_deregister_vol_cal_table_cmd(struct voice_data *v); static int voice_send_set_widevoice_enable_cmd(struct voice_data *v); static int voice_send_set_pp_enable_cmd(struct voice_data *v, uint32_t module_id, int enable); static int voice_cvs_stop_playback(struct voice_data *v); static int voice_cvs_start_playback(struct voice_data *v); static int voice_cvs_start_record(struct voice_data *v, uint32_t rec_mode); static int voice_cvs_stop_record(struct voice_data *v); static int32_t qdsp_mvm_callback(struct apr_client_data *data, void *priv); static int32_t qdsp_cvs_callback(struct apr_client_data *data, void *priv); static int32_t qdsp_cvp_callback(struct apr_client_data *data, void *priv); static int voice_send_set_device_cmd_v2(struct voice_data *v); static u16 voice_get_mvm_handle(struct voice_data *v) { if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return 0; } pr_debug("%s: mvm_handle %d\n", __func__, v->mvm_handle); return v->mvm_handle; } static void voice_set_mvm_handle(struct voice_data *v, u16 mvm_handle) { pr_debug("%s: mvm_handle %d\n", __func__, mvm_handle); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return; } v->mvm_handle = mvm_handle; } static u16 voice_get_cvs_handle(struct voice_data *v) { if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return 0; } pr_debug("%s: cvs_handle %d\n", __func__, v->cvs_handle); return v->cvs_handle; } static void voice_set_cvs_handle(struct voice_data *v, u16 cvs_handle) { pr_debug("%s: cvs_handle %d\n", __func__, cvs_handle); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return; } v->cvs_handle = cvs_handle; } static u16 voice_get_cvp_handle(struct voice_data *v) { if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return 0; } pr_debug("%s: cvp_handle %d\n", __func__, v->cvp_handle); return v->cvp_handle; } static void voice_set_cvp_handle(struct voice_data *v, u16 cvp_handle) { pr_debug("%s: cvp_handle %d\n", __func__, cvp_handle); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return; } v->cvp_handle = cvp_handle; } uint16_t voc_get_session_id(char *name) { u16 session_id = 0; if (name != NULL) { if (!strncmp(name, "Voice session", 13)) session_id = common.voice[VOC_PATH_PASSIVE].session_id; else if (!strncmp(name, "VoLTE session", 13)) session_id = common.voice[VOC_PATH_VOLTE_PASSIVE].session_id; else if (!strncmp(name, "Voice2 session", 14)) session_id = common.voice[VOC_PATH_VOICE2_PASSIVE].session_id; else session_id = common.voice[VOC_PATH_FULL].session_id; pr_debug("%s: %s has session id 0x%x\n", __func__, name, session_id); } return session_id; } static struct voice_data *voice_get_session(u16 session_id) { struct voice_data *v = NULL; if ((session_id >= SESSION_ID_BASE) && (session_id < SESSION_ID_BASE + MAX_VOC_SESSIONS)) { v = &common.voice[session_id - SESSION_ID_BASE]; } pr_debug("%s: session_id 0x%x session handle 0x%x\n", __func__, session_id, (unsigned int)v); return v; } static bool is_voice_session(u16 session_id) { return (session_id == common.voice[VOC_PATH_PASSIVE].session_id); } static bool is_voip_session(u16 session_id) { return (session_id == common.voice[VOC_PATH_FULL].session_id); } static bool is_volte_session(u16 session_id) { return (session_id == common.voice[VOC_PATH_VOLTE_PASSIVE].session_id); } static bool is_voice2_session(u16 session_id) { return (session_id == common.voice[VOC_PATH_VOICE2_PASSIVE].session_id); } /* Only for memory allocated in the voice driver */ /* which includes voip & volte */ static int voice_get_cal_kernel_addr(int16_t session_id, int cal_type, uint32_t *kvaddr) { int i, result = 0; pr_debug("%s\n", __func__); if (kvaddr == NULL) { pr_err("%s: NULL pointer sent to function\n", __func__); result = -EINVAL; goto done; } else if (is_voip_session(session_id)) { i = VOIP_CAL; } else if (is_volte_session(session_id)) { i = VOLTE_CAL; } else { result = -EINVAL; goto done; } if (common.voice_cal[i].cal_data[cal_type].kvaddr == 0) { pr_err("%s: NULL pointer for session_id %d, type %d, cal_type %d\n", __func__, session_id, i, cal_type); result = -EFAULT; goto done; } *kvaddr = common.voice_cal[i].cal_data[cal_type].kvaddr; done: return result; } /* Only for memory allocated in the voice driver */ /* which includes voip & volte */ static int voice_get_cal_phys_addr(int16_t session_id, int cal_type, uint32_t *paddr) { int i, result = 0; pr_debug("%s\n", __func__); if (paddr == NULL) { pr_err("%s: NULL pointer sent to function\n", __func__); result = -EINVAL; goto done; } else if (is_voip_session(session_id)) { i = VOIP_CAL; } else if (is_volte_session(session_id)) { i = VOLTE_CAL; } else { result = -EINVAL; goto done; } if (common.voice_cal[i].cal_data[cal_type].paddr == 0) { pr_err("%s: No addr for session_id %d, type %d, cal_type %d\n", __func__, session_id, i, cal_type); result = -EFAULT; goto done; } *paddr = common.voice_cal[i].cal_data[cal_type].paddr; done: return result; } static int voice_apr_register(void) { pr_debug("%s\n", __func__); mutex_lock(&common.common_lock); /* register callback to APR */ if (common.apr_q6_mvm == NULL) { pr_debug("%s: Start to register MVM callback\n", __func__); common.apr_q6_mvm = apr_register("ADSP", "MVM", qdsp_mvm_callback, 0xFFFFFFFF, &common); if (common.apr_q6_mvm == NULL) { pr_err("%s: Unable to register MVM\n", __func__); goto err; } } if (common.apr_q6_cvs == NULL) { pr_debug("%s: Start to register CVS callback\n", __func__); common.apr_q6_cvs = apr_register("ADSP", "CVS", qdsp_cvs_callback, 0xFFFFFFFF, &common); if (common.apr_q6_cvs == NULL) { pr_err("%s: Unable to register CVS\n", __func__); goto err; } rtac_set_voice_handle(RTAC_CVS, common.apr_q6_cvs); } if (common.apr_q6_cvp == NULL) { pr_debug("%s: Start to register CVP callback\n", __func__); common.apr_q6_cvp = apr_register("ADSP", "CVP", qdsp_cvp_callback, 0xFFFFFFFF, &common); if (common.apr_q6_cvp == NULL) { pr_err("%s: Unable to register CVP\n", __func__); goto err; } rtac_set_voice_handle(RTAC_CVP, common.apr_q6_cvp); } mutex_unlock(&common.common_lock); return 0; err: if (common.apr_q6_cvs != NULL) { apr_deregister(common.apr_q6_cvs); common.apr_q6_cvs = NULL; rtac_set_voice_handle(RTAC_CVS, NULL); } if (common.apr_q6_mvm != NULL) { apr_deregister(common.apr_q6_mvm); common.apr_q6_mvm = NULL; } mutex_unlock(&common.common_lock); return -ENODEV; } static int voice_send_dual_control_cmd(struct voice_data *v) { int ret = 0; struct mvm_modem_dual_control_session_cmd mvm_voice_ctl_cmd; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } pr_debug("%s: VoLTE/Voice2 command to MVM\n", __func__); if (is_volte_session(v->session_id) || is_voice2_session(v->session_id)) { mvm_handle = voice_get_mvm_handle(v); mvm_voice_ctl_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_voice_ctl_cmd.hdr.pkt_size = APR_PKT_SIZE( APR_HDR_SIZE, sizeof(mvm_voice_ctl_cmd) - APR_HDR_SIZE); pr_debug("%s: send mvm Voice Ctl pkt size = %d\n", __func__, mvm_voice_ctl_cmd.hdr.pkt_size); mvm_voice_ctl_cmd.hdr.src_port = v->session_id; mvm_voice_ctl_cmd.hdr.dest_port = mvm_handle; mvm_voice_ctl_cmd.hdr.token = 0; mvm_voice_ctl_cmd.hdr.opcode = VSS_IMVM_CMD_SET_POLICY_DUAL_CONTROL; mvm_voice_ctl_cmd.voice_ctl.enable_flag = true; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_voice_ctl_cmd); if (ret < 0) { pr_err("%s: Error sending MVM Voice CTL CMD\n", __func__); ret = -EINVAL; goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); ret = -EINVAL; goto fail; } } ret = 0; fail: return ret; } static int voice_create_mvm_cvs_session(struct voice_data *v) { int ret = 0; struct mvm_create_ctl_session_cmd mvm_session_cmd; struct cvs_create_passive_ctl_session_cmd cvs_session_cmd; struct cvs_create_full_ctl_session_cmd cvs_full_ctl_cmd; struct mvm_attach_stream_cmd attach_stream_cmd; void *apr_mvm, *apr_cvs, *apr_cvp; u16 mvm_handle, cvs_handle, cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; apr_cvs = common.apr_q6_cvs; apr_cvp = common.apr_q6_cvp; if (!apr_mvm || !apr_cvs || !apr_cvp) { pr_err("%s: apr_mvm or apr_cvs or apr_cvp is NULL\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); cvs_handle = voice_get_cvs_handle(v); cvp_handle = voice_get_cvp_handle(v); pr_debug("%s: mvm_hdl=%d, cvs_hdl=%d\n", __func__, mvm_handle, cvs_handle); /* send cmd to create mvm session and wait for response */ if (!mvm_handle) { if (is_voice_session(v->session_id) || is_volte_session(v->session_id) || is_voice2_session(v->session_id)) { mvm_session_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_session_cmd.hdr.pkt_size = APR_PKT_SIZE( APR_HDR_SIZE, sizeof(mvm_session_cmd) - APR_HDR_SIZE); pr_debug("%s: send mvm create session pkt size = %d\n", __func__, mvm_session_cmd.hdr.pkt_size); mvm_session_cmd.hdr.src_port = v->session_id; mvm_session_cmd.hdr.dest_port = 0; mvm_session_cmd.hdr.token = 0; mvm_session_cmd.hdr.opcode = VSS_IMVM_CMD_CREATE_PASSIVE_CONTROL_SESSION; if (is_volte_session(v->session_id)) { strlcpy(mvm_session_cmd.mvm_session.name, "default volte voice", sizeof(mvm_session_cmd.mvm_session.name) - 1); } else if (is_voice2_session(v->session_id)) { strlcpy(mvm_session_cmd.mvm_session.name, "default modem voice2", sizeof(mvm_session_cmd.mvm_session.name)); } else { strlcpy(mvm_session_cmd.mvm_session.name, "default modem voice", sizeof(mvm_session_cmd.mvm_session.name) - 1); } v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_session_cmd); if (ret < 0) { pr_err("%s: Error sending MVM_CONTROL_SESSION\n", __func__); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } } else { pr_debug("%s: creating MVM full ctrl\n", __func__); mvm_session_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_session_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_session_cmd) - APR_HDR_SIZE); mvm_session_cmd.hdr.src_port = v->session_id; mvm_session_cmd.hdr.dest_port = 0; mvm_session_cmd.hdr.token = 0; mvm_session_cmd.hdr.opcode = VSS_IMVM_CMD_CREATE_FULL_CONTROL_SESSION; strlcpy(mvm_session_cmd.mvm_session.name, "default voip", sizeof(mvm_session_cmd.mvm_session.name)); v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_session_cmd); if (ret < 0) { pr_err("Fail in sending MVM_CONTROL_SESSION\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } } /* Get the created MVM handle. */ mvm_handle = voice_get_mvm_handle(v); } /* send cmd to create cvs session */ if (!cvs_handle) { if (is_voice_session(v->session_id) || is_volte_session(v->session_id) || is_voice2_session(v->session_id)) { pr_debug("%s: creating CVS passive session\n", __func__); cvs_session_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_session_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_session_cmd) - APR_HDR_SIZE); cvs_session_cmd.hdr.src_port = v->session_id; cvs_session_cmd.hdr.dest_port = 0; cvs_session_cmd.hdr.token = 0; cvs_session_cmd.hdr.opcode = VSS_ISTREAM_CMD_CREATE_PASSIVE_CONTROL_SESSION; if (is_volte_session(v->session_id)) { strlcpy(cvs_session_cmd.cvs_session.name, "default volte voice", sizeof(cvs_session_cmd.cvs_session.name) - 1); } else if (is_voice2_session(v->session_id)) { strlcpy(cvs_session_cmd.cvs_session.name, "default modem voice2", sizeof(cvs_session_cmd.cvs_session.name)); } else { strlcpy(cvs_session_cmd.cvs_session.name, "default modem voice", sizeof(cvs_session_cmd.cvs_session.name) - 1); } v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_session_cmd); if (ret < 0) { pr_err("Fail in sending STREAM_CONTROL_SESSION\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* Get the created CVS handle. */ cvs_handle = voice_get_cvs_handle(v); } else { pr_debug("%s: creating CVS full session\n", __func__); cvs_full_ctl_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_full_ctl_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_full_ctl_cmd) - APR_HDR_SIZE); cvs_full_ctl_cmd.hdr.src_port = v->session_id; cvs_full_ctl_cmd.hdr.dest_port = 0; cvs_full_ctl_cmd.hdr.token = 0; cvs_full_ctl_cmd.hdr.opcode = VSS_ISTREAM_CMD_CREATE_FULL_CONTROL_SESSION; cvs_full_ctl_cmd.cvs_session.direction = 2; cvs_full_ctl_cmd.cvs_session.enc_media_type = common.mvs_info.media_type; cvs_full_ctl_cmd.cvs_session.dec_media_type = common.mvs_info.media_type; cvs_full_ctl_cmd.cvs_session.network_id = common.mvs_info.network_type; strlcpy(cvs_full_ctl_cmd.cvs_session.name, "default q6 voice", sizeof(cvs_full_ctl_cmd.cvs_session.name)); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_full_ctl_cmd); if (ret < 0) { pr_err("%s: Err %d sending CREATE_FULL_CTRL\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* Get the created CVS handle. */ cvs_handle = voice_get_cvs_handle(v); /* Attach MVM to CVS. */ pr_debug("%s: Attach MVM to stream\n", __func__); attach_stream_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); attach_stream_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(attach_stream_cmd) - APR_HDR_SIZE); attach_stream_cmd.hdr.src_port = v->session_id; attach_stream_cmd.hdr.dest_port = mvm_handle; attach_stream_cmd.hdr.token = 0; attach_stream_cmd.hdr.opcode = VSS_IMVM_CMD_ATTACH_STREAM; attach_stream_cmd.attach_stream.handle = cvs_handle; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &attach_stream_cmd); if (ret < 0) { pr_err("%s: Error %d sending ATTACH_STREAM\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } } } return 0; fail: return -EINVAL; } static int voice_destroy_mvm_cvs_session(struct voice_data *v) { int ret = 0; struct mvm_detach_stream_cmd detach_stream; struct apr_hdr mvm_destroy; struct apr_hdr cvs_destroy; void *apr_mvm, *apr_cvs; u16 mvm_handle, cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; apr_cvs = common.apr_q6_cvs; if (!apr_mvm || !apr_cvs) { pr_err("%s: apr_mvm or apr_cvs is NULL\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); cvs_handle = voice_get_cvs_handle(v); /* MVM, CVS sessions are destroyed only for Full control sessions. */ if (is_voip_session(v->session_id)) { pr_debug("%s: MVM detach stream\n", __func__); /* Detach voice stream. */ detach_stream.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); detach_stream.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(detach_stream) - APR_HDR_SIZE); detach_stream.hdr.src_port = v->session_id; detach_stream.hdr.dest_port = mvm_handle; detach_stream.hdr.token = 0; detach_stream.hdr.opcode = VSS_IMVM_CMD_DETACH_STREAM; detach_stream.detach_stream.handle = cvs_handle; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &detach_stream); if (ret < 0) { pr_err("%s: Error %d sending DETACH_STREAM\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait event timeout\n", __func__); goto fail; } /* Destroy CVS. */ pr_debug("%s: CVS destroy session\n", __func__); cvs_destroy.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_destroy.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_destroy) - APR_HDR_SIZE); cvs_destroy.src_port = v->session_id; cvs_destroy.dest_port = cvs_handle; cvs_destroy.token = 0; cvs_destroy.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_destroy); if (ret < 0) { pr_err("%s: Error %d sending CVS DESTROY\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait event timeout\n", __func__); goto fail; } cvs_handle = 0; voice_set_cvs_handle(v, cvs_handle); /* Destroy MVM. */ pr_debug("MVM destroy session\n"); mvm_destroy.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_destroy.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_destroy) - APR_HDR_SIZE); mvm_destroy.src_port = v->session_id; mvm_destroy.dest_port = mvm_handle; mvm_destroy.token = 0; mvm_destroy.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_destroy); if (ret < 0) { pr_err("%s: Error %d sending MVM DESTROY\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait event timeout\n", __func__); goto fail; } mvm_handle = 0; voice_set_mvm_handle(v, mvm_handle); } return 0; fail: return -EINVAL; } static int voice_send_tty_mode_cmd(struct voice_data *v) { int ret = 0; struct mvm_set_tty_mode_cmd mvm_tty_mode_cmd; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); if (v->tty_mode) { /* send tty mode cmd to mvm */ mvm_tty_mode_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_tty_mode_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_tty_mode_cmd) - APR_HDR_SIZE); pr_debug("%s: pkt size = %d\n", __func__, mvm_tty_mode_cmd.hdr.pkt_size); mvm_tty_mode_cmd.hdr.src_port = v->session_id; mvm_tty_mode_cmd.hdr.dest_port = mvm_handle; mvm_tty_mode_cmd.hdr.token = 0; mvm_tty_mode_cmd.hdr.opcode = VSS_ISTREAM_CMD_SET_TTY_MODE; mvm_tty_mode_cmd.tty_mode.mode = v->tty_mode; pr_debug("tty mode =%d\n", mvm_tty_mode_cmd.tty_mode.mode); v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_tty_mode_cmd); if (ret < 0) { pr_err("%s: Error %d sending SET_TTY_MODE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } } return 0; fail: return -EINVAL; } static int voice_set_dtx(struct voice_data *v) { int ret = 0; void *apr_cvs; u16 cvs_handle; struct cvs_set_enc_dtx_mode_cmd cvs_set_dtx; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); /* Set DTX */ cvs_set_dtx.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_dtx.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_dtx) - APR_HDR_SIZE); cvs_set_dtx.hdr.src_port = v->session_id; cvs_set_dtx.hdr.dest_port = cvs_handle; cvs_set_dtx.hdr.token = 0; cvs_set_dtx.hdr.opcode = VSS_ISTREAM_CMD_SET_ENC_DTX_MODE; cvs_set_dtx.dtx_mode.enable = common.mvs_info.dtx_mode; pr_debug("%s: Setting DTX %d\n", __func__, common.mvs_info.dtx_mode); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_dtx); if (ret < 0) { pr_err("%s: Error %d sending SET_DTX\n", __func__, ret); return -EINVAL; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); return -EINVAL; } return 0; } static int voice_config_cvs_vocoder(struct voice_data *v) { int ret = 0; void *apr_cvs; u16 cvs_handle; /* Set media type. */ struct cvs_set_media_type_cmd cvs_set_media_cmd; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); cvs_set_media_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_media_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_media_cmd) - APR_HDR_SIZE); cvs_set_media_cmd.hdr.src_port = v->session_id; cvs_set_media_cmd.hdr.dest_port = cvs_handle; cvs_set_media_cmd.hdr.token = 0; cvs_set_media_cmd.hdr.opcode = VSS_ISTREAM_CMD_SET_MEDIA_TYPE; cvs_set_media_cmd.media_type.tx_media_id = common.mvs_info.media_type; cvs_set_media_cmd.media_type.rx_media_id = common.mvs_info.media_type; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_media_cmd); if (ret < 0) { pr_err("%s: Error %d sending SET_MEDIA_TYPE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* Set encoder properties. */ switch (common.mvs_info.media_type) { case VSS_MEDIA_ID_EVRC_MODEM: case VSS_MEDIA_ID_4GV_NB_MODEM: case VSS_MEDIA_ID_4GV_WB_MODEM: { struct cvs_set_cdma_enc_minmax_rate_cmd cvs_set_cdma_rate; pr_debug("Setting EVRC min-max rate\n"); cvs_set_cdma_rate.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_cdma_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_cdma_rate) - APR_HDR_SIZE); cvs_set_cdma_rate.hdr.src_port = v->session_id; cvs_set_cdma_rate.hdr.dest_port = cvs_handle; cvs_set_cdma_rate.hdr.token = 0; cvs_set_cdma_rate.hdr.opcode = VSS_ISTREAM_CMD_CDMA_SET_ENC_MINMAX_RATE; cvs_set_cdma_rate.cdma_rate.min_rate = common.mvs_info.rate; cvs_set_cdma_rate.cdma_rate.max_rate = common.mvs_info.rate; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_cdma_rate); if (ret < 0) { pr_err("%s: Error %d sending SET_EVRC_MINMAX_RATE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } break; } case VSS_MEDIA_ID_AMR_NB_MODEM: { struct cvs_set_amr_enc_rate_cmd cvs_set_amr_rate; pr_debug("Setting AMR rate\n"); cvs_set_amr_rate.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_amr_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_amr_rate) - APR_HDR_SIZE); cvs_set_amr_rate.hdr.src_port = v->session_id; cvs_set_amr_rate.hdr.dest_port = cvs_handle; cvs_set_amr_rate.hdr.token = 0; cvs_set_amr_rate.hdr.opcode = VSS_ISTREAM_CMD_VOC_AMR_SET_ENC_RATE; cvs_set_amr_rate.amr_rate.mode = common.mvs_info.rate; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_amr_rate); if (ret < 0) { pr_err("%s: Error %d sending SET_AMR_RATE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } ret = voice_set_dtx(v); if (ret < 0) goto fail; break; } case VSS_MEDIA_ID_AMR_WB_MODEM: { struct cvs_set_amrwb_enc_rate_cmd cvs_set_amrwb_rate; pr_debug("Setting AMR WB rate\n"); cvs_set_amrwb_rate.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_amrwb_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_amrwb_rate) - APR_HDR_SIZE); cvs_set_amrwb_rate.hdr.src_port = v->session_id; cvs_set_amrwb_rate.hdr.dest_port = cvs_handle; cvs_set_amrwb_rate.hdr.token = 0; cvs_set_amrwb_rate.hdr.opcode = VSS_ISTREAM_CMD_VOC_AMRWB_SET_ENC_RATE; cvs_set_amrwb_rate.amrwb_rate.mode = common.mvs_info.rate; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_amrwb_rate); if (ret < 0) { pr_err("%s: Error %d sending SET_AMRWB_RATE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } ret = voice_set_dtx(v); if (ret < 0) goto fail; break; } case VSS_MEDIA_ID_G729: case VSS_MEDIA_ID_G711_ALAW: case VSS_MEDIA_ID_G711_MULAW: { ret = voice_set_dtx(v); break; } default: /* Do nothing. */ break; } return 0; fail: return -EINVAL; } static int voice_send_start_voice_cmd(struct voice_data *v) { struct apr_hdr mvm_start_voice_cmd; int ret = 0; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); mvm_start_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_start_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_start_voice_cmd) - APR_HDR_SIZE); pr_debug("send mvm_start_voice_cmd pkt size = %d\n", mvm_start_voice_cmd.pkt_size); mvm_start_voice_cmd.src_port = v->session_id; mvm_start_voice_cmd.dest_port = mvm_handle; mvm_start_voice_cmd.token = 0; mvm_start_voice_cmd.opcode = VSS_IMVM_CMD_START_VOICE; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_start_voice_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_START_VOICE\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_disable_vocproc_cmd(struct voice_data *v) { struct apr_hdr cvp_disable_cmd; int ret = 0; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr regist failed\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* disable vocproc and wait for respose */ cvp_disable_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_disable_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_disable_cmd) - APR_HDR_SIZE); pr_debug("cvp_disable_cmd pkt size = %d, cvp_handle=%d\n", cvp_disable_cmd.pkt_size, cvp_handle); cvp_disable_cmd.src_port = v->session_id; cvp_disable_cmd.dest_port = cvp_handle; cvp_disable_cmd.token = 0; cvp_disable_cmd.opcode = VSS_IVOCPROC_CMD_DISABLE; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_disable_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IVOCPROC_CMD_DISABLE\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_set_device_cmd(struct voice_data *v) { struct cvp_set_device_cmd cvp_setdev_cmd; int ret = 0; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* set device and wait for response */ cvp_setdev_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_setdev_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_setdev_cmd) - APR_HDR_SIZE); pr_debug("send create cvp setdev, pkt size = %d\n", cvp_setdev_cmd.hdr.pkt_size); cvp_setdev_cmd.hdr.src_port = v->session_id; cvp_setdev_cmd.hdr.dest_port = cvp_handle; cvp_setdev_cmd.hdr.token = 0; cvp_setdev_cmd.hdr.opcode = VSS_IVOCPROC_CMD_SET_DEVICE; /* Use default topology if invalid value in ACDB */ cvp_setdev_cmd.cvp_set_device.tx_topology_id = get_voice_tx_topology(); if (cvp_setdev_cmd.cvp_set_device.tx_topology_id == 0) cvp_setdev_cmd.cvp_set_device.tx_topology_id = VSS_IVOCPROC_TOPOLOGY_ID_TX_SM_ECNS; cvp_setdev_cmd.cvp_set_device.rx_topology_id = get_voice_rx_topology(); if (cvp_setdev_cmd.cvp_set_device.rx_topology_id == 0) cvp_setdev_cmd.cvp_set_device.rx_topology_id = VSS_IVOCPROC_TOPOLOGY_ID_RX_DEFAULT; cvp_setdev_cmd.cvp_set_device.tx_port_id = v->dev_tx.port_id; cvp_setdev_cmd.cvp_set_device.rx_port_id = v->dev_rx.port_id; pr_debug("topology=%d , tx_port_id=%d, rx_port_id=%d\n", cvp_setdev_cmd.cvp_set_device.tx_topology_id, cvp_setdev_cmd.cvp_set_device.tx_port_id, cvp_setdev_cmd.cvp_set_device.rx_port_id); v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_setdev_cmd); if (ret < 0) { pr_err("Fail in sending VOCPROC_FULL_CONTROL_SESSION\n"); goto fail; } pr_debug("wait for cvp create session event\n"); ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_set_device_cmd_v2(struct voice_data *v) { struct cvp_set_device_cmd_v2 cvp_setdev_cmd_v2; int ret = 0; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* set device and wait for response */ cvp_setdev_cmd_v2.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_setdev_cmd_v2.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_setdev_cmd_v2) - APR_HDR_SIZE); cvp_setdev_cmd_v2.hdr.src_port = v->session_id; cvp_setdev_cmd_v2.hdr.dest_port = cvp_handle; cvp_setdev_cmd_v2.hdr.token = 0; cvp_setdev_cmd_v2.hdr.opcode = VSS_IVOCPROC_CMD_SET_DEVICE_V2; /* Use default topology if invalid value in ACDB */ cvp_setdev_cmd_v2.cvp_set_device_v2.tx_topology_id = get_voice_tx_topology(); if (cvp_setdev_cmd_v2.cvp_set_device_v2.tx_topology_id == 0) cvp_setdev_cmd_v2.cvp_set_device_v2.tx_topology_id = VSS_IVOCPROC_TOPOLOGY_ID_TX_SM_ECNS; cvp_setdev_cmd_v2.cvp_set_device_v2.rx_topology_id = get_voice_rx_topology(); if (cvp_setdev_cmd_v2.cvp_set_device_v2.rx_topology_id == 0) cvp_setdev_cmd_v2.cvp_set_device_v2.rx_topology_id = VSS_IVOCPROC_TOPOLOGY_ID_RX_DEFAULT; cvp_setdev_cmd_v2.cvp_set_device_v2.tx_port_id = v->dev_tx.port_id; cvp_setdev_cmd_v2.cvp_set_device_v2.rx_port_id = v->dev_rx.port_id; if (common.ec_ref_ext == true) { cvp_setdev_cmd_v2.cvp_set_device_v2.vocproc_mode = VSS_IVOCPROC_VOCPROC_MODE_EC_EXT_MIXING; cvp_setdev_cmd_v2.cvp_set_device_v2.ec_ref_port_id = common.ec_port_id; } else { cvp_setdev_cmd_v2.cvp_set_device_v2.vocproc_mode = VSS_IVOCPROC_VOCPROC_MODE_EC_INT_MIXING; cvp_setdev_cmd_v2.cvp_set_device_v2.ec_ref_port_id = VSS_IVOCPROC_PORT_ID_NONE; } pr_debug("%s:topology=%d , tx_port_id=%d, rx_port_id=%d\n" "ec_ref_port_id = %x\n", __func__, cvp_setdev_cmd_v2.cvp_set_device_v2.tx_topology_id, cvp_setdev_cmd_v2.cvp_set_device_v2.tx_port_id, cvp_setdev_cmd_v2.cvp_set_device_v2.rx_port_id, cvp_setdev_cmd_v2.cvp_set_device_v2.ec_ref_port_id); v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_setdev_cmd_v2); if (ret < 0) { pr_err("Fail in sending VSS_IVOCPROC_CMD_SET_DEVICE_V2\n"); goto fail; } pr_debug("wait for cvp create session event\n"); ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_stop_voice_cmd(struct voice_data *v) { struct apr_hdr mvm_stop_voice_cmd; int ret = 0; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); mvm_stop_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_stop_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_stop_voice_cmd) - APR_HDR_SIZE); pr_debug("send mvm_stop_voice_cmd pkt size = %d\n", mvm_stop_voice_cmd.pkt_size); mvm_stop_voice_cmd.src_port = v->session_id; mvm_stop_voice_cmd.dest_port = mvm_handle; mvm_stop_voice_cmd.token = 0; mvm_stop_voice_cmd.opcode = VSS_IMVM_CMD_STOP_VOICE; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_stop_voice_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_STOP_VOICE\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvs_register_cal_cmd(struct voice_data *v) { struct cvs_register_cal_data_cmd cvs_reg_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvs; u16 cvs_handle; uint32_t cal_paddr = 0; uint32_t cal_buf = 0; /* get the cvs cal data */ get_all_vocstrm_cal(&cal_block); if (cal_block.cal_size == 0) goto fail; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } if (is_volte_session(v->session_id) || is_voip_session(v->session_id)) { ret = voice_get_cal_phys_addr(v->session_id, CVS_CAL, &cal_paddr); if (ret < 0) return ret; ret = voice_get_cal_kernel_addr(v->session_id, CVS_CAL, &cal_buf); if (ret < 0) return ret; memcpy((void *)cal_buf, (void *)cal_block.cal_kvaddr, cal_block.cal_size); } else { cal_paddr = cal_block.cal_paddr; } cvs_handle = voice_get_cvs_handle(v); /* fill in the header */ cvs_reg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_reg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_reg_cal_cmd) - APR_HDR_SIZE); cvs_reg_cal_cmd.hdr.src_port = v->session_id; cvs_reg_cal_cmd.hdr.dest_port = cvs_handle; cvs_reg_cal_cmd.hdr.token = 0; cvs_reg_cal_cmd.hdr.opcode = VSS_ISTREAM_CMD_REGISTER_CALIBRATION_DATA; cvs_reg_cal_cmd.cvs_cal_data.phys_addr = cal_paddr; cvs_reg_cal_cmd.cvs_cal_data.mem_size = cal_block.cal_size; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_reg_cal_cmd); if (ret < 0) { pr_err("Fail: sending cvs cal,\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvs_deregister_cal_cmd(struct voice_data *v) { struct cvs_deregister_cal_data_cmd cvs_dereg_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvs; u16 cvs_handle; get_all_vocstrm_cal(&cal_block); if (cal_block.cal_size == 0) return 0; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); /* fill in the header */ cvs_dereg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_dereg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_dereg_cal_cmd) - APR_HDR_SIZE); cvs_dereg_cal_cmd.hdr.src_port = v->session_id; cvs_dereg_cal_cmd.hdr.dest_port = cvs_handle; cvs_dereg_cal_cmd.hdr.token = 0; cvs_dereg_cal_cmd.hdr.opcode = VSS_ISTREAM_CMD_DEREGISTER_CALIBRATION_DATA; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_dereg_cal_cmd); if (ret < 0) { pr_err("Fail: sending cvs cal,\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_map_memory_cmd(struct voice_data *v) { struct vss_map_memory_cmd cvp_map_mem_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvp; u16 cvp_handle; uint32_t cal_paddr = 0; /* get all cvp cal data */ get_all_cvp_cal(&cal_block); if (cal_block.cal_size == 0) goto fail; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } if (is_volte_session(v->session_id) || is_voip_session(v->session_id)) { ret = voice_get_cal_phys_addr(v->session_id, CVP_CAL, &cal_paddr); if (ret < 0) return ret; } else { cal_paddr = cal_block.cal_paddr; } cvp_handle = voice_get_cvp_handle(v); /* fill in the header */ cvp_map_mem_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_map_mem_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_map_mem_cmd) - APR_HDR_SIZE); cvp_map_mem_cmd.hdr.src_port = v->session_id; cvp_map_mem_cmd.hdr.dest_port = cvp_handle; cvp_map_mem_cmd.hdr.token = 0; cvp_map_mem_cmd.hdr.opcode = VSS_ICOMMON_CMD_MAP_MEMORY; pr_debug("%s, phys_addr: 0x%x, mem_size: %d\n", __func__, cal_paddr, cal_block.cal_size); cvp_map_mem_cmd.vss_map_mem.phys_addr = cal_paddr; cvp_map_mem_cmd.vss_map_mem.mem_size = cal_block.cal_size; cvp_map_mem_cmd.vss_map_mem.mem_pool_id = VSS_ICOMMON_MAP_MEMORY_SHMEM8_4K_POOL; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_map_mem_cmd); if (ret < 0) { pr_err("Fail: sending cvp cal,\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_unmap_memory_cmd(struct voice_data *v) { struct vss_unmap_memory_cmd cvp_unmap_mem_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvp; u16 cvp_handle; uint32_t cal_paddr = 0; get_all_cvp_cal(&cal_block); if (cal_block.cal_size == 0) return 0; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } if (is_volte_session(v->session_id) || is_voip_session(v->session_id)) { ret = voice_get_cal_phys_addr(v->session_id, CVP_CAL, &cal_paddr); if (ret < 0) return ret; } else { cal_paddr = cal_block.cal_paddr; } cvp_handle = voice_get_cvp_handle(v); /* fill in the header */ cvp_unmap_mem_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_unmap_mem_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_unmap_mem_cmd) - APR_HDR_SIZE); cvp_unmap_mem_cmd.hdr.src_port = v->session_id; cvp_unmap_mem_cmd.hdr.dest_port = cvp_handle; cvp_unmap_mem_cmd.hdr.token = 0; cvp_unmap_mem_cmd.hdr.opcode = VSS_ICOMMON_CMD_UNMAP_MEMORY; cvp_unmap_mem_cmd.vss_unmap_mem.phys_addr = cal_paddr; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_unmap_mem_cmd); if (ret < 0) { pr_err("Fail: sending cvp cal,\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvs_map_memory_cmd(struct voice_data *v) { struct vss_map_memory_cmd cvs_map_mem_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvs; u16 cvs_handle; uint32_t cal_paddr = 0; /* get all cvs cal data */ get_all_vocstrm_cal(&cal_block); if (cal_block.cal_size == 0) goto fail; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } if (is_volte_session(v->session_id) || is_voip_session(v->session_id)) { ret = voice_get_cal_phys_addr(v->session_id, CVS_CAL, &cal_paddr); if (ret < 0) return ret; } else { cal_paddr = cal_block.cal_paddr; } cvs_handle = voice_get_cvs_handle(v); /* fill in the header */ cvs_map_mem_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_map_mem_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_map_mem_cmd) - APR_HDR_SIZE); cvs_map_mem_cmd.hdr.src_port = v->session_id; cvs_map_mem_cmd.hdr.dest_port = cvs_handle; cvs_map_mem_cmd.hdr.token = 0; cvs_map_mem_cmd.hdr.opcode = VSS_ICOMMON_CMD_MAP_MEMORY; pr_debug("%s, phys_addr: 0x%x, mem_size: %d\n", __func__, cal_paddr, cal_block.cal_size); cvs_map_mem_cmd.vss_map_mem.phys_addr = cal_paddr; cvs_map_mem_cmd.vss_map_mem.mem_size = cal_block.cal_size; cvs_map_mem_cmd.vss_map_mem.mem_pool_id = VSS_ICOMMON_MAP_MEMORY_SHMEM8_4K_POOL; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_map_mem_cmd); if (ret < 0) { pr_err("Fail: sending cvs cal,\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvs_unmap_memory_cmd(struct voice_data *v) { struct vss_unmap_memory_cmd cvs_unmap_mem_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvs; u16 cvs_handle; uint32_t cal_paddr = 0; get_all_vocstrm_cal(&cal_block); if (cal_block.cal_size == 0) return 0; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } if (is_volte_session(v->session_id) || is_voip_session(v->session_id)) { ret = voice_get_cal_phys_addr(v->session_id, CVS_CAL, &cal_paddr); if (ret < 0) return ret; } else { cal_paddr = cal_block.cal_paddr; } cvs_handle = voice_get_cvs_handle(v); /* fill in the header */ cvs_unmap_mem_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_unmap_mem_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_unmap_mem_cmd) - APR_HDR_SIZE); cvs_unmap_mem_cmd.hdr.src_port = v->session_id; cvs_unmap_mem_cmd.hdr.dest_port = cvs_handle; cvs_unmap_mem_cmd.hdr.token = 0; cvs_unmap_mem_cmd.hdr.opcode = VSS_ICOMMON_CMD_UNMAP_MEMORY; cvs_unmap_mem_cmd.vss_unmap_mem.phys_addr = cal_paddr; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_unmap_mem_cmd); if (ret < 0) { pr_err("Fail: sending cvs cal,\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_register_cal_cmd(struct voice_data *v) { struct cvp_register_cal_data_cmd cvp_reg_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvp; u16 cvp_handle; uint32_t cal_paddr = 0; uint32_t cal_buf = 0; /* get the cvp cal data */ get_all_vocproc_cal(&cal_block); if (cal_block.cal_size == 0) goto fail; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } if (is_volte_session(v->session_id) || is_voip_session(v->session_id)) { ret = voice_get_cal_phys_addr(v->session_id, CVP_CAL, &cal_paddr); if (ret < 0) return ret; ret = voice_get_cal_kernel_addr(v->session_id, CVP_CAL, &cal_buf); if (ret < 0) return ret; memcpy((void *)cal_buf, (void *)cal_block.cal_kvaddr, cal_block.cal_size); } else { cal_paddr = cal_block.cal_paddr; } cvp_handle = voice_get_cvp_handle(v); /* fill in the header */ cvp_reg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_reg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_reg_cal_cmd) - APR_HDR_SIZE); cvp_reg_cal_cmd.hdr.src_port = v->session_id; cvp_reg_cal_cmd.hdr.dest_port = cvp_handle; cvp_reg_cal_cmd.hdr.token = 0; cvp_reg_cal_cmd.hdr.opcode = VSS_IVOCPROC_CMD_REGISTER_CALIBRATION_DATA; cvp_reg_cal_cmd.cvp_cal_data.phys_addr = cal_paddr; cvp_reg_cal_cmd.cvp_cal_data.mem_size = cal_block.cal_size; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_reg_cal_cmd); if (ret < 0) { pr_err("Fail: sending cvp cal,\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_deregister_cal_cmd(struct voice_data *v) { struct cvp_deregister_cal_data_cmd cvp_dereg_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvp; u16 cvp_handle; get_all_vocproc_cal(&cal_block); if (cal_block.cal_size == 0) return 0; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* fill in the header */ cvp_dereg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_dereg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_dereg_cal_cmd) - APR_HDR_SIZE); cvp_dereg_cal_cmd.hdr.src_port = v->session_id; cvp_dereg_cal_cmd.hdr.dest_port = cvp_handle; cvp_dereg_cal_cmd.hdr.token = 0; cvp_dereg_cal_cmd.hdr.opcode = VSS_IVOCPROC_CMD_DEREGISTER_CALIBRATION_DATA; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_dereg_cal_cmd); if (ret < 0) { pr_err("Fail: sending cvp cal,\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_register_vol_cal_table_cmd(struct voice_data *v) { struct cvp_register_vol_cal_table_cmd cvp_reg_cal_tbl_cmd; struct acdb_cal_block vol_block; struct acdb_cal_block voc_block; int ret = 0; void *apr_cvp; u16 cvp_handle; uint32_t cal_paddr = 0; uint32_t cal_buf = 0; /* get the cvp vol cal data */ get_all_vocvol_cal(&vol_block); get_all_vocproc_cal(&voc_block); if (vol_block.cal_size == 0) goto fail; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } if (is_volte_session(v->session_id) || is_voip_session(v->session_id)) { ret = voice_get_cal_phys_addr(v->session_id, CVP_CAL, &cal_paddr); if (ret < 0) return ret; cal_paddr += voc_block.cal_size; ret = voice_get_cal_kernel_addr(v->session_id, CVP_CAL, &cal_buf); if (ret < 0) return ret; memcpy((void *)(cal_buf + voc_block.cal_size), (void *)vol_block.cal_kvaddr, vol_block.cal_size); } else { cal_paddr = vol_block.cal_paddr; } cvp_handle = voice_get_cvp_handle(v); /* fill in the header */ cvp_reg_cal_tbl_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_reg_cal_tbl_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_reg_cal_tbl_cmd) - APR_HDR_SIZE); cvp_reg_cal_tbl_cmd.hdr.src_port = v->session_id; cvp_reg_cal_tbl_cmd.hdr.dest_port = cvp_handle; cvp_reg_cal_tbl_cmd.hdr.token = 0; cvp_reg_cal_tbl_cmd.hdr.opcode = VSS_IVOCPROC_CMD_REGISTER_VOLUME_CAL_TABLE; cvp_reg_cal_tbl_cmd.cvp_vol_cal_tbl.phys_addr = cal_paddr; cvp_reg_cal_tbl_cmd.cvp_vol_cal_tbl.mem_size = vol_block.cal_size; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_reg_cal_tbl_cmd); if (ret < 0) { pr_err("Fail: sending cvp cal table,\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_deregister_vol_cal_table_cmd(struct voice_data *v) { struct cvp_deregister_vol_cal_table_cmd cvp_dereg_cal_tbl_cmd; struct acdb_cal_block cal_block; int ret = 0; void *apr_cvp; u16 cvp_handle; get_all_vocvol_cal(&cal_block); if (cal_block.cal_size == 0) return 0; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* fill in the header */ cvp_dereg_cal_tbl_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_dereg_cal_tbl_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_dereg_cal_tbl_cmd) - APR_HDR_SIZE); cvp_dereg_cal_tbl_cmd.hdr.src_port = v->session_id; cvp_dereg_cal_tbl_cmd.hdr.dest_port = cvp_handle; cvp_dereg_cal_tbl_cmd.hdr.token = 0; cvp_dereg_cal_tbl_cmd.hdr.opcode = VSS_IVOCPROC_CMD_DEREGISTER_VOLUME_CAL_TABLE; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_dereg_cal_tbl_cmd); if (ret < 0) { pr_err("Fail: sending cvp cal table,\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_set_widevoice_enable_cmd(struct voice_data *v) { struct mvm_set_widevoice_enable_cmd mvm_set_wv_cmd; int ret = 0; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); /* fill in the header */ mvm_set_wv_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_set_wv_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_set_wv_cmd) - APR_HDR_SIZE); mvm_set_wv_cmd.hdr.src_port = v->session_id; mvm_set_wv_cmd.hdr.dest_port = mvm_handle; mvm_set_wv_cmd.hdr.token = 0; mvm_set_wv_cmd.hdr.opcode = VSS_IWIDEVOICE_CMD_SET_WIDEVOICE; mvm_set_wv_cmd.vss_set_wv.enable = v->wv_enable; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_wv_cmd); if (ret < 0) { pr_err("Fail: sending mvm set widevoice enable,\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_set_pp_enable_cmd(struct voice_data *v, uint32_t module_id, int enable) { struct cvs_set_pp_enable_cmd cvs_set_pp_cmd; int ret = 0; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); /* fill in the header */ cvs_set_pp_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_pp_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_pp_cmd) - APR_HDR_SIZE); cvs_set_pp_cmd.hdr.src_port = v->session_id; cvs_set_pp_cmd.hdr.dest_port = cvs_handle; cvs_set_pp_cmd.hdr.token = 0; cvs_set_pp_cmd.hdr.opcode = VSS_ICOMMON_CMD_SET_UI_PROPERTY; cvs_set_pp_cmd.vss_set_pp.module_id = module_id; cvs_set_pp_cmd.vss_set_pp.param_id = VOICE_PARAM_MOD_ENABLE; cvs_set_pp_cmd.vss_set_pp.param_size = MOD_ENABLE_PARAM_LEN; cvs_set_pp_cmd.vss_set_pp.reserved = 0; cvs_set_pp_cmd.vss_set_pp.enable = enable; cvs_set_pp_cmd.vss_set_pp.reserved_field = 0; pr_debug("voice_send_set_pp_enable_cmd, module_id=%d, enable=%d\n", module_id, enable); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_pp_cmd); if (ret < 0) { pr_err("Fail: sending cvs set slowtalk enable,\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_setup_vocproc(struct voice_data *v) { struct cvp_create_full_ctl_session_cmd cvp_session_cmd; int ret = 0; void *apr_cvp; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } /* create cvp session and wait for response */ cvp_session_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_session_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_session_cmd) - APR_HDR_SIZE); pr_debug(" send create cvp session, pkt size = %d\n", cvp_session_cmd.hdr.pkt_size); cvp_session_cmd.hdr.src_port = v->session_id; cvp_session_cmd.hdr.dest_port = 0; cvp_session_cmd.hdr.token = 0; cvp_session_cmd.hdr.opcode = VSS_IVOCPROC_CMD_CREATE_FULL_CONTROL_SESSION; /* Use default topology if invalid value in ACDB */ cvp_session_cmd.cvp_session.tx_topology_id = get_voice_tx_topology(); if (cvp_session_cmd.cvp_session.tx_topology_id == 0) cvp_session_cmd.cvp_session.tx_topology_id = VSS_IVOCPROC_TOPOLOGY_ID_TX_SM_ECNS; cvp_session_cmd.cvp_session.rx_topology_id = get_voice_rx_topology(); if (cvp_session_cmd.cvp_session.rx_topology_id == 0) cvp_session_cmd.cvp_session.rx_topology_id = VSS_IVOCPROC_TOPOLOGY_ID_RX_DEFAULT; cvp_session_cmd.cvp_session.direction = 2; /*tx and rx*/ cvp_session_cmd.cvp_session.network_id = VSS_NETWORK_ID_DEFAULT; cvp_session_cmd.cvp_session.tx_port_id = v->dev_tx.port_id; cvp_session_cmd.cvp_session.rx_port_id = v->dev_rx.port_id; pr_debug("topology=%d net_id=%d, dir=%d tx_port_id=%d, rx_port_id=%d\n", cvp_session_cmd.cvp_session.tx_topology_id, cvp_session_cmd.cvp_session.network_id, cvp_session_cmd.cvp_session.direction, cvp_session_cmd.cvp_session.tx_port_id, cvp_session_cmd.cvp_session.rx_port_id); v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_session_cmd); if (ret < 0) { pr_err("Fail in sending VOCPROC_FULL_CONTROL_SESSION\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } if (common.ec_ref_ext == true) { ret = voice_send_set_device_cmd_v2(v); if (ret < 0) pr_err("%s: set device V2 failed rc =%x\n", __func__, ret); goto fail; } /* send cvs cal */ ret = voice_send_cvs_map_memory_cmd(v); if (!ret) voice_send_cvs_register_cal_cmd(v); /* send cvp and vol cal */ ret = voice_send_cvp_map_memory_cmd(v); if (!ret) { voice_send_cvp_register_cal_cmd(v); voice_send_cvp_register_vol_cal_table_cmd(v); } /* enable vocproc */ ret = voice_send_enable_vocproc_cmd(v); if (ret < 0) goto fail; /* attach vocproc */ ret = voice_send_attach_vocproc_cmd(v); if (ret < 0) goto fail; /* send tty mode if tty device is used */ voice_send_tty_mode_cmd(v); /* enable widevoice if wv_enable is set */ if (v->wv_enable) voice_send_set_widevoice_enable_cmd(v); /* enable slowtalk if st_enable is set */ if (v->st_enable) voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_ST, v->st_enable); voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_FENS, v->fens_enable); if (is_voip_session(v->session_id)) voice_send_netid_timing_cmd(v); /* Start in-call music delivery if this feature is enabled */ if (v->music_info.play_enable) voice_cvs_start_playback(v); /* Start in-call recording if this feature is enabled */ if (v->rec_info.rec_enable) voice_cvs_start_record(v, v->rec_info.rec_mode); rtac_add_voice(voice_get_cvs_handle(v), voice_get_cvp_handle(v), v->dev_rx.port_id, v->dev_tx.port_id, v->session_id); return 0; fail: return -EINVAL; } static int voice_send_enable_vocproc_cmd(struct voice_data *v) { int ret = 0; struct apr_hdr cvp_enable_cmd; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* enable vocproc and wait for respose */ cvp_enable_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_enable_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_enable_cmd) - APR_HDR_SIZE); pr_debug("cvp_enable_cmd pkt size = %d, cvp_handle=%d\n", cvp_enable_cmd.pkt_size, cvp_handle); cvp_enable_cmd.src_port = v->session_id; cvp_enable_cmd.dest_port = cvp_handle; cvp_enable_cmd.token = 0; cvp_enable_cmd.opcode = VSS_IVOCPROC_CMD_ENABLE; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_enable_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IVOCPROC_CMD_ENABLE\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_netid_timing_cmd(struct voice_data *v) { int ret = 0; void *apr_mvm; u16 mvm_handle; struct mvm_set_network_cmd mvm_set_network; struct mvm_set_voice_timing_cmd mvm_set_voice_timing; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); ret = voice_config_cvs_vocoder(v); if (ret < 0) { pr_err("%s: Error %d configuring CVS voc", __func__, ret); goto fail; } /* Set network ID. */ pr_debug("Setting network ID\n"); mvm_set_network.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_set_network.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_set_network) - APR_HDR_SIZE); mvm_set_network.hdr.src_port = v->session_id; mvm_set_network.hdr.dest_port = mvm_handle; mvm_set_network.hdr.token = 0; mvm_set_network.hdr.opcode = VSS_ICOMMON_CMD_SET_NETWORK; mvm_set_network.network.network_id = common.mvs_info.network_type; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_network); if (ret < 0) { pr_err("%s: Error %d sending SET_NETWORK\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* Set voice timing. */ pr_debug("Setting voice timing\n"); mvm_set_voice_timing.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_set_voice_timing.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_set_voice_timing) - APR_HDR_SIZE); mvm_set_voice_timing.hdr.src_port = v->session_id; mvm_set_voice_timing.hdr.dest_port = mvm_handle; mvm_set_voice_timing.hdr.token = 0; mvm_set_voice_timing.hdr.opcode = VSS_ICOMMON_CMD_SET_VOICE_TIMING; mvm_set_voice_timing.timing.mode = 0; mvm_set_voice_timing.timing.enc_offset = 8000; mvm_set_voice_timing.timing.dec_req_offset = 3300; mvm_set_voice_timing.timing.dec_offset = 8300; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_voice_timing); if (ret < 0) { pr_err("%s: Error %d sending SET_TIMING\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_attach_vocproc_cmd(struct voice_data *v) { int ret = 0; struct mvm_attach_vocproc_cmd mvm_a_vocproc_cmd; void *apr_mvm; u16 mvm_handle, cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); cvp_handle = voice_get_cvp_handle(v); /* attach vocproc and wait for response */ mvm_a_vocproc_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_a_vocproc_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_a_vocproc_cmd) - APR_HDR_SIZE); pr_debug("send mvm_a_vocproc_cmd pkt size = %d\n", mvm_a_vocproc_cmd.hdr.pkt_size); mvm_a_vocproc_cmd.hdr.src_port = v->session_id; mvm_a_vocproc_cmd.hdr.dest_port = mvm_handle; mvm_a_vocproc_cmd.hdr.token = 0; mvm_a_vocproc_cmd.hdr.opcode = VSS_IMVM_CMD_ATTACH_VOCPROC; mvm_a_vocproc_cmd.mvm_attach_cvp_handle.handle = cvp_handle; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_a_vocproc_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_ATTACH_VOCPROC\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_destroy_vocproc(struct voice_data *v) { struct mvm_detach_vocproc_cmd mvm_d_vocproc_cmd; struct apr_hdr cvp_destroy_session_cmd; int ret = 0; void *apr_mvm, *apr_cvp; u16 mvm_handle, cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; apr_cvp = common.apr_q6_cvp; if (!apr_mvm || !apr_cvp) { pr_err("%s: apr_mvm or apr_cvp is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); cvp_handle = voice_get_cvp_handle(v); /* stop playback or recording */ v->music_info.force = 1; voice_cvs_stop_playback(v); voice_cvs_stop_record(v); /* send stop voice cmd */ voice_send_stop_voice_cmd(v); /* Clear mute setting */ v->dev_tx.mute = common.default_mute_val; /* detach VOCPROC and wait for response from mvm */ mvm_d_vocproc_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_d_vocproc_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_d_vocproc_cmd) - APR_HDR_SIZE); pr_debug("mvm_d_vocproc_cmd pkt size = %d\n", mvm_d_vocproc_cmd.hdr.pkt_size); mvm_d_vocproc_cmd.hdr.src_port = v->session_id; mvm_d_vocproc_cmd.hdr.dest_port = mvm_handle; mvm_d_vocproc_cmd.hdr.token = 0; mvm_d_vocproc_cmd.hdr.opcode = VSS_IMVM_CMD_DETACH_VOCPROC; mvm_d_vocproc_cmd.mvm_detach_cvp_handle.handle = cvp_handle; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_d_vocproc_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_DETACH_VOCPROC\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* deregister cvp and vol cal */ voice_send_cvp_deregister_vol_cal_table_cmd(v); voice_send_cvp_deregister_cal_cmd(v); voice_send_cvp_unmap_memory_cmd(v); /* deregister cvs cal */ voice_send_cvs_deregister_cal_cmd(v); voice_send_cvs_unmap_memory_cmd(v); /* destrop cvp session */ cvp_destroy_session_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_destroy_session_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_destroy_session_cmd) - APR_HDR_SIZE); pr_debug("cvp_destroy_session_cmd pkt size = %d\n", cvp_destroy_session_cmd.pkt_size); cvp_destroy_session_cmd.src_port = v->session_id; cvp_destroy_session_cmd.dest_port = cvp_handle; cvp_destroy_session_cmd.token = 0; cvp_destroy_session_cmd.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_destroy_session_cmd); if (ret < 0) { pr_err("Fail in sending APRV2_IBASIC_CMD_DESTROY_SESSION\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } rtac_remove_voice(voice_get_cvs_handle(v)); cvp_handle = 0; voice_set_cvp_handle(v, cvp_handle); return 0; fail: return -EINVAL; } static int voice_send_mute_cmd(struct voice_data *v) { struct cvs_set_mute_cmd cvs_mute_cmd; int ret = 0; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); /* send mute/unmute to cvs */ cvs_mute_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_mute_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_mute_cmd) - APR_HDR_SIZE); cvs_mute_cmd.hdr.src_port = v->session_id; cvs_mute_cmd.hdr.dest_port = cvs_handle; cvs_mute_cmd.hdr.token = 0; cvs_mute_cmd.hdr.opcode = VSS_ISTREAM_CMD_SET_MUTE; cvs_mute_cmd.cvs_set_mute.direction = 0; /*tx*/ cvs_mute_cmd.cvs_set_mute.mute_flag = v->dev_tx.mute; pr_info(" mute value =%d\n", cvs_mute_cmd.cvs_set_mute.mute_flag); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_mute_cmd); if (ret < 0) { pr_err("Fail: send STREAM SET MUTE\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) pr_err("%s: wait_event timeout\n", __func__); return 0; fail: return -EINVAL; } static int voice_send_rx_device_mute_cmd(struct voice_data *v) { struct cvp_set_mute_cmd cvp_mute_cmd; int ret = 0; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); cvp_mute_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_mute_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_mute_cmd) - APR_HDR_SIZE); cvp_mute_cmd.hdr.src_port = v->session_id; cvp_mute_cmd.hdr.dest_port = cvp_handle; cvp_mute_cmd.hdr.token = 0; cvp_mute_cmd.hdr.opcode = VSS_IVOCPROC_CMD_SET_MUTE; cvp_mute_cmd.cvp_set_mute.direction = 1; cvp_mute_cmd.cvp_set_mute.mute_flag = v->dev_rx.mute; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_mute_cmd); if (ret < 0) { pr_err("Fail in sending RX device mute cmd\n"); return -EINVAL; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); return -EINVAL; } return 0; } static int voice_send_vol_index_cmd(struct voice_data *v) { struct cvp_set_rx_volume_index_cmd cvp_vol_cmd; int ret = 0; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* send volume index to cvp */ cvp_vol_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_vol_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_vol_cmd) - APR_HDR_SIZE); cvp_vol_cmd.hdr.src_port = v->session_id; cvp_vol_cmd.hdr.dest_port = cvp_handle; cvp_vol_cmd.hdr.token = 0; cvp_vol_cmd.hdr.opcode = VSS_IVOCPROC_CMD_SET_RX_VOLUME_INDEX; cvp_vol_cmd.cvp_set_vol_idx.vol_index = v->dev_rx.volume; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_vol_cmd); if (ret < 0) { pr_err("Fail in sending RX VOL INDEX\n"); return -EINVAL; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); return -EINVAL; } return 0; } static int voice_cvs_start_record(struct voice_data *v, uint32_t rec_mode) { int ret = 0; void *apr_cvs; u16 cvs_handle; struct cvs_start_record_cmd cvs_start_record; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); if (!v->rec_info.recording) { cvs_start_record.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_start_record.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_start_record) - APR_HDR_SIZE); cvs_start_record.hdr.src_port = v->session_id; cvs_start_record.hdr.dest_port = cvs_handle; cvs_start_record.hdr.token = 0; cvs_start_record.hdr.opcode = VSS_ISTREAM_CMD_START_RECORD; if (rec_mode == VOC_REC_UPLINK) { cvs_start_record.rec_mode.rx_tap_point = VSS_TAP_POINT_NONE; cvs_start_record.rec_mode.tx_tap_point = VSS_TAP_POINT_STREAM_END; } else if (rec_mode == VOC_REC_DOWNLINK) { cvs_start_record.rec_mode.rx_tap_point = VSS_TAP_POINT_STREAM_END; cvs_start_record.rec_mode.tx_tap_point = VSS_TAP_POINT_NONE; } else if (rec_mode == VOC_REC_BOTH) { cvs_start_record.rec_mode.rx_tap_point = VSS_TAP_POINT_STREAM_END; cvs_start_record.rec_mode.tx_tap_point = VSS_TAP_POINT_STREAM_END; } else { pr_err("%s: Invalid in-call rec_mode %d\n", __func__, rec_mode); ret = -EINVAL; goto fail; } v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_start_record); if (ret < 0) { pr_err("%s: Error %d sending START_RECORD\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } v->rec_info.recording = 1; } else { pr_debug("%s: Start record already sent\n", __func__); } return 0; fail: return ret; } static int voice_cvs_stop_record(struct voice_data *v) { int ret = 0; void *apr_cvs; u16 cvs_handle; struct apr_hdr cvs_stop_record; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); if (v->rec_info.recording) { cvs_stop_record.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_stop_record.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_stop_record) - APR_HDR_SIZE); cvs_stop_record.src_port = v->session_id; cvs_stop_record.dest_port = cvs_handle; cvs_stop_record.token = 0; cvs_stop_record.opcode = VSS_ISTREAM_CMD_STOP_RECORD; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_stop_record); if (ret < 0) { pr_err("%s: Error %d sending STOP_RECORD\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } v->rec_info.recording = 0; } else { pr_debug("%s: Stop record already sent\n", __func__); } return 0; fail: return ret; } int voc_start_record(uint32_t port_id, uint32_t set) { int ret = 0; int rec_mode = 0; u16 cvs_handle; int i, rec_set = 0; for (i = 0; i < MAX_VOC_SESSIONS; i++) { struct voice_data *v = &common.voice[i]; pr_debug("%s: i:%d port_id: %d, set: %d\n", __func__, i, port_id, set); mutex_lock(&v->lock); rec_mode = v->rec_info.rec_mode; rec_set = set; if (set) { if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag != 0)) { pr_debug("%s: i=%d, rec mode already set.\n", __func__, i); mutex_unlock(&v->lock); if (i < MAX_VOC_SESSIONS) continue; else return 0; } if (port_id == VOICE_RECORD_TX) { if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag == 0)) { rec_mode = VOC_REC_UPLINK; v->rec_route_state.ul_flag = 1; } else if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag != 0)) { voice_cvs_stop_record(v); rec_mode = VOC_REC_BOTH; v->rec_route_state.ul_flag = 1; } } else if (port_id == VOICE_RECORD_RX) { if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag == 0)) { rec_mode = VOC_REC_DOWNLINK; v->rec_route_state.dl_flag = 1; } else if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag == 0)) { voice_cvs_stop_record(v); rec_mode = VOC_REC_BOTH; v->rec_route_state.dl_flag = 1; } } rec_set = 1; } else { if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag == 0)) { pr_debug("%s: i=%d, rec already stops.\n", __func__, i); mutex_unlock(&v->lock); if (i < MAX_VOC_SESSIONS) continue; else return 0; } if (port_id == VOICE_RECORD_TX) { if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag == 0)) { v->rec_route_state.ul_flag = 0; rec_set = 0; } else if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag != 0)) { voice_cvs_stop_record(v); v->rec_route_state.ul_flag = 0; rec_mode = VOC_REC_DOWNLINK; rec_set = 1; } } else if (port_id == VOICE_RECORD_RX) { if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag != 0)) { v->rec_route_state.dl_flag = 0; rec_set = 0; } else if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag != 0)) { voice_cvs_stop_record(v); v->rec_route_state.dl_flag = 0; rec_mode = VOC_REC_UPLINK; rec_set = 1; } } } pr_debug("%s: i=%d, mode =%d, set =%d\n", __func__, i, rec_mode, rec_set); cvs_handle = voice_get_cvs_handle(v); if (cvs_handle != 0) { if (rec_set) ret = voice_cvs_start_record(v, rec_mode); else ret = voice_cvs_stop_record(v); } /* Cache the value */ v->rec_info.rec_enable = rec_set; v->rec_info.rec_mode = rec_mode; mutex_unlock(&v->lock); } return ret; } static int voice_cvs_start_playback(struct voice_data *v) { int ret = 0; struct apr_hdr cvs_start_playback; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); if (!v->music_info.playing && v->music_info.count) { cvs_start_playback.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_start_playback.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_start_playback) - APR_HDR_SIZE); cvs_start_playback.src_port = v->session_id; cvs_start_playback.dest_port = cvs_handle; cvs_start_playback.token = 0; cvs_start_playback.opcode = VSS_ISTREAM_CMD_START_PLAYBACK; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_start_playback); if (ret < 0) { pr_err("%s: Error %d sending START_PLAYBACK\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } v->music_info.playing = 1; } else { pr_debug("%s: Start playback already sent\n", __func__); } return 0; fail: return ret; } static int voice_cvs_stop_playback(struct voice_data *v) { int ret = 0; struct apr_hdr cvs_stop_playback; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); if (v->music_info.playing && ((!v->music_info.count) || (v->music_info.force))) { cvs_stop_playback.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_stop_playback.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_stop_playback) - APR_HDR_SIZE); cvs_stop_playback.src_port = v->session_id; cvs_stop_playback.dest_port = cvs_handle; cvs_stop_playback.token = 0; cvs_stop_playback.opcode = VSS_ISTREAM_CMD_STOP_PLAYBACK; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_stop_playback); if (ret < 0) { pr_err("%s: Error %d sending STOP_PLAYBACK\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } v->music_info.playing = 0; v->music_info.force = 0; } else { pr_debug("%s: Stop playback already sent\n", __func__); } return 0; fail: return ret; } int voc_start_playback(uint32_t set) { int ret = 0; u16 cvs_handle; int i; for (i = 0; i < MAX_VOC_SESSIONS; i++) { struct voice_data *v = &common.voice[i]; mutex_lock(&v->lock); v->music_info.play_enable = set; if (set) v->music_info.count++; else v->music_info.count--; pr_debug("%s: music_info count =%d\n", __func__, v->music_info.count); cvs_handle = voice_get_cvs_handle(v); if (cvs_handle != 0) { if (set) ret = voice_cvs_start_playback(v); else ret = voice_cvs_stop_playback(v); } mutex_unlock(&v->lock); } return ret; } int voc_disable_cvp(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (v->voc_state == VOC_RUN) { if (v->dev_tx.port_id != RT_PROXY_PORT_001_TX && v->dev_rx.port_id != RT_PROXY_PORT_001_RX) afe_sidetone(v->dev_tx.port_id, v->dev_rx.port_id, 0, 0); rtac_remove_voice(voice_get_cvs_handle(v)); /* send cmd to dsp to disable vocproc */ ret = voice_send_disable_vocproc_cmd(v); if (ret < 0) { pr_err("%s: disable vocproc failed\n", __func__); goto fail; } /* deregister cvp and vol cal */ voice_send_cvp_deregister_vol_cal_table_cmd(v); voice_send_cvp_deregister_cal_cmd(v); voice_send_cvp_unmap_memory_cmd(v); if (common.ec_ref_ext == true) voc_set_ext_ec_ref(AFE_PORT_INVALID, false); v->voc_state = VOC_CHANGE; } fail: mutex_unlock(&v->lock); return ret; } int voc_enable_cvp(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); struct sidetone_cal sidetone_cal_data; int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (v->voc_state == VOC_CHANGE) { if (common.ec_ref_ext == true) { ret = voice_send_set_device_cmd_v2(v); if (ret < 0) pr_err("%s: set device V2 failed\n" "rc =%x\n", __func__, ret); goto fail; } else { ret = voice_send_set_device_cmd(v); if (ret < 0) { pr_err("%s: set device failed rc=%x\n", __func__, ret); goto fail; } } /* send cvp and vol cal */ ret = voice_send_cvp_map_memory_cmd(v); if (!ret) { voice_send_cvp_register_cal_cmd(v); voice_send_cvp_register_vol_cal_table_cmd(v); } ret = voice_send_enable_vocproc_cmd(v); if (ret < 0) { pr_err("%s: enable vocproc failed\n", __func__); goto fail; } /* send tty mode if tty device is used */ voice_send_tty_mode_cmd(v); /* enable widevoice if wv_enable is set */ if (v->wv_enable) voice_send_set_widevoice_enable_cmd(v); /* enable slowtalk */ if (v->st_enable) voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_ST, v->st_enable); /* enable FENS */ if (v->fens_enable) voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_FENS, v->fens_enable); get_sidetone_cal(&sidetone_cal_data); if (v->dev_tx.port_id != RT_PROXY_PORT_001_TX && v->dev_rx.port_id != RT_PROXY_PORT_001_RX) { ret = afe_sidetone(v->dev_tx.port_id, v->dev_rx.port_id, sidetone_cal_data.enable, sidetone_cal_data.gain); if (ret < 0) pr_err("%s: AFE command sidetone failed\n", __func__); } rtac_add_voice(voice_get_cvs_handle(v), voice_get_cvp_handle(v), v->dev_rx.port_id, v->dev_tx.port_id, v->session_id); v->voc_state = VOC_RUN; } fail: mutex_unlock(&v->lock); return ret; } int voc_set_tx_mute(uint16_t session_id, uint32_t dir, uint32_t mute) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->dev_tx.mute = mute; if ((v->voc_state == VOC_RUN) || (v->voc_state == VOC_CHANGE) || (v->voc_state == VOC_STANDBY)) ret = voice_send_mute_cmd(v); mutex_unlock(&v->lock); return ret; } int voc_set_rx_device_mute(uint16_t session_id, uint32_t mute) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->dev_rx.mute = mute; if (v->voc_state == VOC_RUN) ret = voice_send_rx_device_mute_cmd(v); mutex_unlock(&v->lock); return ret; } int voc_get_rx_device_mute(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); ret = v->dev_rx.mute; mutex_unlock(&v->lock); return ret; } int voc_set_tty_mode(uint16_t session_id, uint8_t tty_mode) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->tty_mode = tty_mode; mutex_unlock(&v->lock); return ret; } uint8_t voc_get_tty_mode(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); ret = v->tty_mode; mutex_unlock(&v->lock); return ret; } int voc_set_widevoice_enable(uint16_t session_id, uint32_t wv_enable) { struct voice_data *v = voice_get_session(session_id); u16 mvm_handle; int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->wv_enable = wv_enable; mvm_handle = voice_get_mvm_handle(v); if (mvm_handle != 0) voice_send_set_widevoice_enable_cmd(v); mutex_unlock(&v->lock); return ret; } uint32_t voc_get_widevoice_enable(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); ret = v->wv_enable; mutex_unlock(&v->lock); return ret; } int voc_set_pp_enable(uint16_t session_id, uint32_t module_id, uint32_t enable) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (module_id == MODULE_ID_VOICE_MODULE_ST) v->st_enable = enable; else if (module_id == MODULE_ID_VOICE_MODULE_FENS) v->fens_enable = enable; if (v->voc_state == VOC_RUN) { if (module_id == MODULE_ID_VOICE_MODULE_ST) ret = voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_ST, enable); else if (module_id == MODULE_ID_VOICE_MODULE_FENS) ret = voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_FENS, enable); } mutex_unlock(&v->lock); return ret; } int voc_get_pp_enable(uint16_t session_id, uint32_t module_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (module_id == MODULE_ID_VOICE_MODULE_ST) ret = v->st_enable; else if (module_id == MODULE_ID_VOICE_MODULE_FENS) ret = v->fens_enable; mutex_unlock(&v->lock); return ret; } int voc_set_rx_vol_index(uint16_t session_id, uint32_t dir, uint32_t vol_idx) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->dev_rx.volume = vol_idx; if ((v->voc_state == VOC_RUN) || (v->voc_state == VOC_CHANGE) || (v->voc_state == VOC_STANDBY)) ret = voice_send_vol_index_cmd(v); mutex_unlock(&v->lock); return ret; } int voc_set_rxtx_port(uint16_t session_id, uint32_t port_id, uint32_t dev_type) { struct voice_data *v = voice_get_session(session_id); if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } pr_debug("%s: port_id=%d, type=%d\n", __func__, port_id, dev_type); mutex_lock(&v->lock); if (dev_type == DEV_RX) v->dev_rx.port_id = port_id; else v->dev_tx.port_id = port_id; mutex_unlock(&v->lock); return 0; } int voc_set_route_flag(uint16_t session_id, uint8_t path_dir, uint8_t set) { struct voice_data *v = voice_get_session(session_id); if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } pr_debug("%s: path_dir=%d, set=%d\n", __func__, path_dir, set); mutex_lock(&v->lock); if (path_dir == RX_PATH) v->voc_route_state.rx_route_flag = set; else v->voc_route_state.tx_route_flag = set; mutex_unlock(&v->lock); return 0; } uint8_t voc_get_route_flag(uint16_t session_id, uint8_t path_dir) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return 0; } mutex_lock(&v->lock); if (path_dir == RX_PATH) ret = v->voc_route_state.rx_route_flag; else ret = v->voc_route_state.tx_route_flag; mutex_unlock(&v->lock); return ret; } int voc_end_voice_call(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (v->voc_state == VOC_RUN || v->voc_state == VOC_STANDBY) { if (v->dev_tx.port_id != RT_PROXY_PORT_001_TX && v->dev_rx.port_id != RT_PROXY_PORT_001_RX) afe_sidetone(v->dev_tx.port_id, v->dev_rx.port_id, 0, 0); ret = voice_destroy_vocproc(v); if (ret < 0) pr_err("%s: destroy voice failed\n", __func__); voice_destroy_mvm_cvs_session(v); if (common.ec_ref_ext == true) voc_set_ext_ec_ref(AFE_PORT_INVALID, false); v->voc_state = VOC_RELEASE; } mutex_unlock(&v->lock); return ret; } int voc_resume_voice_call(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); struct apr_hdr mvm_start_voice_cmd; int ret = 0; void *apr_mvm; u16 mvm_handle; pr_debug("%s:\n", __func__); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); mvm_start_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_start_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_start_voice_cmd) - APR_HDR_SIZE); pr_debug("send mvm_start_voice_cmd pkt size = %d\n", mvm_start_voice_cmd.pkt_size); mvm_start_voice_cmd.src_port = v->session_id; mvm_start_voice_cmd.dest_port = mvm_handle; mvm_start_voice_cmd.token = 0; mvm_start_voice_cmd.opcode = VSS_IMVM_CMD_START_VOICE; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_start_voice_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_START_VOICE\n"); goto fail; } v->voc_state = VOC_RUN; return 0; fail: return -EINVAL; } int voc_start_voice_call(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); struct sidetone_cal sidetone_cal_data; int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if ((v->voc_state == VOC_INIT) || (v->voc_state == VOC_RELEASE)) { ret = voice_apr_register(); if (ret < 0) { pr_err("%s: apr register failed\n", __func__); goto fail; } ret = voice_create_mvm_cvs_session(v); if (ret < 0) { pr_err("create mvm and cvs failed\n"); goto fail; } ret = voice_send_dual_control_cmd(v); if (ret < 0) { pr_err("Err Dual command failed\n"); goto fail; } ret = voice_setup_vocproc(v); if (ret < 0) { pr_err("setup voice failed\n"); goto fail; } ret = voice_send_vol_index_cmd(v); if (ret < 0) pr_err("voice volume failed\n"); ret = voice_send_mute_cmd(v); if (ret < 0) pr_err("voice mute failed\n"); ret = voice_send_start_voice_cmd(v); if (ret < 0) { pr_err("start voice failed\n"); goto fail; } get_sidetone_cal(&sidetone_cal_data); if (v->dev_tx.port_id != RT_PROXY_PORT_001_TX && v->dev_rx.port_id != RT_PROXY_PORT_001_RX) { ret = afe_sidetone(v->dev_tx.port_id, v->dev_rx.port_id, sidetone_cal_data.enable, sidetone_cal_data.gain); if (ret < 0) pr_err("AFE command sidetone failed\n"); } v->voc_state = VOC_RUN; } else if (v->voc_state == VOC_STANDBY) { pr_err("Error: PCM Prepare when in Standby\n"); ret = -EINVAL; goto fail; } fail: mutex_unlock(&v->lock); return ret; } int voc_standby_voice_call(uint16_t session_id) { struct voice_data *v = voice_get_session(session_id); struct apr_hdr mvm_standby_voice_cmd; void *apr_mvm; u16 mvm_handle; int ret = 0; pr_debug("%s: voc state=%d", __func__, v->voc_state); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } if (v->voc_state == VOC_RUN) { apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); ret = -EINVAL; goto fail; } mvm_handle = voice_get_mvm_handle(v); mvm_standby_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_standby_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_standby_voice_cmd) - APR_HDR_SIZE); pr_debug("send mvm_standby_voice_cmd pkt size = %d\n", mvm_standby_voice_cmd.pkt_size); mvm_standby_voice_cmd.src_port = v->session_id; mvm_standby_voice_cmd.dest_port = mvm_handle; mvm_standby_voice_cmd.token = 0; mvm_standby_voice_cmd.opcode = VSS_IMVM_CMD_STANDBY_VOICE; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *)&mvm_standby_voice_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_STANDBY_VOICE\n"); ret = -EINVAL; goto fail; } v->voc_state = VOC_STANDBY; } fail: return ret; } int voc_set_ext_ec_ref(uint16_t port_id, bool state) { int ret = 0; mutex_lock(&common.common_lock); if (state == true) { if (port_id == AFE_PORT_INVALID) { pr_err("%s: Invalid port id", __func__); ret = -EINVAL; goto fail; } common.ec_port_id = port_id; common.ec_ref_ext = true; } else { common.ec_ref_ext = false; common.ec_port_id = port_id; } fail: mutex_unlock(&common.common_lock); return ret; } void voc_register_mvs_cb(ul_cb_fn ul_cb, dl_cb_fn dl_cb, void *private_data) { common.mvs_info.ul_cb = ul_cb; common.mvs_info.dl_cb = dl_cb; common.mvs_info.private_data = private_data; } void voc_config_vocoder(uint32_t media_type, uint32_t rate, uint32_t network_type, uint32_t dtx_mode) { common.mvs_info.media_type = media_type; common.mvs_info.rate = rate; common.mvs_info.network_type = network_type; common.mvs_info.dtx_mode = dtx_mode; } static int32_t qdsp_mvm_callback(struct apr_client_data *data, void *priv) { uint32_t *ptr = NULL; struct common_data *c = NULL; struct voice_data *v = NULL; int i = 0; if ((data == NULL) || (priv == NULL)) { pr_err("%s: data or priv is NULL\n", __func__); return -EINVAL; } c = priv; pr_debug("%s: session_id 0x%x\n", __func__, data->dest_port); v = voice_get_session(data->dest_port); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } pr_debug("%s: Payload Length = %d, opcode=%x\n", __func__, data->payload_size, data->opcode); if (data->opcode == RESET_EVENTS) { pr_debug("%s: Reset event received in Voice service\n", __func__); apr_reset(c->apr_q6_mvm); c->apr_q6_mvm = NULL; /* Sub-system restart is applicable to all sessions. */ for (i = 0; i < MAX_VOC_SESSIONS; i++) c->voice[i].mvm_handle = 0; return 0; } if (data->opcode == APR_BASIC_RSP_RESULT) { if (data->payload_size) { ptr = data->payload; pr_info("%x %x\n", ptr[0], ptr[1]); /* ping mvm service ACK */ switch (ptr[0]) { case VSS_IMVM_CMD_CREATE_PASSIVE_CONTROL_SESSION: case VSS_IMVM_CMD_CREATE_FULL_CONTROL_SESSION: /* Passive session is used for CS call * Full session is used for VoIP call. */ pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); if (!ptr[1]) { pr_debug("%s: MVM handle is %d\n", __func__, data->src_port); voice_set_mvm_handle(v, data->src_port); } else pr_err("got NACK for sending \ MVM create session \n"); v->mvm_state = CMD_STATUS_SUCCESS; wake_up(&v->mvm_wait); break; case VSS_IMVM_CMD_START_VOICE: case VSS_IMVM_CMD_ATTACH_VOCPROC: case VSS_IMVM_CMD_STOP_VOICE: case VSS_IMVM_CMD_DETACH_VOCPROC: case VSS_ISTREAM_CMD_SET_TTY_MODE: case APRV2_IBASIC_CMD_DESTROY_SESSION: case VSS_IMVM_CMD_ATTACH_STREAM: case VSS_IMVM_CMD_DETACH_STREAM: case VSS_ICOMMON_CMD_SET_NETWORK: case VSS_ICOMMON_CMD_SET_VOICE_TIMING: case VSS_IWIDEVOICE_CMD_SET_WIDEVOICE: case VSS_IMVM_CMD_SET_POLICY_DUAL_CONTROL: case VSS_IMVM_CMD_STANDBY_VOICE: pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); v->mvm_state = CMD_STATUS_SUCCESS; wake_up(&v->mvm_wait); break; default: pr_debug("%s: not match cmd = 0x%x\n", __func__, ptr[0]); break; } } } return 0; } static int32_t qdsp_cvs_callback(struct apr_client_data *data, void *priv) { uint32_t *ptr = NULL; struct common_data *c = NULL; struct voice_data *v = NULL; int i = 0; if ((data == NULL) || (priv == NULL)) { pr_err("%s: data or priv is NULL\n", __func__); return -EINVAL; } c = priv; pr_debug("%s: session_id 0x%x\n", __func__, data->dest_port); v = voice_get_session(data->dest_port); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } pr_debug("%s: Payload Length = %d, opcode=%x\n", __func__, data->payload_size, data->opcode); if (data->opcode == RESET_EVENTS) { pr_debug("%s: Reset event received in Voice service\n", __func__); apr_reset(c->apr_q6_cvs); c->apr_q6_cvs = NULL; /* Sub-system restart is applicable to all sessions. */ for (i = 0; i < MAX_VOC_SESSIONS; i++) c->voice[i].cvs_handle = 0; return 0; } if (data->opcode == APR_BASIC_RSP_RESULT) { if (data->payload_size) { ptr = data->payload; pr_info("%x %x\n", ptr[0], ptr[1]); /*response from CVS */ switch (ptr[0]) { case VSS_ISTREAM_CMD_CREATE_PASSIVE_CONTROL_SESSION: case VSS_ISTREAM_CMD_CREATE_FULL_CONTROL_SESSION: if (!ptr[1]) { pr_debug("%s: CVS handle is %d\n", __func__, data->src_port); voice_set_cvs_handle(v, data->src_port); } else pr_err("got NACK for sending \ CVS create session \n"); v->cvs_state = CMD_STATUS_SUCCESS; wake_up(&v->cvs_wait); break; case VSS_ISTREAM_CMD_SET_MUTE: case VSS_ISTREAM_CMD_SET_MEDIA_TYPE: case VSS_ISTREAM_CMD_VOC_AMR_SET_ENC_RATE: case VSS_ISTREAM_CMD_VOC_AMRWB_SET_ENC_RATE: case VSS_ISTREAM_CMD_SET_ENC_DTX_MODE: case VSS_ISTREAM_CMD_CDMA_SET_ENC_MINMAX_RATE: case APRV2_IBASIC_CMD_DESTROY_SESSION: case VSS_ISTREAM_CMD_REGISTER_CALIBRATION_DATA: case VSS_ISTREAM_CMD_DEREGISTER_CALIBRATION_DATA: case VSS_ICOMMON_CMD_MAP_MEMORY: case VSS_ICOMMON_CMD_UNMAP_MEMORY: case VSS_ICOMMON_CMD_SET_UI_PROPERTY: case VSS_ISTREAM_CMD_START_PLAYBACK: case VSS_ISTREAM_CMD_STOP_PLAYBACK: case VSS_ISTREAM_CMD_START_RECORD: case VSS_ISTREAM_CMD_STOP_RECORD: pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); v->cvs_state = CMD_STATUS_SUCCESS; wake_up(&v->cvs_wait); break; case VOICE_CMD_SET_PARAM: rtac_make_voice_callback(RTAC_CVS, ptr, data->payload_size); break; default: pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); break; } } } else if (data->opcode == VSS_ISTREAM_EVT_SEND_ENC_BUFFER) { uint32_t *voc_pkt = data->payload; uint32_t pkt_len = data->payload_size; if (voc_pkt != NULL && c->mvs_info.ul_cb != NULL) { pr_debug("%s: Media type is 0x%x\n", __func__, voc_pkt[0]); /* Remove media ID from payload. */ voc_pkt++; pkt_len = pkt_len - 4; c->mvs_info.ul_cb((uint8_t *)voc_pkt, pkt_len, c->mvs_info.private_data); } else pr_err("%s: voc_pkt is 0x%x ul_cb is 0x%x\n", __func__, (unsigned int)voc_pkt, (unsigned int) c->mvs_info.ul_cb); } else if (data->opcode == VSS_ISTREAM_EVT_REQUEST_DEC_BUFFER) { struct cvs_send_dec_buf_cmd send_dec_buf; int ret = 0; uint32_t pkt_len = 0; if (c->mvs_info.dl_cb != NULL) { send_dec_buf.dec_buf.media_id = c->mvs_info.media_type; c->mvs_info.dl_cb( (uint8_t *)&send_dec_buf.dec_buf.packet_data, &pkt_len, c->mvs_info.private_data); send_dec_buf.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); send_dec_buf.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(send_dec_buf.dec_buf.media_id) + pkt_len); send_dec_buf.hdr.src_port = v->session_id; send_dec_buf.hdr.dest_port = voice_get_cvs_handle(v); send_dec_buf.hdr.token = 0; send_dec_buf.hdr.opcode = VSS_ISTREAM_EVT_SEND_DEC_BUFFER; ret = apr_send_pkt(c->apr_q6_cvs, (uint32_t *) &send_dec_buf); if (ret < 0) { pr_err("%s: Error %d sending DEC_BUF\n", __func__, ret); goto fail; } } else pr_debug("%s: dl_cb is NULL\n", __func__); } else if (data->opcode == VSS_ISTREAM_EVT_SEND_DEC_BUFFER) { pr_debug("Send dec buf resp\n"); } else if (data->opcode == VOICE_EVT_GET_PARAM_ACK) { rtac_make_voice_callback(RTAC_CVS, data->payload, data->payload_size); } else pr_debug("Unknown opcode 0x%x\n", data->opcode); fail: return 0; } static int32_t qdsp_cvp_callback(struct apr_client_data *data, void *priv) { uint32_t *ptr = NULL; struct common_data *c = NULL; struct voice_data *v = NULL; int i = 0; if ((data == NULL) || (priv == NULL)) { pr_err("%s: data or priv is NULL\n", __func__); return -EINVAL; } c = priv; v = voice_get_session(data->dest_port); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } pr_debug("%s: Payload Length = %d, opcode=%x\n", __func__, data->payload_size, data->opcode); if (data->opcode == RESET_EVENTS) { pr_debug("%s: Reset event received in Voice service\n", __func__); apr_reset(c->apr_q6_cvp); c->apr_q6_cvp = NULL; /* Sub-system restart is applicable to all sessions. */ for (i = 0; i < MAX_VOC_SESSIONS; i++) c->voice[i].cvp_handle = 0; return 0; } if (data->opcode == APR_BASIC_RSP_RESULT) { if (data->payload_size) { ptr = data->payload; pr_info("%x %x\n", ptr[0], ptr[1]); switch (ptr[0]) { case VSS_IVOCPROC_CMD_CREATE_FULL_CONTROL_SESSION: /*response from CVP */ pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); if (!ptr[1]) { voice_set_cvp_handle(v, data->src_port); pr_debug("cvphdl=%d\n", data->src_port); } else pr_err("got NACK from CVP create \ session response\n"); v->cvp_state = CMD_STATUS_SUCCESS; wake_up(&v->cvp_wait); break; case VSS_IVOCPROC_CMD_SET_DEVICE: case VSS_IVOCPROC_CMD_SET_DEVICE_V2: case VSS_IVOCPROC_CMD_SET_RX_VOLUME_INDEX: case VSS_IVOCPROC_CMD_ENABLE: case VSS_IVOCPROC_CMD_DISABLE: case APRV2_IBASIC_CMD_DESTROY_SESSION: case VSS_IVOCPROC_CMD_REGISTER_VOLUME_CAL_TABLE: case VSS_IVOCPROC_CMD_DEREGISTER_VOLUME_CAL_TABLE: case VSS_IVOCPROC_CMD_REGISTER_CALIBRATION_DATA: case VSS_IVOCPROC_CMD_DEREGISTER_CALIBRATION_DATA: case VSS_ICOMMON_CMD_MAP_MEMORY: case VSS_ICOMMON_CMD_UNMAP_MEMORY: case VSS_IVOCPROC_CMD_SET_MUTE: v->cvp_state = CMD_STATUS_SUCCESS; wake_up(&v->cvp_wait); break; case VOICE_CMD_SET_PARAM: rtac_make_voice_callback(RTAC_CVP, ptr, data->payload_size); break; default: pr_debug("%s: not match cmd = 0x%x\n", __func__, ptr[0]); break; } } } else if (data->opcode == VOICE_EVT_GET_PARAM_ACK) { rtac_make_voice_callback(RTAC_CVP, data->payload, data->payload_size); } return 0; } static void voice_allocate_shared_memory(void) { int i, j, result; int offset = 0; int mem_len; unsigned long paddr; void *kvptr; pr_debug("%s\n", __func__); common.ion_client = msm_ion_client_create(UINT_MAX, "q6voice_client"); if (IS_ERR_OR_NULL((void *)common.ion_client)) { pr_err("%s: ION create client failed\n", __func__); goto err; } common.ion_handle = ion_alloc(common.ion_client, TOTAL_VOICE_CAL_SIZE, SZ_4K, ION_HEAP(ION_AUDIO_HEAP_ID), 0); if (IS_ERR_OR_NULL((void *) common.ion_handle)) { pr_err("%s: ION memory allocation failed\n", __func__); goto err_ion_client; } result = ion_phys(common.ion_client, common.ion_handle, &paddr, (size_t *)&mem_len); if (result) { pr_err("%s: ION Get Physical failed, rc = %d\n", __func__, result); goto err_ion_handle; } kvptr = ion_map_kernel(common.ion_client, common.ion_handle); if (IS_ERR_OR_NULL(kvptr)) { pr_err("%s: ION memory mapping failed\n", __func__); goto err_ion_handle; } /* Make all phys & buf point to the correct address */ for (i = 0; i < NUM_VOICE_CAL_BUFFERS; i++) { for (j = 0; j < NUM_VOICE_CAL_TYPES; j++) { common.voice_cal[i].cal_data[j].paddr = (uint32_t)(paddr + offset); common.voice_cal[i].cal_data[j].kvaddr = (uint32_t)((uint8_t *)kvptr + offset); if (j == CVP_CAL) offset += CVP_CAL_SIZE; else offset += CVS_CAL_SIZE; pr_debug("%s: kernel addr = 0x%x, phys addr = 0x%x\n", __func__, common.voice_cal[i].cal_data[j].kvaddr, common.voice_cal[i].cal_data[j].paddr); } } return; err_ion_handle: ion_free(common.ion_client, common.ion_handle); err_ion_client: ion_client_destroy(common.ion_client); err: return; } static int __init voice_init(void) { int rc = 0, i = 0; memset(&common, 0, sizeof(struct common_data)); /* Allocate shared memory */ voice_allocate_shared_memory(); /* set default value */ common.default_mute_val = 0; /* default is un-mute */ common.default_vol_val = 0; common.default_sample_val = 8000; common.ec_ref_ext = false; /* Initialize MVS info. */ common.mvs_info.network_type = VSS_NETWORK_ID_DEFAULT; mutex_init(&common.common_lock); for (i = 0; i < MAX_VOC_SESSIONS; i++) { common.voice[i].session_id = SESSION_ID_BASE + i; /* initialize dev_rx and dev_tx */ common.voice[i].dev_rx.volume = common.default_vol_val; common.voice[i].dev_rx.mute = 0; common.voice[i].dev_tx.mute = common.default_mute_val; common.voice[i].dev_tx.port_id = 1; common.voice[i].dev_rx.port_id = 0; common.voice[i].sidetone_gain = 0x512; common.voice[i].voc_state = VOC_INIT; init_waitqueue_head(&common.voice[i].mvm_wait); init_waitqueue_head(&common.voice[i].cvs_wait); init_waitqueue_head(&common.voice[i].cvp_wait); mutex_init(&common.voice[i].lock); } return rc; } device_initcall(voice_init);
ansebovi/SmartDeviL_XMD
sound/soc/msm/qdsp6/q6voice.c
C
gpl-2.0
111,873