file_name
int64
0
72.3k
vulnerable_line_numbers
stringlengths
1
1.06k
dataset_type
stringclasses
1 value
commit_hash
stringlengths
40
44
unique_id
int64
0
271k
project
stringclasses
10 values
target
int64
0
1
repo_url
stringclasses
10 values
date
stringlengths
25
25
code
stringlengths
0
20.4M
CVE
stringlengths
13
43
CWE
stringclasses
50 values
commit_link
stringlengths
73
97
severity
stringclasses
4 values
__index_level_0__
int64
0
124k
46,089
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
46,089
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_TEST_ACTIVATION_DELEGATE_H_ #define ASH_WM_TEST_ACTIVATION_DELEGATE_H_ #include "base/compiler_specific.h" #include "base/logging.h" #include "base/macros.h" #include "ui/events/event_handler.h" #include "ui/wm/public/activation_change_observer.h" #include "ui/wm/public/activation_delegate.h" namespace aura { class Window; } namespace ash { // A test ActivationDelegate that can be used to track activation changes for // an aura::Window. class TestActivationDelegate : public ::wm::ActivationDelegate, public ::wm::ActivationChangeObserver { public: TestActivationDelegate(); explicit TestActivationDelegate(bool activate); // Associates this delegate with a Window. void SetWindow(aura::Window* window); bool window_was_active() const { return window_was_active_; } void set_activate(bool v) { activate_ = v; } int activated_count() const { return activated_count_; } int lost_active_count() const { return lost_active_count_; } int should_activate_count() const { return should_activate_count_; } void Clear() { activated_count_ = lost_active_count_ = should_activate_count_ = 0; window_was_active_ = false; } // Overridden from wm::ActivationDelegate: bool ShouldActivate() const override; private: // Overridden from wm:ActivationChangeObserver: void OnWindowActivated( ::wm::ActivationChangeObserver::ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) override; aura::Window* window_; bool window_was_active_; bool activate_; int activated_count_; int lost_active_count_; mutable int should_activate_count_; DISALLOW_COPY_AND_ASSIGN(TestActivationDelegate); }; } // namespace ash #endif // ASH_WM_TEST_ACTIVATION_DELEGATE_H_
null
null
null
null
42,952
49,614
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
49,614
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/app_list/views/search_result_answer_card_view.h" #include <memory> #include <utility> #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/unguessable_token.h" #include "ui/accessibility/ax_node_data.h" #include "ui/app_list/answer_card_contents_registry.h" #include "ui/app_list/app_list_constants.h" #include "ui/app_list/test/app_list_test_view_delegate.h" #include "ui/app_list/test/test_search_result.h" #include "ui/app_list/views/search_result_view.h" #include "ui/views/background.h" #include "ui/views/test/views_test_base.h" namespace app_list { namespace test { namespace { constexpr char kResultTitle[] = "The weather is fine"; constexpr double kRelevance = 13.0; } // namespace class SearchResultAnswerCardViewTest : public views::ViewsTestBase { public: SearchResultAnswerCardViewTest() {} // Overridden from testing::Test: void SetUp() override { views::ViewsTestBase::SetUp(); search_card_view_ = std::make_unique<views::View>(); result_container_view_ = new SearchResultAnswerCardView(&view_delegate_); search_card_view_->AddChildView(result_container_view_); result_container_view_->SetResults( view_delegate_.GetSearchModel()->results()); result_view_ = std::make_unique<views::View>(); result_view_->set_owned_by_client(); token_ = contents_registry_.Register(result_view_.get()); SetUpSearchResult(); } protected: void SetUpSearchResult() { SearchModel::SearchResults* results = GetResults(); std::unique_ptr<TestSearchResult> result = std::make_unique<TestSearchResult>(); result->set_display_type(ash::SearchResultDisplayType::kCard); result->set_title(base::UTF8ToUTF16(kResultTitle)); result->set_answer_card_contents_token(token_); result->set_relevance(kRelevance); results->Add(std::move(result)); // Adding results will schedule Update(). RunPendingMessages(); result_container_view_->OnContainerSelected(false, false); } int GetOpenResultCountAndReset(int ranking) { EXPECT_GT(view_delegate_.open_search_result_counts().count(ranking), 0u); int result = view_delegate_.open_search_result_counts()[ranking]; view_delegate_.open_search_result_counts().clear(); return result; } void ClearSelectedIndex() { result_container_view_->ClearSelectedIndex(); } void DeleteResult() { GetResults()->DeleteAt(0); RunPendingMessages(); } bool KeyPress(ui::KeyboardCode key_code) { ui::KeyEvent event(ui::ET_KEY_PRESSED, key_code, ui::EF_NONE); return result_container_view_->OnKeyPressed(event); } SearchModel::SearchResults* GetResults() { return view_delegate_.GetSearchModel()->results(); } views::View* search_card_view() const { return search_card_view_.get(); } int GetYSize() const { return result_container_view_->GetYSize(); } int GetResultCountFromView() { return result_container_view_->num_results(); } int GetSelectedIndex() { return result_container_view_->selected_index(); } double GetContainerScore() const { return result_container_view_->container_score(); } void GetAccessibleNodeData(ui::AXNodeData* node_data) { result_container_view_->child_at(0)->GetAccessibleNodeData(node_data); } views::View* result_view() const { return result_view_.get(); } private: AppListTestViewDelegate view_delegate_; // The root of the test's view hierarchy. In the real view hierarchy it's // SearchCardView. std::unique_ptr<views::View> search_card_view_; // Result container that we are testing. It's a child of search_card_view_. // Owned by the view hierarchy. SearchResultAnswerCardView* result_container_view_; // View sent within the search result. May be shown within // result_container_view_. Has set_owned_by_client() called. std::unique_ptr<views::View> result_view_; AnswerCardContentsRegistry contents_registry_; base::UnguessableToken token_; DISALLOW_COPY_AND_ASSIGN(SearchResultAnswerCardViewTest); }; TEST_F(SearchResultAnswerCardViewTest, Basic) { EXPECT_EQ(kRelevance, GetContainerScore()); EXPECT_EQ(1, GetResultCountFromView()); // Result view should be added to the hierarchy. EXPECT_EQ(search_card_view(), result_view()->parent()->parent()->parent()); ASSERT_TRUE(search_card_view()->visible()); EXPECT_EQ(0, GetSelectedIndex()); EXPECT_EQ(1, GetYSize()); } TEST_F(SearchResultAnswerCardViewTest, KeyboardEvents) { EXPECT_TRUE(KeyPress(ui::VKEY_RETURN)); EXPECT_EQ(1, GetOpenResultCountAndReset(0)); // When navigating up/down/next off the the result, pass the event to the // parent to handle. EXPECT_FALSE(KeyPress(ui::VKEY_DOWN)); EXPECT_EQ(0, GetSelectedIndex()); EXPECT_FALSE(KeyPress(ui::VKEY_UP)); EXPECT_EQ(0, GetSelectedIndex()); EXPECT_FALSE(KeyPress(ui::VKEY_TAB)); EXPECT_EQ(0, GetSelectedIndex()); } TEST_F(SearchResultAnswerCardViewTest, SpokenFeedback) { ui::AXNodeData node_data; GetAccessibleNodeData(&node_data); EXPECT_EQ(ax::mojom::Role::kGenericContainer, node_data.role); EXPECT_EQ(kResultTitle, node_data.GetStringAttribute(ax::mojom::StringAttribute::kName)); } TEST_F(SearchResultAnswerCardViewTest, DeleteResult) { DeleteResult(); EXPECT_EQ(0UL, GetResults()->item_count()); EXPECT_EQ(nullptr, result_view()->parent()); EXPECT_EQ(0, GetYSize()); ASSERT_FALSE(search_card_view()->visible()); EXPECT_EQ(0, GetContainerScore()); } } // namespace test } // namespace app_list
null
null
null
null
46,477
56,534
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
56,534
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/ui/preloaded_web_view.h" #include "base/callback_helpers.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/idle_detector.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "ui/views/controls/webview/webview.h" namespace chromeos { namespace { // Duration of user inactivity before running the preload function. constexpr int kIdleSecondsBeforePreloadingLockScreen = 8; } // namespace PreloadedWebView::PreloadedWebView(Profile* profile) : profile_(profile), weak_factory_(this) { registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); memory_pressure_listener_ = std::make_unique<base::MemoryPressureListener>(base::Bind( &PreloadedWebView::OnMemoryPressure, weak_factory_.GetWeakPtr())); } PreloadedWebView::~PreloadedWebView() {} void PreloadedWebView::PreloadOnIdle(PreloadCallback preload) { preload_function_ = std::move(preload); idle_detector_ = std::make_unique<chromeos::IdleDetector>( base::Bind(&PreloadedWebView::RunPreloader, weak_factory_.GetWeakPtr())); idle_detector_->Start( base::TimeDelta::FromSeconds(kIdleSecondsBeforePreloadingLockScreen)); } std::unique_ptr<views::WebView> PreloadedWebView::TryTake() { idle_detector_.reset(); // Clear cached reference if it is no longer valid (ie, destroyed in task // manager). if (preloaded_instance_ && !preloaded_instance_->GetWebContents() ->GetRenderViewHost() ->GetWidget() ->GetView()) { preloaded_instance_.reset(); } return std::move(preloaded_instance_); } void PreloadedWebView::Shutdown() { preloaded_instance_.reset(); } void PreloadedWebView::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_EQ(chrome::NOTIFICATION_APP_TERMINATING, type); preloaded_instance_.reset(); } void PreloadedWebView::OnMemoryPressure( base::MemoryPressureListener::MemoryPressureLevel level) { switch (level) { case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE: break; case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE: case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL: preloaded_instance_.reset(); break; } } void PreloadedWebView::RunPreloader() { idle_detector_.reset(); preloaded_instance_ = std::move(preload_function_).Run(profile_); } } // namespace chromeos
null
null
null
null
53,397
12,807
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
177,802
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Freescale hypervisor call interface * * Copyright 2008-2010 Freescale Semiconductor, Inc. * * Author: Timur Tabi <timur@freescale.com> * * This file is provided under a dual BSD/GPL license. When using or * redistributing this file, you may do so under either license. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Freescale Semiconductor nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") as published by the Free Software * Foundation, either version 2 of that License or (at your option) any * later version. * * THIS SOFTWARE IS PROVIDED BY Freescale Semiconductor ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Freescale Semiconductor BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FSL_HCALLS_H #define _FSL_HCALLS_H #include <linux/types.h> #include <linux/errno.h> #include <asm/byteorder.h> #include <asm/epapr_hcalls.h> #define FH_API_VERSION 1 #define FH_ERR_GET_INFO 1 #define FH_PARTITION_GET_DTPROP 2 #define FH_PARTITION_SET_DTPROP 3 #define FH_PARTITION_RESTART 4 #define FH_PARTITION_GET_STATUS 5 #define FH_PARTITION_START 6 #define FH_PARTITION_STOP 7 #define FH_PARTITION_MEMCPY 8 #define FH_DMA_ENABLE 9 #define FH_DMA_DISABLE 10 #define FH_SEND_NMI 11 #define FH_VMPIC_GET_MSIR 12 #define FH_SYSTEM_RESET 13 #define FH_GET_CORE_STATE 14 #define FH_ENTER_NAP 15 #define FH_EXIT_NAP 16 #define FH_CLAIM_DEVICE 17 #define FH_PARTITION_STOP_DMA 18 /* vendor ID: Freescale Semiconductor */ #define FH_HCALL_TOKEN(num) _EV_HCALL_TOKEN(EV_FSL_VENDOR_ID, num) /* * We use "uintptr_t" to define a register because it's guaranteed to be a * 32-bit integer on a 32-bit platform, and a 64-bit integer on a 64-bit * platform. * * All registers are either input/output or output only. Registers that are * initialized before making the hypercall are input/output. All * input/output registers are represented with "+r". Output-only registers * are represented with "=r". Do not specify any unused registers. The * clobber list will tell the compiler that the hypercall modifies those * registers, which is good enough. */ /** * fh_send_nmi - send NMI to virtual cpu(s). * @vcpu_mask: send NMI to virtual cpu(s) specified by this mask. * * Returns 0 for success, or EINVAL for invalid vcpu_mask. */ static inline unsigned int fh_send_nmi(unsigned int vcpu_mask) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); r11 = FH_HCALL_TOKEN(FH_SEND_NMI); r3 = vcpu_mask; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3) : : EV_HCALL_CLOBBERS1 ); return r3; } /* Arbitrary limits to avoid excessive memory allocation in hypervisor */ #define FH_DTPROP_MAX_PATHLEN 4096 #define FH_DTPROP_MAX_PROPLEN 32768 /** * fh_partition_get_dtprop - get a property from a guest device tree. * @handle: handle of partition whose device tree is to be accessed * @dtpath_addr: physical address of device tree path to access * @propname_addr: physical address of name of property * @propvalue_addr: physical address of property value buffer * @propvalue_len: length of buffer on entry, length of property on return * * Returns zero on success, non-zero on error. */ static inline unsigned int fh_partition_get_dtprop(int handle, uint64_t dtpath_addr, uint64_t propname_addr, uint64_t propvalue_addr, uint32_t *propvalue_len) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); register uintptr_t r5 __asm__("r5"); register uintptr_t r6 __asm__("r6"); register uintptr_t r7 __asm__("r7"); register uintptr_t r8 __asm__("r8"); register uintptr_t r9 __asm__("r9"); register uintptr_t r10 __asm__("r10"); r11 = FH_HCALL_TOKEN(FH_PARTITION_GET_DTPROP); r3 = handle; #ifdef CONFIG_PHYS_64BIT r4 = dtpath_addr >> 32; r6 = propname_addr >> 32; r8 = propvalue_addr >> 32; #else r4 = 0; r6 = 0; r8 = 0; #endif r5 = (uint32_t)dtpath_addr; r7 = (uint32_t)propname_addr; r9 = (uint32_t)propvalue_addr; r10 = *propvalue_len; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "+r" (r4), "+r" (r5), "+r" (r6), "+r" (r7), "+r" (r8), "+r" (r9), "+r" (r10) : : EV_HCALL_CLOBBERS8 ); *propvalue_len = r4; return r3; } /** * Set a property in a guest device tree. * @handle: handle of partition whose device tree is to be accessed * @dtpath_addr: physical address of device tree path to access * @propname_addr: physical address of name of property * @propvalue_addr: physical address of property value * @propvalue_len: length of property * * Returns zero on success, non-zero on error. */ static inline unsigned int fh_partition_set_dtprop(int handle, uint64_t dtpath_addr, uint64_t propname_addr, uint64_t propvalue_addr, uint32_t propvalue_len) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); register uintptr_t r6 __asm__("r6"); register uintptr_t r8 __asm__("r8"); register uintptr_t r5 __asm__("r5"); register uintptr_t r7 __asm__("r7"); register uintptr_t r9 __asm__("r9"); register uintptr_t r10 __asm__("r10"); r11 = FH_HCALL_TOKEN(FH_PARTITION_SET_DTPROP); r3 = handle; #ifdef CONFIG_PHYS_64BIT r4 = dtpath_addr >> 32; r6 = propname_addr >> 32; r8 = propvalue_addr >> 32; #else r4 = 0; r6 = 0; r8 = 0; #endif r5 = (uint32_t)dtpath_addr; r7 = (uint32_t)propname_addr; r9 = (uint32_t)propvalue_addr; r10 = propvalue_len; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "+r" (r4), "+r" (r5), "+r" (r6), "+r" (r7), "+r" (r8), "+r" (r9), "+r" (r10) : : EV_HCALL_CLOBBERS8 ); return r3; } /** * fh_partition_restart - reboot the current partition * @partition: partition ID * * Returns an error code if reboot failed. Does not return if it succeeds. */ static inline unsigned int fh_partition_restart(unsigned int partition) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); r11 = FH_HCALL_TOKEN(FH_PARTITION_RESTART); r3 = partition; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3) : : EV_HCALL_CLOBBERS1 ); return r3; } #define FH_PARTITION_STOPPED 0 #define FH_PARTITION_RUNNING 1 #define FH_PARTITION_STARTING 2 #define FH_PARTITION_STOPPING 3 #define FH_PARTITION_PAUSING 4 #define FH_PARTITION_PAUSED 5 #define FH_PARTITION_RESUMING 6 /** * fh_partition_get_status - gets the status of a partition * @partition: partition ID * @status: returned status code * * Returns 0 for success, or an error code. */ static inline unsigned int fh_partition_get_status(unsigned int partition, unsigned int *status) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); r11 = FH_HCALL_TOKEN(FH_PARTITION_GET_STATUS); r3 = partition; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "=r" (r4) : : EV_HCALL_CLOBBERS2 ); *status = r4; return r3; } /** * fh_partition_start - boots and starts execution of the specified partition * @partition: partition ID * @entry_point: guest physical address to start execution * * The hypervisor creates a 1-to-1 virtual/physical IMA mapping, so at boot * time, guest physical address are the same as guest virtual addresses. * * Returns 0 for success, or an error code. */ static inline unsigned int fh_partition_start(unsigned int partition, uint32_t entry_point, int load) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); register uintptr_t r5 __asm__("r5"); r11 = FH_HCALL_TOKEN(FH_PARTITION_START); r3 = partition; r4 = entry_point; r5 = load; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "+r" (r4), "+r" (r5) : : EV_HCALL_CLOBBERS3 ); return r3; } /** * fh_partition_stop - stops another partition * @partition: partition ID * * Returns 0 for success, or an error code. */ static inline unsigned int fh_partition_stop(unsigned int partition) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); r11 = FH_HCALL_TOKEN(FH_PARTITION_STOP); r3 = partition; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3) : : EV_HCALL_CLOBBERS1 ); return r3; } /** * struct fh_sg_list: definition of the fh_partition_memcpy S/G list * @source: guest physical address to copy from * @target: guest physical address to copy to * @size: number of bytes to copy * @reserved: reserved, must be zero * * The scatter/gather list for fh_partition_memcpy() is an array of these * structures. The array must be guest physically contiguous. * * This structure must be aligned on 32-byte boundary, so that no single * strucuture can span two pages. */ struct fh_sg_list { uint64_t source; /**< guest physical address to copy from */ uint64_t target; /**< guest physical address to copy to */ uint64_t size; /**< number of bytes to copy */ uint64_t reserved; /**< reserved, must be zero */ } __attribute__ ((aligned(32))); /** * fh_partition_memcpy - copies data from one guest to another * @source: the ID of the partition to copy from * @target: the ID of the partition to copy to * @sg_list: guest physical address of an array of &fh_sg_list structures * @count: the number of entries in @sg_list * * Returns 0 for success, or an error code. */ static inline unsigned int fh_partition_memcpy(unsigned int source, unsigned int target, phys_addr_t sg_list, unsigned int count) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); register uintptr_t r5 __asm__("r5"); register uintptr_t r6 __asm__("r6"); register uintptr_t r7 __asm__("r7"); r11 = FH_HCALL_TOKEN(FH_PARTITION_MEMCPY); r3 = source; r4 = target; r5 = (uint32_t) sg_list; #ifdef CONFIG_PHYS_64BIT r6 = sg_list >> 32; #else r6 = 0; #endif r7 = count; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "+r" (r4), "+r" (r5), "+r" (r6), "+r" (r7) : : EV_HCALL_CLOBBERS5 ); return r3; } /** * fh_dma_enable - enable DMA for the specified device * @liodn: the LIODN of the I/O device for which to enable DMA * * Returns 0 for success, or an error code. */ static inline unsigned int fh_dma_enable(unsigned int liodn) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); r11 = FH_HCALL_TOKEN(FH_DMA_ENABLE); r3 = liodn; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3) : : EV_HCALL_CLOBBERS1 ); return r3; } /** * fh_dma_disable - disable DMA for the specified device * @liodn: the LIODN of the I/O device for which to disable DMA * * Returns 0 for success, or an error code. */ static inline unsigned int fh_dma_disable(unsigned int liodn) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); r11 = FH_HCALL_TOKEN(FH_DMA_DISABLE); r3 = liodn; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3) : : EV_HCALL_CLOBBERS1 ); return r3; } /** * fh_vmpic_get_msir - returns the MPIC-MSI register value * @interrupt: the interrupt number * @msir_val: returned MPIC-MSI register value * * Returns 0 for success, or an error code. */ static inline unsigned int fh_vmpic_get_msir(unsigned int interrupt, unsigned int *msir_val) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); r11 = FH_HCALL_TOKEN(FH_VMPIC_GET_MSIR); r3 = interrupt; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "=r" (r4) : : EV_HCALL_CLOBBERS2 ); *msir_val = r4; return r3; } /** * fh_system_reset - reset the system * * Returns 0 for success, or an error code. */ static inline unsigned int fh_system_reset(void) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); r11 = FH_HCALL_TOKEN(FH_SYSTEM_RESET); asm volatile("bl epapr_hypercall_start" : "+r" (r11), "=r" (r3) : : EV_HCALL_CLOBBERS1 ); return r3; } /** * fh_err_get_info - get platform error information * @queue id: * 0 for guest error event queue * 1 for global error event queue * * @pointer to store the platform error data: * platform error data is returned in registers r4 - r11 * * Returns 0 for success, or an error code. */ static inline unsigned int fh_err_get_info(int queue, uint32_t *bufsize, uint32_t addr_hi, uint32_t addr_lo, int peek) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); register uintptr_t r5 __asm__("r5"); register uintptr_t r6 __asm__("r6"); register uintptr_t r7 __asm__("r7"); r11 = FH_HCALL_TOKEN(FH_ERR_GET_INFO); r3 = queue; r4 = *bufsize; r5 = addr_hi; r6 = addr_lo; r7 = peek; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "+r" (r4), "+r" (r5), "+r" (r6), "+r" (r7) : : EV_HCALL_CLOBBERS5 ); *bufsize = r4; return r3; } #define FH_VCPU_RUN 0 #define FH_VCPU_IDLE 1 #define FH_VCPU_NAP 2 /** * fh_get_core_state - get the state of a vcpu * * @handle: handle of partition containing the vcpu * @vcpu: vcpu number within the partition * @state:the current state of the vcpu, see FH_VCPU_* * * Returns 0 for success, or an error code. */ static inline unsigned int fh_get_core_state(unsigned int handle, unsigned int vcpu, unsigned int *state) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); r11 = FH_HCALL_TOKEN(FH_GET_CORE_STATE); r3 = handle; r4 = vcpu; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "+r" (r4) : : EV_HCALL_CLOBBERS2 ); *state = r4; return r3; } /** * fh_enter_nap - enter nap on a vcpu * * Note that though the API supports entering nap on a vcpu other * than the caller, this may not be implmented and may return EINVAL. * * @handle: handle of partition containing the vcpu * @vcpu: vcpu number within the partition * * Returns 0 for success, or an error code. */ static inline unsigned int fh_enter_nap(unsigned int handle, unsigned int vcpu) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); r11 = FH_HCALL_TOKEN(FH_ENTER_NAP); r3 = handle; r4 = vcpu; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "+r" (r4) : : EV_HCALL_CLOBBERS2 ); return r3; } /** * fh_exit_nap - exit nap on a vcpu * @handle: handle of partition containing the vcpu * @vcpu: vcpu number within the partition * * Returns 0 for success, or an error code. */ static inline unsigned int fh_exit_nap(unsigned int handle, unsigned int vcpu) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); register uintptr_t r4 __asm__("r4"); r11 = FH_HCALL_TOKEN(FH_EXIT_NAP); r3 = handle; r4 = vcpu; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3), "+r" (r4) : : EV_HCALL_CLOBBERS2 ); return r3; } /** * fh_claim_device - claim a "claimable" shared device * @handle: fsl,hv-device-handle of node to claim * * Returns 0 for success, or an error code. */ static inline unsigned int fh_claim_device(unsigned int handle) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); r11 = FH_HCALL_TOKEN(FH_CLAIM_DEVICE); r3 = handle; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3) : : EV_HCALL_CLOBBERS1 ); return r3; } /** * Run deferred DMA disabling on a partition's private devices * * This applies to devices which a partition owns either privately, * or which are claimable and still actively owned by that partition, * and which do not have the no-dma-disable property. * * @handle: partition (must be stopped) whose DMA is to be disabled * * Returns 0 for success, or an error code. */ static inline unsigned int fh_partition_stop_dma(unsigned int handle) { register uintptr_t r11 __asm__("r11"); register uintptr_t r3 __asm__("r3"); r11 = FH_HCALL_TOKEN(FH_PARTITION_STOP_DMA); r3 = handle; asm volatile("bl epapr_hypercall_start" : "+r" (r11), "+r" (r3) : : EV_HCALL_CLOBBERS1 ); return r3; } #endif
null
null
null
null
86,149
621
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
train_val
cd0bd79d6ebdb72183e6f0833673464cc10b3600
621
Chrome
1
https://github.com/chromium/chromium
2012-04-14 00:52:16+00:00
void GpuProcessHost::OnProcessLaunched() { // Send the GPU process handle to the UI thread before it has to // respond to any requests to establish a GPU channel. The response // to such requests require that the GPU process handle be known. base::ProcessHandle child_handle = in_process_ ? base::GetCurrentProcessHandle() : process_->GetData().handle; #if defined(OS_WIN) DuplicateHandle(base::GetCurrentProcessHandle(), child_handle, base::GetCurrentProcessHandle(), &gpu_process_, PROCESS_DUP_HANDLE, FALSE, 0); #else gpu_process_ = child_handle; #endif UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime", base::TimeTicks::Now() - init_start_time_); }
CVE-2012-2816
null
https://github.com/chromium/chromium/commit/cd0bd79d6ebdb72183e6f0833673464cc10b3600
Low
621
6,787
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
6,787
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy_resolution/mock_pac_file_fetcher.h" #include "base/callback_helpers.h" #include "base/logging.h" #include "base/run_loop.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "net/base/net_errors.h" namespace net { MockPacFileFetcher::MockPacFileFetcher() : pending_request_text_(NULL), waiting_for_fetch_(false), is_shutdown_(false) {} MockPacFileFetcher::~MockPacFileFetcher() = default; // PacFileFetcher implementation. int MockPacFileFetcher::Fetch( const GURL& url, base::string16* text, const CompletionCallback& callback, const NetworkTrafficAnnotationTag traffic_annotation) { DCHECK(!has_pending_request()); if (waiting_for_fetch_) base::RunLoop::QuitCurrentWhenIdleDeprecated(); if (is_shutdown_) return ERR_CONTEXT_SHUT_DOWN; // Save the caller's information, and have them wait. pending_request_url_ = url; pending_request_callback_ = callback; pending_request_text_ = text; return ERR_IO_PENDING; } void MockPacFileFetcher::NotifyFetchCompletion(int result, const std::string& ascii_text) { DCHECK(has_pending_request()); *pending_request_text_ = base::ASCIIToUTF16(ascii_text); base::ResetAndReturn(&pending_request_callback_).Run(result); } void MockPacFileFetcher::Cancel() { pending_request_callback_.Reset(); } void MockPacFileFetcher::OnShutdown() { is_shutdown_ = true; if (pending_request_callback_) { base::ResetAndReturn(&pending_request_callback_).Run(ERR_CONTEXT_SHUT_DOWN); } } URLRequestContext* MockPacFileFetcher::GetRequestContext() const { return NULL; } const GURL& MockPacFileFetcher::pending_request_url() const { return pending_request_url_; } bool MockPacFileFetcher::has_pending_request() const { return !pending_request_callback_.is_null(); } void MockPacFileFetcher::WaitUntilFetch() { DCHECK(!has_pending_request()); waiting_for_fetch_ = true; base::RunLoop().Run(); waiting_for_fetch_ = false; } } // namespace net
null
null
null
null
3,650
71,037
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
71,037
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_DATA_DECODER_PUBLIC_CPP_SAFE_JSON_PARSER_IMPL_H_ #define SERVICES_DATA_DECODER_PUBLIC_CPP_SAFE_JSON_PARSER_IMPL_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/threading/thread_checker.h" #include "services/data_decoder/public/cpp/safe_json_parser.h" #include "services/data_decoder/public/mojom/json_parser.mojom.h" namespace base { class Value; } namespace service_manager { class Connector; } namespace data_decoder { class SafeJsonParserImpl : public SafeJsonParser { public: SafeJsonParserImpl(service_manager::Connector* connector, const std::string& unsafe_json, const SuccessCallback& success_callback, const ErrorCallback& error_callback); private: ~SafeJsonParserImpl() override; // SafeJsonParser implementation. void Start() override; void StartOnIOThread(); void OnConnectionError(); // mojom::SafeJsonParser::Parse callback. void OnParseDone(std::unique_ptr<base::Value> result, const base::Optional<std::string>& error); // Reports the result on the calling task runner via the |success_callback_| // or the |error_callback_|. void ReportResults(std::unique_ptr<base::Value> parsed_json, const std::string& error); const std::string unsafe_json_; SuccessCallback success_callback_; ErrorCallback error_callback_; mojom::JsonParserPtr json_parser_ptr_; SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(SafeJsonParserImpl); }; } // namespace data_decoder #endif // SERVICES_DATA_DECODER_PUBLIC_CPP_SAFE_JSON_PARSER_IMPL_H_
null
null
null
null
67,900
67,148
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
67,148
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/apps/app_browsertest_util.h" #include "content/public/browser/notification_service.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_utils.h" #include "extensions/browser/notification_types.h" #include "extensions/test/extension_test_message_listener.h" using extensions::Extension; using extensions::PlatformAppBrowserTest; namespace { class AppEventPageTest : public PlatformAppBrowserTest { protected: void TestUnloadEventPage(const char* app_path) { // Load and launch the app. const Extension* extension = LoadAndLaunchPlatformApp(app_path, "launched"); ASSERT_TRUE(extension); content::WindowedNotificationObserver event_page_suspended( extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, content::NotificationService::AllSources()); // Close the app window. EXPECT_EQ(1U, GetAppWindowCount()); extensions::AppWindow* app_window = GetFirstAppWindow(); ASSERT_TRUE(app_window); CloseAppWindow(app_window); // Verify that the event page is destroyed. event_page_suspended.Wait(); } }; } // namespace // Tests that an app's event page will eventually be unloaded. The onSuspend // event handler of this app does not make any API calls. IN_PROC_BROWSER_TEST_F(AppEventPageTest, OnSuspendNoApiUse) { TestUnloadEventPage("event_page/suspend_simple"); } // Tests that an app's event page will eventually be unloaded. The onSuspend // event handler of this app calls a chrome.storage API function. // See: http://crbug.com/296834 IN_PROC_BROWSER_TEST_F(AppEventPageTest, OnSuspendUseStorageApi) { TestUnloadEventPage("event_page/suspend_storage_api"); }
null
null
null
null
64,011
6,088
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
6,088
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/components/tether/fake_wifi_hotspot_disconnector.h" namespace chromeos { namespace tether { FakeWifiHotspotDisconnector::FakeWifiHotspotDisconnector() = default; FakeWifiHotspotDisconnector::~FakeWifiHotspotDisconnector() = default; void FakeWifiHotspotDisconnector::DisconnectFromWifiHotspot( const std::string& wifi_network_guid, const base::Closure& success_callback, const network_handler::StringResultCallback& error_callback) { last_disconnected_wifi_network_guid_ = wifi_network_guid; if (disconnection_error_name_.empty()) success_callback.Run(); else error_callback.Run(disconnection_error_name_); } } // namespace tether } // namespace chromeos
null
null
null
null
2,951
6,039
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
171,034
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * simone.c -- ASoC audio for Simplemachines Sim.One board * * Copyright (c) 2010 Mika Westerberg * * Based on snappercl15 machine driver by Ryan Mallon. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/module.h> #include <linux/platform_device.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <asm/mach-types.h> #include <mach/hardware.h> static struct snd_soc_dai_link simone_dai = { .name = "AC97", .stream_name = "AC97 HiFi", .cpu_dai_name = "ep93xx-ac97", .codec_dai_name = "ac97-hifi", .codec_name = "ac97-codec", .platform_name = "ep93xx-ac97", }; static struct snd_soc_card snd_soc_simone = { .name = "Sim.One", .owner = THIS_MODULE, .dai_link = &simone_dai, .num_links = 1, }; static struct platform_device *simone_snd_ac97_device; static int simone_probe(struct platform_device *pdev) { struct snd_soc_card *card = &snd_soc_simone; int ret; simone_snd_ac97_device = platform_device_register_simple("ac97-codec", -1, NULL, 0); if (IS_ERR(simone_snd_ac97_device)) return PTR_ERR(simone_snd_ac97_device); card->dev = &pdev->dev; ret = snd_soc_register_card(card); if (ret) { dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n", ret); platform_device_unregister(simone_snd_ac97_device); } return ret; } static int simone_remove(struct platform_device *pdev) { struct snd_soc_card *card = platform_get_drvdata(pdev); snd_soc_unregister_card(card); platform_device_unregister(simone_snd_ac97_device); return 0; } static struct platform_driver simone_driver = { .driver = { .name = "simone-audio", }, .probe = simone_probe, .remove = simone_remove, }; module_platform_driver(simone_driver); MODULE_DESCRIPTION("ALSA SoC Simplemachines Sim.One"); MODULE_AUTHOR("Mika Westerberg <mika.westerberg@iki.fi>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:simone-audio");
null
null
null
null
79,381
19,404
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
184,399
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2015 Microchip Technology * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #ifndef _LAN78XX_H #define _LAN78XX_H /* USB Vendor Requests */ #define USB_VENDOR_REQUEST_WRITE_REGISTER 0xA0 #define USB_VENDOR_REQUEST_READ_REGISTER 0xA1 #define USB_VENDOR_REQUEST_GET_STATS 0xA2 /* Interrupt Endpoint status word bitfields */ #define INT_ENP_EEE_START_TX_LPI_INT BIT(26) #define INT_ENP_EEE_STOP_TX_LPI_INT BIT(25) #define INT_ENP_EEE_RX_LPI_INT BIT(24) #define INT_ENP_RDFO_INT BIT(22) #define INT_ENP_TXE_INT BIT(21) #define INT_ENP_TX_DIS_INT BIT(19) #define INT_ENP_RX_DIS_INT BIT(18) #define INT_ENP_PHY_INT BIT(17) #define INT_ENP_DP_INT BIT(16) #define INT_ENP_MAC_ERR_INT BIT(15) #define INT_ENP_TDFU_INT BIT(14) #define INT_ENP_TDFO_INT BIT(13) #define INT_ENP_UTX_FP_INT BIT(12) #define TX_PKT_ALIGNMENT 4 #define RX_PKT_ALIGNMENT 4 /* Tx Command A */ #define TX_CMD_A_IGE_ (0x20000000) #define TX_CMD_A_ICE_ (0x10000000) #define TX_CMD_A_LSO_ (0x08000000) #define TX_CMD_A_IPE_ (0x04000000) #define TX_CMD_A_TPE_ (0x02000000) #define TX_CMD_A_IVTG_ (0x01000000) #define TX_CMD_A_RVTG_ (0x00800000) #define TX_CMD_A_FCS_ (0x00400000) #define TX_CMD_A_LEN_MASK_ (0x000FFFFF) /* Tx Command B */ #define TX_CMD_B_MSS_SHIFT_ (16) #define TX_CMD_B_MSS_MASK_ (0x3FFF0000) #define TX_CMD_B_MSS_MIN_ ((unsigned short)8) #define TX_CMD_B_VTAG_MASK_ (0x0000FFFF) #define TX_CMD_B_VTAG_PRI_MASK_ (0x0000E000) #define TX_CMD_B_VTAG_CFI_MASK_ (0x00001000) #define TX_CMD_B_VTAG_VID_MASK_ (0x00000FFF) /* Rx Command A */ #define RX_CMD_A_ICE_ (0x80000000) #define RX_CMD_A_TCE_ (0x40000000) #define RX_CMD_A_CSE_MASK_ (0xC0000000) #define RX_CMD_A_IPV_ (0x20000000) #define RX_CMD_A_PID_MASK_ (0x18000000) #define RX_CMD_A_PID_NONE_IP_ (0x00000000) #define RX_CMD_A_PID_TCP_IP_ (0x08000000) #define RX_CMD_A_PID_UDP_IP_ (0x10000000) #define RX_CMD_A_PID_IP_ (0x18000000) #define RX_CMD_A_PFF_ (0x04000000) #define RX_CMD_A_BAM_ (0x02000000) #define RX_CMD_A_MAM_ (0x01000000) #define RX_CMD_A_FVTG_ (0x00800000) #define RX_CMD_A_RED_ (0x00400000) #define RX_CMD_A_RX_ERRS_MASK_ (0xC03F0000) #define RX_CMD_A_RWT_ (0x00200000) #define RX_CMD_A_RUNT_ (0x00100000) #define RX_CMD_A_LONG_ (0x00080000) #define RX_CMD_A_RXE_ (0x00040000) #define RX_CMD_A_DRB_ (0x00020000) #define RX_CMD_A_FCS_ (0x00010000) #define RX_CMD_A_UAM_ (0x00008000) #define RX_CMD_A_ICSM_ (0x00004000) #define RX_CMD_A_LEN_MASK_ (0x00003FFF) /* Rx Command B */ #define RX_CMD_B_CSUM_SHIFT_ (16) #define RX_CMD_B_CSUM_MASK_ (0xFFFF0000) #define RX_CMD_B_VTAG_MASK_ (0x0000FFFF) #define RX_CMD_B_VTAG_PRI_MASK_ (0x0000E000) #define RX_CMD_B_VTAG_CFI_MASK_ (0x00001000) #define RX_CMD_B_VTAG_VID_MASK_ (0x00000FFF) /* Rx Command C */ #define RX_CMD_C_WAKE_SHIFT_ (15) #define RX_CMD_C_WAKE_ (0x8000) #define RX_CMD_C_REF_FAIL_SHIFT_ (14) #define RX_CMD_C_REF_FAIL_ (0x4000) /* SCSRs */ #define NUMBER_OF_REGS (193) #define ID_REV (0x00) #define ID_REV_CHIP_ID_MASK_ (0xFFFF0000) #define ID_REV_CHIP_REV_MASK_ (0x0000FFFF) #define ID_REV_CHIP_ID_7800_ (0x7800) #define ID_REV_CHIP_ID_7850_ (0x7850) #define ID_REV_CHIP_ID_7801_ (0x7801) #define FPGA_REV (0x04) #define FPGA_REV_MINOR_MASK_ (0x0000FF00) #define FPGA_REV_MAJOR_MASK_ (0x000000FF) #define INT_STS (0x0C) #define INT_STS_CLEAR_ALL_ (0xFFFFFFFF) #define INT_STS_EEE_TX_LPI_STRT_ (0x04000000) #define INT_STS_EEE_TX_LPI_STOP_ (0x02000000) #define INT_STS_EEE_RX_LPI_ (0x01000000) #define INT_STS_RDFO_ (0x00400000) #define INT_STS_TXE_ (0x00200000) #define INT_STS_TX_DIS_ (0x00080000) #define INT_STS_RX_DIS_ (0x00040000) #define INT_STS_PHY_INT_ (0x00020000) #define INT_STS_DP_INT_ (0x00010000) #define INT_STS_MAC_ERR_ (0x00008000) #define INT_STS_TDFU_ (0x00004000) #define INT_STS_TDFO_ (0x00002000) #define INT_STS_UFX_FP_ (0x00001000) #define INT_STS_GPIO_MASK_ (0x00000FFF) #define INT_STS_GPIO11_ (0x00000800) #define INT_STS_GPIO10_ (0x00000400) #define INT_STS_GPIO9_ (0x00000200) #define INT_STS_GPIO8_ (0x00000100) #define INT_STS_GPIO7_ (0x00000080) #define INT_STS_GPIO6_ (0x00000040) #define INT_STS_GPIO5_ (0x00000020) #define INT_STS_GPIO4_ (0x00000010) #define INT_STS_GPIO3_ (0x00000008) #define INT_STS_GPIO2_ (0x00000004) #define INT_STS_GPIO1_ (0x00000002) #define INT_STS_GPIO0_ (0x00000001) #define HW_CFG (0x010) #define HW_CFG_CLK125_EN_ (0x02000000) #define HW_CFG_REFCLK25_EN_ (0x01000000) #define HW_CFG_LED3_EN_ (0x00800000) #define HW_CFG_LED2_EN_ (0x00400000) #define HW_CFG_LED1_EN_ (0x00200000) #define HW_CFG_LED0_EN_ (0x00100000) #define HW_CFG_EEE_PHY_LUSU_ (0x00020000) #define HW_CFG_EEE_TSU_ (0x00010000) #define HW_CFG_NETDET_STS_ (0x00008000) #define HW_CFG_NETDET_EN_ (0x00004000) #define HW_CFG_EEM_ (0x00002000) #define HW_CFG_RST_PROTECT_ (0x00001000) #define HW_CFG_CONNECT_BUF_ (0x00000400) #define HW_CFG_CONNECT_EN_ (0x00000200) #define HW_CFG_CONNECT_POL_ (0x00000100) #define HW_CFG_SUSPEND_N_SEL_MASK_ (0x000000C0) #define HW_CFG_SUSPEND_N_SEL_2 (0x00000000) #define HW_CFG_SUSPEND_N_SEL_12N (0x00000040) #define HW_CFG_SUSPEND_N_SEL_012N (0x00000080) #define HW_CFG_SUSPEND_N_SEL_0123N (0x000000C0) #define HW_CFG_SUSPEND_N_POL_ (0x00000020) #define HW_CFG_MEF_ (0x00000010) #define HW_CFG_ETC_ (0x00000008) #define HW_CFG_LRST_ (0x00000002) #define HW_CFG_SRST_ (0x00000001) #define PMT_CTL (0x014) #define PMT_CTL_EEE_WAKEUP_EN_ (0x00002000) #define PMT_CTL_EEE_WUPS_ (0x00001000) #define PMT_CTL_MAC_SRST_ (0x00000800) #define PMT_CTL_PHY_PWRUP_ (0x00000400) #define PMT_CTL_RES_CLR_WKP_MASK_ (0x00000300) #define PMT_CTL_RES_CLR_WKP_STS_ (0x00000200) #define PMT_CTL_RES_CLR_WKP_EN_ (0x00000100) #define PMT_CTL_READY_ (0x00000080) #define PMT_CTL_SUS_MODE_MASK_ (0x00000060) #define PMT_CTL_SUS_MODE_0_ (0x00000000) #define PMT_CTL_SUS_MODE_1_ (0x00000020) #define PMT_CTL_SUS_MODE_2_ (0x00000040) #define PMT_CTL_SUS_MODE_3_ (0x00000060) #define PMT_CTL_PHY_RST_ (0x00000010) #define PMT_CTL_WOL_EN_ (0x00000008) #define PMT_CTL_PHY_WAKE_EN_ (0x00000004) #define PMT_CTL_WUPS_MASK_ (0x00000003) #define PMT_CTL_WUPS_MLT_ (0x00000003) #define PMT_CTL_WUPS_MAC_ (0x00000002) #define PMT_CTL_WUPS_PHY_ (0x00000001) #define GPIO_CFG0 (0x018) #define GPIO_CFG0_GPIOEN_MASK_ (0x0000F000) #define GPIO_CFG0_GPIOEN3_ (0x00008000) #define GPIO_CFG0_GPIOEN2_ (0x00004000) #define GPIO_CFG0_GPIOEN1_ (0x00002000) #define GPIO_CFG0_GPIOEN0_ (0x00001000) #define GPIO_CFG0_GPIOBUF_MASK_ (0x00000F00) #define GPIO_CFG0_GPIOBUF3_ (0x00000800) #define GPIO_CFG0_GPIOBUF2_ (0x00000400) #define GPIO_CFG0_GPIOBUF1_ (0x00000200) #define GPIO_CFG0_GPIOBUF0_ (0x00000100) #define GPIO_CFG0_GPIODIR_MASK_ (0x000000F0) #define GPIO_CFG0_GPIODIR3_ (0x00000080) #define GPIO_CFG0_GPIODIR2_ (0x00000040) #define GPIO_CFG0_GPIODIR1_ (0x00000020) #define GPIO_CFG0_GPIODIR0_ (0x00000010) #define GPIO_CFG0_GPIOD_MASK_ (0x0000000F) #define GPIO_CFG0_GPIOD3_ (0x00000008) #define GPIO_CFG0_GPIOD2_ (0x00000004) #define GPIO_CFG0_GPIOD1_ (0x00000002) #define GPIO_CFG0_GPIOD0_ (0x00000001) #define GPIO_CFG1 (0x01C) #define GPIO_CFG1_GPIOEN_MASK_ (0xFF000000) #define GPIO_CFG1_GPIOEN11_ (0x80000000) #define GPIO_CFG1_GPIOEN10_ (0x40000000) #define GPIO_CFG1_GPIOEN9_ (0x20000000) #define GPIO_CFG1_GPIOEN8_ (0x10000000) #define GPIO_CFG1_GPIOEN7_ (0x08000000) #define GPIO_CFG1_GPIOEN6_ (0x04000000) #define GPIO_CFG1_GPIOEN5_ (0x02000000) #define GPIO_CFG1_GPIOEN4_ (0x01000000) #define GPIO_CFG1_GPIOBUF_MASK_ (0x00FF0000) #define GPIO_CFG1_GPIOBUF11_ (0x00800000) #define GPIO_CFG1_GPIOBUF10_ (0x00400000) #define GPIO_CFG1_GPIOBUF9_ (0x00200000) #define GPIO_CFG1_GPIOBUF8_ (0x00100000) #define GPIO_CFG1_GPIOBUF7_ (0x00080000) #define GPIO_CFG1_GPIOBUF6_ (0x00040000) #define GPIO_CFG1_GPIOBUF5_ (0x00020000) #define GPIO_CFG1_GPIOBUF4_ (0x00010000) #define GPIO_CFG1_GPIODIR_MASK_ (0x0000FF00) #define GPIO_CFG1_GPIODIR11_ (0x00008000) #define GPIO_CFG1_GPIODIR10_ (0x00004000) #define GPIO_CFG1_GPIODIR9_ (0x00002000) #define GPIO_CFG1_GPIODIR8_ (0x00001000) #define GPIO_CFG1_GPIODIR7_ (0x00000800) #define GPIO_CFG1_GPIODIR6_ (0x00000400) #define GPIO_CFG1_GPIODIR5_ (0x00000200) #define GPIO_CFG1_GPIODIR4_ (0x00000100) #define GPIO_CFG1_GPIOD_MASK_ (0x000000FF) #define GPIO_CFG1_GPIOD11_ (0x00000080) #define GPIO_CFG1_GPIOD10_ (0x00000040) #define GPIO_CFG1_GPIOD9_ (0x00000020) #define GPIO_CFG1_GPIOD8_ (0x00000010) #define GPIO_CFG1_GPIOD7_ (0x00000008) #define GPIO_CFG1_GPIOD6_ (0x00000004) #define GPIO_CFG1_GPIOD6_ (0x00000004) #define GPIO_CFG1_GPIOD5_ (0x00000002) #define GPIO_CFG1_GPIOD4_ (0x00000001) #define GPIO_WAKE (0x020) #define GPIO_WAKE_GPIOPOL_MASK_ (0x0FFF0000) #define GPIO_WAKE_GPIOPOL11_ (0x08000000) #define GPIO_WAKE_GPIOPOL10_ (0x04000000) #define GPIO_WAKE_GPIOPOL9_ (0x02000000) #define GPIO_WAKE_GPIOPOL8_ (0x01000000) #define GPIO_WAKE_GPIOPOL7_ (0x00800000) #define GPIO_WAKE_GPIOPOL6_ (0x00400000) #define GPIO_WAKE_GPIOPOL5_ (0x00200000) #define GPIO_WAKE_GPIOPOL4_ (0x00100000) #define GPIO_WAKE_GPIOPOL3_ (0x00080000) #define GPIO_WAKE_GPIOPOL2_ (0x00040000) #define GPIO_WAKE_GPIOPOL1_ (0x00020000) #define GPIO_WAKE_GPIOPOL0_ (0x00010000) #define GPIO_WAKE_GPIOWK_MASK_ (0x00000FFF) #define GPIO_WAKE_GPIOWK11_ (0x00000800) #define GPIO_WAKE_GPIOWK10_ (0x00000400) #define GPIO_WAKE_GPIOWK9_ (0x00000200) #define GPIO_WAKE_GPIOWK8_ (0x00000100) #define GPIO_WAKE_GPIOWK7_ (0x00000080) #define GPIO_WAKE_GPIOWK6_ (0x00000040) #define GPIO_WAKE_GPIOWK5_ (0x00000020) #define GPIO_WAKE_GPIOWK4_ (0x00000010) #define GPIO_WAKE_GPIOWK3_ (0x00000008) #define GPIO_WAKE_GPIOWK2_ (0x00000004) #define GPIO_WAKE_GPIOWK1_ (0x00000002) #define GPIO_WAKE_GPIOWK0_ (0x00000001) #define DP_SEL (0x024) #define DP_SEL_DPRDY_ (0x80000000) #define DP_SEL_RSEL_MASK_ (0x0000000F) #define DP_SEL_RSEL_USB_PHY_CSRS_ (0x0000000F) #define DP_SEL_RSEL_OTP_64BIT_ (0x00000009) #define DP_SEL_RSEL_OTP_8BIT_ (0x00000008) #define DP_SEL_RSEL_UTX_BUF_RAM_ (0x00000007) #define DP_SEL_RSEL_DESC_RAM_ (0x00000005) #define DP_SEL_RSEL_TXFIFO_ (0x00000004) #define DP_SEL_RSEL_RXFIFO_ (0x00000003) #define DP_SEL_RSEL_LSO_ (0x00000002) #define DP_SEL_RSEL_VLAN_DA_ (0x00000001) #define DP_SEL_RSEL_URXBUF_ (0x00000000) #define DP_SEL_VHF_HASH_LEN (16) #define DP_SEL_VHF_VLAN_LEN (128) #define DP_CMD (0x028) #define DP_CMD_WRITE_ (0x00000001) #define DP_CMD_READ_ (0x00000000) #define DP_ADDR (0x02C) #define DP_ADDR_MASK_ (0x00003FFF) #define DP_DATA (0x030) #define E2P_CMD (0x040) #define E2P_CMD_EPC_BUSY_ (0x80000000) #define E2P_CMD_EPC_CMD_MASK_ (0x70000000) #define E2P_CMD_EPC_CMD_RELOAD_ (0x70000000) #define E2P_CMD_EPC_CMD_ERAL_ (0x60000000) #define E2P_CMD_EPC_CMD_ERASE_ (0x50000000) #define E2P_CMD_EPC_CMD_WRAL_ (0x40000000) #define E2P_CMD_EPC_CMD_WRITE_ (0x30000000) #define E2P_CMD_EPC_CMD_EWEN_ (0x20000000) #define E2P_CMD_EPC_CMD_EWDS_ (0x10000000) #define E2P_CMD_EPC_CMD_READ_ (0x00000000) #define E2P_CMD_EPC_TIMEOUT_ (0x00000400) #define E2P_CMD_EPC_DL_ (0x00000200) #define E2P_CMD_EPC_ADDR_MASK_ (0x000001FF) #define E2P_DATA (0x044) #define E2P_DATA_EEPROM_DATA_MASK_ (0x000000FF) #define BOS_ATTR (0x050) #define BOS_ATTR_BLOCK_SIZE_MASK_ (0x000000FF) #define SS_ATTR (0x054) #define SS_ATTR_POLL_INT_MASK_ (0x00FF0000) #define SS_ATTR_DEV_DESC_SIZE_MASK_ (0x0000FF00) #define SS_ATTR_CFG_BLK_SIZE_MASK_ (0x000000FF) #define HS_ATTR (0x058) #define HS_ATTR_POLL_INT_MASK_ (0x00FF0000) #define HS_ATTR_DEV_DESC_SIZE_MASK_ (0x0000FF00) #define HS_ATTR_CFG_BLK_SIZE_MASK_ (0x000000FF) #define FS_ATTR (0x05C) #define FS_ATTR_POLL_INT_MASK_ (0x00FF0000) #define FS_ATTR_DEV_DESC_SIZE_MASK_ (0x0000FF00) #define FS_ATTR_CFG_BLK_SIZE_MASK_ (0x000000FF) #define STR_ATTR0 (0x060) #define STR_ATTR0_CFGSTR_DESC_SIZE_MASK_ (0xFF000000) #define STR_ATTR0_SERSTR_DESC_SIZE_MASK_ (0x00FF0000) #define STR_ATTR0_PRODSTR_DESC_SIZE_MASK_ (0x0000FF00) #define STR_ATTR0_MANUF_DESC_SIZE_MASK_ (0x000000FF) #define STR_ATTR1 (0x064) #define STR_ATTR1_INTSTR_DESC_SIZE_MASK_ (0x000000FF) #define STR_FLAG_ATTR (0x068) #define STR_FLAG_ATTR_PME_FLAGS_MASK_ (0x000000FF) #define USB_CFG0 (0x080) #define USB_CFG_LPM_RESPONSE_ (0x80000000) #define USB_CFG_LPM_CAPABILITY_ (0x40000000) #define USB_CFG_LPM_ENBL_SLPM_ (0x20000000) #define USB_CFG_HIRD_THR_MASK_ (0x1F000000) #define USB_CFG_HIRD_THR_960_ (0x1C000000) #define USB_CFG_HIRD_THR_885_ (0x1B000000) #define USB_CFG_HIRD_THR_810_ (0x1A000000) #define USB_CFG_HIRD_THR_735_ (0x19000000) #define USB_CFG_HIRD_THR_660_ (0x18000000) #define USB_CFG_HIRD_THR_585_ (0x17000000) #define USB_CFG_HIRD_THR_510_ (0x16000000) #define USB_CFG_HIRD_THR_435_ (0x15000000) #define USB_CFG_HIRD_THR_360_ (0x14000000) #define USB_CFG_HIRD_THR_285_ (0x13000000) #define USB_CFG_HIRD_THR_210_ (0x12000000) #define USB_CFG_HIRD_THR_135_ (0x11000000) #define USB_CFG_HIRD_THR_60_ (0x10000000) #define USB_CFG_MAX_BURST_BI_MASK_ (0x00F00000) #define USB_CFG_MAX_BURST_BO_MASK_ (0x000F0000) #define USB_CFG_MAX_DEV_SPEED_MASK_ (0x0000E000) #define USB_CFG_MAX_DEV_SPEED_SS_ (0x00008000) #define USB_CFG_MAX_DEV_SPEED_HS_ (0x00000000) #define USB_CFG_MAX_DEV_SPEED_FS_ (0x00002000) #define USB_CFG_PHY_BOOST_MASK_ (0x00000180) #define USB_CFG_PHY_BOOST_PLUS_12_ (0x00000180) #define USB_CFG_PHY_BOOST_PLUS_8_ (0x00000100) #define USB_CFG_PHY_BOOST_PLUS_4_ (0x00000080) #define USB_CFG_PHY_BOOST_NORMAL_ (0x00000000) #define USB_CFG_BIR_ (0x00000040) #define USB_CFG_BCE_ (0x00000020) #define USB_CFG_PORT_SWAP_ (0x00000010) #define USB_CFG_LPM_EN_ (0x00000008) #define USB_CFG_RMT_WKP_ (0x00000004) #define USB_CFG_PWR_SEL_ (0x00000002) #define USB_CFG_STALL_BO_DIS_ (0x00000001) #define USB_CFG1 (0x084) #define USB_CFG1_U1_TIMEOUT_MASK_ (0xFF000000) #define USB_CFG1_U2_TIMEOUT_MASK_ (0x00FF0000) #define USB_CFG1_HS_TOUT_CAL_MASK_ (0x0000E000) #define USB_CFG1_DEV_U2_INIT_EN_ (0x00001000) #define USB_CFG1_DEV_U2_EN_ (0x00000800) #define USB_CFG1_DEV_U1_INIT_EN_ (0x00000400) #define USB_CFG1_DEV_U1_EN_ (0x00000200) #define USB_CFG1_LTM_ENABLE_ (0x00000100) #define USB_CFG1_FS_TOUT_CAL_MASK_ (0x00000070) #define USB_CFG1_SCALE_DOWN_MASK_ (0x00000003) #define USB_CFG1_SCALE_DOWN_MODE3_ (0x00000003) #define USB_CFG1_SCALE_DOWN_MODE2_ (0x00000002) #define USB_CFG1_SCALE_DOWN_MODE1_ (0x00000001) #define USB_CFG1_SCALE_DOWN_MODE0_ (0x00000000) #define USB_CFG2 (0x088) #define USB_CFG2_SS_DETACH_TIME_MASK_ (0xFFFF0000) #define USB_CFG2_HS_DETACH_TIME_MASK_ (0x0000FFFF) #define BURST_CAP (0x090) #define BURST_CAP_SIZE_MASK_ (0x000000FF) #define BULK_IN_DLY (0x094) #define BULK_IN_DLY_MASK_ (0x0000FFFF) #define INT_EP_CTL (0x098) #define INT_EP_INTEP_ON_ (0x80000000) #define INT_STS_EEE_TX_LPI_STRT_EN_ (0x04000000) #define INT_STS_EEE_TX_LPI_STOP_EN_ (0x02000000) #define INT_STS_EEE_RX_LPI_EN_ (0x01000000) #define INT_EP_RDFO_EN_ (0x00400000) #define INT_EP_TXE_EN_ (0x00200000) #define INT_EP_TX_DIS_EN_ (0x00080000) #define INT_EP_RX_DIS_EN_ (0x00040000) #define INT_EP_PHY_INT_EN_ (0x00020000) #define INT_EP_DP_INT_EN_ (0x00010000) #define INT_EP_MAC_ERR_EN_ (0x00008000) #define INT_EP_TDFU_EN_ (0x00004000) #define INT_EP_TDFO_EN_ (0x00002000) #define INT_EP_UTX_FP_EN_ (0x00001000) #define INT_EP_GPIO_EN_MASK_ (0x00000FFF) #define PIPE_CTL (0x09C) #define PIPE_CTL_TXSWING_ (0x00000040) #define PIPE_CTL_TXMARGIN_MASK_ (0x00000038) #define PIPE_CTL_TXDEEMPHASIS_MASK_ (0x00000006) #define PIPE_CTL_ELASTICITYBUFFERMODE_ (0x00000001) #define U1_LATENCY (0xA0) #define U2_LATENCY (0xA4) #define USB_STATUS (0x0A8) #define USB_STATUS_REMOTE_WK_ (0x00100000) #define USB_STATUS_FUNC_REMOTE_WK_ (0x00080000) #define USB_STATUS_LTM_ENABLE_ (0x00040000) #define USB_STATUS_U2_ENABLE_ (0x00020000) #define USB_STATUS_U1_ENABLE_ (0x00010000) #define USB_STATUS_SET_SEL_ (0x00000020) #define USB_STATUS_REMOTE_WK_STS_ (0x00000010) #define USB_STATUS_FUNC_REMOTE_WK_STS_ (0x00000008) #define USB_STATUS_LTM_ENABLE_STS_ (0x00000004) #define USB_STATUS_U2_ENABLE_STS_ (0x00000002) #define USB_STATUS_U1_ENABLE_STS_ (0x00000001) #define USB_CFG3 (0x0AC) #define USB_CFG3_EN_U2_LTM_ (0x40000000) #define USB_CFG3_BULK_OUT_NUMP_OVR_ (0x20000000) #define USB_CFG3_DIS_FAST_U1_EXIT_ (0x10000000) #define USB_CFG3_LPM_NYET_THR_ (0x0F000000) #define USB_CFG3_RX_DET_2_POL_LFPS_ (0x00800000) #define USB_CFG3_LFPS_FILT_ (0x00400000) #define USB_CFG3_SKIP_RX_DET_ (0x00200000) #define USB_CFG3_DELAY_P1P2P3_ (0x001C0000) #define USB_CFG3_DELAY_PHY_PWR_CHG_ (0x00020000) #define USB_CFG3_U1U2_EXIT_FR_ (0x00010000) #define USB_CFG3_REQ_P1P2P3 (0x00008000) #define USB_CFG3_HST_PRT_CMPL_ (0x00004000) #define USB_CFG3_DIS_SCRAMB_ (0x00002000) #define USB_CFG3_PWR_DN_SCALE_ (0x00001FFF) #define RFE_CTL (0x0B0) #define RFE_CTL_IGMP_COE_ (0x00004000) #define RFE_CTL_ICMP_COE_ (0x00002000) #define RFE_CTL_TCPUDP_COE_ (0x00001000) #define RFE_CTL_IP_COE_ (0x00000800) #define RFE_CTL_BCAST_EN_ (0x00000400) #define RFE_CTL_MCAST_EN_ (0x00000200) #define RFE_CTL_UCAST_EN_ (0x00000100) #define RFE_CTL_VLAN_STRIP_ (0x00000080) #define RFE_CTL_DISCARD_UNTAGGED_ (0x00000040) #define RFE_CTL_VLAN_FILTER_ (0x00000020) #define RFE_CTL_SA_FILTER_ (0x00000010) #define RFE_CTL_MCAST_HASH_ (0x00000008) #define RFE_CTL_DA_HASH_ (0x00000004) #define RFE_CTL_DA_PERFECT_ (0x00000002) #define RFE_CTL_RST_ (0x00000001) #define VLAN_TYPE (0x0B4) #define VLAN_TYPE_MASK_ (0x0000FFFF) #define FCT_RX_CTL (0x0C0) #define FCT_RX_CTL_EN_ (0x80000000) #define FCT_RX_CTL_RST_ (0x40000000) #define FCT_RX_CTL_SBF_ (0x02000000) #define FCT_RX_CTL_OVFL_ (0x01000000) #define FCT_RX_CTL_DROP_ (0x00800000) #define FCT_RX_CTL_NOT_EMPTY_ (0x00400000) #define FCT_RX_CTL_EMPTY_ (0x00200000) #define FCT_RX_CTL_DIS_ (0x00100000) #define FCT_RX_CTL_USED_MASK_ (0x0000FFFF) #define FCT_TX_CTL (0x0C4) #define FCT_TX_CTL_EN_ (0x80000000) #define FCT_TX_CTL_RST_ (0x40000000) #define FCT_TX_CTL_NOT_EMPTY_ (0x00400000) #define FCT_TX_CTL_EMPTY_ (0x00200000) #define FCT_TX_CTL_DIS_ (0x00100000) #define FCT_TX_CTL_USED_MASK_ (0x0000FFFF) #define FCT_RX_FIFO_END (0x0C8) #define FCT_RX_FIFO_END_MASK_ (0x0000007F) #define FCT_TX_FIFO_END (0x0CC) #define FCT_TX_FIFO_END_MASK_ (0x0000003F) #define FCT_FLOW (0x0D0) #define FCT_FLOW_OFF_MASK_ (0x00007F00) #define FCT_FLOW_ON_MASK_ (0x0000007F) #define RX_DP_STOR (0x0D4) #define RX_DP_STORE_TOT_RXUSED_MASK_ (0xFFFF0000) #define RX_DP_STORE_UTX_RXUSED_MASK_ (0x0000FFFF) #define TX_DP_STOR (0x0D8) #define TX_DP_STORE_TOT_TXUSED_MASK_ (0xFFFF0000) #define TX_DP_STORE_URX_TXUSED_MASK_ (0x0000FFFF) #define LTM_BELT_IDLE0 (0x0E0) #define LTM_BELT_IDLE0_IDLE1000_ (0x0FFF0000) #define LTM_BELT_IDLE0_IDLE100_ (0x00000FFF) #define LTM_BELT_IDLE1 (0x0E4) #define LTM_BELT_IDLE1_IDLE10_ (0x00000FFF) #define LTM_BELT_ACT0 (0x0E8) #define LTM_BELT_ACT0_ACT1000_ (0x0FFF0000) #define LTM_BELT_ACT0_ACT100_ (0x00000FFF) #define LTM_BELT_ACT1 (0x0EC) #define LTM_BELT_ACT1_ACT10_ (0x00000FFF) #define LTM_INACTIVE0 (0x0F0) #define LTM_INACTIVE0_TIMER1000_ (0xFFFF0000) #define LTM_INACTIVE0_TIMER100_ (0x0000FFFF) #define LTM_INACTIVE1 (0x0F4) #define LTM_INACTIVE1_TIMER10_ (0x0000FFFF) #define MAC_CR (0x100) #define MAC_CR_GMII_EN_ (0x00080000) #define MAC_CR_EEE_TX_CLK_STOP_EN_ (0x00040000) #define MAC_CR_EEE_EN_ (0x00020000) #define MAC_CR_EEE_TLAR_EN_ (0x00010000) #define MAC_CR_ADP_ (0x00002000) #define MAC_CR_AUTO_DUPLEX_ (0x00001000) #define MAC_CR_AUTO_SPEED_ (0x00000800) #define MAC_CR_LOOPBACK_ (0x00000400) #define MAC_CR_BOLMT_MASK_ (0x000000C0) #define MAC_CR_FULL_DUPLEX_ (0x00000008) #define MAC_CR_SPEED_MASK_ (0x00000006) #define MAC_CR_SPEED_1000_ (0x00000004) #define MAC_CR_SPEED_100_ (0x00000002) #define MAC_CR_SPEED_10_ (0x00000000) #define MAC_CR_RST_ (0x00000001) #define MAC_RX (0x104) #define MAC_RX_MAX_SIZE_SHIFT_ (16) #define MAC_RX_MAX_SIZE_MASK_ (0x3FFF0000) #define MAC_RX_FCS_STRIP_ (0x00000010) #define MAC_RX_VLAN_FSE_ (0x00000004) #define MAC_RX_RXD_ (0x00000002) #define MAC_RX_RXEN_ (0x00000001) #define MAC_TX (0x108) #define MAC_TX_BAD_FCS_ (0x00000004) #define MAC_TX_TXD_ (0x00000002) #define MAC_TX_TXEN_ (0x00000001) #define FLOW (0x10C) #define FLOW_CR_FORCE_FC_ (0x80000000) #define FLOW_CR_TX_FCEN_ (0x40000000) #define FLOW_CR_RX_FCEN_ (0x20000000) #define FLOW_CR_FPF_ (0x10000000) #define FLOW_CR_FCPT_MASK_ (0x0000FFFF) #define RAND_SEED (0x110) #define RAND_SEED_MASK_ (0x0000FFFF) #define ERR_STS (0x114) #define ERR_STS_FERR_ (0x00000100) #define ERR_STS_LERR_ (0x00000080) #define ERR_STS_RFERR_ (0x00000040) #define ERR_STS_ECERR_ (0x00000010) #define ERR_STS_ALERR_ (0x00000008) #define ERR_STS_URERR_ (0x00000004) #define RX_ADDRH (0x118) #define RX_ADDRH_MASK_ (0x0000FFFF) #define RX_ADDRL (0x11C) #define RX_ADDRL_MASK_ (0xFFFFFFFF) #define MII_ACC (0x120) #define MII_ACC_PHY_ADDR_SHIFT_ (11) #define MII_ACC_PHY_ADDR_MASK_ (0x0000F800) #define MII_ACC_MIIRINDA_SHIFT_ (6) #define MII_ACC_MIIRINDA_MASK_ (0x000007C0) #define MII_ACC_MII_READ_ (0x00000000) #define MII_ACC_MII_WRITE_ (0x00000002) #define MII_ACC_MII_BUSY_ (0x00000001) #define MII_DATA (0x124) #define MII_DATA_MASK_ (0x0000FFFF) #define MAC_RGMII_ID (0x128) #define MAC_RGMII_ID_TXC_DELAY_EN_ (0x00000002) #define MAC_RGMII_ID_RXC_DELAY_EN_ (0x00000001) #define EEE_TX_LPI_REQ_DLY (0x130) #define EEE_TX_LPI_REQ_DLY_CNT_MASK_ (0xFFFFFFFF) #define EEE_TW_TX_SYS (0x134) #define EEE_TW_TX_SYS_CNT1G_MASK_ (0xFFFF0000) #define EEE_TW_TX_SYS_CNT100M_MASK_ (0x0000FFFF) #define EEE_TX_LPI_REM_DLY (0x138) #define EEE_TX_LPI_REM_DLY_CNT_ (0x00FFFFFF) #define WUCSR (0x140) #define WUCSR_TESTMODE_ (0x80000000) #define WUCSR_RFE_WAKE_EN_ (0x00004000) #define WUCSR_EEE_TX_WAKE_ (0x00002000) #define WUCSR_EEE_TX_WAKE_EN_ (0x00001000) #define WUCSR_EEE_RX_WAKE_ (0x00000800) #define WUCSR_EEE_RX_WAKE_EN_ (0x00000400) #define WUCSR_RFE_WAKE_FR_ (0x00000200) #define WUCSR_STORE_WAKE_ (0x00000100) #define WUCSR_PFDA_FR_ (0x00000080) #define WUCSR_WUFR_ (0x00000040) #define WUCSR_MPR_ (0x00000020) #define WUCSR_BCST_FR_ (0x00000010) #define WUCSR_PFDA_EN_ (0x00000008) #define WUCSR_WAKE_EN_ (0x00000004) #define WUCSR_MPEN_ (0x00000002) #define WUCSR_BCST_EN_ (0x00000001) #define WK_SRC (0x144) #define WK_SRC_GPIOX_INT_WK_SHIFT_ (20) #define WK_SRC_GPIOX_INT_WK_MASK_ (0xFFF00000) #define WK_SRC_IPV6_TCPSYN_RCD_WK_ (0x00010000) #define WK_SRC_IPV4_TCPSYN_RCD_WK_ (0x00008000) #define WK_SRC_EEE_TX_WK_ (0x00004000) #define WK_SRC_EEE_RX_WK_ (0x00002000) #define WK_SRC_GOOD_FR_WK_ (0x00001000) #define WK_SRC_PFDA_FR_WK_ (0x00000800) #define WK_SRC_MP_FR_WK_ (0x00000400) #define WK_SRC_BCAST_FR_WK_ (0x00000200) #define WK_SRC_WU_FR_WK_ (0x00000100) #define WK_SRC_WUFF_MATCH_MASK_ (0x0000001F) #define WUF_CFG0 (0x150) #define NUM_OF_WUF_CFG (32) #define WUF_CFG_BEGIN (WUF_CFG0) #define WUF_CFG(index) (WUF_CFG_BEGIN + (4 * (index))) #define WUF_CFGX_EN_ (0x80000000) #define WUF_CFGX_TYPE_MASK_ (0x03000000) #define WUF_CFGX_TYPE_MCAST_ (0x02000000) #define WUF_CFGX_TYPE_ALL_ (0x01000000) #define WUF_CFGX_TYPE_UCAST_ (0x00000000) #define WUF_CFGX_OFFSET_SHIFT_ (16) #define WUF_CFGX_OFFSET_MASK_ (0x00FF0000) #define WUF_CFGX_CRC16_MASK_ (0x0000FFFF) #define WUF_MASK0_0 (0x200) #define WUF_MASK0_1 (0x204) #define WUF_MASK0_2 (0x208) #define WUF_MASK0_3 (0x20C) #define NUM_OF_WUF_MASK (32) #define WUF_MASK0_BEGIN (WUF_MASK0_0) #define WUF_MASK1_BEGIN (WUF_MASK0_1) #define WUF_MASK2_BEGIN (WUF_MASK0_2) #define WUF_MASK3_BEGIN (WUF_MASK0_3) #define WUF_MASK0(index) (WUF_MASK0_BEGIN + (0x10 * (index))) #define WUF_MASK1(index) (WUF_MASK1_BEGIN + (0x10 * (index))) #define WUF_MASK2(index) (WUF_MASK2_BEGIN + (0x10 * (index))) #define WUF_MASK3(index) (WUF_MASK3_BEGIN + (0x10 * (index))) #define MAF_BASE (0x400) #define MAF_HIX (0x00) #define MAF_LOX (0x04) #define NUM_OF_MAF (33) #define MAF_HI_BEGIN (MAF_BASE + MAF_HIX) #define MAF_LO_BEGIN (MAF_BASE + MAF_LOX) #define MAF_HI(index) (MAF_BASE + (8 * (index)) + (MAF_HIX)) #define MAF_LO(index) (MAF_BASE + (8 * (index)) + (MAF_LOX)) #define MAF_HI_VALID_ (0x80000000) #define MAF_HI_TYPE_MASK_ (0x40000000) #define MAF_HI_TYPE_SRC_ (0x40000000) #define MAF_HI_TYPE_DST_ (0x00000000) #define MAF_HI_ADDR_MASK (0x0000FFFF) #define MAF_LO_ADDR_MASK (0xFFFFFFFF) #define WUCSR2 (0x600) #define WUCSR2_CSUM_DISABLE_ (0x80000000) #define WUCSR2_NA_SA_SEL_ (0x00000100) #define WUCSR2_NS_RCD_ (0x00000080) #define WUCSR2_ARP_RCD_ (0x00000040) #define WUCSR2_IPV6_TCPSYN_RCD_ (0x00000020) #define WUCSR2_IPV4_TCPSYN_RCD_ (0x00000010) #define WUCSR2_NS_OFFLOAD_EN_ (0x00000008) #define WUCSR2_ARP_OFFLOAD_EN_ (0x00000004) #define WUCSR2_IPV6_TCPSYN_WAKE_EN_ (0x00000002) #define WUCSR2_IPV4_TCPSYN_WAKE_EN_ (0x00000001) #define NS1_IPV6_ADDR_DEST0 (0x610) #define NS1_IPV6_ADDR_DEST1 (0x614) #define NS1_IPV6_ADDR_DEST2 (0x618) #define NS1_IPV6_ADDR_DEST3 (0x61C) #define NS1_IPV6_ADDR_SRC0 (0x620) #define NS1_IPV6_ADDR_SRC1 (0x624) #define NS1_IPV6_ADDR_SRC2 (0x628) #define NS1_IPV6_ADDR_SRC3 (0x62C) #define NS1_ICMPV6_ADDR0_0 (0x630) #define NS1_ICMPV6_ADDR0_1 (0x634) #define NS1_ICMPV6_ADDR0_2 (0x638) #define NS1_ICMPV6_ADDR0_3 (0x63C) #define NS1_ICMPV6_ADDR1_0 (0x640) #define NS1_ICMPV6_ADDR1_1 (0x644) #define NS1_ICMPV6_ADDR1_2 (0x648) #define NS1_ICMPV6_ADDR1_3 (0x64C) #define NS2_IPV6_ADDR_DEST0 (0x650) #define NS2_IPV6_ADDR_DEST1 (0x654) #define NS2_IPV6_ADDR_DEST2 (0x658) #define NS2_IPV6_ADDR_DEST3 (0x65C) #define NS2_IPV6_ADDR_SRC0 (0x660) #define NS2_IPV6_ADDR_SRC1 (0x664) #define NS2_IPV6_ADDR_SRC2 (0x668) #define NS2_IPV6_ADDR_SRC3 (0x66C) #define NS2_ICMPV6_ADDR0_0 (0x670) #define NS2_ICMPV6_ADDR0_1 (0x674) #define NS2_ICMPV6_ADDR0_2 (0x678) #define NS2_ICMPV6_ADDR0_3 (0x67C) #define NS2_ICMPV6_ADDR1_0 (0x680) #define NS2_ICMPV6_ADDR1_1 (0x684) #define NS2_ICMPV6_ADDR1_2 (0x688) #define NS2_ICMPV6_ADDR1_3 (0x68C) #define SYN_IPV4_ADDR_SRC (0x690) #define SYN_IPV4_ADDR_DEST (0x694) #define SYN_IPV4_TCP_PORTS (0x698) #define SYN_IPV4_TCP_PORTS_IPV4_DEST_PORT_SHIFT_ (16) #define SYN_IPV4_TCP_PORTS_IPV4_DEST_PORT_MASK_ (0xFFFF0000) #define SYN_IPV4_TCP_PORTS_IPV4_SRC_PORT_MASK_ (0x0000FFFF) #define SYN_IPV6_ADDR_SRC0 (0x69C) #define SYN_IPV6_ADDR_SRC1 (0x6A0) #define SYN_IPV6_ADDR_SRC2 (0x6A4) #define SYN_IPV6_ADDR_SRC3 (0x6A8) #define SYN_IPV6_ADDR_DEST0 (0x6AC) #define SYN_IPV6_ADDR_DEST1 (0x6B0) #define SYN_IPV6_ADDR_DEST2 (0x6B4) #define SYN_IPV6_ADDR_DEST3 (0x6B8) #define SYN_IPV6_TCP_PORTS (0x6BC) #define SYN_IPV6_TCP_PORTS_IPV6_DEST_PORT_SHIFT_ (16) #define SYN_IPV6_TCP_PORTS_IPV6_DEST_PORT_MASK_ (0xFFFF0000) #define SYN_IPV6_TCP_PORTS_IPV6_SRC_PORT_MASK_ (0x0000FFFF) #define ARP_SPA (0x6C0) #define ARP_TPA (0x6C4) #define PHY_DEV_ID (0x700) #define PHY_DEV_ID_REV_SHIFT_ (28) #define PHY_DEV_ID_REV_SHIFT_ (28) #define PHY_DEV_ID_REV_MASK_ (0xF0000000) #define PHY_DEV_ID_MODEL_SHIFT_ (22) #define PHY_DEV_ID_MODEL_MASK_ (0x0FC00000) #define PHY_DEV_ID_OUI_MASK_ (0x003FFFFF) #define RGMII_TX_BYP_DLL (0x708) #define RGMII_TX_BYP_DLL_TX_TUNE_ADJ_MASK_ (0x000FC00) #define RGMII_TX_BYP_DLL_TX_TUNE_SEL_MASK_ (0x00003F0) #define RGMII_TX_BYP_DLL_TX_DLL_RESET_ (0x0000002) #define RGMII_TX_BYP_DLL_TX_DLL_BYPASS_ (0x0000001) #define RGMII_RX_BYP_DLL (0x70C) #define RGMII_RX_BYP_DLL_RX_TUNE_ADJ_MASK_ (0x000FC00) #define RGMII_RX_BYP_DLL_RX_TUNE_SEL_MASK_ (0x00003F0) #define RGMII_RX_BYP_DLL_RX_DLL_RESET_ (0x0000002) #define RGMII_RX_BYP_DLL_RX_DLL_BYPASS_ (0x0000001) #define OTP_BASE_ADDR (0x00001000) #define OTP_ADDR_RANGE_ (0x1FF) #define OTP_PWR_DN (OTP_BASE_ADDR + 4 * 0x00) #define OTP_PWR_DN_PWRDN_N_ (0x01) #define OTP_ADDR1 (OTP_BASE_ADDR + 4 * 0x01) #define OTP_ADDR1_15_11 (0x1F) #define OTP_ADDR2 (OTP_BASE_ADDR + 4 * 0x02) #define OTP_ADDR2_10_3 (0xFF) #define OTP_ADDR3 (OTP_BASE_ADDR + 4 * 0x03) #define OTP_ADDR3_2_0 (0x03) #define OTP_PRGM_DATA (OTP_BASE_ADDR + 4 * 0x04) #define OTP_PRGM_MODE (OTP_BASE_ADDR + 4 * 0x05) #define OTP_PRGM_MODE_BYTE_ (0x01) #define OTP_RD_DATA (OTP_BASE_ADDR + 4 * 0x06) #define OTP_FUNC_CMD (OTP_BASE_ADDR + 4 * 0x08) #define OTP_FUNC_CMD_RESET_ (0x04) #define OTP_FUNC_CMD_PROGRAM_ (0x02) #define OTP_FUNC_CMD_READ_ (0x01) #define OTP_TST_CMD (OTP_BASE_ADDR + 4 * 0x09) #define OTP_TST_CMD_TEST_DEC_SEL_ (0x10) #define OTP_TST_CMD_PRGVRFY_ (0x08) #define OTP_TST_CMD_WRTEST_ (0x04) #define OTP_TST_CMD_TESTDEC_ (0x02) #define OTP_TST_CMD_BLANKCHECK_ (0x01) #define OTP_CMD_GO (OTP_BASE_ADDR + 4 * 0x0A) #define OTP_CMD_GO_GO_ (0x01) #define OTP_PASS_FAIL (OTP_BASE_ADDR + 4 * 0x0B) #define OTP_PASS_FAIL_PASS_ (0x02) #define OTP_PASS_FAIL_FAIL_ (0x01) #define OTP_STATUS (OTP_BASE_ADDR + 4 * 0x0C) #define OTP_STATUS_OTP_LOCK_ (0x10) #define OTP_STATUS_WEB_ (0x08) #define OTP_STATUS_PGMEN (0x04) #define OTP_STATUS_CPUMPEN_ (0x02) #define OTP_STATUS_BUSY_ (0x01) #define OTP_MAX_PRG (OTP_BASE_ADDR + 4 * 0x0D) #define OTP_MAX_PRG_MAX_PROG (0x1F) #define OTP_INTR_STATUS (OTP_BASE_ADDR + 4 * 0x10) #define OTP_INTR_STATUS_READY_ (0x01) #define OTP_INTR_MASK (OTP_BASE_ADDR + 4 * 0x11) #define OTP_INTR_MASK_READY_ (0x01) #define OTP_RSTB_PW1 (OTP_BASE_ADDR + 4 * 0x14) #define OTP_RSTB_PW2 (OTP_BASE_ADDR + 4 * 0x15) #define OTP_PGM_PW1 (OTP_BASE_ADDR + 4 * 0x18) #define OTP_PGM_PW2 (OTP_BASE_ADDR + 4 * 0x19) #define OTP_READ_PW1 (OTP_BASE_ADDR + 4 * 0x1C) #define OTP_READ_PW2 (OTP_BASE_ADDR + 4 * 0x1D) #define OTP_TCRST (OTP_BASE_ADDR + 4 * 0x20) #define OTP_RSRD (OTP_BASE_ADDR + 4 * 0x21) #define OTP_TREADEN_VAL (OTP_BASE_ADDR + 4 * 0x22) #define OTP_TDLES_VAL (OTP_BASE_ADDR + 4 * 0x23) #define OTP_TWWL_VAL (OTP_BASE_ADDR + 4 * 0x24) #define OTP_TDLEH_VAL (OTP_BASE_ADDR + 4 * 0x25) #define OTP_TWPED_VAL (OTP_BASE_ADDR + 4 * 0x26) #define OTP_TPES_VAL (OTP_BASE_ADDR + 4 * 0x27) #define OTP_TCPS_VAL (OTP_BASE_ADDR + 4 * 0x28) #define OTP_TCPH_VAL (OTP_BASE_ADDR + 4 * 0x29) #define OTP_TPGMVFY_VAL (OTP_BASE_ADDR + 4 * 0x2A) #define OTP_TPEH_VAL (OTP_BASE_ADDR + 4 * 0x2B) #define OTP_TPGRST_VAL (OTP_BASE_ADDR + 4 * 0x2C) #define OTP_TCLES_VAL (OTP_BASE_ADDR + 4 * 0x2D) #define OTP_TCLEH_VAL (OTP_BASE_ADDR + 4 * 0x2E) #define OTP_TRDES_VAL (OTP_BASE_ADDR + 4 * 0x2F) #define OTP_TBCACC_VAL (OTP_BASE_ADDR + 4 * 0x30) #define OTP_TAAC_VAL (OTP_BASE_ADDR + 4 * 0x31) #define OTP_TACCT_VAL (OTP_BASE_ADDR + 4 * 0x32) #define OTP_TRDEP_VAL (OTP_BASE_ADDR + 4 * 0x38) #define OTP_TPGSV_VAL (OTP_BASE_ADDR + 4 * 0x39) #define OTP_TPVSR_VAL (OTP_BASE_ADDR + 4 * 0x3A) #define OTP_TPVHR_VAL (OTP_BASE_ADDR + 4 * 0x3B) #define OTP_TPVSA_VAL (OTP_BASE_ADDR + 4 * 0x3C) #endif /* _LAN78XX_H */
null
null
null
null
92,746
66,767
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
66,767
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SYNC_FILE_SYSTEM_SYNC_FILE_SYSTEM_SERVICE_H_ #define CHROME_BROWSER_SYNC_FILE_SYSTEM_SYNC_FILE_SYSTEM_SERVICE_H_ #include <map> #include <memory> #include <string> #include <vector> #include "base/callback_forward.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "chrome/browser/sync_file_system/conflict_resolution_policy.h" #include "chrome/browser/sync_file_system/file_status_observer.h" #include "chrome/browser/sync_file_system/remote_file_sync_service.h" #include "chrome/browser/sync_file_system/sync_callbacks.h" #include "chrome/browser/sync_file_system/sync_process_runner.h" #include "chrome/browser/sync_file_system/sync_service_state.h" #include "chrome/browser/sync_file_system/task_logger.h" #include "components/keyed_service/core/keyed_service.h" #include "components/sync/driver/sync_service_observer.h" #include "extensions/browser/extension_registry_observer.h" #include "url/gurl.h" class Profile; namespace storage { class FileSystemContext; } namespace syncer { class SyncService; } namespace sync_file_system { class LocalFileSyncService; class LocalSyncRunner; class RemoteSyncRunner; class SyncEventObserver; class SyncFileSystemService : public KeyedService, public SyncProcessRunner::Client, public syncer::SyncServiceObserver, public FileStatusObserver, public extensions::ExtensionRegistryObserver, public base::SupportsWeakPtr<SyncFileSystemService> { public: typedef base::Callback<void(const base::ListValue&)> DumpFilesCallback; typedef base::Callback<void(const RemoteFileSyncService::OriginStatusMap&)> ExtensionStatusMapCallback; // KeyedService implementation. void Shutdown() override; void InitializeForApp(storage::FileSystemContext* file_system_context, const GURL& app_origin, const SyncStatusCallback& callback); void GetExtensionStatusMap(const ExtensionStatusMapCallback& callback); void DumpFiles(const GURL& origin, const DumpFilesCallback& callback); void DumpDatabase(const DumpFilesCallback& callback); // Returns the file |url|'s sync status. void GetFileSyncStatus(const storage::FileSystemURL& url, const SyncFileStatusCallback& callback); void AddSyncEventObserver(SyncEventObserver* observer); void RemoveSyncEventObserver(SyncEventObserver* observer); LocalChangeProcessor* GetLocalChangeProcessor(const GURL& origin); // SyncProcessRunner::Client implementations. void OnSyncIdle() override; SyncServiceState GetSyncServiceState() override; SyncFileSystemService* GetSyncService() override; void OnPromotionCompleted(int* num_running_jobs); void CheckIfIdle(); TaskLogger* task_logger() { return &task_logger_; } void CallOnIdleForTesting(const base::Closure& callback); private: friend class SyncFileSystemServiceFactory; friend class SyncFileSystemServiceTest; friend class SyncFileSystemTest; friend std::default_delete<SyncFileSystemService>; friend class LocalSyncRunner; friend class RemoteSyncRunner; explicit SyncFileSystemService(Profile* profile); ~SyncFileSystemService() override; void Initialize(std::unique_ptr<LocalFileSyncService> local_file_service, std::unique_ptr<RemoteFileSyncService> remote_file_service); // Callbacks for InitializeForApp. void DidInitializeFileSystem(const GURL& app_origin, const SyncStatusCallback& callback, SyncStatusCode status); void DidRegisterOrigin(const GURL& app_origin, const SyncStatusCallback& callback, SyncStatusCode status); void DidInitializeFileSystemForDump(const GURL& app_origin, const DumpFilesCallback& callback, SyncStatusCode status); void DidDumpFiles(const GURL& app_origin, const DumpFilesCallback& callback, std::unique_ptr<base::ListValue> files); void DidDumpDatabase(const DumpFilesCallback& callback, std::unique_ptr<base::ListValue> list); void DidGetExtensionStatusMap( const ExtensionStatusMapCallback& callback, std::unique_ptr<RemoteFileSyncService::OriginStatusMap> status_map); // Overrides sync_enabled_ setting. This should be called only by tests. void SetSyncEnabledForTesting(bool enabled); void DidGetLocalChangeStatus(const SyncFileStatusCallback& callback, SyncStatusCode status, bool has_pending_local_changes); void OnRemoteServiceStateUpdated(RemoteServiceState state, const std::string& description); // extensions::ExtensionRegistryObserver implementations. void OnExtensionInstalled(content::BrowserContext* browser_context, const extensions::Extension* extension, bool is_update) override; void OnExtensionUnloaded(content::BrowserContext* browser_context, const extensions::Extension* extension, extensions::UnloadedExtensionReason reason) override; void OnExtensionUninstalled(content::BrowserContext* browser_context, const extensions::Extension* extension, extensions::UninstallReason reason) override; void OnExtensionLoaded(content::BrowserContext* browser_context, const extensions::Extension* extension) override; // syncer::SyncServiceObserver implementation. void OnStateChanged(syncer::SyncService* sync) override; // SyncFileStatusObserver implementation. void OnFileStatusChanged(const storage::FileSystemURL& url, SyncFileType file_type, SyncFileStatus sync_status, SyncAction action_taken, SyncDirection direction) override; // Check the profile's sync preference settings and call // remote_file_service_->SetSyncEnabled() to update the status. // |profile_sync_service| must be non-null. void UpdateSyncEnabledStatus(syncer::SyncService* profile_sync_service); // Runs the SyncProcessRunner method of all sync runners (e.g. for Local sync // and Remote sync). void RunForEachSyncRunners(void(SyncProcessRunner::*method)()); Profile* profile_; std::unique_ptr<LocalFileSyncService> local_service_; std::unique_ptr<RemoteFileSyncService> remote_service_; // Holds all SyncProcessRunners. std::vector<std::unique_ptr<SyncProcessRunner>> local_sync_runners_; std::vector<std::unique_ptr<SyncProcessRunner>> remote_sync_runners_; // Indicates if sync is currently enabled or not. bool sync_enabled_; TaskLogger task_logger_; base::ObserverList<SyncEventObserver> observers_; bool promoting_demoted_changes_; base::Closure idle_callback_; DISALLOW_COPY_AND_ASSIGN(SyncFileSystemService); }; } // namespace sync_file_system #endif // CHROME_BROWSER_SYNC_FILE_SYSTEM_SYNC_FILE_SYSTEM_SERVICE_H_
null
null
null
null
63,630
36,861
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
201,856
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/******************************************************************************* * * Module Name: dbtest - Various debug-related tests * ******************************************************************************/ /* * Copyright (C) 2000 - 2017, Intel Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. */ #include <acpi/acpi.h> #include "accommon.h" #include "acdebug.h" #include "acnamesp.h" #include "acpredef.h" #define _COMPONENT ACPI_CA_DEBUGGER ACPI_MODULE_NAME("dbtest") /* Local prototypes */ static void acpi_db_test_all_objects(void); static acpi_status acpi_db_test_one_object(acpi_handle obj_handle, u32 nesting_level, void *context, void **return_value); static acpi_status acpi_db_test_integer_type(struct acpi_namespace_node *node, u32 bit_length); static acpi_status acpi_db_test_buffer_type(struct acpi_namespace_node *node, u32 bit_length); static acpi_status acpi_db_test_string_type(struct acpi_namespace_node *node, u32 byte_length); static acpi_status acpi_db_read_from_object(struct acpi_namespace_node *node, acpi_object_type expected_type, union acpi_object **value); static acpi_status acpi_db_write_to_object(struct acpi_namespace_node *node, union acpi_object *value); static void acpi_db_evaluate_all_predefined_names(char *count_arg); static acpi_status acpi_db_evaluate_one_predefined_name(acpi_handle obj_handle, u32 nesting_level, void *context, void **return_value); /* * Test subcommands */ static struct acpi_db_argument_info acpi_db_test_types[] = { {"OBJECTS"}, {"PREDEFINED"}, {NULL} /* Must be null terminated */ }; #define CMD_TEST_OBJECTS 0 #define CMD_TEST_PREDEFINED 1 #define BUFFER_FILL_VALUE 0xFF /* * Support for the special debugger read/write control methods. * These methods are installed into the current namespace and are * used to read and write the various namespace objects. The point * is to force the AML interpreter do all of the work. */ #define ACPI_DB_READ_METHOD "\\_T98" #define ACPI_DB_WRITE_METHOD "\\_T99" static acpi_handle read_handle = NULL; static acpi_handle write_handle = NULL; /* ASL Definitions of the debugger read/write control methods */ #if 0 definition_block("ssdt.aml", "SSDT", 2, "Intel", "DEBUG", 0x00000001) { method(_T98, 1, not_serialized) { /* Read */ return (de_ref_of(arg0)) } } definition_block("ssdt2.aml", "SSDT", 2, "Intel", "DEBUG", 0x00000001) { method(_T99, 2, not_serialized) { /* Write */ store(arg1, arg0) } } #endif static unsigned char read_method_code[] = { 0x53, 0x53, 0x44, 0x54, 0x2E, 0x00, 0x00, 0x00, /* 00000000 "SSDT...." */ 0x02, 0xC9, 0x49, 0x6E, 0x74, 0x65, 0x6C, 0x00, /* 00000008 "..Intel." */ 0x44, 0x45, 0x42, 0x55, 0x47, 0x00, 0x00, 0x00, /* 00000010 "DEBUG..." */ 0x01, 0x00, 0x00, 0x00, 0x49, 0x4E, 0x54, 0x4C, /* 00000018 "....INTL" */ 0x18, 0x12, 0x13, 0x20, 0x14, 0x09, 0x5F, 0x54, /* 00000020 "... .._T" */ 0x39, 0x38, 0x01, 0xA4, 0x83, 0x68 /* 00000028 "98...h" */ }; static unsigned char write_method_code[] = { 0x53, 0x53, 0x44, 0x54, 0x2E, 0x00, 0x00, 0x00, /* 00000000 "SSDT...." */ 0x02, 0x15, 0x49, 0x6E, 0x74, 0x65, 0x6C, 0x00, /* 00000008 "..Intel." */ 0x44, 0x45, 0x42, 0x55, 0x47, 0x00, 0x00, 0x00, /* 00000010 "DEBUG..." */ 0x01, 0x00, 0x00, 0x00, 0x49, 0x4E, 0x54, 0x4C, /* 00000018 "....INTL" */ 0x18, 0x12, 0x13, 0x20, 0x14, 0x09, 0x5F, 0x54, /* 00000020 "... .._T" */ 0x39, 0x39, 0x02, 0x70, 0x69, 0x68 /* 00000028 "99.pih" */ }; /******************************************************************************* * * FUNCTION: acpi_db_execute_test * * PARAMETERS: type_arg - Subcommand * * RETURN: None * * DESCRIPTION: Execute various debug tests. * * Note: Code is prepared for future expansion of the TEST command. * ******************************************************************************/ void acpi_db_execute_test(char *type_arg) { u32 temp; acpi_ut_strupr(type_arg); temp = acpi_db_match_argument(type_arg, acpi_db_test_types); if (temp == ACPI_TYPE_NOT_FOUND) { acpi_os_printf("Invalid or unsupported argument\n"); return; } switch (temp) { case CMD_TEST_OBJECTS: acpi_db_test_all_objects(); break; case CMD_TEST_PREDEFINED: acpi_db_evaluate_all_predefined_names(NULL); break; default: break; } } /******************************************************************************* * * FUNCTION: acpi_db_test_all_objects * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: This test implements the OBJECTS subcommand. It exercises the * namespace by reading/writing/comparing all data objects such * as integers, strings, buffers, fields, buffer fields, etc. * ******************************************************************************/ static void acpi_db_test_all_objects(void) { acpi_status status; /* Install the debugger read-object control method if necessary */ if (!read_handle) { status = acpi_install_method(read_method_code); if (ACPI_FAILURE(status)) { acpi_os_printf ("%s, Could not install debugger read method\n", acpi_format_exception(status)); return; } status = acpi_get_handle(NULL, ACPI_DB_READ_METHOD, &read_handle); if (ACPI_FAILURE(status)) { acpi_os_printf ("Could not obtain handle for debug method %s\n", ACPI_DB_READ_METHOD); return; } } /* Install the debugger write-object control method if necessary */ if (!write_handle) { status = acpi_install_method(write_method_code); if (ACPI_FAILURE(status)) { acpi_os_printf ("%s, Could not install debugger write method\n", acpi_format_exception(status)); return; } status = acpi_get_handle(NULL, ACPI_DB_WRITE_METHOD, &write_handle); if (ACPI_FAILURE(status)) { acpi_os_printf ("Could not obtain handle for debug method %s\n", ACPI_DB_WRITE_METHOD); return; } } /* Walk the entire namespace, testing each supported named data object */ (void)acpi_walk_namespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, acpi_db_test_one_object, NULL, NULL, NULL); } /******************************************************************************* * * FUNCTION: acpi_db_test_one_object * * PARAMETERS: acpi_walk_callback * * RETURN: Status * * DESCRIPTION: Test one namespace object. Supported types are Integer, * String, Buffer, buffer_field, and field_unit. All other object * types are simply ignored. * * Note: Support for Packages is not implemented. * ******************************************************************************/ static acpi_status acpi_db_test_one_object(acpi_handle obj_handle, u32 nesting_level, void *context, void **return_value) { struct acpi_namespace_node *node; union acpi_operand_object *obj_desc; union acpi_operand_object *region_obj; acpi_object_type local_type; u32 bit_length = 0; u32 byte_length = 0; acpi_status status = AE_OK; node = ACPI_CAST_PTR(struct acpi_namespace_node, obj_handle); obj_desc = node->object; /* * For the supported types, get the actual bit length or * byte length. Map the type to one of Integer/String/Buffer. */ switch (node->type) { case ACPI_TYPE_INTEGER: /* Integer width is either 32 or 64 */ local_type = ACPI_TYPE_INTEGER; bit_length = acpi_gbl_integer_bit_width; break; case ACPI_TYPE_STRING: local_type = ACPI_TYPE_STRING; byte_length = obj_desc->string.length; break; case ACPI_TYPE_BUFFER: local_type = ACPI_TYPE_BUFFER; byte_length = obj_desc->buffer.length; bit_length = byte_length * 8; break; case ACPI_TYPE_FIELD_UNIT: case ACPI_TYPE_BUFFER_FIELD: case ACPI_TYPE_LOCAL_REGION_FIELD: case ACPI_TYPE_LOCAL_INDEX_FIELD: case ACPI_TYPE_LOCAL_BANK_FIELD: local_type = ACPI_TYPE_INTEGER; if (obj_desc) { /* * Returned object will be a Buffer if the field length * is larger than the size of an Integer (32 or 64 bits * depending on the DSDT version). */ bit_length = obj_desc->common_field.bit_length; byte_length = ACPI_ROUND_BITS_UP_TO_BYTES(bit_length); if (bit_length > acpi_gbl_integer_bit_width) { local_type = ACPI_TYPE_BUFFER; } } break; default: /* Ignore all other types */ return (AE_OK); } /* Emit the common prefix: Type:Name */ acpi_os_printf("%14s: %4.4s", acpi_ut_get_type_name(node->type), node->name.ascii); if (!obj_desc) { acpi_os_printf(" Ignoring, no attached object\n"); return (AE_OK); } /* * Check for unsupported region types. Note: acpi_exec simulates * access to system_memory, system_IO, PCI_Config, and EC. */ switch (node->type) { case ACPI_TYPE_LOCAL_REGION_FIELD: region_obj = obj_desc->field.region_obj; switch (region_obj->region.space_id) { case ACPI_ADR_SPACE_SYSTEM_MEMORY: case ACPI_ADR_SPACE_SYSTEM_IO: case ACPI_ADR_SPACE_PCI_CONFIG: case ACPI_ADR_SPACE_EC: break; default: acpi_os_printf (" %s space is not supported [%4.4s]\n", acpi_ut_get_region_name(region_obj->region. space_id), region_obj->region.node->name.ascii); return (AE_OK); } break; default: break; } /* At this point, we have resolved the object to one of the major types */ switch (local_type) { case ACPI_TYPE_INTEGER: status = acpi_db_test_integer_type(node, bit_length); break; case ACPI_TYPE_STRING: status = acpi_db_test_string_type(node, byte_length); break; case ACPI_TYPE_BUFFER: status = acpi_db_test_buffer_type(node, bit_length); break; default: acpi_os_printf(" Ignoring, type not implemented (%2.2X)", local_type); break; } switch (node->type) { case ACPI_TYPE_LOCAL_REGION_FIELD: region_obj = obj_desc->field.region_obj; acpi_os_printf(" (%s)", acpi_ut_get_region_name(region_obj->region. space_id)); break; default: break; } acpi_os_printf("\n"); return (status); } /******************************************************************************* * * FUNCTION: acpi_db_test_integer_type * * PARAMETERS: node - Parent NS node for the object * bit_length - Actual length of the object. Used for * support of arbitrary length field_unit * and buffer_field objects. * * RETURN: Status * * DESCRIPTION: Test read/write for an Integer-valued object. Performs a * write/read/compare of an arbitrary new value, then performs * a write/read/compare of the original value. * ******************************************************************************/ static acpi_status acpi_db_test_integer_type(struct acpi_namespace_node *node, u32 bit_length) { union acpi_object *temp1 = NULL; union acpi_object *temp2 = NULL; union acpi_object *temp3 = NULL; union acpi_object write_value; u64 value_to_write; acpi_status status; if (bit_length > 64) { acpi_os_printf(" Invalid length for an Integer: %u", bit_length); return (AE_OK); } /* Read the original value */ status = acpi_db_read_from_object(node, ACPI_TYPE_INTEGER, &temp1); if (ACPI_FAILURE(status)) { return (status); } acpi_os_printf(" (%4.4X/%3.3X) %8.8X%8.8X", bit_length, ACPI_ROUND_BITS_UP_TO_BYTES(bit_length), ACPI_FORMAT_UINT64(temp1->integer.value)); value_to_write = ACPI_UINT64_MAX >> (64 - bit_length); if (temp1->integer.value == value_to_write) { value_to_write = 0; } /* Write a new value */ write_value.type = ACPI_TYPE_INTEGER; write_value.integer.value = value_to_write; status = acpi_db_write_to_object(node, &write_value); if (ACPI_FAILURE(status)) { goto exit; } /* Ensure that we can read back the new value */ status = acpi_db_read_from_object(node, ACPI_TYPE_INTEGER, &temp2); if (ACPI_FAILURE(status)) { goto exit; } if (temp2->integer.value != value_to_write) { acpi_os_printf(" MISMATCH 2: %8.8X%8.8X, expecting %8.8X%8.8X", ACPI_FORMAT_UINT64(temp2->integer.value), ACPI_FORMAT_UINT64(value_to_write)); } /* Write back the original value */ write_value.integer.value = temp1->integer.value; status = acpi_db_write_to_object(node, &write_value); if (ACPI_FAILURE(status)) { goto exit; } /* Ensure that we can read back the original value */ status = acpi_db_read_from_object(node, ACPI_TYPE_INTEGER, &temp3); if (ACPI_FAILURE(status)) { goto exit; } if (temp3->integer.value != temp1->integer.value) { acpi_os_printf(" MISMATCH 3: %8.8X%8.8X, expecting %8.8X%8.8X", ACPI_FORMAT_UINT64(temp3->integer.value), ACPI_FORMAT_UINT64(temp1->integer.value)); } exit: if (temp1) { acpi_os_free(temp1); } if (temp2) { acpi_os_free(temp2); } if (temp3) { acpi_os_free(temp3); } return (AE_OK); } /******************************************************************************* * * FUNCTION: acpi_db_test_buffer_type * * PARAMETERS: node - Parent NS node for the object * bit_length - Actual length of the object. * * RETURN: Status * * DESCRIPTION: Test read/write for an Buffer-valued object. Performs a * write/read/compare of an arbitrary new value, then performs * a write/read/compare of the original value. * ******************************************************************************/ static acpi_status acpi_db_test_buffer_type(struct acpi_namespace_node *node, u32 bit_length) { union acpi_object *temp1 = NULL; union acpi_object *temp2 = NULL; union acpi_object *temp3 = NULL; u8 *buffer; union acpi_object write_value; acpi_status status; u32 byte_length; u32 i; u8 extra_bits; byte_length = ACPI_ROUND_BITS_UP_TO_BYTES(bit_length); if (byte_length == 0) { acpi_os_printf(" Ignoring zero length buffer"); return (AE_OK); } /* Allocate a local buffer */ buffer = ACPI_ALLOCATE_ZEROED(byte_length); if (!buffer) { return (AE_NO_MEMORY); } /* Read the original value */ status = acpi_db_read_from_object(node, ACPI_TYPE_BUFFER, &temp1); if (ACPI_FAILURE(status)) { goto exit; } /* Emit a few bytes of the buffer */ acpi_os_printf(" (%4.4X/%3.3X)", bit_length, temp1->buffer.length); for (i = 0; ((i < 4) && (i < byte_length)); i++) { acpi_os_printf(" %2.2X", temp1->buffer.pointer[i]); } acpi_os_printf("... "); /* * Write a new value. * * Handle possible extra bits at the end of the buffer. Can * happen for field_units larger than an integer, but the bit * count is not an integral number of bytes. Zero out the * unused bits. */ memset(buffer, BUFFER_FILL_VALUE, byte_length); extra_bits = bit_length % 8; if (extra_bits) { buffer[byte_length - 1] = ACPI_MASK_BITS_ABOVE(extra_bits); } write_value.type = ACPI_TYPE_BUFFER; write_value.buffer.length = byte_length; write_value.buffer.pointer = buffer; status = acpi_db_write_to_object(node, &write_value); if (ACPI_FAILURE(status)) { goto exit; } /* Ensure that we can read back the new value */ status = acpi_db_read_from_object(node, ACPI_TYPE_BUFFER, &temp2); if (ACPI_FAILURE(status)) { goto exit; } if (memcmp(temp2->buffer.pointer, buffer, byte_length)) { acpi_os_printf(" MISMATCH 2: New buffer value"); } /* Write back the original value */ write_value.buffer.length = byte_length; write_value.buffer.pointer = temp1->buffer.pointer; status = acpi_db_write_to_object(node, &write_value); if (ACPI_FAILURE(status)) { goto exit; } /* Ensure that we can read back the original value */ status = acpi_db_read_from_object(node, ACPI_TYPE_BUFFER, &temp3); if (ACPI_FAILURE(status)) { goto exit; } if (memcmp(temp1->buffer.pointer, temp3->buffer.pointer, byte_length)) { acpi_os_printf(" MISMATCH 3: While restoring original buffer"); } exit: ACPI_FREE(buffer); if (temp1) { acpi_os_free(temp1); } if (temp2) { acpi_os_free(temp2); } if (temp3) { acpi_os_free(temp3); } return (status); } /******************************************************************************* * * FUNCTION: acpi_db_test_string_type * * PARAMETERS: node - Parent NS node for the object * byte_length - Actual length of the object. * * RETURN: Status * * DESCRIPTION: Test read/write for an String-valued object. Performs a * write/read/compare of an arbitrary new value, then performs * a write/read/compare of the original value. * ******************************************************************************/ static acpi_status acpi_db_test_string_type(struct acpi_namespace_node *node, u32 byte_length) { union acpi_object *temp1 = NULL; union acpi_object *temp2 = NULL; union acpi_object *temp3 = NULL; char *value_to_write = "Test String from AML Debugger"; union acpi_object write_value; acpi_status status; /* Read the original value */ status = acpi_db_read_from_object(node, ACPI_TYPE_STRING, &temp1); if (ACPI_FAILURE(status)) { return (status); } acpi_os_printf(" (%4.4X/%3.3X) \"%s\"", (temp1->string.length * 8), temp1->string.length, temp1->string.pointer); /* Write a new value */ write_value.type = ACPI_TYPE_STRING; write_value.string.length = strlen(value_to_write); write_value.string.pointer = value_to_write; status = acpi_db_write_to_object(node, &write_value); if (ACPI_FAILURE(status)) { goto exit; } /* Ensure that we can read back the new value */ status = acpi_db_read_from_object(node, ACPI_TYPE_STRING, &temp2); if (ACPI_FAILURE(status)) { goto exit; } if (strcmp(temp2->string.pointer, value_to_write)) { acpi_os_printf(" MISMATCH 2: %s, expecting %s", temp2->string.pointer, value_to_write); } /* Write back the original value */ write_value.string.length = strlen(temp1->string.pointer); write_value.string.pointer = temp1->string.pointer; status = acpi_db_write_to_object(node, &write_value); if (ACPI_FAILURE(status)) { goto exit; } /* Ensure that we can read back the original value */ status = acpi_db_read_from_object(node, ACPI_TYPE_STRING, &temp3); if (ACPI_FAILURE(status)) { goto exit; } if (strcmp(temp1->string.pointer, temp3->string.pointer)) { acpi_os_printf(" MISMATCH 3: %s, expecting %s", temp3->string.pointer, temp1->string.pointer); } exit: if (temp1) { acpi_os_free(temp1); } if (temp2) { acpi_os_free(temp2); } if (temp3) { acpi_os_free(temp3); } return (status); } /******************************************************************************* * * FUNCTION: acpi_db_read_from_object * * PARAMETERS: node - Parent NS node for the object * expected_type - Object type expected from the read * value - Where the value read is returned * * RETURN: Status * * DESCRIPTION: Performs a read from the specified object by invoking the * special debugger control method that reads the object. Thus, * the AML interpreter is doing all of the work, increasing the * validity of the test. * ******************************************************************************/ static acpi_status acpi_db_read_from_object(struct acpi_namespace_node *node, acpi_object_type expected_type, union acpi_object **value) { union acpi_object *ret_value; struct acpi_object_list param_objects; union acpi_object params[2]; struct acpi_buffer return_obj; acpi_status status; params[0].type = ACPI_TYPE_LOCAL_REFERENCE; params[0].reference.actual_type = node->type; params[0].reference.handle = ACPI_CAST_PTR(acpi_handle, node); param_objects.count = 1; param_objects.pointer = params; return_obj.length = ACPI_ALLOCATE_BUFFER; acpi_gbl_method_executing = TRUE; status = acpi_evaluate_object(read_handle, NULL, &param_objects, &return_obj); acpi_gbl_method_executing = FALSE; if (ACPI_FAILURE(status)) { acpi_os_printf("Could not read from object, %s", acpi_format_exception(status)); return (status); } ret_value = (union acpi_object *)return_obj.pointer; switch (ret_value->type) { case ACPI_TYPE_INTEGER: case ACPI_TYPE_BUFFER: case ACPI_TYPE_STRING: /* * Did we receive the type we wanted? Most important for the * Integer/Buffer case (when a field is larger than an Integer, * it should return a Buffer). */ if (ret_value->type != expected_type) { acpi_os_printf (" Type mismatch: Expected %s, Received %s", acpi_ut_get_type_name(expected_type), acpi_ut_get_type_name(ret_value->type)); return (AE_TYPE); } *value = ret_value; break; default: acpi_os_printf(" Unsupported return object type, %s", acpi_ut_get_type_name(ret_value->type)); acpi_os_free(return_obj.pointer); return (AE_TYPE); } return (status); } /******************************************************************************* * * FUNCTION: acpi_db_write_to_object * * PARAMETERS: node - Parent NS node for the object * value - Value to be written * * RETURN: Status * * DESCRIPTION: Performs a write to the specified object by invoking the * special debugger control method that writes the object. Thus, * the AML interpreter is doing all of the work, increasing the * validity of the test. * ******************************************************************************/ static acpi_status acpi_db_write_to_object(struct acpi_namespace_node *node, union acpi_object *value) { struct acpi_object_list param_objects; union acpi_object params[2]; acpi_status status; params[0].type = ACPI_TYPE_LOCAL_REFERENCE; params[0].reference.actual_type = node->type; params[0].reference.handle = ACPI_CAST_PTR(acpi_handle, node); /* Copy the incoming user parameter */ memcpy(&params[1], value, sizeof(union acpi_object)); param_objects.count = 2; param_objects.pointer = params; acpi_gbl_method_executing = TRUE; status = acpi_evaluate_object(write_handle, NULL, &param_objects, NULL); acpi_gbl_method_executing = FALSE; if (ACPI_FAILURE(status)) { acpi_os_printf("Could not write to object, %s", acpi_format_exception(status)); } return (status); } /******************************************************************************* * * FUNCTION: acpi_db_evaluate_all_predefined_names * * PARAMETERS: count_arg - Max number of methods to execute * * RETURN: None * * DESCRIPTION: Namespace batch execution. Execute predefined names in the * namespace, up to the max count, if specified. * ******************************************************************************/ static void acpi_db_evaluate_all_predefined_names(char *count_arg) { struct acpi_db_execute_walk info; info.count = 0; info.max_count = ACPI_UINT32_MAX; if (count_arg) { info.max_count = strtoul(count_arg, NULL, 0); } /* Search all nodes in namespace */ (void)acpi_walk_namespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT, ACPI_UINT32_MAX, acpi_db_evaluate_one_predefined_name, NULL, (void *)&info, NULL); acpi_os_printf("Evaluated %u predefined names in the namespace\n", info.count); } /******************************************************************************* * * FUNCTION: acpi_db_evaluate_one_predefined_name * * PARAMETERS: Callback from walk_namespace * * RETURN: Status * * DESCRIPTION: Batch execution module. Currently only executes predefined * ACPI names. * ******************************************************************************/ static acpi_status acpi_db_evaluate_one_predefined_name(acpi_handle obj_handle, u32 nesting_level, void *context, void **return_value) { struct acpi_namespace_node *node = (struct acpi_namespace_node *)obj_handle; struct acpi_db_execute_walk *info = (struct acpi_db_execute_walk *)context; char *pathname; const union acpi_predefined_info *predefined; struct acpi_device_info *obj_info; struct acpi_object_list param_objects; union acpi_object params[ACPI_METHOD_NUM_ARGS]; union acpi_object *this_param; struct acpi_buffer return_obj; acpi_status status; u16 arg_type_list; u8 arg_count; u8 arg_type; u32 i; /* The name must be a predefined ACPI name */ predefined = acpi_ut_match_predefined_method(node->name.ascii); if (!predefined) { return (AE_OK); } if (node->type == ACPI_TYPE_LOCAL_SCOPE) { return (AE_OK); } pathname = acpi_ns_get_normalized_pathname(node, TRUE); if (!pathname) { return (AE_OK); } /* Get the object info for number of method parameters */ status = acpi_get_object_info(obj_handle, &obj_info); if (ACPI_FAILURE(status)) { ACPI_FREE(pathname); return (status); } param_objects.count = 0; param_objects.pointer = NULL; if (obj_info->type == ACPI_TYPE_METHOD) { /* Setup default parameters (with proper types) */ arg_type_list = predefined->info.argument_list; arg_count = METHOD_GET_ARG_COUNT(arg_type_list); /* * Setup the ACPI-required number of arguments, regardless of what * the actual method defines. If there is a difference, then the * method is wrong and a warning will be issued during execution. */ this_param = params; for (i = 0; i < arg_count; i++) { arg_type = METHOD_GET_NEXT_TYPE(arg_type_list); this_param->type = arg_type; switch (arg_type) { case ACPI_TYPE_INTEGER: this_param->integer.value = 1; break; case ACPI_TYPE_STRING: this_param->string.pointer = "This is the default argument string"; this_param->string.length = strlen(this_param->string.pointer); break; case ACPI_TYPE_BUFFER: this_param->buffer.pointer = (u8 *)params; /* just a garbage buffer */ this_param->buffer.length = 48; break; case ACPI_TYPE_PACKAGE: this_param->package.elements = NULL; this_param->package.count = 0; break; default: acpi_os_printf ("%s: Unsupported argument type: %u\n", pathname, arg_type); break; } this_param++; } param_objects.count = arg_count; param_objects.pointer = params; } ACPI_FREE(obj_info); return_obj.pointer = NULL; return_obj.length = ACPI_ALLOCATE_BUFFER; /* Do the actual method execution */ acpi_gbl_method_executing = TRUE; status = acpi_evaluate_object(node, NULL, &param_objects, &return_obj); acpi_os_printf("%-32s returned %s\n", pathname, acpi_format_exception(status)); acpi_gbl_method_executing = FALSE; ACPI_FREE(pathname); /* Ignore status from method execution */ status = AE_OK; /* Update count, check if we have executed enough methods */ info->count++; if (info->count >= info->max_count) { status = AE_CTRL_TERMINATE; } return (status); }
null
null
null
null
110,203
30,332
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
195,327
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Rockchip PCIe PHY driver * * Copyright (C) 2016 Shawn Lin <shawn.lin@rock-chips.com> * Copyright (C) 2016 ROCKCHIP, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License. * * 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/clk.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_platform.h> #include <linux/phy/phy.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include <linux/reset.h> /* * The higher 16-bit of this register is used for write protection * only if BIT(x + 16) set to 1 the BIT(x) can be written. */ #define HIWORD_UPDATE(val, mask, shift) \ ((val) << (shift) | (mask) << ((shift) + 16)) #define PHY_MAX_LANE_NUM 4 #define PHY_CFG_DATA_SHIFT 7 #define PHY_CFG_ADDR_SHIFT 1 #define PHY_CFG_DATA_MASK 0xf #define PHY_CFG_ADDR_MASK 0x3f #define PHY_CFG_RD_MASK 0x3ff #define PHY_CFG_WR_ENABLE 1 #define PHY_CFG_WR_DISABLE 1 #define PHY_CFG_WR_SHIFT 0 #define PHY_CFG_WR_MASK 1 #define PHY_CFG_PLL_LOCK 0x10 #define PHY_CFG_CLK_TEST 0x10 #define PHY_CFG_CLK_SCC 0x12 #define PHY_CFG_SEPE_RATE BIT(3) #define PHY_CFG_PLL_100M BIT(3) #define PHY_PLL_LOCKED BIT(9) #define PHY_PLL_OUTPUT BIT(10) #define PHY_LANE_A_STATUS 0x30 #define PHY_LANE_B_STATUS 0x31 #define PHY_LANE_C_STATUS 0x32 #define PHY_LANE_D_STATUS 0x33 #define PHY_LANE_RX_DET_SHIFT 11 #define PHY_LANE_RX_DET_TH 0x1 #define PHY_LANE_IDLE_OFF 0x1 #define PHY_LANE_IDLE_MASK 0x1 #define PHY_LANE_IDLE_A_SHIFT 3 #define PHY_LANE_IDLE_B_SHIFT 4 #define PHY_LANE_IDLE_C_SHIFT 5 #define PHY_LANE_IDLE_D_SHIFT 6 struct rockchip_pcie_data { unsigned int pcie_conf; unsigned int pcie_status; unsigned int pcie_laneoff; }; struct rockchip_pcie_phy { struct rockchip_pcie_data *phy_data; struct regmap *reg_base; struct reset_control *phy_rst; struct clk *clk_pciephy_ref; }; static inline void phy_wr_cfg(struct rockchip_pcie_phy *rk_phy, u32 addr, u32 data) { regmap_write(rk_phy->reg_base, rk_phy->phy_data->pcie_conf, HIWORD_UPDATE(data, PHY_CFG_DATA_MASK, PHY_CFG_DATA_SHIFT) | HIWORD_UPDATE(addr, PHY_CFG_ADDR_MASK, PHY_CFG_ADDR_SHIFT)); udelay(1); regmap_write(rk_phy->reg_base, rk_phy->phy_data->pcie_conf, HIWORD_UPDATE(PHY_CFG_WR_ENABLE, PHY_CFG_WR_MASK, PHY_CFG_WR_SHIFT)); udelay(1); regmap_write(rk_phy->reg_base, rk_phy->phy_data->pcie_conf, HIWORD_UPDATE(PHY_CFG_WR_DISABLE, PHY_CFG_WR_MASK, PHY_CFG_WR_SHIFT)); } static inline u32 phy_rd_cfg(struct rockchip_pcie_phy *rk_phy, u32 addr) { u32 val; regmap_write(rk_phy->reg_base, rk_phy->phy_data->pcie_conf, HIWORD_UPDATE(addr, PHY_CFG_RD_MASK, PHY_CFG_ADDR_SHIFT)); regmap_read(rk_phy->reg_base, rk_phy->phy_data->pcie_status, &val); return val; } static int rockchip_pcie_phy_power_off(struct phy *phy) { struct rockchip_pcie_phy *rk_phy = phy_get_drvdata(phy); int err = 0; err = reset_control_assert(rk_phy->phy_rst); if (err) { dev_err(&phy->dev, "assert phy_rst err %d\n", err); return err; } return 0; } static int rockchip_pcie_phy_power_on(struct phy *phy) { struct rockchip_pcie_phy *rk_phy = phy_get_drvdata(phy); int err = 0; u32 status; unsigned long timeout; err = reset_control_deassert(rk_phy->phy_rst); if (err) { dev_err(&phy->dev, "deassert phy_rst err %d\n", err); return err; } regmap_write(rk_phy->reg_base, rk_phy->phy_data->pcie_conf, HIWORD_UPDATE(PHY_CFG_PLL_LOCK, PHY_CFG_ADDR_MASK, PHY_CFG_ADDR_SHIFT)); /* * No documented timeout value for phy operation below, * so we make it large enough here. And we use loop-break * method which should not be harmful. */ timeout = jiffies + msecs_to_jiffies(1000); err = -EINVAL; while (time_before(jiffies, timeout)) { regmap_read(rk_phy->reg_base, rk_phy->phy_data->pcie_status, &status); if (status & PHY_PLL_LOCKED) { dev_dbg(&phy->dev, "pll locked!\n"); err = 0; break; } msleep(20); } if (err) { dev_err(&phy->dev, "pll lock timeout!\n"); goto err_pll_lock; } phy_wr_cfg(rk_phy, PHY_CFG_CLK_TEST, PHY_CFG_SEPE_RATE); phy_wr_cfg(rk_phy, PHY_CFG_CLK_SCC, PHY_CFG_PLL_100M); err = -ETIMEDOUT; while (time_before(jiffies, timeout)) { regmap_read(rk_phy->reg_base, rk_phy->phy_data->pcie_status, &status); if (!(status & PHY_PLL_OUTPUT)) { dev_dbg(&phy->dev, "pll output enable done!\n"); err = 0; break; } msleep(20); } if (err) { dev_err(&phy->dev, "pll output enable timeout!\n"); goto err_pll_lock; } regmap_write(rk_phy->reg_base, rk_phy->phy_data->pcie_conf, HIWORD_UPDATE(PHY_CFG_PLL_LOCK, PHY_CFG_ADDR_MASK, PHY_CFG_ADDR_SHIFT)); err = -EINVAL; while (time_before(jiffies, timeout)) { regmap_read(rk_phy->reg_base, rk_phy->phy_data->pcie_status, &status); if (status & PHY_PLL_LOCKED) { dev_dbg(&phy->dev, "pll relocked!\n"); err = 0; break; } msleep(20); } if (err) { dev_err(&phy->dev, "pll relock timeout!\n"); goto err_pll_lock; } return 0; err_pll_lock: reset_control_assert(rk_phy->phy_rst); return err; } static int rockchip_pcie_phy_init(struct phy *phy) { struct rockchip_pcie_phy *rk_phy = phy_get_drvdata(phy); int err = 0; err = clk_prepare_enable(rk_phy->clk_pciephy_ref); if (err) { dev_err(&phy->dev, "Fail to enable pcie ref clock.\n"); goto err_refclk; } err = reset_control_assert(rk_phy->phy_rst); if (err) { dev_err(&phy->dev, "assert phy_rst err %d\n", err); goto err_reset; } return err; err_reset: clk_disable_unprepare(rk_phy->clk_pciephy_ref); err_refclk: return err; } static int rockchip_pcie_phy_exit(struct phy *phy) { struct rockchip_pcie_phy *rk_phy = phy_get_drvdata(phy); clk_disable_unprepare(rk_phy->clk_pciephy_ref); return 0; } static const struct phy_ops ops = { .init = rockchip_pcie_phy_init, .exit = rockchip_pcie_phy_exit, .power_on = rockchip_pcie_phy_power_on, .power_off = rockchip_pcie_phy_power_off, .owner = THIS_MODULE, }; static const struct rockchip_pcie_data rk3399_pcie_data = { .pcie_conf = 0xe220, .pcie_status = 0xe2a4, .pcie_laneoff = 0xe214, }; static const struct of_device_id rockchip_pcie_phy_dt_ids[] = { { .compatible = "rockchip,rk3399-pcie-phy", .data = &rk3399_pcie_data, }, {} }; MODULE_DEVICE_TABLE(of, rockchip_pcie_phy_dt_ids); static int rockchip_pcie_phy_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct rockchip_pcie_phy *rk_phy; struct phy *generic_phy; struct phy_provider *phy_provider; struct regmap *grf; const struct of_device_id *of_id; grf = syscon_node_to_regmap(dev->parent->of_node); if (IS_ERR(grf)) { dev_err(dev, "Cannot find GRF syscon\n"); return PTR_ERR(grf); } rk_phy = devm_kzalloc(dev, sizeof(*rk_phy), GFP_KERNEL); if (!rk_phy) return -ENOMEM; of_id = of_match_device(rockchip_pcie_phy_dt_ids, &pdev->dev); if (!of_id) return -EINVAL; rk_phy->phy_data = (struct rockchip_pcie_data *)of_id->data; rk_phy->reg_base = grf; rk_phy->phy_rst = devm_reset_control_get(dev, "phy"); if (IS_ERR(rk_phy->phy_rst)) { if (PTR_ERR(rk_phy->phy_rst) != -EPROBE_DEFER) dev_err(dev, "missing phy property for reset controller\n"); return PTR_ERR(rk_phy->phy_rst); } rk_phy->clk_pciephy_ref = devm_clk_get(dev, "refclk"); if (IS_ERR(rk_phy->clk_pciephy_ref)) { dev_err(dev, "refclk not found.\n"); return PTR_ERR(rk_phy->clk_pciephy_ref); } generic_phy = devm_phy_create(dev, dev->of_node, &ops); if (IS_ERR(generic_phy)) { dev_err(dev, "failed to create PHY\n"); return PTR_ERR(generic_phy); } phy_set_drvdata(generic_phy, rk_phy); phy_provider = devm_of_phy_provider_register(dev, of_phy_simple_xlate); return PTR_ERR_OR_ZERO(phy_provider); } static struct platform_driver rockchip_pcie_driver = { .probe = rockchip_pcie_phy_probe, .driver = { .name = "rockchip-pcie-phy", .of_match_table = rockchip_pcie_phy_dt_ids, }, }; module_platform_driver(rockchip_pcie_driver); MODULE_AUTHOR("Shawn Lin <shawn.lin@rock-chips.com>"); MODULE_DESCRIPTION("Rockchip PCIe PHY driver"); MODULE_LICENSE("GPL v2");
null
null
null
null
103,674
9,088
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
174,083
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * OMAP3 Voltage Controller (VC) data * * Copyright (C) 2007, 2010 Texas Instruments, Inc. * Rajendra Nayak <rnayak@ti.com> * Lesly A M <x0080970@ti.com> * Thara Gopinath <thara@ti.com> * * Copyright (C) 2008, 2011 Nokia Corporation * Kalle Jokiniemi * Paul Walmsley * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/io.h> #include <linux/err.h> #include <linux/init.h> #include "common.h" #include "prm-regbits-34xx.h" #include "voltage.h" #include "vc.h" /* * VC data common to 34xx/36xx chips * XXX This stuff presumably belongs in the vc3xxx.c or vc.c file. */ static struct omap_vc_common omap3_vc_common = { .bypass_val_reg = OMAP3_PRM_VC_BYPASS_VAL_OFFSET, .data_shift = OMAP3430_DATA_SHIFT, .slaveaddr_shift = OMAP3430_SLAVEADDR_SHIFT, .regaddr_shift = OMAP3430_REGADDR_SHIFT, .valid = OMAP3430_VALID_MASK, .cmd_on_shift = OMAP3430_VC_CMD_ON_SHIFT, .cmd_on_mask = OMAP3430_VC_CMD_ON_MASK, .cmd_onlp_shift = OMAP3430_VC_CMD_ONLP_SHIFT, .cmd_ret_shift = OMAP3430_VC_CMD_RET_SHIFT, .cmd_off_shift = OMAP3430_VC_CMD_OFF_SHIFT, .i2c_cfg_clear_mask = OMAP3430_SREN_MASK | OMAP3430_HSEN_MASK, .i2c_cfg_hsen_mask = OMAP3430_HSEN_MASK, .i2c_cfg_reg = OMAP3_PRM_VC_I2C_CFG_OFFSET, .i2c_mcode_mask = OMAP3430_MCODE_MASK, }; struct omap_vc_channel omap3_vc_mpu = { .flags = OMAP_VC_CHANNEL_DEFAULT, .common = &omap3_vc_common, .smps_sa_reg = OMAP3_PRM_VC_SMPS_SA_OFFSET, .smps_volra_reg = OMAP3_PRM_VC_SMPS_VOL_RA_OFFSET, .smps_cmdra_reg = OMAP3_PRM_VC_SMPS_CMD_RA_OFFSET, .cfg_channel_reg = OMAP3_PRM_VC_CH_CONF_OFFSET, .cmdval_reg = OMAP3_PRM_VC_CMD_VAL_0_OFFSET, .smps_sa_mask = OMAP3430_PRM_VC_SMPS_SA_SA0_MASK, .smps_volra_mask = OMAP3430_VOLRA0_MASK, .smps_cmdra_mask = OMAP3430_CMDRA0_MASK, .cfg_channel_sa_shift = OMAP3430_PRM_VC_SMPS_SA_SA0_SHIFT, }; struct omap_vc_channel omap3_vc_core = { .common = &omap3_vc_common, .smps_sa_reg = OMAP3_PRM_VC_SMPS_SA_OFFSET, .smps_volra_reg = OMAP3_PRM_VC_SMPS_VOL_RA_OFFSET, .smps_cmdra_reg = OMAP3_PRM_VC_SMPS_CMD_RA_OFFSET, .cfg_channel_reg = OMAP3_PRM_VC_CH_CONF_OFFSET, .cmdval_reg = OMAP3_PRM_VC_CMD_VAL_1_OFFSET, .smps_sa_mask = OMAP3430_PRM_VC_SMPS_SA_SA1_MASK, .smps_volra_mask = OMAP3430_VOLRA1_MASK, .smps_cmdra_mask = OMAP3430_CMDRA1_MASK, .cfg_channel_sa_shift = OMAP3430_PRM_VC_SMPS_SA_SA1_SHIFT, }; /* * Voltage levels for different operating modes: on, sleep, retention and off */ #define OMAP3_ON_VOLTAGE_UV 1200000 #define OMAP3_ONLP_VOLTAGE_UV 1000000 #define OMAP3_RET_VOLTAGE_UV 975000 #define OMAP3_OFF_VOLTAGE_UV 600000 struct omap_vc_param omap3_mpu_vc_data = { .on = OMAP3_ON_VOLTAGE_UV, .onlp = OMAP3_ONLP_VOLTAGE_UV, .ret = OMAP3_RET_VOLTAGE_UV, .off = OMAP3_OFF_VOLTAGE_UV, }; struct omap_vc_param omap3_core_vc_data = { .on = OMAP3_ON_VOLTAGE_UV, .onlp = OMAP3_ONLP_VOLTAGE_UV, .ret = OMAP3_RET_VOLTAGE_UV, .off = OMAP3_OFF_VOLTAGE_UV, };
null
null
null
null
82,430
23,069
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
188,064
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * bq2415x charger driver * * Copyright (C) 2011-2013 Pali Rohár <pali.rohar@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 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. * * Datasheets: * http://www.ti.com/product/bq24150 * http://www.ti.com/product/bq24150a * http://www.ti.com/product/bq24152 * http://www.ti.com/product/bq24153 * http://www.ti.com/product/bq24153a * http://www.ti.com/product/bq24155 * http://www.ti.com/product/bq24157s * http://www.ti.com/product/bq24158 */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/param.h> #include <linux/err.h> #include <linux/workqueue.h> #include <linux/sysfs.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/idr.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/power/bq2415x_charger.h> /* timeout for resetting chip timer */ #define BQ2415X_TIMER_TIMEOUT 10 #define BQ2415X_REG_STATUS 0x00 #define BQ2415X_REG_CONTROL 0x01 #define BQ2415X_REG_VOLTAGE 0x02 #define BQ2415X_REG_VENDER 0x03 #define BQ2415X_REG_CURRENT 0x04 /* reset state for all registers */ #define BQ2415X_RESET_STATUS BIT(6) #define BQ2415X_RESET_CONTROL (BIT(4)|BIT(5)) #define BQ2415X_RESET_VOLTAGE (BIT(1)|BIT(3)) #define BQ2415X_RESET_CURRENT (BIT(0)|BIT(3)|BIT(7)) /* status register */ #define BQ2415X_BIT_TMR_RST 7 #define BQ2415X_BIT_OTG 7 #define BQ2415X_BIT_EN_STAT 6 #define BQ2415X_MASK_STAT (BIT(4)|BIT(5)) #define BQ2415X_SHIFT_STAT 4 #define BQ2415X_BIT_BOOST 3 #define BQ2415X_MASK_FAULT (BIT(0)|BIT(1)|BIT(2)) #define BQ2415X_SHIFT_FAULT 0 /* control register */ #define BQ2415X_MASK_LIMIT (BIT(6)|BIT(7)) #define BQ2415X_SHIFT_LIMIT 6 #define BQ2415X_MASK_VLOWV (BIT(4)|BIT(5)) #define BQ2415X_SHIFT_VLOWV 4 #define BQ2415X_BIT_TE 3 #define BQ2415X_BIT_CE 2 #define BQ2415X_BIT_HZ_MODE 1 #define BQ2415X_BIT_OPA_MODE 0 /* voltage register */ #define BQ2415X_MASK_VO (BIT(2)|BIT(3)|BIT(4)|BIT(5)|BIT(6)|BIT(7)) #define BQ2415X_SHIFT_VO 2 #define BQ2415X_BIT_OTG_PL 1 #define BQ2415X_BIT_OTG_EN 0 /* vender register */ #define BQ2415X_MASK_VENDER (BIT(5)|BIT(6)|BIT(7)) #define BQ2415X_SHIFT_VENDER 5 #define BQ2415X_MASK_PN (BIT(3)|BIT(4)) #define BQ2415X_SHIFT_PN 3 #define BQ2415X_MASK_REVISION (BIT(0)|BIT(1)|BIT(2)) #define BQ2415X_SHIFT_REVISION 0 /* current register */ #define BQ2415X_MASK_RESET BIT(7) #define BQ2415X_MASK_VI_CHRG (BIT(4)|BIT(5)|BIT(6)) #define BQ2415X_SHIFT_VI_CHRG 4 /* N/A BIT(3) */ #define BQ2415X_MASK_VI_TERM (BIT(0)|BIT(1)|BIT(2)) #define BQ2415X_SHIFT_VI_TERM 0 enum bq2415x_command { BQ2415X_TIMER_RESET, BQ2415X_OTG_STATUS, BQ2415X_STAT_PIN_STATUS, BQ2415X_STAT_PIN_ENABLE, BQ2415X_STAT_PIN_DISABLE, BQ2415X_CHARGE_STATUS, BQ2415X_BOOST_STATUS, BQ2415X_FAULT_STATUS, BQ2415X_CHARGE_TERMINATION_STATUS, BQ2415X_CHARGE_TERMINATION_ENABLE, BQ2415X_CHARGE_TERMINATION_DISABLE, BQ2415X_CHARGER_STATUS, BQ2415X_CHARGER_ENABLE, BQ2415X_CHARGER_DISABLE, BQ2415X_HIGH_IMPEDANCE_STATUS, BQ2415X_HIGH_IMPEDANCE_ENABLE, BQ2415X_HIGH_IMPEDANCE_DISABLE, BQ2415X_BOOST_MODE_STATUS, BQ2415X_BOOST_MODE_ENABLE, BQ2415X_BOOST_MODE_DISABLE, BQ2415X_OTG_LEVEL, BQ2415X_OTG_ACTIVATE_HIGH, BQ2415X_OTG_ACTIVATE_LOW, BQ2415X_OTG_PIN_STATUS, BQ2415X_OTG_PIN_ENABLE, BQ2415X_OTG_PIN_DISABLE, BQ2415X_VENDER_CODE, BQ2415X_PART_NUMBER, BQ2415X_REVISION, }; enum bq2415x_chip { BQUNKNOWN, BQ24150, BQ24150A, BQ24151, BQ24151A, BQ24152, BQ24153, BQ24153A, BQ24155, BQ24156, BQ24156A, BQ24157S, BQ24158, }; static char *bq2415x_chip_name[] = { "unknown", "bq24150", "bq24150a", "bq24151", "bq24151a", "bq24152", "bq24153", "bq24153a", "bq24155", "bq24156", "bq24156a", "bq24157s", "bq24158", }; struct bq2415x_device { struct device *dev; struct bq2415x_platform_data init_data; struct power_supply *charger; struct power_supply_desc charger_desc; struct delayed_work work; struct device_node *notify_node; struct notifier_block nb; enum bq2415x_mode reported_mode;/* mode reported by hook function */ enum bq2415x_mode mode; /* currently configured mode */ enum bq2415x_chip chip; const char *timer_error; char *model; char *name; int autotimer; /* 1 - if driver automatically reset timer, 0 - not */ int automode; /* 1 - enabled, 0 - disabled; -1 - not supported */ int id; }; /* each registered chip must have unique id */ static DEFINE_IDR(bq2415x_id); static DEFINE_MUTEX(bq2415x_id_mutex); static DEFINE_MUTEX(bq2415x_timer_mutex); static DEFINE_MUTEX(bq2415x_i2c_mutex); /**** i2c read functions ****/ /* read value from register */ static int bq2415x_i2c_read(struct bq2415x_device *bq, u8 reg) { struct i2c_client *client = to_i2c_client(bq->dev); struct i2c_msg msg[2]; u8 val; int ret; if (!client->adapter) return -ENODEV; msg[0].addr = client->addr; msg[0].flags = 0; msg[0].buf = &reg; msg[0].len = sizeof(reg); msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].buf = &val; msg[1].len = sizeof(val); mutex_lock(&bq2415x_i2c_mutex); ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); mutex_unlock(&bq2415x_i2c_mutex); if (ret < 0) return ret; return val; } /* read value from register, apply mask and right shift it */ static int bq2415x_i2c_read_mask(struct bq2415x_device *bq, u8 reg, u8 mask, u8 shift) { int ret; if (shift > 8) return -EINVAL; ret = bq2415x_i2c_read(bq, reg); if (ret < 0) return ret; return (ret & mask) >> shift; } /* read value from register and return one specified bit */ static int bq2415x_i2c_read_bit(struct bq2415x_device *bq, u8 reg, u8 bit) { if (bit > 8) return -EINVAL; return bq2415x_i2c_read_mask(bq, reg, BIT(bit), bit); } /**** i2c write functions ****/ /* write value to register */ static int bq2415x_i2c_write(struct bq2415x_device *bq, u8 reg, u8 val) { struct i2c_client *client = to_i2c_client(bq->dev); struct i2c_msg msg[1]; u8 data[2]; int ret; data[0] = reg; data[1] = val; msg[0].addr = client->addr; msg[0].flags = 0; msg[0].buf = data; msg[0].len = ARRAY_SIZE(data); mutex_lock(&bq2415x_i2c_mutex); ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); mutex_unlock(&bq2415x_i2c_mutex); /* i2c_transfer returns number of messages transferred */ if (ret < 0) return ret; else if (ret != 1) return -EIO; return 0; } /* read value from register, change it with mask left shifted and write back */ static int bq2415x_i2c_write_mask(struct bq2415x_device *bq, u8 reg, u8 val, u8 mask, u8 shift) { int ret; if (shift > 8) return -EINVAL; ret = bq2415x_i2c_read(bq, reg); if (ret < 0) return ret; ret &= ~mask; ret |= val << shift; return bq2415x_i2c_write(bq, reg, ret); } /* change only one bit in register */ static int bq2415x_i2c_write_bit(struct bq2415x_device *bq, u8 reg, bool val, u8 bit) { if (bit > 8) return -EINVAL; return bq2415x_i2c_write_mask(bq, reg, val, BIT(bit), bit); } /**** global functions ****/ /* exec command function */ static int bq2415x_exec_command(struct bq2415x_device *bq, enum bq2415x_command command) { int ret; switch (command) { case BQ2415X_TIMER_RESET: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_STATUS, 1, BQ2415X_BIT_TMR_RST); case BQ2415X_OTG_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_STATUS, BQ2415X_BIT_OTG); case BQ2415X_STAT_PIN_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_STATUS, BQ2415X_BIT_EN_STAT); case BQ2415X_STAT_PIN_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_STATUS, 1, BQ2415X_BIT_EN_STAT); case BQ2415X_STAT_PIN_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_STATUS, 0, BQ2415X_BIT_EN_STAT); case BQ2415X_CHARGE_STATUS: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_STATUS, BQ2415X_MASK_STAT, BQ2415X_SHIFT_STAT); case BQ2415X_BOOST_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_STATUS, BQ2415X_BIT_BOOST); case BQ2415X_FAULT_STATUS: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_STATUS, BQ2415X_MASK_FAULT, BQ2415X_SHIFT_FAULT); case BQ2415X_CHARGE_TERMINATION_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_CONTROL, BQ2415X_BIT_TE); case BQ2415X_CHARGE_TERMINATION_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 1, BQ2415X_BIT_TE); case BQ2415X_CHARGE_TERMINATION_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 0, BQ2415X_BIT_TE); case BQ2415X_CHARGER_STATUS: ret = bq2415x_i2c_read_bit(bq, BQ2415X_REG_CONTROL, BQ2415X_BIT_CE); if (ret < 0) return ret; return ret > 0 ? 0 : 1; case BQ2415X_CHARGER_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 0, BQ2415X_BIT_CE); case BQ2415X_CHARGER_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 1, BQ2415X_BIT_CE); case BQ2415X_HIGH_IMPEDANCE_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_CONTROL, BQ2415X_BIT_HZ_MODE); case BQ2415X_HIGH_IMPEDANCE_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 1, BQ2415X_BIT_HZ_MODE); case BQ2415X_HIGH_IMPEDANCE_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 0, BQ2415X_BIT_HZ_MODE); case BQ2415X_BOOST_MODE_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_CONTROL, BQ2415X_BIT_OPA_MODE); case BQ2415X_BOOST_MODE_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 1, BQ2415X_BIT_OPA_MODE); case BQ2415X_BOOST_MODE_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 0, BQ2415X_BIT_OPA_MODE); case BQ2415X_OTG_LEVEL: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_VOLTAGE, BQ2415X_BIT_OTG_PL); case BQ2415X_OTG_ACTIVATE_HIGH: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_VOLTAGE, 1, BQ2415X_BIT_OTG_PL); case BQ2415X_OTG_ACTIVATE_LOW: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_VOLTAGE, 0, BQ2415X_BIT_OTG_PL); case BQ2415X_OTG_PIN_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_VOLTAGE, BQ2415X_BIT_OTG_EN); case BQ2415X_OTG_PIN_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_VOLTAGE, 1, BQ2415X_BIT_OTG_EN); case BQ2415X_OTG_PIN_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_VOLTAGE, 0, BQ2415X_BIT_OTG_EN); case BQ2415X_VENDER_CODE: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_VENDER, BQ2415X_MASK_VENDER, BQ2415X_SHIFT_VENDER); case BQ2415X_PART_NUMBER: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_VENDER, BQ2415X_MASK_PN, BQ2415X_SHIFT_PN); case BQ2415X_REVISION: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_VENDER, BQ2415X_MASK_REVISION, BQ2415X_SHIFT_REVISION); } return -EINVAL; } /* detect chip type */ static enum bq2415x_chip bq2415x_detect_chip(struct bq2415x_device *bq) { struct i2c_client *client = to_i2c_client(bq->dev); int ret = bq2415x_exec_command(bq, BQ2415X_PART_NUMBER); if (ret < 0) return ret; switch (client->addr) { case 0x6b: switch (ret) { case 0: if (bq->chip == BQ24151A) return bq->chip; return BQ24151; case 1: if (bq->chip == BQ24150A || bq->chip == BQ24152 || bq->chip == BQ24155) return bq->chip; return BQ24150; case 2: if (bq->chip == BQ24153A) return bq->chip; return BQ24153; default: return BQUNKNOWN; } break; case 0x6a: switch (ret) { case 0: if (bq->chip == BQ24156A) return bq->chip; return BQ24156; case 2: if (bq->chip == BQ24157S) return bq->chip; return BQ24158; default: return BQUNKNOWN; } break; } return BQUNKNOWN; } /* detect chip revision */ static int bq2415x_detect_revision(struct bq2415x_device *bq) { int ret = bq2415x_exec_command(bq, BQ2415X_REVISION); int chip = bq2415x_detect_chip(bq); if (ret < 0 || chip < 0) return -1; switch (chip) { case BQ24150: case BQ24150A: case BQ24151: case BQ24151A: case BQ24152: if (ret >= 0 && ret <= 3) return ret; return -1; case BQ24153: case BQ24153A: case BQ24156: case BQ24156A: case BQ24157S: case BQ24158: if (ret == 3) return 0; else if (ret == 1) return 1; return -1; case BQ24155: if (ret == 3) return 3; return -1; case BQUNKNOWN: return -1; } return -1; } /* return chip vender code */ static int bq2415x_get_vender_code(struct bq2415x_device *bq) { int ret; ret = bq2415x_exec_command(bq, BQ2415X_VENDER_CODE); if (ret < 0) return 0; /* convert to binary */ return (ret & 0x1) + ((ret >> 1) & 0x1) * 10 + ((ret >> 2) & 0x1) * 100; } /* reset all chip registers to default state */ static void bq2415x_reset_chip(struct bq2415x_device *bq) { bq2415x_i2c_write(bq, BQ2415X_REG_CURRENT, BQ2415X_RESET_CURRENT); bq2415x_i2c_write(bq, BQ2415X_REG_VOLTAGE, BQ2415X_RESET_VOLTAGE); bq2415x_i2c_write(bq, BQ2415X_REG_CONTROL, BQ2415X_RESET_CONTROL); bq2415x_i2c_write(bq, BQ2415X_REG_STATUS, BQ2415X_RESET_STATUS); bq->timer_error = NULL; } /**** properties functions ****/ /* set current limit in mA */ static int bq2415x_set_current_limit(struct bq2415x_device *bq, int mA) { int val; if (mA <= 100) val = 0; else if (mA <= 500) val = 1; else if (mA <= 800) val = 2; else val = 3; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_CONTROL, val, BQ2415X_MASK_LIMIT, BQ2415X_SHIFT_LIMIT); } /* get current limit in mA */ static int bq2415x_get_current_limit(struct bq2415x_device *bq) { int ret; ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_CONTROL, BQ2415X_MASK_LIMIT, BQ2415X_SHIFT_LIMIT); if (ret < 0) return ret; else if (ret == 0) return 100; else if (ret == 1) return 500; else if (ret == 2) return 800; else if (ret == 3) return 1800; return -EINVAL; } /* set weak battery voltage in mV */ static int bq2415x_set_weak_battery_voltage(struct bq2415x_device *bq, int mV) { int val; /* round to 100mV */ if (mV <= 3400 + 50) val = 0; else if (mV <= 3500 + 50) val = 1; else if (mV <= 3600 + 50) val = 2; else val = 3; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_CONTROL, val, BQ2415X_MASK_VLOWV, BQ2415X_SHIFT_VLOWV); } /* get weak battery voltage in mV */ static int bq2415x_get_weak_battery_voltage(struct bq2415x_device *bq) { int ret; ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_CONTROL, BQ2415X_MASK_VLOWV, BQ2415X_SHIFT_VLOWV); if (ret < 0) return ret; return 100 * (34 + ret); } /* set battery regulation voltage in mV */ static int bq2415x_set_battery_regulation_voltage(struct bq2415x_device *bq, int mV) { int val = (mV/10 - 350) / 2; /* * According to datasheet, maximum battery regulation voltage is * 4440mV which is b101111 = 47. */ if (val < 0) val = 0; else if (val > 47) return -EINVAL; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_VOLTAGE, val, BQ2415X_MASK_VO, BQ2415X_SHIFT_VO); } /* get battery regulation voltage in mV */ static int bq2415x_get_battery_regulation_voltage(struct bq2415x_device *bq) { int ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_VOLTAGE, BQ2415X_MASK_VO, BQ2415X_SHIFT_VO); if (ret < 0) return ret; return 10 * (350 + 2*ret); } /* set charge current in mA (platform data must provide resistor sense) */ static int bq2415x_set_charge_current(struct bq2415x_device *bq, int mA) { int val; if (bq->init_data.resistor_sense <= 0) return -EINVAL; val = (mA * bq->init_data.resistor_sense - 37400) / 6800; if (val < 0) val = 0; else if (val > 7) val = 7; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_CURRENT, val, BQ2415X_MASK_VI_CHRG | BQ2415X_MASK_RESET, BQ2415X_SHIFT_VI_CHRG); } /* get charge current in mA (platform data must provide resistor sense) */ static int bq2415x_get_charge_current(struct bq2415x_device *bq) { int ret; if (bq->init_data.resistor_sense <= 0) return -EINVAL; ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_CURRENT, BQ2415X_MASK_VI_CHRG, BQ2415X_SHIFT_VI_CHRG); if (ret < 0) return ret; return (37400 + 6800*ret) / bq->init_data.resistor_sense; } /* set termination current in mA (platform data must provide resistor sense) */ static int bq2415x_set_termination_current(struct bq2415x_device *bq, int mA) { int val; if (bq->init_data.resistor_sense <= 0) return -EINVAL; val = (mA * bq->init_data.resistor_sense - 3400) / 3400; if (val < 0) val = 0; else if (val > 7) val = 7; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_CURRENT, val, BQ2415X_MASK_VI_TERM | BQ2415X_MASK_RESET, BQ2415X_SHIFT_VI_TERM); } /* get termination current in mA (platform data must provide resistor sense) */ static int bq2415x_get_termination_current(struct bq2415x_device *bq) { int ret; if (bq->init_data.resistor_sense <= 0) return -EINVAL; ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_CURRENT, BQ2415X_MASK_VI_TERM, BQ2415X_SHIFT_VI_TERM); if (ret < 0) return ret; return (3400 + 3400*ret) / bq->init_data.resistor_sense; } /* set default value of property */ #define bq2415x_set_default_value(bq, prop) \ do { \ int ret = 0; \ if (bq->init_data.prop != -1) \ ret = bq2415x_set_##prop(bq, bq->init_data.prop); \ if (ret < 0) \ return ret; \ } while (0) /* set default values of all properties */ static int bq2415x_set_defaults(struct bq2415x_device *bq) { bq2415x_exec_command(bq, BQ2415X_BOOST_MODE_DISABLE); bq2415x_exec_command(bq, BQ2415X_CHARGER_DISABLE); bq2415x_exec_command(bq, BQ2415X_CHARGE_TERMINATION_DISABLE); bq2415x_set_default_value(bq, current_limit); bq2415x_set_default_value(bq, weak_battery_voltage); bq2415x_set_default_value(bq, battery_regulation_voltage); if (bq->init_data.resistor_sense > 0) { bq2415x_set_default_value(bq, charge_current); bq2415x_set_default_value(bq, termination_current); bq2415x_exec_command(bq, BQ2415X_CHARGE_TERMINATION_ENABLE); } bq2415x_exec_command(bq, BQ2415X_CHARGER_ENABLE); return 0; } /**** charger mode functions ****/ /* set charger mode */ static int bq2415x_set_mode(struct bq2415x_device *bq, enum bq2415x_mode mode) { int ret = 0; int charger = 0; int boost = 0; if (mode == BQ2415X_MODE_BOOST) boost = 1; else if (mode != BQ2415X_MODE_OFF) charger = 1; if (!charger) ret = bq2415x_exec_command(bq, BQ2415X_CHARGER_DISABLE); if (!boost) ret = bq2415x_exec_command(bq, BQ2415X_BOOST_MODE_DISABLE); if (ret < 0) return ret; switch (mode) { case BQ2415X_MODE_OFF: dev_dbg(bq->dev, "changing mode to: Offline\n"); ret = bq2415x_set_current_limit(bq, 100); break; case BQ2415X_MODE_NONE: dev_dbg(bq->dev, "changing mode to: N/A\n"); ret = bq2415x_set_current_limit(bq, 100); break; case BQ2415X_MODE_HOST_CHARGER: dev_dbg(bq->dev, "changing mode to: Host/HUB charger\n"); ret = bq2415x_set_current_limit(bq, 500); break; case BQ2415X_MODE_DEDICATED_CHARGER: dev_dbg(bq->dev, "changing mode to: Dedicated charger\n"); ret = bq2415x_set_current_limit(bq, 1800); break; case BQ2415X_MODE_BOOST: /* Boost mode */ dev_dbg(bq->dev, "changing mode to: Boost\n"); ret = bq2415x_set_current_limit(bq, 100); break; } if (ret < 0) return ret; if (charger) ret = bq2415x_exec_command(bq, BQ2415X_CHARGER_ENABLE); else if (boost) ret = bq2415x_exec_command(bq, BQ2415X_BOOST_MODE_ENABLE); if (ret < 0) return ret; bq2415x_set_default_value(bq, weak_battery_voltage); bq2415x_set_default_value(bq, battery_regulation_voltage); bq->mode = mode; sysfs_notify(&bq->charger->dev.kobj, NULL, "mode"); return 0; } static bool bq2415x_update_reported_mode(struct bq2415x_device *bq, int mA) { enum bq2415x_mode mode; if (mA == 0) mode = BQ2415X_MODE_OFF; else if (mA < 500) mode = BQ2415X_MODE_NONE; else if (mA < 1800) mode = BQ2415X_MODE_HOST_CHARGER; else mode = BQ2415X_MODE_DEDICATED_CHARGER; if (bq->reported_mode == mode) return false; bq->reported_mode = mode; return true; } static int bq2415x_notifier_call(struct notifier_block *nb, unsigned long val, void *v) { struct bq2415x_device *bq = container_of(nb, struct bq2415x_device, nb); struct power_supply *psy = v; union power_supply_propval prop; int ret; if (val != PSY_EVENT_PROP_CHANGED) return NOTIFY_OK; /* Ignore event if it was not send by notify_node/notify_device */ if (bq->notify_node) { if (!psy->dev.parent || psy->dev.parent->of_node != bq->notify_node) return NOTIFY_OK; } else if (bq->init_data.notify_device) { if (strcmp(psy->desc->name, bq->init_data.notify_device) != 0) return NOTIFY_OK; } dev_dbg(bq->dev, "notifier call was called\n"); ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_CURRENT_MAX, &prop); if (ret != 0) return NOTIFY_OK; if (!bq2415x_update_reported_mode(bq, prop.intval)) return NOTIFY_OK; /* if automode is not enabled do not tell about reported_mode */ if (bq->automode < 1) return NOTIFY_OK; schedule_delayed_work(&bq->work, 0); return NOTIFY_OK; } /**** timer functions ****/ /* enable/disable auto resetting chip timer */ static void bq2415x_set_autotimer(struct bq2415x_device *bq, int state) { mutex_lock(&bq2415x_timer_mutex); if (bq->autotimer == state) { mutex_unlock(&bq2415x_timer_mutex); return; } bq->autotimer = state; if (state) { schedule_delayed_work(&bq->work, BQ2415X_TIMER_TIMEOUT * HZ); bq2415x_exec_command(bq, BQ2415X_TIMER_RESET); bq->timer_error = NULL; } else { cancel_delayed_work_sync(&bq->work); } mutex_unlock(&bq2415x_timer_mutex); } /* called by bq2415x_timer_work on timer error */ static void bq2415x_timer_error(struct bq2415x_device *bq, const char *msg) { bq->timer_error = msg; sysfs_notify(&bq->charger->dev.kobj, NULL, "timer"); dev_err(bq->dev, "%s\n", msg); if (bq->automode > 0) bq->automode = 0; bq2415x_set_mode(bq, BQ2415X_MODE_OFF); bq2415x_set_autotimer(bq, 0); } /* delayed work function for auto resetting chip timer */ static void bq2415x_timer_work(struct work_struct *work) { struct bq2415x_device *bq = container_of(work, struct bq2415x_device, work.work); int ret; int error; int boost; if (bq->automode > 0 && (bq->reported_mode != bq->mode)) { sysfs_notify(&bq->charger->dev.kobj, NULL, "reported_mode"); bq2415x_set_mode(bq, bq->reported_mode); } if (!bq->autotimer) return; ret = bq2415x_exec_command(bq, BQ2415X_TIMER_RESET); if (ret < 0) { bq2415x_timer_error(bq, "Resetting timer failed"); return; } boost = bq2415x_exec_command(bq, BQ2415X_BOOST_MODE_STATUS); if (boost < 0) { bq2415x_timer_error(bq, "Unknown error"); return; } error = bq2415x_exec_command(bq, BQ2415X_FAULT_STATUS); if (error < 0) { bq2415x_timer_error(bq, "Unknown error"); return; } if (boost) { switch (error) { /* Non fatal errors, chip is OK */ case 0: /* No error */ break; case 6: /* Timer expired */ dev_err(bq->dev, "Timer expired\n"); break; case 3: /* Battery voltage too low */ dev_err(bq->dev, "Battery voltage to low\n"); break; /* Fatal errors, disable and reset chip */ case 1: /* Overvoltage protection (chip fried) */ bq2415x_timer_error(bq, "Overvoltage protection (chip fried)"); return; case 2: /* Overload */ bq2415x_timer_error(bq, "Overload"); return; case 4: /* Battery overvoltage protection */ bq2415x_timer_error(bq, "Battery overvoltage protection"); return; case 5: /* Thermal shutdown (too hot) */ bq2415x_timer_error(bq, "Thermal shutdown (too hot)"); return; case 7: /* N/A */ bq2415x_timer_error(bq, "Unknown error"); return; } } else { switch (error) { /* Non fatal errors, chip is OK */ case 0: /* No error */ break; case 2: /* Sleep mode */ dev_err(bq->dev, "Sleep mode\n"); break; case 3: /* Poor input source */ dev_err(bq->dev, "Poor input source\n"); break; case 6: /* Timer expired */ dev_err(bq->dev, "Timer expired\n"); break; case 7: /* No battery */ dev_err(bq->dev, "No battery\n"); break; /* Fatal errors, disable and reset chip */ case 1: /* Overvoltage protection (chip fried) */ bq2415x_timer_error(bq, "Overvoltage protection (chip fried)"); return; case 4: /* Battery overvoltage protection */ bq2415x_timer_error(bq, "Battery overvoltage protection"); return; case 5: /* Thermal shutdown (too hot) */ bq2415x_timer_error(bq, "Thermal shutdown (too hot)"); return; } } schedule_delayed_work(&bq->work, BQ2415X_TIMER_TIMEOUT * HZ); } /**** power supply interface code ****/ static enum power_supply_property bq2415x_power_supply_props[] = { /* TODO: maybe add more power supply properties */ POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_MODEL_NAME, }; static int bq2415x_power_supply_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct bq2415x_device *bq = power_supply_get_drvdata(psy); int ret; switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = bq2415x_exec_command(bq, BQ2415X_CHARGE_STATUS); if (ret < 0) return ret; else if (ret == 0) /* Ready */ val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; else if (ret == 1) /* Charge in progress */ val->intval = POWER_SUPPLY_STATUS_CHARGING; else if (ret == 2) /* Charge done */ val->intval = POWER_SUPPLY_STATUS_FULL; else val->intval = POWER_SUPPLY_STATUS_UNKNOWN; break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = bq->model; break; default: return -EINVAL; } return 0; } static int bq2415x_power_supply_init(struct bq2415x_device *bq) { int ret; int chip; char revstr[8]; struct power_supply_config psy_cfg = { .drv_data = bq, }; bq->charger_desc.name = bq->name; bq->charger_desc.type = POWER_SUPPLY_TYPE_USB; bq->charger_desc.properties = bq2415x_power_supply_props; bq->charger_desc.num_properties = ARRAY_SIZE(bq2415x_power_supply_props); bq->charger_desc.get_property = bq2415x_power_supply_get_property; ret = bq2415x_detect_chip(bq); if (ret < 0) chip = BQUNKNOWN; else chip = ret; ret = bq2415x_detect_revision(bq); if (ret < 0) strcpy(revstr, "unknown"); else sprintf(revstr, "1.%d", ret); bq->model = kasprintf(GFP_KERNEL, "chip %s, revision %s, vender code %.3d", bq2415x_chip_name[chip], revstr, bq2415x_get_vender_code(bq)); if (!bq->model) { dev_err(bq->dev, "failed to allocate model name\n"); return -ENOMEM; } bq->charger = power_supply_register(bq->dev, &bq->charger_desc, &psy_cfg); if (IS_ERR(bq->charger)) { kfree(bq->model); return PTR_ERR(bq->charger); } return 0; } static void bq2415x_power_supply_exit(struct bq2415x_device *bq) { bq->autotimer = 0; if (bq->automode > 0) bq->automode = 0; cancel_delayed_work_sync(&bq->work); power_supply_unregister(bq->charger); kfree(bq->model); } /**** additional sysfs entries for power supply interface ****/ /* show *_status entries */ static ssize_t bq2415x_sysfs_show_status(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); enum bq2415x_command command; int ret; if (strcmp(attr->attr.name, "otg_status") == 0) command = BQ2415X_OTG_STATUS; else if (strcmp(attr->attr.name, "charge_status") == 0) command = BQ2415X_CHARGE_STATUS; else if (strcmp(attr->attr.name, "boost_status") == 0) command = BQ2415X_BOOST_STATUS; else if (strcmp(attr->attr.name, "fault_status") == 0) command = BQ2415X_FAULT_STATUS; else return -EINVAL; ret = bq2415x_exec_command(bq, command); if (ret < 0) return ret; return sprintf(buf, "%d\n", ret); } /* * set timer entry: * auto - enable auto mode * off - disable auto mode * (other values) - reset chip timer */ static ssize_t bq2415x_sysfs_set_timer(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); int ret = 0; if (strncmp(buf, "auto", 4) == 0) bq2415x_set_autotimer(bq, 1); else if (strncmp(buf, "off", 3) == 0) bq2415x_set_autotimer(bq, 0); else ret = bq2415x_exec_command(bq, BQ2415X_TIMER_RESET); if (ret < 0) return ret; return count; } /* show timer entry (auto or off) */ static ssize_t bq2415x_sysfs_show_timer(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); if (bq->timer_error) return sprintf(buf, "%s\n", bq->timer_error); if (bq->autotimer) return sprintf(buf, "auto\n"); return sprintf(buf, "off\n"); } /* * set mode entry: * auto - if automode is supported, enable it and set mode to reported * none - disable charger and boost mode * host - charging mode for host/hub chargers (current limit 500mA) * dedicated - charging mode for dedicated chargers (unlimited current limit) * boost - disable charger and enable boost mode */ static ssize_t bq2415x_sysfs_set_mode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); enum bq2415x_mode mode; int ret = 0; if (strncmp(buf, "auto", 4) == 0) { if (bq->automode < 0) return -EINVAL; bq->automode = 1; mode = bq->reported_mode; } else if (strncmp(buf, "off", 3) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_OFF; } else if (strncmp(buf, "none", 4) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_NONE; } else if (strncmp(buf, "host", 4) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_HOST_CHARGER; } else if (strncmp(buf, "dedicated", 9) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_DEDICATED_CHARGER; } else if (strncmp(buf, "boost", 5) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_BOOST; } else if (strncmp(buf, "reset", 5) == 0) { bq2415x_reset_chip(bq); bq2415x_set_defaults(bq); if (bq->automode <= 0) return count; bq->automode = 1; mode = bq->reported_mode; } else { return -EINVAL; } ret = bq2415x_set_mode(bq, mode); if (ret < 0) return ret; return count; } /* show mode entry (auto, none, host, dedicated or boost) */ static ssize_t bq2415x_sysfs_show_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); ssize_t ret = 0; if (bq->automode > 0) ret += sprintf(buf+ret, "auto ("); switch (bq->mode) { case BQ2415X_MODE_OFF: ret += sprintf(buf+ret, "off"); break; case BQ2415X_MODE_NONE: ret += sprintf(buf+ret, "none"); break; case BQ2415X_MODE_HOST_CHARGER: ret += sprintf(buf+ret, "host"); break; case BQ2415X_MODE_DEDICATED_CHARGER: ret += sprintf(buf+ret, "dedicated"); break; case BQ2415X_MODE_BOOST: ret += sprintf(buf+ret, "boost"); break; } if (bq->automode > 0) ret += sprintf(buf+ret, ")"); ret += sprintf(buf+ret, "\n"); return ret; } /* show reported_mode entry (none, host, dedicated or boost) */ static ssize_t bq2415x_sysfs_show_reported_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); if (bq->automode < 0) return -EINVAL; switch (bq->reported_mode) { case BQ2415X_MODE_OFF: return sprintf(buf, "off\n"); case BQ2415X_MODE_NONE: return sprintf(buf, "none\n"); case BQ2415X_MODE_HOST_CHARGER: return sprintf(buf, "host\n"); case BQ2415X_MODE_DEDICATED_CHARGER: return sprintf(buf, "dedicated\n"); case BQ2415X_MODE_BOOST: return sprintf(buf, "boost\n"); } return -EINVAL; } /* directly set raw value to chip register, format: 'register value' */ static ssize_t bq2415x_sysfs_set_registers(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); ssize_t ret = 0; unsigned int reg; unsigned int val; if (sscanf(buf, "%x %x", &reg, &val) != 2) return -EINVAL; if (reg > 4 || val > 255) return -EINVAL; ret = bq2415x_i2c_write(bq, reg, val); if (ret < 0) return ret; return count; } /* print value of chip register, format: 'register=value' */ static ssize_t bq2415x_sysfs_print_reg(struct bq2415x_device *bq, u8 reg, char *buf) { int ret = bq2415x_i2c_read(bq, reg); if (ret < 0) return sprintf(buf, "%#.2x=error %d\n", reg, ret); return sprintf(buf, "%#.2x=%#.2x\n", reg, ret); } /* show all raw values of chip register, format per line: 'register=value' */ static ssize_t bq2415x_sysfs_show_registers(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); ssize_t ret = 0; ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_STATUS, buf+ret); ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_CONTROL, buf+ret); ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_VOLTAGE, buf+ret); ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_VENDER, buf+ret); ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_CURRENT, buf+ret); return ret; } /* set current and voltage limit entries (in mA or mV) */ static ssize_t bq2415x_sysfs_set_limit(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); long val; int ret; if (kstrtol(buf, 10, &val) < 0) return -EINVAL; if (strcmp(attr->attr.name, "current_limit") == 0) ret = bq2415x_set_current_limit(bq, val); else if (strcmp(attr->attr.name, "weak_battery_voltage") == 0) ret = bq2415x_set_weak_battery_voltage(bq, val); else if (strcmp(attr->attr.name, "battery_regulation_voltage") == 0) ret = bq2415x_set_battery_regulation_voltage(bq, val); else if (strcmp(attr->attr.name, "charge_current") == 0) ret = bq2415x_set_charge_current(bq, val); else if (strcmp(attr->attr.name, "termination_current") == 0) ret = bq2415x_set_termination_current(bq, val); else return -EINVAL; if (ret < 0) return ret; return count; } /* show current and voltage limit entries (in mA or mV) */ static ssize_t bq2415x_sysfs_show_limit(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); int ret; if (strcmp(attr->attr.name, "current_limit") == 0) ret = bq2415x_get_current_limit(bq); else if (strcmp(attr->attr.name, "weak_battery_voltage") == 0) ret = bq2415x_get_weak_battery_voltage(bq); else if (strcmp(attr->attr.name, "battery_regulation_voltage") == 0) ret = bq2415x_get_battery_regulation_voltage(bq); else if (strcmp(attr->attr.name, "charge_current") == 0) ret = bq2415x_get_charge_current(bq); else if (strcmp(attr->attr.name, "termination_current") == 0) ret = bq2415x_get_termination_current(bq); else return -EINVAL; if (ret < 0) return ret; return sprintf(buf, "%d\n", ret); } /* set *_enable entries */ static ssize_t bq2415x_sysfs_set_enable(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); enum bq2415x_command command; long val; int ret; if (kstrtol(buf, 10, &val) < 0) return -EINVAL; if (strcmp(attr->attr.name, "charge_termination_enable") == 0) command = val ? BQ2415X_CHARGE_TERMINATION_ENABLE : BQ2415X_CHARGE_TERMINATION_DISABLE; else if (strcmp(attr->attr.name, "high_impedance_enable") == 0) command = val ? BQ2415X_HIGH_IMPEDANCE_ENABLE : BQ2415X_HIGH_IMPEDANCE_DISABLE; else if (strcmp(attr->attr.name, "otg_pin_enable") == 0) command = val ? BQ2415X_OTG_PIN_ENABLE : BQ2415X_OTG_PIN_DISABLE; else if (strcmp(attr->attr.name, "stat_pin_enable") == 0) command = val ? BQ2415X_STAT_PIN_ENABLE : BQ2415X_STAT_PIN_DISABLE; else return -EINVAL; ret = bq2415x_exec_command(bq, command); if (ret < 0) return ret; return count; } /* show *_enable entries */ static ssize_t bq2415x_sysfs_show_enable(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); enum bq2415x_command command; int ret; if (strcmp(attr->attr.name, "charge_termination_enable") == 0) command = BQ2415X_CHARGE_TERMINATION_STATUS; else if (strcmp(attr->attr.name, "high_impedance_enable") == 0) command = BQ2415X_HIGH_IMPEDANCE_STATUS; else if (strcmp(attr->attr.name, "otg_pin_enable") == 0) command = BQ2415X_OTG_PIN_STATUS; else if (strcmp(attr->attr.name, "stat_pin_enable") == 0) command = BQ2415X_STAT_PIN_STATUS; else return -EINVAL; ret = bq2415x_exec_command(bq, command); if (ret < 0) return ret; return sprintf(buf, "%d\n", ret); } static DEVICE_ATTR(current_limit, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(weak_battery_voltage, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(battery_regulation_voltage, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(charge_current, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(termination_current, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(charge_termination_enable, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_enable, bq2415x_sysfs_set_enable); static DEVICE_ATTR(high_impedance_enable, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_enable, bq2415x_sysfs_set_enable); static DEVICE_ATTR(otg_pin_enable, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_enable, bq2415x_sysfs_set_enable); static DEVICE_ATTR(stat_pin_enable, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_enable, bq2415x_sysfs_set_enable); static DEVICE_ATTR(reported_mode, S_IRUGO, bq2415x_sysfs_show_reported_mode, NULL); static DEVICE_ATTR(mode, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_mode, bq2415x_sysfs_set_mode); static DEVICE_ATTR(timer, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_timer, bq2415x_sysfs_set_timer); static DEVICE_ATTR(registers, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_registers, bq2415x_sysfs_set_registers); static DEVICE_ATTR(otg_status, S_IRUGO, bq2415x_sysfs_show_status, NULL); static DEVICE_ATTR(charge_status, S_IRUGO, bq2415x_sysfs_show_status, NULL); static DEVICE_ATTR(boost_status, S_IRUGO, bq2415x_sysfs_show_status, NULL); static DEVICE_ATTR(fault_status, S_IRUGO, bq2415x_sysfs_show_status, NULL); static struct attribute *bq2415x_sysfs_attributes[] = { /* * TODO: some (appropriate) of these attrs should be switched to * use power supply class props. */ &dev_attr_current_limit.attr, &dev_attr_weak_battery_voltage.attr, &dev_attr_battery_regulation_voltage.attr, &dev_attr_charge_current.attr, &dev_attr_termination_current.attr, &dev_attr_charge_termination_enable.attr, &dev_attr_high_impedance_enable.attr, &dev_attr_otg_pin_enable.attr, &dev_attr_stat_pin_enable.attr, &dev_attr_reported_mode.attr, &dev_attr_mode.attr, &dev_attr_timer.attr, &dev_attr_registers.attr, &dev_attr_otg_status.attr, &dev_attr_charge_status.attr, &dev_attr_boost_status.attr, &dev_attr_fault_status.attr, NULL, }; static const struct attribute_group bq2415x_sysfs_attr_group = { .attrs = bq2415x_sysfs_attributes, }; static int bq2415x_sysfs_init(struct bq2415x_device *bq) { return sysfs_create_group(&bq->charger->dev.kobj, &bq2415x_sysfs_attr_group); } static void bq2415x_sysfs_exit(struct bq2415x_device *bq) { sysfs_remove_group(&bq->charger->dev.kobj, &bq2415x_sysfs_attr_group); } /* main bq2415x probe function */ static int bq2415x_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret; int num; char *name = NULL; struct bq2415x_device *bq; struct device_node *np = client->dev.of_node; struct bq2415x_platform_data *pdata = client->dev.platform_data; const struct acpi_device_id *acpi_id = NULL; struct power_supply *notify_psy = NULL; union power_supply_propval prop; if (!np && !pdata && !ACPI_HANDLE(&client->dev)) { dev_err(&client->dev, "Neither devicetree, nor platform data, nor ACPI support\n"); return -ENODEV; } /* Get new ID for the new device */ mutex_lock(&bq2415x_id_mutex); num = idr_alloc(&bq2415x_id, client, 0, 0, GFP_KERNEL); mutex_unlock(&bq2415x_id_mutex); if (num < 0) return num; if (id) { name = kasprintf(GFP_KERNEL, "%s-%d", id->name, num); } else if (ACPI_HANDLE(&client->dev)) { acpi_id = acpi_match_device(client->dev.driver->acpi_match_table, &client->dev); if (!acpi_id) { dev_err(&client->dev, "failed to match device name\n"); ret = -ENODEV; goto error_1; } name = kasprintf(GFP_KERNEL, "%s-%d", acpi_id->id, num); } if (!name) { dev_err(&client->dev, "failed to allocate device name\n"); ret = -ENOMEM; goto error_1; } bq = devm_kzalloc(&client->dev, sizeof(*bq), GFP_KERNEL); if (!bq) { ret = -ENOMEM; goto error_2; } i2c_set_clientdata(client, bq); bq->id = num; bq->dev = &client->dev; if (id) bq->chip = id->driver_data; else if (ACPI_HANDLE(bq->dev)) bq->chip = acpi_id->driver_data; bq->name = name; bq->mode = BQ2415X_MODE_OFF; bq->reported_mode = BQ2415X_MODE_OFF; bq->autotimer = 0; bq->automode = 0; if (np || ACPI_HANDLE(bq->dev)) { ret = device_property_read_u32(bq->dev, "ti,current-limit", &bq->init_data.current_limit); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,weak-battery-voltage", &bq->init_data.weak_battery_voltage); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,battery-regulation-voltage", &bq->init_data.battery_regulation_voltage); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,charge-current", &bq->init_data.charge_current); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,termination-current", &bq->init_data.termination_current); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,resistor-sense", &bq->init_data.resistor_sense); if (ret) goto error_2; if (np) bq->notify_node = of_parse_phandle(np, "ti,usb-charger-detection", 0); } else { memcpy(&bq->init_data, pdata, sizeof(bq->init_data)); } bq2415x_reset_chip(bq); ret = bq2415x_power_supply_init(bq); if (ret) { dev_err(bq->dev, "failed to register power supply: %d\n", ret); goto error_2; } ret = bq2415x_sysfs_init(bq); if (ret) { dev_err(bq->dev, "failed to create sysfs entries: %d\n", ret); goto error_3; } ret = bq2415x_set_defaults(bq); if (ret) { dev_err(bq->dev, "failed to set default values: %d\n", ret); goto error_4; } if (bq->notify_node || bq->init_data.notify_device) { bq->nb.notifier_call = bq2415x_notifier_call; ret = power_supply_reg_notifier(&bq->nb); if (ret) { dev_err(bq->dev, "failed to reg notifier: %d\n", ret); goto error_4; } bq->automode = 1; dev_info(bq->dev, "automode supported, waiting for events\n"); } else { bq->automode = -1; dev_info(bq->dev, "automode not supported\n"); } /* Query for initial reported_mode and set it */ if (bq->nb.notifier_call) { if (np) { notify_psy = power_supply_get_by_phandle(np, "ti,usb-charger-detection"); if (IS_ERR(notify_psy)) notify_psy = NULL; } else if (bq->init_data.notify_device) { notify_psy = power_supply_get_by_name( bq->init_data.notify_device); } } if (notify_psy) { ret = power_supply_get_property(notify_psy, POWER_SUPPLY_PROP_CURRENT_MAX, &prop); power_supply_put(notify_psy); if (ret == 0) { bq2415x_update_reported_mode(bq, prop.intval); bq2415x_set_mode(bq, bq->reported_mode); } } INIT_DELAYED_WORK(&bq->work, bq2415x_timer_work); bq2415x_set_autotimer(bq, 1); dev_info(bq->dev, "driver registered\n"); return 0; error_4: bq2415x_sysfs_exit(bq); error_3: bq2415x_power_supply_exit(bq); error_2: if (bq) of_node_put(bq->notify_node); kfree(name); error_1: mutex_lock(&bq2415x_id_mutex); idr_remove(&bq2415x_id, num); mutex_unlock(&bq2415x_id_mutex); return ret; } /* main bq2415x remove function */ static int bq2415x_remove(struct i2c_client *client) { struct bq2415x_device *bq = i2c_get_clientdata(client); if (bq->nb.notifier_call) power_supply_unreg_notifier(&bq->nb); of_node_put(bq->notify_node); bq2415x_sysfs_exit(bq); bq2415x_power_supply_exit(bq); bq2415x_reset_chip(bq); mutex_lock(&bq2415x_id_mutex); idr_remove(&bq2415x_id, bq->id); mutex_unlock(&bq2415x_id_mutex); dev_info(bq->dev, "driver unregistered\n"); kfree(bq->name); return 0; } static const struct i2c_device_id bq2415x_i2c_id_table[] = { { "bq2415x", BQUNKNOWN }, { "bq24150", BQ24150 }, { "bq24150a", BQ24150A }, { "bq24151", BQ24151 }, { "bq24151a", BQ24151A }, { "bq24152", BQ24152 }, { "bq24153", BQ24153 }, { "bq24153a", BQ24153A }, { "bq24155", BQ24155 }, { "bq24156", BQ24156 }, { "bq24156a", BQ24156A }, { "bq24157s", BQ24157S }, { "bq24158", BQ24158 }, {}, }; MODULE_DEVICE_TABLE(i2c, bq2415x_i2c_id_table); #ifdef CONFIG_ACPI static const struct acpi_device_id bq2415x_i2c_acpi_match[] = { { "BQ2415X", BQUNKNOWN }, { "BQ241500", BQ24150 }, { "BQA24150", BQ24150A }, { "BQ241510", BQ24151 }, { "BQA24151", BQ24151A }, { "BQ241520", BQ24152 }, { "BQ241530", BQ24153 }, { "BQA24153", BQ24153A }, { "BQ241550", BQ24155 }, { "BQ241560", BQ24156 }, { "BQA24156", BQ24156A }, { "BQS24157", BQ24157S }, { "BQ241580", BQ24158 }, {}, }; MODULE_DEVICE_TABLE(acpi, bq2415x_i2c_acpi_match); #endif #ifdef CONFIG_OF static const struct of_device_id bq2415x_of_match_table[] = { { .compatible = "ti,bq24150" }, { .compatible = "ti,bq24150a" }, { .compatible = "ti,bq24151" }, { .compatible = "ti,bq24151a" }, { .compatible = "ti,bq24152" }, { .compatible = "ti,bq24153" }, { .compatible = "ti,bq24153a" }, { .compatible = "ti,bq24155" }, { .compatible = "ti,bq24156" }, { .compatible = "ti,bq24156a" }, { .compatible = "ti,bq24157s" }, { .compatible = "ti,bq24158" }, {}, }; MODULE_DEVICE_TABLE(of, bq2415x_of_match_table); #endif static struct i2c_driver bq2415x_driver = { .driver = { .name = "bq2415x-charger", .of_match_table = of_match_ptr(bq2415x_of_match_table), .acpi_match_table = ACPI_PTR(bq2415x_i2c_acpi_match), }, .probe = bq2415x_probe, .remove = bq2415x_remove, .id_table = bq2415x_i2c_id_table, }; module_i2c_driver(bq2415x_driver); MODULE_AUTHOR("Pali Rohár <pali.rohar@gmail.com>"); MODULE_DESCRIPTION("bq2415x charger driver"); MODULE_LICENSE("GPL");
null
null
null
null
96,411
48,762
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
48,762
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "base/at_exit.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/i18n/icu_util.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/power_monitor/power_monitor.h" #include "base/power_monitor/power_monitor_device_source.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "base/test/test_discardable_memory_allocator.h" #include "build/build_config.h" #include "components/viz/host/host_frame_sink_manager.h" #include "ui/base/ime/input_method_initializer.h" #include "ui/base/material_design/material_design_controller.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/compositor/test/in_process_context_factory.h" #include "ui/display/screen.h" #include "ui/gl/init/gl_factory.h" #include "ui/views/examples/example_base.h" #include "ui/views/examples/examples_window.h" #include "ui/views/test/desktop_test_views_delegate.h" #if defined(USE_AURA) #include "ui/aura/env.h" #include "ui/wm/core/wm_state.h" #endif #if !defined(OS_CHROMEOS) && defined(USE_AURA) #include "ui/views/widget/desktop_aura/desktop_screen.h" #endif #if defined(OS_WIN) #include "ui/base/win/scoped_ole_initializer.h" #include "ui/gfx/win/direct_write.h" #endif #if defined(USE_X11) #include "ui/gfx/x/x11_connection.h" // nogncheck #endif base::LazyInstance<base::TestDiscardableMemoryAllocator>::DestructorAtExit g_discardable_memory_allocator = LAZY_INSTANCE_INITIALIZER; int main(int argc, char** argv) { #if defined(OS_WIN) ui::ScopedOleInitializer ole_initializer_; #endif base::CommandLine::Init(argc, argv); base::AtExitManager at_exit; #if defined(USE_X11) // This demo uses InProcessContextFactory which uses X on a separate Gpu // thread. gfx::InitializeThreadedX11(); #endif gl::init::InitializeGLOneOff(); // The ContextFactory must exist before any Compositors are created. viz::HostFrameSinkManager host_frame_sink_manager; viz::FrameSinkManagerImpl frame_sink_manager; host_frame_sink_manager.SetLocalManager(&frame_sink_manager); frame_sink_manager.SetLocalClient(&host_frame_sink_manager); auto context_factory = std::make_unique<ui::InProcessContextFactory>( &host_frame_sink_manager, &frame_sink_manager); context_factory->set_use_test_surface(false); base::test::ScopedTaskEnvironment scoped_task_environment( base::test::ScopedTaskEnvironment::MainThreadType::UI); base::i18n::InitializeICU(); ui::RegisterPathProvider(); base::FilePath ui_test_pak_path; CHECK(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); base::DiscardableMemoryAllocator::SetInstance( g_discardable_memory_allocator.Pointer()); base::PowerMonitor power_monitor( base::WrapUnique(new base::PowerMonitorDeviceSource)); #if defined(OS_WIN) gfx::win::MaybeInitializeDirectWrite(); #endif #if defined(USE_AURA) std::unique_ptr<aura::Env> env = aura::Env::CreateInstance(); aura::Env::GetInstance()->set_context_factory(context_factory.get()); aura::Env::GetInstance()->set_context_factory_private(context_factory.get()); #endif ui::InitializeInputMethodForTesting(); ui::MaterialDesignController::Initialize(); { views::DesktopTestViewsDelegate views_delegate; #if defined(USE_AURA) wm::WMState wm_state; #endif #if !defined(OS_CHROMEOS) && defined(USE_AURA) std::unique_ptr<display::Screen> desktop_screen( views::CreateDesktopScreen()); display::Screen::SetScreenInstance(desktop_screen.get()); #endif views::examples::ShowExamplesWindow(views::examples::QUIT_ON_CLOSE); base::RunLoop().Run(); ui::ResourceBundle::CleanupSharedInstance(); } ui::ShutdownInputMethod(); #if defined(USE_AURA) env.reset(); #endif return 0; }
null
null
null
null
45,625
20,489
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
185,484
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* Intel PRO/1000 Linux driver * Copyright(c) 1999 - 2015 Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". * * Contact Information: * Linux NICS <linux.nics@intel.com> * e1000-devel Mailing List <e1000-devel@lists.sourceforge.net> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 */ /* ethtool support for e1000 */ #include <linux/netdevice.h> #include <linux/interrupt.h> #include <linux/ethtool.h> #include <linux/pci.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/vmalloc.h> #include <linux/pm_runtime.h> #include "e1000.h" enum { NETDEV_STATS, E1000_STATS }; struct e1000_stats { char stat_string[ETH_GSTRING_LEN]; int type; int sizeof_stat; int stat_offset; }; #define E1000_STAT(str, m) { \ .stat_string = str, \ .type = E1000_STATS, \ .sizeof_stat = sizeof(((struct e1000_adapter *)0)->m), \ .stat_offset = offsetof(struct e1000_adapter, m) } #define E1000_NETDEV_STAT(str, m) { \ .stat_string = str, \ .type = NETDEV_STATS, \ .sizeof_stat = sizeof(((struct rtnl_link_stats64 *)0)->m), \ .stat_offset = offsetof(struct rtnl_link_stats64, m) } static const struct e1000_stats e1000_gstrings_stats[] = { E1000_STAT("rx_packets", stats.gprc), E1000_STAT("tx_packets", stats.gptc), E1000_STAT("rx_bytes", stats.gorc), E1000_STAT("tx_bytes", stats.gotc), E1000_STAT("rx_broadcast", stats.bprc), E1000_STAT("tx_broadcast", stats.bptc), E1000_STAT("rx_multicast", stats.mprc), E1000_STAT("tx_multicast", stats.mptc), E1000_NETDEV_STAT("rx_errors", rx_errors), E1000_NETDEV_STAT("tx_errors", tx_errors), E1000_NETDEV_STAT("tx_dropped", tx_dropped), E1000_STAT("multicast", stats.mprc), E1000_STAT("collisions", stats.colc), E1000_NETDEV_STAT("rx_length_errors", rx_length_errors), E1000_NETDEV_STAT("rx_over_errors", rx_over_errors), E1000_STAT("rx_crc_errors", stats.crcerrs), E1000_NETDEV_STAT("rx_frame_errors", rx_frame_errors), E1000_STAT("rx_no_buffer_count", stats.rnbc), E1000_STAT("rx_missed_errors", stats.mpc), E1000_STAT("tx_aborted_errors", stats.ecol), E1000_STAT("tx_carrier_errors", stats.tncrs), E1000_NETDEV_STAT("tx_fifo_errors", tx_fifo_errors), E1000_NETDEV_STAT("tx_heartbeat_errors", tx_heartbeat_errors), E1000_STAT("tx_window_errors", stats.latecol), E1000_STAT("tx_abort_late_coll", stats.latecol), E1000_STAT("tx_deferred_ok", stats.dc), E1000_STAT("tx_single_coll_ok", stats.scc), E1000_STAT("tx_multi_coll_ok", stats.mcc), E1000_STAT("tx_timeout_count", tx_timeout_count), E1000_STAT("tx_restart_queue", restart_queue), E1000_STAT("rx_long_length_errors", stats.roc), E1000_STAT("rx_short_length_errors", stats.ruc), E1000_STAT("rx_align_errors", stats.algnerrc), E1000_STAT("tx_tcp_seg_good", stats.tsctc), E1000_STAT("tx_tcp_seg_failed", stats.tsctfc), E1000_STAT("rx_flow_control_xon", stats.xonrxc), E1000_STAT("rx_flow_control_xoff", stats.xoffrxc), E1000_STAT("tx_flow_control_xon", stats.xontxc), E1000_STAT("tx_flow_control_xoff", stats.xofftxc), E1000_STAT("rx_csum_offload_good", hw_csum_good), E1000_STAT("rx_csum_offload_errors", hw_csum_err), E1000_STAT("rx_header_split", rx_hdr_split), E1000_STAT("alloc_rx_buff_failed", alloc_rx_buff_failed), E1000_STAT("tx_smbus", stats.mgptc), E1000_STAT("rx_smbus", stats.mgprc), E1000_STAT("dropped_smbus", stats.mgpdc), E1000_STAT("rx_dma_failed", rx_dma_failed), E1000_STAT("tx_dma_failed", tx_dma_failed), E1000_STAT("rx_hwtstamp_cleared", rx_hwtstamp_cleared), E1000_STAT("uncorr_ecc_errors", uncorr_errors), E1000_STAT("corr_ecc_errors", corr_errors), E1000_STAT("tx_hwtstamp_timeouts", tx_hwtstamp_timeouts), }; #define E1000_GLOBAL_STATS_LEN ARRAY_SIZE(e1000_gstrings_stats) #define E1000_STATS_LEN (E1000_GLOBAL_STATS_LEN) static const char e1000_gstrings_test[][ETH_GSTRING_LEN] = { "Register test (offline)", "Eeprom test (offline)", "Interrupt test (offline)", "Loopback test (offline)", "Link test (on/offline)" }; #define E1000_TEST_LEN ARRAY_SIZE(e1000_gstrings_test) static int e1000_get_settings(struct net_device *netdev, struct ethtool_cmd *ecmd) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 speed; if (hw->phy.media_type == e1000_media_type_copper) { ecmd->supported = (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_1000baseT_Full | SUPPORTED_Autoneg | SUPPORTED_TP); if (hw->phy.type == e1000_phy_ife) ecmd->supported &= ~SUPPORTED_1000baseT_Full; ecmd->advertising = ADVERTISED_TP; if (hw->mac.autoneg == 1) { ecmd->advertising |= ADVERTISED_Autoneg; /* the e1000 autoneg seems to match ethtool nicely */ ecmd->advertising |= hw->phy.autoneg_advertised; } ecmd->port = PORT_TP; ecmd->phy_address = hw->phy.addr; ecmd->transceiver = XCVR_INTERNAL; } else { ecmd->supported = (SUPPORTED_1000baseT_Full | SUPPORTED_FIBRE | SUPPORTED_Autoneg); ecmd->advertising = (ADVERTISED_1000baseT_Full | ADVERTISED_FIBRE | ADVERTISED_Autoneg); ecmd->port = PORT_FIBRE; ecmd->transceiver = XCVR_EXTERNAL; } speed = SPEED_UNKNOWN; ecmd->duplex = DUPLEX_UNKNOWN; if (netif_running(netdev)) { if (netif_carrier_ok(netdev)) { speed = adapter->link_speed; ecmd->duplex = adapter->link_duplex - 1; } } else if (!pm_runtime_suspended(netdev->dev.parent)) { u32 status = er32(STATUS); if (status & E1000_STATUS_LU) { if (status & E1000_STATUS_SPEED_1000) speed = SPEED_1000; else if (status & E1000_STATUS_SPEED_100) speed = SPEED_100; else speed = SPEED_10; if (status & E1000_STATUS_FD) ecmd->duplex = DUPLEX_FULL; else ecmd->duplex = DUPLEX_HALF; } } ethtool_cmd_speed_set(ecmd, speed); ecmd->autoneg = ((hw->phy.media_type == e1000_media_type_fiber) || hw->mac.autoneg) ? AUTONEG_ENABLE : AUTONEG_DISABLE; /* MDI-X => 2; MDI =>1; Invalid =>0 */ if ((hw->phy.media_type == e1000_media_type_copper) && netif_carrier_ok(netdev)) ecmd->eth_tp_mdix = hw->phy.is_mdix ? ETH_TP_MDI_X : ETH_TP_MDI; else ecmd->eth_tp_mdix = ETH_TP_MDI_INVALID; if (hw->phy.mdix == AUTO_ALL_MODES) ecmd->eth_tp_mdix_ctrl = ETH_TP_MDI_AUTO; else ecmd->eth_tp_mdix_ctrl = hw->phy.mdix; if (hw->phy.media_type != e1000_media_type_copper) ecmd->eth_tp_mdix_ctrl = ETH_TP_MDI_INVALID; return 0; } static int e1000_set_spd_dplx(struct e1000_adapter *adapter, u32 spd, u8 dplx) { struct e1000_mac_info *mac = &adapter->hw.mac; mac->autoneg = 0; /* Make sure dplx is at most 1 bit and lsb of speed is not set * for the switch() below to work */ if ((spd & 1) || (dplx & ~1)) goto err_inval; /* Fiber NICs only allow 1000 gbps Full duplex */ if ((adapter->hw.phy.media_type == e1000_media_type_fiber) && (spd != SPEED_1000) && (dplx != DUPLEX_FULL)) { goto err_inval; } switch (spd + dplx) { case SPEED_10 + DUPLEX_HALF: mac->forced_speed_duplex = ADVERTISE_10_HALF; break; case SPEED_10 + DUPLEX_FULL: mac->forced_speed_duplex = ADVERTISE_10_FULL; break; case SPEED_100 + DUPLEX_HALF: mac->forced_speed_duplex = ADVERTISE_100_HALF; break; case SPEED_100 + DUPLEX_FULL: mac->forced_speed_duplex = ADVERTISE_100_FULL; break; case SPEED_1000 + DUPLEX_FULL: if (adapter->hw.phy.media_type == e1000_media_type_copper) { mac->autoneg = 1; adapter->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL; } else { mac->forced_speed_duplex = ADVERTISE_1000_FULL; } break; case SPEED_1000 + DUPLEX_HALF: /* not supported */ default: goto err_inval; } /* clear MDI, MDI(-X) override is only allowed when autoneg enabled */ adapter->hw.phy.mdix = AUTO_ALL_MODES; return 0; err_inval: e_err("Unsupported Speed/Duplex configuration\n"); return -EINVAL; } static int e1000_set_settings(struct net_device *netdev, struct ethtool_cmd *ecmd) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int ret_val = 0; pm_runtime_get_sync(netdev->dev.parent); /* When SoL/IDER sessions are active, autoneg/speed/duplex * cannot be changed */ if (hw->phy.ops.check_reset_block && hw->phy.ops.check_reset_block(hw)) { e_err("Cannot change link characteristics when SoL/IDER is active.\n"); ret_val = -EINVAL; goto out; } /* MDI setting is only allowed when autoneg enabled because * some hardware doesn't allow MDI setting when speed or * duplex is forced. */ if (ecmd->eth_tp_mdix_ctrl) { if (hw->phy.media_type != e1000_media_type_copper) { ret_val = -EOPNOTSUPP; goto out; } if ((ecmd->eth_tp_mdix_ctrl != ETH_TP_MDI_AUTO) && (ecmd->autoneg != AUTONEG_ENABLE)) { e_err("forcing MDI/MDI-X state is not supported when link speed and/or duplex are forced\n"); ret_val = -EINVAL; goto out; } } while (test_and_set_bit(__E1000_RESETTING, &adapter->state)) usleep_range(1000, 2000); if (ecmd->autoneg == AUTONEG_ENABLE) { hw->mac.autoneg = 1; if (hw->phy.media_type == e1000_media_type_fiber) hw->phy.autoneg_advertised = ADVERTISED_1000baseT_Full | ADVERTISED_FIBRE | ADVERTISED_Autoneg; else hw->phy.autoneg_advertised = ecmd->advertising | ADVERTISED_TP | ADVERTISED_Autoneg; ecmd->advertising = hw->phy.autoneg_advertised; if (adapter->fc_autoneg) hw->fc.requested_mode = e1000_fc_default; } else { u32 speed = ethtool_cmd_speed(ecmd); /* calling this overrides forced MDI setting */ if (e1000_set_spd_dplx(adapter, speed, ecmd->duplex)) { ret_val = -EINVAL; goto out; } } /* MDI-X => 2; MDI => 1; Auto => 3 */ if (ecmd->eth_tp_mdix_ctrl) { /* fix up the value for auto (3 => 0) as zero is mapped * internally to auto */ if (ecmd->eth_tp_mdix_ctrl == ETH_TP_MDI_AUTO) hw->phy.mdix = AUTO_ALL_MODES; else hw->phy.mdix = ecmd->eth_tp_mdix_ctrl; } /* reset the link */ if (netif_running(adapter->netdev)) { e1000e_down(adapter, true); e1000e_up(adapter); } else { e1000e_reset(adapter); } out: pm_runtime_put_sync(netdev->dev.parent); clear_bit(__E1000_RESETTING, &adapter->state); return ret_val; } static void e1000_get_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; pause->autoneg = (adapter->fc_autoneg ? AUTONEG_ENABLE : AUTONEG_DISABLE); if (hw->fc.current_mode == e1000_fc_rx_pause) { pause->rx_pause = 1; } else if (hw->fc.current_mode == e1000_fc_tx_pause) { pause->tx_pause = 1; } else if (hw->fc.current_mode == e1000_fc_full) { pause->rx_pause = 1; pause->tx_pause = 1; } } static int e1000_set_pauseparam(struct net_device *netdev, struct ethtool_pauseparam *pause) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; int retval = 0; adapter->fc_autoneg = pause->autoneg; while (test_and_set_bit(__E1000_RESETTING, &adapter->state)) usleep_range(1000, 2000); pm_runtime_get_sync(netdev->dev.parent); if (adapter->fc_autoneg == AUTONEG_ENABLE) { hw->fc.requested_mode = e1000_fc_default; if (netif_running(adapter->netdev)) { e1000e_down(adapter, true); e1000e_up(adapter); } else { e1000e_reset(adapter); } } else { if (pause->rx_pause && pause->tx_pause) hw->fc.requested_mode = e1000_fc_full; else if (pause->rx_pause && !pause->tx_pause) hw->fc.requested_mode = e1000_fc_rx_pause; else if (!pause->rx_pause && pause->tx_pause) hw->fc.requested_mode = e1000_fc_tx_pause; else if (!pause->rx_pause && !pause->tx_pause) hw->fc.requested_mode = e1000_fc_none; hw->fc.current_mode = hw->fc.requested_mode; if (hw->phy.media_type == e1000_media_type_fiber) { retval = hw->mac.ops.setup_link(hw); /* implicit goto out */ } else { retval = e1000e_force_mac_fc(hw); if (retval) goto out; e1000e_set_fc_watermarks(hw); } } out: pm_runtime_put_sync(netdev->dev.parent); clear_bit(__E1000_RESETTING, &adapter->state); return retval; } static u32 e1000_get_msglevel(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); return adapter->msg_enable; } static void e1000_set_msglevel(struct net_device *netdev, u32 data) { struct e1000_adapter *adapter = netdev_priv(netdev); adapter->msg_enable = data; } static int e1000_get_regs_len(struct net_device __always_unused *netdev) { #define E1000_REGS_LEN 32 /* overestimate */ return E1000_REGS_LEN * sizeof(u32); } static void e1000_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 *regs_buff = p; u16 phy_data; pm_runtime_get_sync(netdev->dev.parent); memset(p, 0, E1000_REGS_LEN * sizeof(u32)); regs->version = (1u << 24) | (adapter->pdev->revision << 16) | adapter->pdev->device; regs_buff[0] = er32(CTRL); regs_buff[1] = er32(STATUS); regs_buff[2] = er32(RCTL); regs_buff[3] = er32(RDLEN(0)); regs_buff[4] = er32(RDH(0)); regs_buff[5] = er32(RDT(0)); regs_buff[6] = er32(RDTR); regs_buff[7] = er32(TCTL); regs_buff[8] = er32(TDLEN(0)); regs_buff[9] = er32(TDH(0)); regs_buff[10] = er32(TDT(0)); regs_buff[11] = er32(TIDV); regs_buff[12] = adapter->hw.phy.type; /* PHY type (IGP=1, M88=0) */ /* ethtool doesn't use anything past this point, so all this * code is likely legacy junk for apps that may or may not exist */ if (hw->phy.type == e1000_phy_m88) { e1e_rphy(hw, M88E1000_PHY_SPEC_STATUS, &phy_data); regs_buff[13] = (u32)phy_data; /* cable length */ regs_buff[14] = 0; /* Dummy (to align w/ IGP phy reg dump) */ regs_buff[15] = 0; /* Dummy (to align w/ IGP phy reg dump) */ regs_buff[16] = 0; /* Dummy (to align w/ IGP phy reg dump) */ e1e_rphy(hw, M88E1000_PHY_SPEC_CTRL, &phy_data); regs_buff[17] = (u32)phy_data; /* extended 10bt distance */ regs_buff[18] = regs_buff[13]; /* cable polarity */ regs_buff[19] = 0; /* Dummy (to align w/ IGP phy reg dump) */ regs_buff[20] = regs_buff[17]; /* polarity correction */ /* phy receive errors */ regs_buff[22] = adapter->phy_stats.receive_errors; regs_buff[23] = regs_buff[13]; /* mdix mode */ } regs_buff[21] = 0; /* was idle_errors */ e1e_rphy(hw, MII_STAT1000, &phy_data); regs_buff[24] = (u32)phy_data; /* phy local receiver status */ regs_buff[25] = regs_buff[24]; /* phy remote receiver status */ pm_runtime_put_sync(netdev->dev.parent); } static int e1000_get_eeprom_len(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); return adapter->hw.nvm.word_size * 2; } static int e1000_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u16 *eeprom_buff; int first_word; int last_word; int ret_val = 0; u16 i; if (eeprom->len == 0) return -EINVAL; eeprom->magic = adapter->pdev->vendor | (adapter->pdev->device << 16); first_word = eeprom->offset >> 1; last_word = (eeprom->offset + eeprom->len - 1) >> 1; eeprom_buff = kmalloc(sizeof(u16) * (last_word - first_word + 1), GFP_KERNEL); if (!eeprom_buff) return -ENOMEM; pm_runtime_get_sync(netdev->dev.parent); if (hw->nvm.type == e1000_nvm_eeprom_spi) { ret_val = e1000_read_nvm(hw, first_word, last_word - first_word + 1, eeprom_buff); } else { for (i = 0; i < last_word - first_word + 1; i++) { ret_val = e1000_read_nvm(hw, first_word + i, 1, &eeprom_buff[i]); if (ret_val) break; } } pm_runtime_put_sync(netdev->dev.parent); if (ret_val) { /* a read error occurred, throw away the result */ memset(eeprom_buff, 0xff, sizeof(u16) * (last_word - first_word + 1)); } else { /* Device's eeprom is always little-endian, word addressable */ for (i = 0; i < last_word - first_word + 1; i++) le16_to_cpus(&eeprom_buff[i]); } memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 1), eeprom->len); kfree(eeprom_buff); return ret_val; } static int e1000_set_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u16 *eeprom_buff; void *ptr; int max_len; int first_word; int last_word; int ret_val = 0; u16 i; if (eeprom->len == 0) return -EOPNOTSUPP; if (eeprom->magic != (adapter->pdev->vendor | (adapter->pdev->device << 16))) return -EFAULT; if (adapter->flags & FLAG_READ_ONLY_NVM) return -EINVAL; max_len = hw->nvm.word_size * 2; first_word = eeprom->offset >> 1; last_word = (eeprom->offset + eeprom->len - 1) >> 1; eeprom_buff = kmalloc(max_len, GFP_KERNEL); if (!eeprom_buff) return -ENOMEM; ptr = (void *)eeprom_buff; pm_runtime_get_sync(netdev->dev.parent); if (eeprom->offset & 1) { /* need read/modify/write of first changed EEPROM word */ /* only the second byte of the word is being modified */ ret_val = e1000_read_nvm(hw, first_word, 1, &eeprom_buff[0]); ptr++; } if (((eeprom->offset + eeprom->len) & 1) && (!ret_val)) /* need read/modify/write of last changed EEPROM word */ /* only the first byte of the word is being modified */ ret_val = e1000_read_nvm(hw, last_word, 1, &eeprom_buff[last_word - first_word]); if (ret_val) goto out; /* Device's eeprom is always little-endian, word addressable */ for (i = 0; i < last_word - first_word + 1; i++) le16_to_cpus(&eeprom_buff[i]); memcpy(ptr, bytes, eeprom->len); for (i = 0; i < last_word - first_word + 1; i++) cpu_to_le16s(&eeprom_buff[i]); ret_val = e1000_write_nvm(hw, first_word, last_word - first_word + 1, eeprom_buff); if (ret_val) goto out; /* Update the checksum over the first part of the EEPROM if needed * and flush shadow RAM for applicable controllers */ if ((first_word <= NVM_CHECKSUM_REG) || (hw->mac.type == e1000_82583) || (hw->mac.type == e1000_82574) || (hw->mac.type == e1000_82573)) ret_val = e1000e_update_nvm_checksum(hw); out: pm_runtime_put_sync(netdev->dev.parent); kfree(eeprom_buff); return ret_val; } static void e1000_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo) { struct e1000_adapter *adapter = netdev_priv(netdev); strlcpy(drvinfo->driver, e1000e_driver_name, sizeof(drvinfo->driver)); strlcpy(drvinfo->version, e1000e_driver_version, sizeof(drvinfo->version)); /* EEPROM image version # is reported as firmware version # for * PCI-E controllers */ snprintf(drvinfo->fw_version, sizeof(drvinfo->fw_version), "%d.%d-%d", (adapter->eeprom_vers & 0xF000) >> 12, (adapter->eeprom_vers & 0x0FF0) >> 4, (adapter->eeprom_vers & 0x000F)); strlcpy(drvinfo->bus_info, pci_name(adapter->pdev), sizeof(drvinfo->bus_info)); } static void e1000_get_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring) { struct e1000_adapter *adapter = netdev_priv(netdev); ring->rx_max_pending = E1000_MAX_RXD; ring->tx_max_pending = E1000_MAX_TXD; ring->rx_pending = adapter->rx_ring_count; ring->tx_pending = adapter->tx_ring_count; } static int e1000_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_ring *temp_tx = NULL, *temp_rx = NULL; int err = 0, size = sizeof(struct e1000_ring); bool set_tx = false, set_rx = false; u16 new_rx_count, new_tx_count; if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending)) return -EINVAL; new_rx_count = clamp_t(u32, ring->rx_pending, E1000_MIN_RXD, E1000_MAX_RXD); new_rx_count = ALIGN(new_rx_count, REQ_RX_DESCRIPTOR_MULTIPLE); new_tx_count = clamp_t(u32, ring->tx_pending, E1000_MIN_TXD, E1000_MAX_TXD); new_tx_count = ALIGN(new_tx_count, REQ_TX_DESCRIPTOR_MULTIPLE); if ((new_tx_count == adapter->tx_ring_count) && (new_rx_count == adapter->rx_ring_count)) /* nothing to do */ return 0; while (test_and_set_bit(__E1000_RESETTING, &adapter->state)) usleep_range(1000, 2000); if (!netif_running(adapter->netdev)) { /* Set counts now and allocate resources during open() */ adapter->tx_ring->count = new_tx_count; adapter->rx_ring->count = new_rx_count; adapter->tx_ring_count = new_tx_count; adapter->rx_ring_count = new_rx_count; goto clear_reset; } set_tx = (new_tx_count != adapter->tx_ring_count); set_rx = (new_rx_count != adapter->rx_ring_count); /* Allocate temporary storage for ring updates */ if (set_tx) { temp_tx = vmalloc(size); if (!temp_tx) { err = -ENOMEM; goto free_temp; } } if (set_rx) { temp_rx = vmalloc(size); if (!temp_rx) { err = -ENOMEM; goto free_temp; } } pm_runtime_get_sync(netdev->dev.parent); e1000e_down(adapter, true); /* We can't just free everything and then setup again, because the * ISRs in MSI-X mode get passed pointers to the Tx and Rx ring * structs. First, attempt to allocate new resources... */ if (set_tx) { memcpy(temp_tx, adapter->tx_ring, size); temp_tx->count = new_tx_count; err = e1000e_setup_tx_resources(temp_tx); if (err) goto err_setup; } if (set_rx) { memcpy(temp_rx, adapter->rx_ring, size); temp_rx->count = new_rx_count; err = e1000e_setup_rx_resources(temp_rx); if (err) goto err_setup_rx; } /* ...then free the old resources and copy back any new ring data */ if (set_tx) { e1000e_free_tx_resources(adapter->tx_ring); memcpy(adapter->tx_ring, temp_tx, size); adapter->tx_ring_count = new_tx_count; } if (set_rx) { e1000e_free_rx_resources(adapter->rx_ring); memcpy(adapter->rx_ring, temp_rx, size); adapter->rx_ring_count = new_rx_count; } err_setup_rx: if (err && set_tx) e1000e_free_tx_resources(temp_tx); err_setup: e1000e_up(adapter); pm_runtime_put_sync(netdev->dev.parent); free_temp: vfree(temp_tx); vfree(temp_rx); clear_reset: clear_bit(__E1000_RESETTING, &adapter->state); return err; } static bool reg_pattern_test(struct e1000_adapter *adapter, u64 *data, int reg, int offset, u32 mask, u32 write) { u32 pat, val; static const u32 test[] = { 0x5A5A5A5A, 0xA5A5A5A5, 0x00000000, 0xFFFFFFFF }; for (pat = 0; pat < ARRAY_SIZE(test); pat++) { E1000_WRITE_REG_ARRAY(&adapter->hw, reg, offset, (test[pat] & write)); val = E1000_READ_REG_ARRAY(&adapter->hw, reg, offset); if (val != (test[pat] & write & mask)) { e_err("pattern test failed (reg 0x%05X): got 0x%08X expected 0x%08X\n", reg + (offset << 2), val, (test[pat] & write & mask)); *data = reg; return true; } } return false; } static bool reg_set_and_check(struct e1000_adapter *adapter, u64 *data, int reg, u32 mask, u32 write) { u32 val; __ew32(&adapter->hw, reg, write & mask); val = __er32(&adapter->hw, reg); if ((write & mask) != (val & mask)) { e_err("set/check test failed (reg 0x%05X): got 0x%08X expected 0x%08X\n", reg, (val & mask), (write & mask)); *data = reg; return true; } return false; } #define REG_PATTERN_TEST_ARRAY(reg, offset, mask, write) \ do { \ if (reg_pattern_test(adapter, data, reg, offset, mask, write)) \ return 1; \ } while (0) #define REG_PATTERN_TEST(reg, mask, write) \ REG_PATTERN_TEST_ARRAY(reg, 0, mask, write) #define REG_SET_AND_CHECK(reg, mask, write) \ do { \ if (reg_set_and_check(adapter, data, reg, mask, write)) \ return 1; \ } while (0) static int e1000_reg_test(struct e1000_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; struct e1000_mac_info *mac = &adapter->hw.mac; u32 value; u32 before; u32 after; u32 i; u32 toggle; u32 mask; u32 wlock_mac = 0; /* The status register is Read Only, so a write should fail. * Some bits that get toggled are ignored. There are several bits * on newer hardware that are r/w. */ switch (mac->type) { case e1000_82571: case e1000_82572: case e1000_80003es2lan: toggle = 0x7FFFF3FF; break; default: toggle = 0x7FFFF033; break; } before = er32(STATUS); value = (er32(STATUS) & toggle); ew32(STATUS, toggle); after = er32(STATUS) & toggle; if (value != after) { e_err("failed STATUS register test got: 0x%08X expected: 0x%08X\n", after, value); *data = 1; return 1; } /* restore previous status */ ew32(STATUS, before); if (!(adapter->flags & FLAG_IS_ICH)) { REG_PATTERN_TEST(E1000_FCAL, 0xFFFFFFFF, 0xFFFFFFFF); REG_PATTERN_TEST(E1000_FCAH, 0x0000FFFF, 0xFFFFFFFF); REG_PATTERN_TEST(E1000_FCT, 0x0000FFFF, 0xFFFFFFFF); REG_PATTERN_TEST(E1000_VET, 0x0000FFFF, 0xFFFFFFFF); } REG_PATTERN_TEST(E1000_RDTR, 0x0000FFFF, 0xFFFFFFFF); REG_PATTERN_TEST(E1000_RDBAH(0), 0xFFFFFFFF, 0xFFFFFFFF); REG_PATTERN_TEST(E1000_RDLEN(0), 0x000FFF80, 0x000FFFFF); REG_PATTERN_TEST(E1000_RDH(0), 0x0000FFFF, 0x0000FFFF); REG_PATTERN_TEST(E1000_RDT(0), 0x0000FFFF, 0x0000FFFF); REG_PATTERN_TEST(E1000_FCRTH, 0x0000FFF8, 0x0000FFF8); REG_PATTERN_TEST(E1000_FCTTV, 0x0000FFFF, 0x0000FFFF); REG_PATTERN_TEST(E1000_TIPG, 0x3FFFFFFF, 0x3FFFFFFF); REG_PATTERN_TEST(E1000_TDBAH(0), 0xFFFFFFFF, 0xFFFFFFFF); REG_PATTERN_TEST(E1000_TDLEN(0), 0x000FFF80, 0x000FFFFF); REG_SET_AND_CHECK(E1000_RCTL, 0xFFFFFFFF, 0x00000000); before = ((adapter->flags & FLAG_IS_ICH) ? 0x06C3B33E : 0x06DFB3FE); REG_SET_AND_CHECK(E1000_RCTL, before, 0x003FFFFB); REG_SET_AND_CHECK(E1000_TCTL, 0xFFFFFFFF, 0x00000000); REG_SET_AND_CHECK(E1000_RCTL, before, 0xFFFFFFFF); REG_PATTERN_TEST(E1000_RDBAL(0), 0xFFFFFFF0, 0xFFFFFFFF); if (!(adapter->flags & FLAG_IS_ICH)) REG_PATTERN_TEST(E1000_TXCW, 0xC000FFFF, 0x0000FFFF); REG_PATTERN_TEST(E1000_TDBAL(0), 0xFFFFFFF0, 0xFFFFFFFF); REG_PATTERN_TEST(E1000_TIDV, 0x0000FFFF, 0x0000FFFF); mask = 0x8003FFFF; switch (mac->type) { case e1000_ich10lan: case e1000_pchlan: case e1000_pch2lan: case e1000_pch_lpt: case e1000_pch_spt: mask |= BIT(18); break; default: break; } if ((mac->type == e1000_pch_lpt) || (mac->type == e1000_pch_spt)) wlock_mac = (er32(FWSM) & E1000_FWSM_WLOCK_MAC_MASK) >> E1000_FWSM_WLOCK_MAC_SHIFT; for (i = 0; i < mac->rar_entry_count; i++) { if ((mac->type == e1000_pch_lpt) || (mac->type == e1000_pch_spt)) { /* Cannot test write-protected SHRAL[n] registers */ if ((wlock_mac == 1) || (wlock_mac && (i > wlock_mac))) continue; /* SHRAH[9] different than the others */ if (i == 10) mask |= BIT(30); else mask &= ~BIT(30); } if (mac->type == e1000_pch2lan) { /* SHRAH[0,1,2] different than previous */ if (i == 1) mask &= 0xFFF4FFFF; /* SHRAH[3] different than SHRAH[0,1,2] */ if (i == 4) mask |= BIT(30); /* RAR[1-6] owned by management engine - skipping */ if (i > 0) i += 6; } REG_PATTERN_TEST_ARRAY(E1000_RA, ((i << 1) + 1), mask, 0xFFFFFFFF); /* reset index to actual value */ if ((mac->type == e1000_pch2lan) && (i > 6)) i -= 6; } for (i = 0; i < mac->mta_reg_count; i++) REG_PATTERN_TEST_ARRAY(E1000_MTA, i, 0xFFFFFFFF, 0xFFFFFFFF); *data = 0; return 0; } static int e1000_eeprom_test(struct e1000_adapter *adapter, u64 *data) { u16 temp; u16 checksum = 0; u16 i; *data = 0; /* Read and add up the contents of the EEPROM */ for (i = 0; i < (NVM_CHECKSUM_REG + 1); i++) { if ((e1000_read_nvm(&adapter->hw, i, 1, &temp)) < 0) { *data = 1; return *data; } checksum += temp; } /* If Checksum is not Correct return error else test passed */ if ((checksum != (u16)NVM_SUM) && !(*data)) *data = 2; return *data; } static irqreturn_t e1000_test_intr(int __always_unused irq, void *data) { struct net_device *netdev = (struct net_device *)data; struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; adapter->test_icr |= er32(ICR); return IRQ_HANDLED; } static int e1000_intr_test(struct e1000_adapter *adapter, u64 *data) { struct net_device *netdev = adapter->netdev; struct e1000_hw *hw = &adapter->hw; u32 mask; u32 shared_int = 1; u32 irq = adapter->pdev->irq; int i; int ret_val = 0; int int_mode = E1000E_INT_MODE_LEGACY; *data = 0; /* NOTE: we don't test MSI/MSI-X interrupts here, yet */ if (adapter->int_mode == E1000E_INT_MODE_MSIX) { int_mode = adapter->int_mode; e1000e_reset_interrupt_capability(adapter); adapter->int_mode = E1000E_INT_MODE_LEGACY; e1000e_set_interrupt_capability(adapter); } /* Hook up test interrupt handler just for this test */ if (!request_irq(irq, e1000_test_intr, IRQF_PROBE_SHARED, netdev->name, netdev)) { shared_int = 0; } else if (request_irq(irq, e1000_test_intr, IRQF_SHARED, netdev->name, netdev)) { *data = 1; ret_val = -1; goto out; } e_info("testing %s interrupt\n", (shared_int ? "shared" : "unshared")); /* Disable all the interrupts */ ew32(IMC, 0xFFFFFFFF); e1e_flush(); usleep_range(10000, 20000); /* Test each interrupt */ for (i = 0; i < 10; i++) { /* Interrupt to test */ mask = BIT(i); if (adapter->flags & FLAG_IS_ICH) { switch (mask) { case E1000_ICR_RXSEQ: continue; case 0x00000100: if (adapter->hw.mac.type == e1000_ich8lan || adapter->hw.mac.type == e1000_ich9lan) continue; break; default: break; } } if (!shared_int) { /* Disable the interrupt to be reported in * the cause register and then force the same * interrupt and see if one gets posted. If * an interrupt was posted to the bus, the * test failed. */ adapter->test_icr = 0; ew32(IMC, mask); ew32(ICS, mask); e1e_flush(); usleep_range(10000, 20000); if (adapter->test_icr & mask) { *data = 3; break; } } /* Enable the interrupt to be reported in * the cause register and then force the same * interrupt and see if one gets posted. If * an interrupt was not posted to the bus, the * test failed. */ adapter->test_icr = 0; ew32(IMS, mask); ew32(ICS, mask); e1e_flush(); usleep_range(10000, 20000); if (!(adapter->test_icr & mask)) { *data = 4; break; } if (!shared_int) { /* Disable the other interrupts to be reported in * the cause register and then force the other * interrupts and see if any get posted. If * an interrupt was posted to the bus, the * test failed. */ adapter->test_icr = 0; ew32(IMC, ~mask & 0x00007FFF); ew32(ICS, ~mask & 0x00007FFF); e1e_flush(); usleep_range(10000, 20000); if (adapter->test_icr) { *data = 5; break; } } } /* Disable all the interrupts */ ew32(IMC, 0xFFFFFFFF); e1e_flush(); usleep_range(10000, 20000); /* Unhook test interrupt handler */ free_irq(irq, netdev); out: if (int_mode == E1000E_INT_MODE_MSIX) { e1000e_reset_interrupt_capability(adapter); adapter->int_mode = int_mode; e1000e_set_interrupt_capability(adapter); } return ret_val; } static void e1000_free_desc_rings(struct e1000_adapter *adapter) { struct e1000_ring *tx_ring = &adapter->test_tx_ring; struct e1000_ring *rx_ring = &adapter->test_rx_ring; struct pci_dev *pdev = adapter->pdev; struct e1000_buffer *buffer_info; int i; if (tx_ring->desc && tx_ring->buffer_info) { for (i = 0; i < tx_ring->count; i++) { buffer_info = &tx_ring->buffer_info[i]; if (buffer_info->dma) dma_unmap_single(&pdev->dev, buffer_info->dma, buffer_info->length, DMA_TO_DEVICE); if (buffer_info->skb) dev_kfree_skb(buffer_info->skb); } } if (rx_ring->desc && rx_ring->buffer_info) { for (i = 0; i < rx_ring->count; i++) { buffer_info = &rx_ring->buffer_info[i]; if (buffer_info->dma) dma_unmap_single(&pdev->dev, buffer_info->dma, 2048, DMA_FROM_DEVICE); if (buffer_info->skb) dev_kfree_skb(buffer_info->skb); } } if (tx_ring->desc) { dma_free_coherent(&pdev->dev, tx_ring->size, tx_ring->desc, tx_ring->dma); tx_ring->desc = NULL; } if (rx_ring->desc) { dma_free_coherent(&pdev->dev, rx_ring->size, rx_ring->desc, rx_ring->dma); rx_ring->desc = NULL; } kfree(tx_ring->buffer_info); tx_ring->buffer_info = NULL; kfree(rx_ring->buffer_info); rx_ring->buffer_info = NULL; } static int e1000_setup_desc_rings(struct e1000_adapter *adapter) { struct e1000_ring *tx_ring = &adapter->test_tx_ring; struct e1000_ring *rx_ring = &adapter->test_rx_ring; struct pci_dev *pdev = adapter->pdev; struct e1000_hw *hw = &adapter->hw; u32 rctl; int i; int ret_val; /* Setup Tx descriptor ring and Tx buffers */ if (!tx_ring->count) tx_ring->count = E1000_DEFAULT_TXD; tx_ring->buffer_info = kcalloc(tx_ring->count, sizeof(struct e1000_buffer), GFP_KERNEL); if (!tx_ring->buffer_info) { ret_val = 1; goto err_nomem; } tx_ring->size = tx_ring->count * sizeof(struct e1000_tx_desc); tx_ring->size = ALIGN(tx_ring->size, 4096); tx_ring->desc = dma_alloc_coherent(&pdev->dev, tx_ring->size, &tx_ring->dma, GFP_KERNEL); if (!tx_ring->desc) { ret_val = 2; goto err_nomem; } tx_ring->next_to_use = 0; tx_ring->next_to_clean = 0; ew32(TDBAL(0), ((u64)tx_ring->dma & 0x00000000FFFFFFFF)); ew32(TDBAH(0), ((u64)tx_ring->dma >> 32)); ew32(TDLEN(0), tx_ring->count * sizeof(struct e1000_tx_desc)); ew32(TDH(0), 0); ew32(TDT(0), 0); ew32(TCTL, E1000_TCTL_PSP | E1000_TCTL_EN | E1000_TCTL_MULR | E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT | E1000_COLLISION_DISTANCE << E1000_COLD_SHIFT); for (i = 0; i < tx_ring->count; i++) { struct e1000_tx_desc *tx_desc = E1000_TX_DESC(*tx_ring, i); struct sk_buff *skb; unsigned int skb_size = 1024; skb = alloc_skb(skb_size, GFP_KERNEL); if (!skb) { ret_val = 3; goto err_nomem; } skb_put(skb, skb_size); tx_ring->buffer_info[i].skb = skb; tx_ring->buffer_info[i].length = skb->len; tx_ring->buffer_info[i].dma = dma_map_single(&pdev->dev, skb->data, skb->len, DMA_TO_DEVICE); if (dma_mapping_error(&pdev->dev, tx_ring->buffer_info[i].dma)) { ret_val = 4; goto err_nomem; } tx_desc->buffer_addr = cpu_to_le64(tx_ring->buffer_info[i].dma); tx_desc->lower.data = cpu_to_le32(skb->len); tx_desc->lower.data |= cpu_to_le32(E1000_TXD_CMD_EOP | E1000_TXD_CMD_IFCS | E1000_TXD_CMD_RS); tx_desc->upper.data = 0; } /* Setup Rx descriptor ring and Rx buffers */ if (!rx_ring->count) rx_ring->count = E1000_DEFAULT_RXD; rx_ring->buffer_info = kcalloc(rx_ring->count, sizeof(struct e1000_buffer), GFP_KERNEL); if (!rx_ring->buffer_info) { ret_val = 5; goto err_nomem; } rx_ring->size = rx_ring->count * sizeof(union e1000_rx_desc_extended); rx_ring->desc = dma_alloc_coherent(&pdev->dev, rx_ring->size, &rx_ring->dma, GFP_KERNEL); if (!rx_ring->desc) { ret_val = 6; goto err_nomem; } rx_ring->next_to_use = 0; rx_ring->next_to_clean = 0; rctl = er32(RCTL); if (!(adapter->flags2 & FLAG2_NO_DISABLE_RX)) ew32(RCTL, rctl & ~E1000_RCTL_EN); ew32(RDBAL(0), ((u64)rx_ring->dma & 0xFFFFFFFF)); ew32(RDBAH(0), ((u64)rx_ring->dma >> 32)); ew32(RDLEN(0), rx_ring->size); ew32(RDH(0), 0); ew32(RDT(0), 0); rctl = E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_SZ_2048 | E1000_RCTL_UPE | E1000_RCTL_MPE | E1000_RCTL_LPE | E1000_RCTL_SBP | E1000_RCTL_SECRC | E1000_RCTL_LBM_NO | E1000_RCTL_RDMTS_HALF | (adapter->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT); ew32(RCTL, rctl); for (i = 0; i < rx_ring->count; i++) { union e1000_rx_desc_extended *rx_desc; struct sk_buff *skb; skb = alloc_skb(2048 + NET_IP_ALIGN, GFP_KERNEL); if (!skb) { ret_val = 7; goto err_nomem; } skb_reserve(skb, NET_IP_ALIGN); rx_ring->buffer_info[i].skb = skb; rx_ring->buffer_info[i].dma = dma_map_single(&pdev->dev, skb->data, 2048, DMA_FROM_DEVICE); if (dma_mapping_error(&pdev->dev, rx_ring->buffer_info[i].dma)) { ret_val = 8; goto err_nomem; } rx_desc = E1000_RX_DESC_EXT(*rx_ring, i); rx_desc->read.buffer_addr = cpu_to_le64(rx_ring->buffer_info[i].dma); memset(skb->data, 0x00, skb->len); } return 0; err_nomem: e1000_free_desc_rings(adapter); return ret_val; } static void e1000_phy_disable_receiver(struct e1000_adapter *adapter) { /* Write out to PHY registers 29 and 30 to disable the Receiver. */ e1e_wphy(&adapter->hw, 29, 0x001F); e1e_wphy(&adapter->hw, 30, 0x8FFC); e1e_wphy(&adapter->hw, 29, 0x001A); e1e_wphy(&adapter->hw, 30, 0x8FF0); } static int e1000_integrated_phy_loopback(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrl_reg = 0; u16 phy_reg = 0; s32 ret_val = 0; hw->mac.autoneg = 0; if (hw->phy.type == e1000_phy_ife) { /* force 100, set loopback */ e1e_wphy(hw, MII_BMCR, 0x6100); /* Now set up the MAC to the same speed/duplex as the PHY. */ ctrl_reg = er32(CTRL); ctrl_reg &= ~E1000_CTRL_SPD_SEL; /* Clear the speed sel bits */ ctrl_reg |= (E1000_CTRL_FRCSPD | /* Set the Force Speed Bit */ E1000_CTRL_FRCDPX | /* Set the Force Duplex Bit */ E1000_CTRL_SPD_100 |/* Force Speed to 100 */ E1000_CTRL_FD); /* Force Duplex to FULL */ ew32(CTRL, ctrl_reg); e1e_flush(); usleep_range(500, 1000); return 0; } /* Specific PHY configuration for loopback */ switch (hw->phy.type) { case e1000_phy_m88: /* Auto-MDI/MDIX Off */ e1e_wphy(hw, M88E1000_PHY_SPEC_CTRL, 0x0808); /* reset to update Auto-MDI/MDIX */ e1e_wphy(hw, MII_BMCR, 0x9140); /* autoneg off */ e1e_wphy(hw, MII_BMCR, 0x8140); break; case e1000_phy_gg82563: e1e_wphy(hw, GG82563_PHY_KMRN_MODE_CTRL, 0x1CC); break; case e1000_phy_bm: /* Set Default MAC Interface speed to 1GB */ e1e_rphy(hw, PHY_REG(2, 21), &phy_reg); phy_reg &= ~0x0007; phy_reg |= 0x006; e1e_wphy(hw, PHY_REG(2, 21), phy_reg); /* Assert SW reset for above settings to take effect */ hw->phy.ops.commit(hw); usleep_range(1000, 2000); /* Force Full Duplex */ e1e_rphy(hw, PHY_REG(769, 16), &phy_reg); e1e_wphy(hw, PHY_REG(769, 16), phy_reg | 0x000C); /* Set Link Up (in force link) */ e1e_rphy(hw, PHY_REG(776, 16), &phy_reg); e1e_wphy(hw, PHY_REG(776, 16), phy_reg | 0x0040); /* Force Link */ e1e_rphy(hw, PHY_REG(769, 16), &phy_reg); e1e_wphy(hw, PHY_REG(769, 16), phy_reg | 0x0040); /* Set Early Link Enable */ e1e_rphy(hw, PHY_REG(769, 20), &phy_reg); e1e_wphy(hw, PHY_REG(769, 20), phy_reg | 0x0400); break; case e1000_phy_82577: case e1000_phy_82578: /* Workaround: K1 must be disabled for stable 1Gbps operation */ ret_val = hw->phy.ops.acquire(hw); if (ret_val) { e_err("Cannot setup 1Gbps loopback.\n"); return ret_val; } e1000_configure_k1_ich8lan(hw, false); hw->phy.ops.release(hw); break; case e1000_phy_82579: /* Disable PHY energy detect power down */ e1e_rphy(hw, PHY_REG(0, 21), &phy_reg); e1e_wphy(hw, PHY_REG(0, 21), phy_reg & ~BIT(3)); /* Disable full chip energy detect */ e1e_rphy(hw, PHY_REG(776, 18), &phy_reg); e1e_wphy(hw, PHY_REG(776, 18), phy_reg | 1); /* Enable loopback on the PHY */ e1e_wphy(hw, I82577_PHY_LBK_CTRL, 0x8001); break; default: break; } /* force 1000, set loopback */ e1e_wphy(hw, MII_BMCR, 0x4140); msleep(250); /* Now set up the MAC to the same speed/duplex as the PHY. */ ctrl_reg = er32(CTRL); ctrl_reg &= ~E1000_CTRL_SPD_SEL; /* Clear the speed sel bits */ ctrl_reg |= (E1000_CTRL_FRCSPD | /* Set the Force Speed Bit */ E1000_CTRL_FRCDPX | /* Set the Force Duplex Bit */ E1000_CTRL_SPD_1000 |/* Force Speed to 1000 */ E1000_CTRL_FD); /* Force Duplex to FULL */ if (adapter->flags & FLAG_IS_ICH) ctrl_reg |= E1000_CTRL_SLU; /* Set Link Up */ if (hw->phy.media_type == e1000_media_type_copper && hw->phy.type == e1000_phy_m88) { ctrl_reg |= E1000_CTRL_ILOS; /* Invert Loss of Signal */ } else { /* Set the ILOS bit on the fiber Nic if half duplex link is * detected. */ if ((er32(STATUS) & E1000_STATUS_FD) == 0) ctrl_reg |= (E1000_CTRL_ILOS | E1000_CTRL_SLU); } ew32(CTRL, ctrl_reg); /* Disable the receiver on the PHY so when a cable is plugged in, the * PHY does not begin to autoneg when a cable is reconnected to the NIC. */ if (hw->phy.type == e1000_phy_m88) e1000_phy_disable_receiver(adapter); usleep_range(500, 1000); return 0; } static int e1000_set_82571_fiber_loopback(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrl = er32(CTRL); int link; /* special requirements for 82571/82572 fiber adapters */ /* jump through hoops to make sure link is up because serdes * link is hardwired up */ ctrl |= E1000_CTRL_SLU; ew32(CTRL, ctrl); /* disable autoneg */ ctrl = er32(TXCW); ctrl &= ~BIT(31); ew32(TXCW, ctrl); link = (er32(STATUS) & E1000_STATUS_LU); if (!link) { /* set invert loss of signal */ ctrl = er32(CTRL); ctrl |= E1000_CTRL_ILOS; ew32(CTRL, ctrl); } /* special write to serdes control register to enable SerDes analog * loopback */ ew32(SCTL, E1000_SCTL_ENABLE_SERDES_LOOPBACK); e1e_flush(); usleep_range(10000, 20000); return 0; } /* only call this for fiber/serdes connections to es2lan */ static int e1000_set_es2lan_mac_loopback(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 ctrlext = er32(CTRL_EXT); u32 ctrl = er32(CTRL); /* save CTRL_EXT to restore later, reuse an empty variable (unused * on mac_type 80003es2lan) */ adapter->tx_fifo_head = ctrlext; /* clear the serdes mode bits, putting the device into mac loopback */ ctrlext &= ~E1000_CTRL_EXT_LINK_MODE_PCIE_SERDES; ew32(CTRL_EXT, ctrlext); /* force speed to 1000/FD, link up */ ctrl &= ~(E1000_CTRL_SPD_1000 | E1000_CTRL_SPD_100); ctrl |= (E1000_CTRL_SLU | E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX | E1000_CTRL_SPD_1000 | E1000_CTRL_FD); ew32(CTRL, ctrl); /* set mac loopback */ ctrl = er32(RCTL); ctrl |= E1000_RCTL_LBM_MAC; ew32(RCTL, ctrl); /* set testing mode parameters (no need to reset later) */ #define KMRNCTRLSTA_OPMODE (0x1F << 16) #define KMRNCTRLSTA_OPMODE_1GB_FD_GMII 0x0582 ew32(KMRNCTRLSTA, (KMRNCTRLSTA_OPMODE | KMRNCTRLSTA_OPMODE_1GB_FD_GMII)); return 0; } static int e1000_setup_loopback_test(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 rctl, fext_nvm11, tarc0; if (hw->mac.type == e1000_pch_spt) { fext_nvm11 = er32(FEXTNVM11); fext_nvm11 |= E1000_FEXTNVM11_DISABLE_MULR_FIX; ew32(FEXTNVM11, fext_nvm11); tarc0 = er32(TARC(0)); /* clear bits 28 & 29 (control of MULR concurrent requests) */ tarc0 &= 0xcfffffff; /* set bit 29 (value of MULR requests is now 2) */ tarc0 |= 0x20000000; ew32(TARC(0), tarc0); } if (hw->phy.media_type == e1000_media_type_fiber || hw->phy.media_type == e1000_media_type_internal_serdes) { switch (hw->mac.type) { case e1000_80003es2lan: return e1000_set_es2lan_mac_loopback(adapter); case e1000_82571: case e1000_82572: return e1000_set_82571_fiber_loopback(adapter); default: rctl = er32(RCTL); rctl |= E1000_RCTL_LBM_TCVR; ew32(RCTL, rctl); return 0; } } else if (hw->phy.media_type == e1000_media_type_copper) { return e1000_integrated_phy_loopback(adapter); } return 7; } static void e1000_loopback_cleanup(struct e1000_adapter *adapter) { struct e1000_hw *hw = &adapter->hw; u32 rctl, fext_nvm11, tarc0; u16 phy_reg; rctl = er32(RCTL); rctl &= ~(E1000_RCTL_LBM_TCVR | E1000_RCTL_LBM_MAC); ew32(RCTL, rctl); switch (hw->mac.type) { case e1000_pch_spt: fext_nvm11 = er32(FEXTNVM11); fext_nvm11 &= ~E1000_FEXTNVM11_DISABLE_MULR_FIX; ew32(FEXTNVM11, fext_nvm11); tarc0 = er32(TARC(0)); /* clear bits 28 & 29 (control of MULR concurrent requests) */ /* set bit 29 (value of MULR requests is now 0) */ tarc0 &= 0xcfffffff; ew32(TARC(0), tarc0); /* fall through */ case e1000_80003es2lan: if (hw->phy.media_type == e1000_media_type_fiber || hw->phy.media_type == e1000_media_type_internal_serdes) { /* restore CTRL_EXT, stealing space from tx_fifo_head */ ew32(CTRL_EXT, adapter->tx_fifo_head); adapter->tx_fifo_head = 0; } /* fall through */ case e1000_82571: case e1000_82572: if (hw->phy.media_type == e1000_media_type_fiber || hw->phy.media_type == e1000_media_type_internal_serdes) { ew32(SCTL, E1000_SCTL_DISABLE_SERDES_LOOPBACK); e1e_flush(); usleep_range(10000, 20000); break; } /* Fall Through */ default: hw->mac.autoneg = 1; if (hw->phy.type == e1000_phy_gg82563) e1e_wphy(hw, GG82563_PHY_KMRN_MODE_CTRL, 0x180); e1e_rphy(hw, MII_BMCR, &phy_reg); if (phy_reg & BMCR_LOOPBACK) { phy_reg &= ~BMCR_LOOPBACK; e1e_wphy(hw, MII_BMCR, phy_reg); if (hw->phy.ops.commit) hw->phy.ops.commit(hw); } break; } } static void e1000_create_lbtest_frame(struct sk_buff *skb, unsigned int frame_size) { memset(skb->data, 0xFF, frame_size); frame_size &= ~1; memset(&skb->data[frame_size / 2], 0xAA, frame_size / 2 - 1); memset(&skb->data[frame_size / 2 + 10], 0xBE, 1); memset(&skb->data[frame_size / 2 + 12], 0xAF, 1); } static int e1000_check_lbtest_frame(struct sk_buff *skb, unsigned int frame_size) { frame_size &= ~1; if (*(skb->data + 3) == 0xFF) if ((*(skb->data + frame_size / 2 + 10) == 0xBE) && (*(skb->data + frame_size / 2 + 12) == 0xAF)) return 0; return 13; } static int e1000_run_loopback_test(struct e1000_adapter *adapter) { struct e1000_ring *tx_ring = &adapter->test_tx_ring; struct e1000_ring *rx_ring = &adapter->test_rx_ring; struct pci_dev *pdev = adapter->pdev; struct e1000_hw *hw = &adapter->hw; struct e1000_buffer *buffer_info; int i, j, k, l; int lc; int good_cnt; int ret_val = 0; unsigned long time; ew32(RDT(0), rx_ring->count - 1); /* Calculate the loop count based on the largest descriptor ring * The idea is to wrap the largest ring a number of times using 64 * send/receive pairs during each loop */ if (rx_ring->count <= tx_ring->count) lc = ((tx_ring->count / 64) * 2) + 1; else lc = ((rx_ring->count / 64) * 2) + 1; k = 0; l = 0; /* loop count loop */ for (j = 0; j <= lc; j++) { /* send the packets */ for (i = 0; i < 64; i++) { buffer_info = &tx_ring->buffer_info[k]; e1000_create_lbtest_frame(buffer_info->skb, 1024); dma_sync_single_for_device(&pdev->dev, buffer_info->dma, buffer_info->length, DMA_TO_DEVICE); k++; if (k == tx_ring->count) k = 0; } ew32(TDT(0), k); e1e_flush(); msleep(200); time = jiffies; /* set the start time for the receive */ good_cnt = 0; /* receive the sent packets */ do { buffer_info = &rx_ring->buffer_info[l]; dma_sync_single_for_cpu(&pdev->dev, buffer_info->dma, 2048, DMA_FROM_DEVICE); ret_val = e1000_check_lbtest_frame(buffer_info->skb, 1024); if (!ret_val) good_cnt++; l++; if (l == rx_ring->count) l = 0; /* time + 20 msecs (200 msecs on 2.4) is more than * enough time to complete the receives, if it's * exceeded, break and error off */ } while ((good_cnt < 64) && !time_after(jiffies, time + 20)); if (good_cnt != 64) { ret_val = 13; /* ret_val is the same as mis-compare */ break; } if (time_after(jiffies, time + 20)) { ret_val = 14; /* error code for time out error */ break; } } return ret_val; } static int e1000_loopback_test(struct e1000_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; /* PHY loopback cannot be performed if SoL/IDER sessions are active */ if (hw->phy.ops.check_reset_block && hw->phy.ops.check_reset_block(hw)) { e_err("Cannot do PHY loopback test when SoL/IDER is active.\n"); *data = 0; goto out; } *data = e1000_setup_desc_rings(adapter); if (*data) goto out; *data = e1000_setup_loopback_test(adapter); if (*data) goto err_loopback; *data = e1000_run_loopback_test(adapter); e1000_loopback_cleanup(adapter); err_loopback: e1000_free_desc_rings(adapter); out: return *data; } static int e1000_link_test(struct e1000_adapter *adapter, u64 *data) { struct e1000_hw *hw = &adapter->hw; *data = 0; if (hw->phy.media_type == e1000_media_type_internal_serdes) { int i = 0; hw->mac.serdes_has_link = false; /* On some blade server designs, link establishment * could take as long as 2-3 minutes */ do { hw->mac.ops.check_for_link(hw); if (hw->mac.serdes_has_link) return *data; msleep(20); } while (i++ < 3750); *data = 1; } else { hw->mac.ops.check_for_link(hw); if (hw->mac.autoneg) /* On some Phy/switch combinations, link establishment * can take a few seconds more than expected. */ msleep_interruptible(5000); if (!(er32(STATUS) & E1000_STATUS_LU)) *data = 1; } return *data; } static int e1000e_get_sset_count(struct net_device __always_unused *netdev, int sset) { switch (sset) { case ETH_SS_TEST: return E1000_TEST_LEN; case ETH_SS_STATS: return E1000_STATS_LEN; default: return -EOPNOTSUPP; } } static void e1000_diag_test(struct net_device *netdev, struct ethtool_test *eth_test, u64 *data) { struct e1000_adapter *adapter = netdev_priv(netdev); u16 autoneg_advertised; u8 forced_speed_duplex; u8 autoneg; bool if_running = netif_running(netdev); pm_runtime_get_sync(netdev->dev.parent); set_bit(__E1000_TESTING, &adapter->state); if (!if_running) { /* Get control of and reset hardware */ if (adapter->flags & FLAG_HAS_AMT) e1000e_get_hw_control(adapter); e1000e_power_up_phy(adapter); adapter->hw.phy.autoneg_wait_to_complete = 1; e1000e_reset(adapter); adapter->hw.phy.autoneg_wait_to_complete = 0; } if (eth_test->flags == ETH_TEST_FL_OFFLINE) { /* Offline tests */ /* save speed, duplex, autoneg settings */ autoneg_advertised = adapter->hw.phy.autoneg_advertised; forced_speed_duplex = adapter->hw.mac.forced_speed_duplex; autoneg = adapter->hw.mac.autoneg; e_info("offline testing starting\n"); if (if_running) /* indicate we're in test mode */ e1000e_close(netdev); if (e1000_reg_test(adapter, &data[0])) eth_test->flags |= ETH_TEST_FL_FAILED; e1000e_reset(adapter); if (e1000_eeprom_test(adapter, &data[1])) eth_test->flags |= ETH_TEST_FL_FAILED; e1000e_reset(adapter); if (e1000_intr_test(adapter, &data[2])) eth_test->flags |= ETH_TEST_FL_FAILED; e1000e_reset(adapter); if (e1000_loopback_test(adapter, &data[3])) eth_test->flags |= ETH_TEST_FL_FAILED; /* force this routine to wait until autoneg complete/timeout */ adapter->hw.phy.autoneg_wait_to_complete = 1; e1000e_reset(adapter); adapter->hw.phy.autoneg_wait_to_complete = 0; if (e1000_link_test(adapter, &data[4])) eth_test->flags |= ETH_TEST_FL_FAILED; /* restore speed, duplex, autoneg settings */ adapter->hw.phy.autoneg_advertised = autoneg_advertised; adapter->hw.mac.forced_speed_duplex = forced_speed_duplex; adapter->hw.mac.autoneg = autoneg; e1000e_reset(adapter); clear_bit(__E1000_TESTING, &adapter->state); if (if_running) e1000e_open(netdev); } else { /* Online tests */ e_info("online testing starting\n"); /* register, eeprom, intr and loopback tests not run online */ data[0] = 0; data[1] = 0; data[2] = 0; data[3] = 0; if (e1000_link_test(adapter, &data[4])) eth_test->flags |= ETH_TEST_FL_FAILED; clear_bit(__E1000_TESTING, &adapter->state); } if (!if_running) { e1000e_reset(adapter); if (adapter->flags & FLAG_HAS_AMT) e1000e_release_hw_control(adapter); } msleep_interruptible(4 * 1000); pm_runtime_put_sync(netdev->dev.parent); } static void e1000_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct e1000_adapter *adapter = netdev_priv(netdev); wol->supported = 0; wol->wolopts = 0; if (!(adapter->flags & FLAG_HAS_WOL) || !device_can_wakeup(&adapter->pdev->dev)) return; wol->supported = WAKE_UCAST | WAKE_MCAST | WAKE_BCAST | WAKE_MAGIC | WAKE_PHY; /* apply any specific unsupported masks here */ if (adapter->flags & FLAG_NO_WAKE_UCAST) { wol->supported &= ~WAKE_UCAST; if (adapter->wol & E1000_WUFC_EX) e_err("Interface does not support directed (unicast) frame wake-up packets\n"); } if (adapter->wol & E1000_WUFC_EX) wol->wolopts |= WAKE_UCAST; if (adapter->wol & E1000_WUFC_MC) wol->wolopts |= WAKE_MCAST; if (adapter->wol & E1000_WUFC_BC) wol->wolopts |= WAKE_BCAST; if (adapter->wol & E1000_WUFC_MAG) wol->wolopts |= WAKE_MAGIC; if (adapter->wol & E1000_WUFC_LNKC) wol->wolopts |= WAKE_PHY; } static int e1000_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct e1000_adapter *adapter = netdev_priv(netdev); if (!(adapter->flags & FLAG_HAS_WOL) || !device_can_wakeup(&adapter->pdev->dev) || (wol->wolopts & ~(WAKE_UCAST | WAKE_MCAST | WAKE_BCAST | WAKE_MAGIC | WAKE_PHY))) return -EOPNOTSUPP; /* these settings will always override what we currently have */ adapter->wol = 0; if (wol->wolopts & WAKE_UCAST) adapter->wol |= E1000_WUFC_EX; if (wol->wolopts & WAKE_MCAST) adapter->wol |= E1000_WUFC_MC; if (wol->wolopts & WAKE_BCAST) adapter->wol |= E1000_WUFC_BC; if (wol->wolopts & WAKE_MAGIC) adapter->wol |= E1000_WUFC_MAG; if (wol->wolopts & WAKE_PHY) adapter->wol |= E1000_WUFC_LNKC; device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol); return 0; } static int e1000_set_phys_id(struct net_device *netdev, enum ethtool_phys_id_state state) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; switch (state) { case ETHTOOL_ID_ACTIVE: pm_runtime_get_sync(netdev->dev.parent); if (!hw->mac.ops.blink_led) return 2; /* cycle on/off twice per second */ hw->mac.ops.blink_led(hw); break; case ETHTOOL_ID_INACTIVE: if (hw->phy.type == e1000_phy_ife) e1e_wphy(hw, IFE_PHY_SPECIAL_CONTROL_LED, 0); hw->mac.ops.led_off(hw); hw->mac.ops.cleanup_led(hw); pm_runtime_put_sync(netdev->dev.parent); break; case ETHTOOL_ID_ON: hw->mac.ops.led_on(hw); break; case ETHTOOL_ID_OFF: hw->mac.ops.led_off(hw); break; } return 0; } static int e1000_get_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec) { struct e1000_adapter *adapter = netdev_priv(netdev); if (adapter->itr_setting <= 4) ec->rx_coalesce_usecs = adapter->itr_setting; else ec->rx_coalesce_usecs = 1000000 / adapter->itr_setting; return 0; } static int e1000_set_coalesce(struct net_device *netdev, struct ethtool_coalesce *ec) { struct e1000_adapter *adapter = netdev_priv(netdev); if ((ec->rx_coalesce_usecs > E1000_MAX_ITR_USECS) || ((ec->rx_coalesce_usecs > 4) && (ec->rx_coalesce_usecs < E1000_MIN_ITR_USECS)) || (ec->rx_coalesce_usecs == 2)) return -EINVAL; if (ec->rx_coalesce_usecs == 4) { adapter->itr_setting = 4; adapter->itr = adapter->itr_setting; } else if (ec->rx_coalesce_usecs <= 3) { adapter->itr = 20000; adapter->itr_setting = ec->rx_coalesce_usecs; } else { adapter->itr = (1000000 / ec->rx_coalesce_usecs); adapter->itr_setting = adapter->itr & ~3; } pm_runtime_get_sync(netdev->dev.parent); if (adapter->itr_setting != 0) e1000e_write_itr(adapter, adapter->itr); else e1000e_write_itr(adapter, 0); pm_runtime_put_sync(netdev->dev.parent); return 0; } static int e1000_nway_reset(struct net_device *netdev) { struct e1000_adapter *adapter = netdev_priv(netdev); if (!netif_running(netdev)) return -EAGAIN; if (!adapter->hw.mac.autoneg) return -EINVAL; pm_runtime_get_sync(netdev->dev.parent); e1000e_reinit_locked(adapter); pm_runtime_put_sync(netdev->dev.parent); return 0; } static void e1000_get_ethtool_stats(struct net_device *netdev, struct ethtool_stats __always_unused *stats, u64 *data) { struct e1000_adapter *adapter = netdev_priv(netdev); struct rtnl_link_stats64 net_stats; int i; char *p = NULL; pm_runtime_get_sync(netdev->dev.parent); e1000e_get_stats64(netdev, &net_stats); pm_runtime_put_sync(netdev->dev.parent); for (i = 0; i < E1000_GLOBAL_STATS_LEN; i++) { switch (e1000_gstrings_stats[i].type) { case NETDEV_STATS: p = (char *)&net_stats + e1000_gstrings_stats[i].stat_offset; break; case E1000_STATS: p = (char *)adapter + e1000_gstrings_stats[i].stat_offset; break; default: data[i] = 0; continue; } data[i] = (e1000_gstrings_stats[i].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p; } } static void e1000_get_strings(struct net_device __always_unused *netdev, u32 stringset, u8 *data) { u8 *p = data; int i; switch (stringset) { case ETH_SS_TEST: memcpy(data, e1000_gstrings_test, sizeof(e1000_gstrings_test)); break; case ETH_SS_STATS: for (i = 0; i < E1000_GLOBAL_STATS_LEN; i++) { memcpy(p, e1000_gstrings_stats[i].stat_string, ETH_GSTRING_LEN); p += ETH_GSTRING_LEN; } break; } } static int e1000_get_rxnfc(struct net_device *netdev, struct ethtool_rxnfc *info, u32 __always_unused *rule_locs) { info->data = 0; switch (info->cmd) { case ETHTOOL_GRXFH: { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u32 mrqc; pm_runtime_get_sync(netdev->dev.parent); mrqc = er32(MRQC); pm_runtime_put_sync(netdev->dev.parent); if (!(mrqc & E1000_MRQC_RSS_FIELD_MASK)) return 0; switch (info->flow_type) { case TCP_V4_FLOW: if (mrqc & E1000_MRQC_RSS_FIELD_IPV4_TCP) info->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; /* fall through */ case UDP_V4_FLOW: case SCTP_V4_FLOW: case AH_ESP_V4_FLOW: case IPV4_FLOW: if (mrqc & E1000_MRQC_RSS_FIELD_IPV4) info->data |= RXH_IP_SRC | RXH_IP_DST; break; case TCP_V6_FLOW: if (mrqc & E1000_MRQC_RSS_FIELD_IPV6_TCP) info->data |= RXH_L4_B_0_1 | RXH_L4_B_2_3; /* fall through */ case UDP_V6_FLOW: case SCTP_V6_FLOW: case AH_ESP_V6_FLOW: case IPV6_FLOW: if (mrqc & E1000_MRQC_RSS_FIELD_IPV6) info->data |= RXH_IP_SRC | RXH_IP_DST; break; default: break; } return 0; } default: return -EOPNOTSUPP; } } static int e1000e_get_eee(struct net_device *netdev, struct ethtool_eee *edata) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; u16 cap_addr, lpa_addr, pcs_stat_addr, phy_data; u32 ret_val; if (!(adapter->flags2 & FLAG2_HAS_EEE)) return -EOPNOTSUPP; switch (hw->phy.type) { case e1000_phy_82579: cap_addr = I82579_EEE_CAPABILITY; lpa_addr = I82579_EEE_LP_ABILITY; pcs_stat_addr = I82579_EEE_PCS_STATUS; break; case e1000_phy_i217: cap_addr = I217_EEE_CAPABILITY; lpa_addr = I217_EEE_LP_ABILITY; pcs_stat_addr = I217_EEE_PCS_STATUS; break; default: return -EOPNOTSUPP; } pm_runtime_get_sync(netdev->dev.parent); ret_val = hw->phy.ops.acquire(hw); if (ret_val) { pm_runtime_put_sync(netdev->dev.parent); return -EBUSY; } /* EEE Capability */ ret_val = e1000_read_emi_reg_locked(hw, cap_addr, &phy_data); if (ret_val) goto release; edata->supported = mmd_eee_cap_to_ethtool_sup_t(phy_data); /* EEE Advertised */ edata->advertised = mmd_eee_adv_to_ethtool_adv_t(adapter->eee_advert); /* EEE Link Partner Advertised */ ret_val = e1000_read_emi_reg_locked(hw, lpa_addr, &phy_data); if (ret_val) goto release; edata->lp_advertised = mmd_eee_adv_to_ethtool_adv_t(phy_data); /* EEE PCS Status */ ret_val = e1000_read_emi_reg_locked(hw, pcs_stat_addr, &phy_data); if (ret_val) goto release; if (hw->phy.type == e1000_phy_82579) phy_data <<= 8; /* Result of the EEE auto negotiation - there is no register that * has the status of the EEE negotiation so do a best-guess based * on whether Tx or Rx LPI indications have been received. */ if (phy_data & (E1000_EEE_TX_LPI_RCVD | E1000_EEE_RX_LPI_RCVD)) edata->eee_active = true; edata->eee_enabled = !hw->dev_spec.ich8lan.eee_disable; edata->tx_lpi_enabled = true; edata->tx_lpi_timer = er32(LPIC) >> E1000_LPIC_LPIET_SHIFT; release: hw->phy.ops.release(hw); if (ret_val) ret_val = -ENODATA; pm_runtime_put_sync(netdev->dev.parent); return ret_val; } static int e1000e_set_eee(struct net_device *netdev, struct ethtool_eee *edata) { struct e1000_adapter *adapter = netdev_priv(netdev); struct e1000_hw *hw = &adapter->hw; struct ethtool_eee eee_curr; s32 ret_val; ret_val = e1000e_get_eee(netdev, &eee_curr); if (ret_val) return ret_val; if (eee_curr.tx_lpi_enabled != edata->tx_lpi_enabled) { e_err("Setting EEE tx-lpi is not supported\n"); return -EINVAL; } if (eee_curr.tx_lpi_timer != edata->tx_lpi_timer) { e_err("Setting EEE Tx LPI timer is not supported\n"); return -EINVAL; } if (edata->advertised & ~(ADVERTISE_100_FULL | ADVERTISE_1000_FULL)) { e_err("EEE advertisement supports only 100TX and/or 1000T full-duplex\n"); return -EINVAL; } adapter->eee_advert = ethtool_adv_to_mmd_eee_adv_t(edata->advertised); hw->dev_spec.ich8lan.eee_disable = !edata->eee_enabled; pm_runtime_get_sync(netdev->dev.parent); /* reset the link */ if (netif_running(netdev)) e1000e_reinit_locked(adapter); else e1000e_reset(adapter); pm_runtime_put_sync(netdev->dev.parent); return 0; } static int e1000e_get_ts_info(struct net_device *netdev, struct ethtool_ts_info *info) { struct e1000_adapter *adapter = netdev_priv(netdev); ethtool_op_get_ts_info(netdev, info); if (!(adapter->flags & FLAG_HAS_HW_TIMESTAMP)) return 0; info->so_timestamping |= (SOF_TIMESTAMPING_TX_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_RAW_HARDWARE); info->tx_types = BIT(HWTSTAMP_TX_OFF) | BIT(HWTSTAMP_TX_ON); info->rx_filters = (BIT(HWTSTAMP_FILTER_NONE) | BIT(HWTSTAMP_FILTER_PTP_V1_L4_SYNC) | BIT(HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ) | BIT(HWTSTAMP_FILTER_PTP_V2_L4_SYNC) | BIT(HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ) | BIT(HWTSTAMP_FILTER_PTP_V2_L2_SYNC) | BIT(HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ) | BIT(HWTSTAMP_FILTER_PTP_V2_EVENT) | BIT(HWTSTAMP_FILTER_PTP_V2_SYNC) | BIT(HWTSTAMP_FILTER_PTP_V2_DELAY_REQ) | BIT(HWTSTAMP_FILTER_ALL)); if (adapter->ptp_clock) info->phc_index = ptp_clock_index(adapter->ptp_clock); return 0; } static const struct ethtool_ops e1000_ethtool_ops = { .get_settings = e1000_get_settings, .set_settings = e1000_set_settings, .get_drvinfo = e1000_get_drvinfo, .get_regs_len = e1000_get_regs_len, .get_regs = e1000_get_regs, .get_wol = e1000_get_wol, .set_wol = e1000_set_wol, .get_msglevel = e1000_get_msglevel, .set_msglevel = e1000_set_msglevel, .nway_reset = e1000_nway_reset, .get_link = ethtool_op_get_link, .get_eeprom_len = e1000_get_eeprom_len, .get_eeprom = e1000_get_eeprom, .set_eeprom = e1000_set_eeprom, .get_ringparam = e1000_get_ringparam, .set_ringparam = e1000_set_ringparam, .get_pauseparam = e1000_get_pauseparam, .set_pauseparam = e1000_set_pauseparam, .self_test = e1000_diag_test, .get_strings = e1000_get_strings, .set_phys_id = e1000_set_phys_id, .get_ethtool_stats = e1000_get_ethtool_stats, .get_sset_count = e1000e_get_sset_count, .get_coalesce = e1000_get_coalesce, .set_coalesce = e1000_set_coalesce, .get_rxnfc = e1000_get_rxnfc, .get_ts_info = e1000e_get_ts_info, .get_eee = e1000e_get_eee, .set_eee = e1000e_set_eee, }; void e1000e_set_ethtool_ops(struct net_device *netdev) { netdev->ethtool_ops = &e1000_ethtool_ops; }
null
null
null
null
93,831
702
null
train_val
31e986bc171719c9e6d40d0c2cb1501796a69e6c
259,657
php-src
0
https://github.com/php/php-src
2016-10-24 10:37:20+01:00
/** * this is a small sample script to use libmbfl. * Rui Hirokawa <hirokawa@php.net> * * this file is encoded in EUC-JP. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mbfl/mbfilter.h" static void hexdump(const mbfl_string *ptr) { unsigned int i; for (i = 0; i < ptr->len; i++) { printf("%%%02x", ptr->val[i]); } printf(" (%u)\n", ptr->len); } //#define TEST_DOCOMO //#define TEST_KDDI #define TEST_SOFTBANK int main(int argc, char **argv) { enum mbfl_no_encoding from_encoding, to_encoding; enum mbfl_no_language no_language; mbfl_buffer_converter *convd = NULL, *convd2 = NULL; mbfl_memory_device dev, dev2; mbfl_string string, result, *ret; #ifdef TEST_DOCOMO //char str[] = {0xF9,0xD7,0x00}; // U+2122 //char str[] = {0xF9,0x82,0x00}; // U+1F195 char str[] = {0xF9,0xD6,0x00}; // U+00A9 #endif #ifdef TEST_KDDI //char str[] = {0xF7,0x6A,0x00};// U+2122 //char str[] = {0xF7,0xE5,0x00}; // U+1F195 //char str[] = {0xF3,0xD2,0x00}; // U+1F1E8 U+1F1F3 char str[] = {0xF7,0x74,0x00}; // U+00A9 #endif #ifdef TEST_SOFTBANK //char str[] = {0xFB,0xD7,0x00};// U+2122 //char str[] = {0xF7,0xB2,0x00}; // U+1F195 //char str[] = {0xFB,0xB3,0x00}; // U+1F1E8 U+1F1F3 char str[] = {0xF7,0xEE,0x00}; // U+00A9 #endif int final = 0; int state = 0; int i; no_language = mbfl_name2no_language("Japanese"); #ifdef TEST_DOCOMO from_encoding = mbfl_name2no_encoding("SJIS-win#DOCOMO"); #endif #ifdef TEST_KDDI from_encoding = mbfl_name2no_encoding("SJIS-win#KDDI"); #endif #ifdef TEST_SOFTBANK from_encoding = mbfl_name2no_encoding("SJIS-win#SOFTBANK"); #endif to_encoding = mbfl_name2no_encoding("UTF-8"); convd = mbfl_buffer_converter_new(from_encoding, to_encoding, 0); mbfl_memory_device_init(&dev, 0, 4096); mbfl_string_init_set(&string, no_language, from_encoding); mbfl_memory_device_realloc(&dev, dev.length + dev.allocsz, dev.allocsz); strcpy(dev.buffer, str); dev.pos += strlen(str); mbfl_memory_device_result(&dev, &string); mbfl_string_init_set(&result, no_language, to_encoding); ret = mbfl_buffer_converter_feed_result(convd, &string, &result); #if 0 for (i = 0; i < result.len; i+= 2) { if (result.val[i] >= 0xD8 && result.val[i] < 0xE0) { // Surrogate pair int h = (result.val[i] & 0x07)<<8 | result.val[i+1]; int l = (result.val[i+2] & 0x03)<<8 | result.val[i+3]; int c = (h<<(2+8)) | l; printf("U+%x\n",c+0x10000); i+=2; } else { printf("U+%x\n",(result.val[i] << 8) | result.val[i+1]); } } hexdump(&result); #endif #if 1 convd2 = mbfl_buffer_converter_new(to_encoding, from_encoding, 0); mbfl_memory_device_init(&dev2, 0, 4096); mbfl_string_init_set(&string, no_language, to_encoding); mbfl_memory_device_realloc(&dev2, dev2.length + dev2.allocsz, dev2.allocsz); memcpy(dev2.buffer, result.val, result.len+1); dev2.pos += strlen(dev2.buffer); mbfl_memory_device_result(&dev2, &string); mbfl_string_init_set(&result, no_language, from_encoding); ret = mbfl_buffer_converter_feed_result(convd2, &string, &result); hexdump(&result); mbfl_buffer_converter_delete(convd2); #endif mbfl_string_clear(&result); mbfl_string_clear(&string); mbfl_buffer_converter_delete(convd); return EXIT_SUCCESS; }
null
null
null
null
119,578
49,358
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
49,358
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/mojo/buffer_types_struct_traits.h" #include "build/build_config.h" #include "mojo/public/cpp/system/platform_handle.h" namespace mojo { // static bool StructTraits<gfx::mojom::BufferUsageAndFormatDataView, gfx::BufferUsageAndFormat>:: Read(gfx::mojom::BufferUsageAndFormatDataView data, gfx::BufferUsageAndFormat* out) { return data.ReadUsage(&out->usage) && data.ReadFormat(&out->format); } std::vector<mojo::ScopedHandle> StructTraits<gfx::mojom::NativePixmapHandleDataView, gfx::NativePixmapHandle>:: fds(const gfx::NativePixmapHandle& pixmap_handle) { std::vector<mojo::ScopedHandle> handles; #if defined(OS_LINUX) for (const base::FileDescriptor& fd : pixmap_handle.fds) handles.emplace_back(mojo::WrapPlatformFile(fd.fd)); #endif // defined(OS_LINUX) return handles; } bool StructTraits< gfx::mojom::NativePixmapHandleDataView, gfx::NativePixmapHandle>::Read(gfx::mojom::NativePixmapHandleDataView data, gfx::NativePixmapHandle* out) { #if defined(OS_LINUX) mojo::ArrayDataView<mojo::ScopedHandle> handles_data_view; data.GetFdsDataView(&handles_data_view); for (size_t i = 0; i < handles_data_view.size(); ++i) { mojo::ScopedHandle handle = handles_data_view.Take(i); base::PlatformFile platform_file; if (mojo::UnwrapPlatformFile(std::move(handle), &platform_file) != MOJO_RESULT_OK) return false; constexpr bool auto_close = true; out->fds.push_back(base::FileDescriptor(platform_file, auto_close)); } return data.ReadPlanes(&out->planes); #else return false; #endif } mojo::ScopedSharedBufferHandle StructTraits<gfx::mojom::GpuMemoryBufferHandleDataView, gfx::GpuMemoryBufferHandle>:: shared_memory_handle(const gfx::GpuMemoryBufferHandle& handle) { if (handle.type != gfx::SHARED_MEMORY_BUFFER && handle.type != gfx::DXGI_SHARED_HANDLE && handle.type != gfx::ANDROID_HARDWARE_BUFFER) return mojo::ScopedSharedBufferHandle(); return mojo::WrapSharedMemoryHandle( handle.handle, handle.handle.GetSize(), mojo::UnwrappedSharedMemoryHandleProtection::kReadWrite); } const gfx::NativePixmapHandle& StructTraits<gfx::mojom::GpuMemoryBufferHandleDataView, gfx::GpuMemoryBufferHandle>:: native_pixmap_handle(const gfx::GpuMemoryBufferHandle& handle) { #if defined(OS_LINUX) return handle.native_pixmap_handle; #else static gfx::NativePixmapHandle pixmap_handle; return pixmap_handle; #endif } mojo::ScopedHandle StructTraits<gfx::mojom::GpuMemoryBufferHandleDataView, gfx::GpuMemoryBufferHandle>:: mach_port(const gfx::GpuMemoryBufferHandle& handle) { #if defined(OS_MACOSX) && !defined(OS_IOS) if (handle.type != gfx::IO_SURFACE_BUFFER) return mojo::ScopedHandle(); return mojo::WrapMachPort(handle.mach_port.get()); #else return mojo::ScopedHandle(); #endif } bool StructTraits<gfx::mojom::GpuMemoryBufferHandleDataView, gfx::GpuMemoryBufferHandle>:: Read(gfx::mojom::GpuMemoryBufferHandleDataView data, gfx::GpuMemoryBufferHandle* out) { if (!data.ReadType(&out->type) || !data.ReadId(&out->id)) return false; if (out->type == gfx::SHARED_MEMORY_BUFFER || out->type == gfx::DXGI_SHARED_HANDLE || out->type == gfx::ANDROID_HARDWARE_BUFFER) { mojo::ScopedSharedBufferHandle handle = data.TakeSharedMemoryHandle(); if (handle.is_valid()) { MojoResult unwrap_result = mojo::UnwrapSharedMemoryHandle( std::move(handle), &out->handle, nullptr, nullptr); if (unwrap_result != MOJO_RESULT_OK) return false; } out->offset = data.offset(); out->stride = data.stride(); } #if defined(OS_LINUX) if (out->type == gfx::NATIVE_PIXMAP && !data.ReadNativePixmapHandle(&out->native_pixmap_handle)) return false; #endif #if defined(OS_MACOSX) && !defined(OS_IOS) if (out->type == gfx::IO_SURFACE_BUFFER) { mach_port_t mach_port; MojoResult unwrap_result = mojo::UnwrapMachPort(data.TakeMachPort(), &mach_port); if (unwrap_result != MOJO_RESULT_OK) return false; out->mach_port.reset(mach_port); } #endif return true; } } // namespace mojo
null
null
null
null
46,221
61,257
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
61,257
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/android/jni_string.h" #include "chrome/browser/dom_distiller/tab_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "components/dom_distiller/core/experiments.h" #include "components/navigation_interception/intercept_navigation_delegate.h" #include "components/url_formatter/url_formatter.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_constants.h" #include "jni/DomDistillerTabUtils_jni.h" #include "url/gurl.h" using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; namespace android { void JNI_DomDistillerTabUtils_DistillCurrentPageAndView( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jobject>& j_web_contents) { content::WebContents* web_contents = content::WebContents::FromJavaWebContents(j_web_contents); ::DistillCurrentPageAndView(web_contents); } void JNI_DomDistillerTabUtils_DistillCurrentPage( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jobject>& j_source_web_contents) { content::WebContents* source_web_contents = content::WebContents::FromJavaWebContents(j_source_web_contents); ::DistillCurrentPage(source_web_contents); } void JNI_DomDistillerTabUtils_DistillAndView( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jobject>& j_source_web_contents, const JavaParamRef<jobject>& j_destination_web_contents) { content::WebContents* source_web_contents = content::WebContents::FromJavaWebContents(j_source_web_contents); content::WebContents* destination_web_contents = content::WebContents::FromJavaWebContents(j_destination_web_contents); ::DistillAndView(source_web_contents, destination_web_contents); } ScopedJavaLocalRef<jstring> JNI_DomDistillerTabUtils_GetFormattedUrlFromOriginalDistillerUrl( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jstring>& j_url) { GURL url(base::android::ConvertJavaStringToUTF8(env, j_url)); if (url.spec().length() > content::kMaxURLDisplayChars) url = url.IsStandard() ? url.GetOrigin() : GURL(url.scheme() + ":"); // Note that we can't unescape spaces here, because if the user copies this // and pastes it into another program, that program may think the URL ends at // the space. return base::android::ConvertUTF16ToJavaString( env, url_formatter::FormatUrl(url, url_formatter::kFormatUrlOmitDefaults, net::UnescapeRule::NORMAL, nullptr, nullptr, nullptr)); } jint JNI_DomDistillerTabUtils_GetDistillerHeuristics( JNIEnv* env, const JavaParamRef<jclass>& clazz) { return static_cast<jint>(dom_distiller::GetDistillerHeuristicsType()); } void JNI_DomDistillerTabUtils_SetInterceptNavigationDelegate( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jobject>& delegate, const JavaParamRef<jobject>& j_web_contents) { content::WebContents* web_contents = content::WebContents::FromJavaWebContents(j_web_contents); DCHECK(web_contents); navigation_interception::InterceptNavigationDelegate::Associate( web_contents, std::make_unique<navigation_interception::InterceptNavigationDelegate>( env, delegate)); } } // namespace android
null
null
null
null
58,120
34,264
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
34,264
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/paint/paint_property_tree_printer.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/layout/layout_embedded_content.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/paint/object_paint_properties.h" #include <iomanip> #include <sstream> #if DCHECK_IS_ON() namespace blink { namespace { template <typename PropertyTreeNode> class PropertyTreePrinterTraits; template <typename PropertyTreeNode> class FrameViewPropertyTreePrinter : public PropertyTreePrinter<PropertyTreeNode> { public: String TreeAsString(const LocalFrameView& frame_view) { CollectNodes(frame_view); return PropertyTreePrinter<PropertyTreeNode>::NodesAsTreeString(); } private: using Traits = PropertyTreePrinterTraits<PropertyTreeNode>; void CollectNodes(const LocalFrameView& frame_view) { Traits::AddFrameViewProperties(frame_view, *this); if (LayoutView* layout_view = frame_view.GetLayoutView()) CollectNodes(*layout_view); for (Frame* child = frame_view.GetFrame().Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (!child->IsLocalFrame()) continue; if (LocalFrameView* child_view = ToLocalFrame(child)->View()) CollectNodes(*child_view); } } void CollectNodes(const LayoutObject& object) { for (const auto* fragment = &object.FirstFragment(); fragment; fragment = fragment->NextFragment()) { if (const auto* properties = fragment->PaintProperties()) Traits::AddObjectPaintProperties(object, *properties, *this); } for (const auto* child = object.SlowFirstChild(); child; child = child->NextSibling()) { CollectNodes(*child); } } }; template <> class PropertyTreePrinterTraits<TransformPaintPropertyNode> { public: static void AddFrameViewProperties( const LocalFrameView& frame_view, PropertyTreePrinter<TransformPaintPropertyNode>& printer) { printer.AddNode(frame_view.PreTranslation()); printer.AddNode(frame_view.ScrollTranslation()); } static void AddObjectPaintProperties( const LayoutObject& object, const ObjectPaintProperties& properties, PropertyTreePrinter<TransformPaintPropertyNode>& printer) { printer.AddNode(properties.PaintOffsetTranslation()); printer.AddNode(properties.Transform()); printer.AddNode(properties.Perspective()); printer.AddNode(properties.SvgLocalToBorderBoxTransform()); printer.AddNode(properties.ScrollTranslation()); } }; template <> class PropertyTreePrinterTraits<ClipPaintPropertyNode> { public: static void AddFrameViewProperties( const LocalFrameView& frame_view, PropertyTreePrinter<ClipPaintPropertyNode>& printer) { printer.AddNode(frame_view.ContentClip()); } static void AddObjectPaintProperties( const LayoutObject& object, const ObjectPaintProperties& properties, PropertyTreePrinter<ClipPaintPropertyNode>& printer) { printer.AddNode(properties.FragmentClip()); printer.AddNode(properties.MaskClip()); printer.AddNode(properties.CssClip()); printer.AddNode(properties.CssClipFixedPosition()); printer.AddNode(properties.OverflowControlsClip()); printer.AddNode(properties.InnerBorderRadiusClip()); printer.AddNode(OverflowClip(properties)); } }; template <> class PropertyTreePrinterTraits<EffectPaintPropertyNode> { public: static void AddFrameViewProperties( const LocalFrameView& frame_view, PropertyTreePrinter<EffectPaintPropertyNode>& printer) {} static void AddObjectPaintProperties( const LayoutObject& object, const ObjectPaintProperties& properties, PropertyTreePrinter<EffectPaintPropertyNode>& printer) { printer.AddNode(properties.Effect()); printer.AddNode(properties.Filter()); printer.AddNode(properties.Mask()); } }; template <> class PropertyTreePrinterTraits<ScrollPaintPropertyNode> { public: static void AddFrameViewProperties( const LocalFrameView& frame_view, PropertyTreePrinter<ScrollPaintPropertyNode>& printer) { printer.AddNode(frame_view.ScrollNode()); } static void AddObjectPaintProperties( const LayoutObject& object, const ObjectPaintProperties& properties, PropertyTreePrinter<ScrollPaintPropertyNode>& printer) { printer.AddNode(properties.Scroll()); } }; template <typename PropertyTreeNode> void SetDebugName(const PropertyTreeNode* node, const String& debug_name) { if (node) const_cast<PropertyTreeNode*>(node)->SetDebugName(debug_name); } template <typename PropertyTreeNode> void SetDebugName(const PropertyTreeNode* node, const String& name, const LayoutObject& object) { if (node) SetDebugName(node, name + " (" + object.DebugName() + ")"); } } // namespace namespace PaintPropertyTreePrinter { void UpdateDebugNames(const LocalFrameView& frame_view) { SetDebugName(frame_view.PreTranslation(), "PreTranslation (FrameView)"); SetDebugName(frame_view.ScrollTranslation(), "ScrollTranslation (FrameView)"); SetDebugName(frame_view.ContentClip(), "ContentClip (FrameView)"); SetDebugName(frame_view.ScrollNode(), "Scroll (FrameView)"); } void UpdateDebugNames(const LayoutObject& object, ObjectPaintProperties& properties) { SetDebugName(properties.PaintOffsetTranslation(), "PaintOffsetTranslation", object); SetDebugName(properties.Transform(), "Transform", object); SetDebugName(properties.Perspective(), "Perspective", object); SetDebugName(properties.SvgLocalToBorderBoxTransform(), "SvgLocalToBorderBoxTransform", object); SetDebugName(properties.ScrollTranslation(), "ScrollTranslation", object); SetDebugName(properties.FragmentClip(), "FragmentClip", object); SetDebugName(properties.ClipPathClip(), "ClipPathClip", object); SetDebugName(properties.MaskClip(), "MaskClip", object); SetDebugName(properties.CssClip(), "CssClip", object); SetDebugName(properties.CssClipFixedPosition(), "CssClipFixedPosition", object); SetDebugName(properties.OverflowControlsClip(), "OverflowControlsClip", object); SetDebugName(properties.InnerBorderRadiusClip(), "InnerBorderRadiusClip", object); SetDebugName(OverflowClip(properties), "OverflowClip", object); SetDebugName(properties.Effect(), "Effect", object); SetDebugName(properties.Filter(), "Filter", object); SetDebugName(properties.Mask(), "Mask", object); SetDebugName(properties.ClipPath(), "ClipPath", object); SetDebugName(properties.Scroll(), "Scroll", object); } } // namespace PaintPropertyTreePrinter } // namespace blink CORE_EXPORT void showAllPropertyTrees(const blink::LocalFrameView& rootFrame) { showTransformPropertyTree(rootFrame); showClipPropertyTree(rootFrame); showEffectPropertyTree(rootFrame); showScrollPropertyTree(rootFrame); } void showTransformPropertyTree(const blink::LocalFrameView& rootFrame) { LOG(ERROR) << "Transform tree:\n" << transformPropertyTreeAsString(rootFrame).Utf8().data(); } void showClipPropertyTree(const blink::LocalFrameView& rootFrame) { LOG(ERROR) << "Clip tree:\n" << clipPropertyTreeAsString(rootFrame).Utf8().data(); } void showEffectPropertyTree(const blink::LocalFrameView& rootFrame) { LOG(ERROR) << "Effect tree:\n" << effectPropertyTreeAsString(rootFrame).Utf8().data(); } void showScrollPropertyTree(const blink::LocalFrameView& rootFrame) { LOG(ERROR) << "Scroll tree:\n" << scrollPropertyTreeAsString(rootFrame).Utf8().data(); } String transformPropertyTreeAsString(const blink::LocalFrameView& rootFrame) { return blink::FrameViewPropertyTreePrinter< blink::TransformPaintPropertyNode>() .TreeAsString(rootFrame); } String clipPropertyTreeAsString(const blink::LocalFrameView& rootFrame) { return blink::FrameViewPropertyTreePrinter<blink::ClipPaintPropertyNode>() .TreeAsString(rootFrame); } String effectPropertyTreeAsString(const blink::LocalFrameView& rootFrame) { return blink::FrameViewPropertyTreePrinter<blink::EffectPaintPropertyNode>() .TreeAsString(rootFrame); } String scrollPropertyTreeAsString(const blink::LocalFrameView& rootFrame) { return blink::FrameViewPropertyTreePrinter<blink::ScrollPaintPropertyNode>() .TreeAsString(rootFrame); } #endif // DCHECK_IS_ON()
null
null
null
null
31,127
17,940
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
182,935
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef _ASM_XEN_OPS_H #define _ASM_XEN_OPS_H void xen_efi_runtime_setup(void); #endif /* _ASM_XEN_OPS_H */
null
null
null
null
91,282
34,042
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
199,037
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * * (c) 2004 Gerd Knorr <kraxel@bytesex.org> [SuSE Labs] * * Extended 3 / 2005 by Hartmut Hackmann to support various * cards with the tda10046 DVB-T channel decoder * * 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. */ #include "saa7134.h" #include "saa7134-reg.h" #include <linux/init.h> #include <linux/list.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/kthread.h> #include <linux/suspend.h> #include <media/v4l2-common.h> #include "dvb-pll.h" #include <dvb_frontend.h> #include "mt352.h" #include "mt352_priv.h" /* FIXME */ #include "tda1004x.h" #include "nxt200x.h" #include "tuner-xc2028.h" #include "xc5000.h" #include "tda10086.h" #include "tda826x.h" #include "tda827x.h" #include "isl6421.h" #include "isl6405.h" #include "lnbp21.h" #include "tuner-simple.h" #include "tda10048.h" #include "tda18271.h" #include "lgdt3305.h" #include "tda8290.h" #include "mb86a20s.h" #include "lgs8gxx.h" #include "zl10353.h" #include "qt1010.h" #include "zl10036.h" #include "zl10039.h" #include "mt312.h" #include "s5h1411.h" MODULE_AUTHOR("Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]"); MODULE_LICENSE("GPL"); static unsigned int antenna_pwr; module_param(antenna_pwr, int, 0444); MODULE_PARM_DESC(antenna_pwr,"enable antenna power (Pinnacle 300i)"); static int use_frontend; module_param(use_frontend, int, 0644); MODULE_PARM_DESC(use_frontend,"for cards with multiple frontends (0: terrestrial, 1: satellite)"); DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr); /* ------------------------------------------------------------------ * mt352 based DVB-T cards */ static int pinnacle_antenna_pwr(struct saa7134_dev *dev, int on) { u32 ok; if (!on) { saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 26)); saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26)); return 0; } saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 26)); saa_setl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26)); udelay(10); saa_setl(SAA7134_GPIO_GPMODE0 >> 2, (1 << 28)); saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 28)); udelay(10); saa_setl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 28)); udelay(10); ok = saa_readl(SAA7134_GPIO_GPSTATUS0) & (1 << 27); pr_debug("%s %s\n", __func__, ok ? "on" : "off"); if (!ok) saa_clearl(SAA7134_GPIO_GPSTATUS0 >> 2, (1 << 26)); return ok; } static int mt352_pinnacle_init(struct dvb_frontend* fe) { static u8 clock_config [] = { CLOCK_CTL, 0x3d, 0x28 }; static u8 reset [] = { RESET, 0x80 }; static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 }; static u8 agc_cfg [] = { AGC_TARGET, 0x28, 0xa0 }; static u8 capt_range_cfg[] = { CAPT_RANGE, 0x31 }; static u8 fsm_ctl_cfg[] = { 0x7b, 0x04 }; static u8 gpp_ctl_cfg [] = { GPP_CTL, 0x0f }; static u8 scan_ctl_cfg [] = { SCAN_CTL, 0x0d }; static u8 irq_cfg [] = { INTERRUPT_EN_0, 0x00, 0x00, 0x00, 0x00 }; pr_debug("%s called\n", __func__); mt352_write(fe, clock_config, sizeof(clock_config)); udelay(200); mt352_write(fe, reset, sizeof(reset)); mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg)); mt352_write(fe, agc_cfg, sizeof(agc_cfg)); mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg)); mt352_write(fe, gpp_ctl_cfg, sizeof(gpp_ctl_cfg)); mt352_write(fe, fsm_ctl_cfg, sizeof(fsm_ctl_cfg)); mt352_write(fe, scan_ctl_cfg, sizeof(scan_ctl_cfg)); mt352_write(fe, irq_cfg, sizeof(irq_cfg)); return 0; } static int mt352_aver777_init(struct dvb_frontend* fe) { static u8 clock_config [] = { CLOCK_CTL, 0x38, 0x2d }; static u8 reset [] = { RESET, 0x80 }; static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 }; static u8 agc_cfg [] = { AGC_TARGET, 0x28, 0xa0 }; static u8 capt_range_cfg[] = { CAPT_RANGE, 0x33 }; mt352_write(fe, clock_config, sizeof(clock_config)); udelay(200); mt352_write(fe, reset, sizeof(reset)); mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg)); mt352_write(fe, agc_cfg, sizeof(agc_cfg)); mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg)); return 0; } static int mt352_avermedia_xc3028_init(struct dvb_frontend *fe) { static u8 clock_config [] = { CLOCK_CTL, 0x38, 0x2d }; static u8 reset [] = { RESET, 0x80 }; static u8 adc_ctl_1_cfg [] = { ADC_CTL_1, 0x40 }; static u8 agc_cfg [] = { AGC_TARGET, 0xe }; static u8 capt_range_cfg[] = { CAPT_RANGE, 0x33 }; mt352_write(fe, clock_config, sizeof(clock_config)); udelay(200); mt352_write(fe, reset, sizeof(reset)); mt352_write(fe, adc_ctl_1_cfg, sizeof(adc_ctl_1_cfg)); mt352_write(fe, agc_cfg, sizeof(agc_cfg)); mt352_write(fe, capt_range_cfg, sizeof(capt_range_cfg)); return 0; } static int mt352_pinnacle_tuner_set_params(struct dvb_frontend *fe) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; u8 off[] = { 0x00, 0xf1}; u8 on[] = { 0x00, 0x71}; struct i2c_msg msg = {.addr=0x43, .flags=0, .buf=off, .len = sizeof(off)}; struct saa7134_dev *dev = fe->dvb->priv; struct v4l2_frequency f; /* set frequency (mt2050) */ f.tuner = 0; f.type = V4L2_TUNER_DIGITAL_TV; f.frequency = c->frequency / 1000 * 16 / 1000; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); i2c_transfer(&dev->i2c_adap, &msg, 1); saa_call_all(dev, tuner, s_frequency, &f); msg.buf = on; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); i2c_transfer(&dev->i2c_adap, &msg, 1); pinnacle_antenna_pwr(dev, antenna_pwr); /* mt352 setup */ return mt352_pinnacle_init(fe); } static struct mt352_config pinnacle_300i = { .demod_address = 0x3c >> 1, .adc_clock = 20333, .if2 = 36150, .no_tuner = 1, .demod_init = mt352_pinnacle_init, }; static struct mt352_config avermedia_777 = { .demod_address = 0xf, .demod_init = mt352_aver777_init, }; static struct mt352_config avermedia_xc3028_mt352_dev = { .demod_address = (0x1e >> 1), .no_tuner = 1, .demod_init = mt352_avermedia_xc3028_init, }; static struct tda18271_std_map mb86a20s_tda18271_std_map = { .dvbt_6 = { .if_freq = 3300, .agc_mode = 3, .std = 4, .if_lvl = 7, .rfagc_top = 0x37, }, }; static struct tda18271_config kworld_tda18271_config = { .std_map = &mb86a20s_tda18271_std_map, .gate = TDA18271_GATE_DIGITAL, .config = 3, /* Use tuner callback for AGC */ }; static const struct mb86a20s_config kworld_mb86a20s_config = { .demod_address = 0x10, }; static int kworld_sbtvd_gate_ctrl(struct dvb_frontend* fe, int enable) { struct saa7134_dev *dev = fe->dvb->priv; unsigned char initmsg[] = {0x45, 0x97}; unsigned char msg_enable[] = {0x45, 0xc1}; unsigned char msg_disable[] = {0x45, 0x81}; struct i2c_msg msg = {.addr = 0x4b, .flags = 0, .buf = initmsg, .len = 2}; if (i2c_transfer(&dev->i2c_adap, &msg, 1) != 1) { pr_warn("could not access the I2C gate\n"); return -EIO; } if (enable) msg.buf = msg_enable; else msg.buf = msg_disable; if (i2c_transfer(&dev->i2c_adap, &msg, 1) != 1) { pr_warn("could not access the I2C gate\n"); return -EIO; } msleep(20); return 0; } /* ================================================================== * tda1004x based DVB-T cards, helper functions */ static int philips_tda1004x_request_firmware(struct dvb_frontend *fe, const struct firmware **fw, char *name) { struct saa7134_dev *dev = fe->dvb->priv; return request_firmware(fw, name, &dev->pci->dev); } /* ------------------------------------------------------------------ * these tuners are tu1216, td1316(a) */ static int philips_tda6651_pll_set(struct dvb_frontend *fe) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct saa7134_dev *dev = fe->dvb->priv; struct tda1004x_state *state = fe->demodulator_priv; u8 addr = state->config->tuner_address; u8 tuner_buf[4]; struct i2c_msg tuner_msg = {.addr = addr,.flags = 0,.buf = tuner_buf,.len = sizeof(tuner_buf) }; int tuner_frequency = 0; u8 band, cp, filter; /* determine charge pump */ tuner_frequency = c->frequency + 36166000; if (tuner_frequency < 87000000) return -EINVAL; else if (tuner_frequency < 130000000) cp = 3; else if (tuner_frequency < 160000000) cp = 5; else if (tuner_frequency < 200000000) cp = 6; else if (tuner_frequency < 290000000) cp = 3; else if (tuner_frequency < 420000000) cp = 5; else if (tuner_frequency < 480000000) cp = 6; else if (tuner_frequency < 620000000) cp = 3; else if (tuner_frequency < 830000000) cp = 5; else if (tuner_frequency < 895000000) cp = 7; else return -EINVAL; /* determine band */ if (c->frequency < 49000000) return -EINVAL; else if (c->frequency < 161000000) band = 1; else if (c->frequency < 444000000) band = 2; else if (c->frequency < 861000000) band = 4; else return -EINVAL; /* setup PLL filter */ switch (c->bandwidth_hz) { case 6000000: filter = 0; break; case 7000000: filter = 0; break; case 8000000: filter = 1; break; default: return -EINVAL; } /* calculate divisor * ((36166000+((1000000/6)/2)) + Finput)/(1000000/6) */ tuner_frequency = (((c->frequency / 1000) * 6) + 217496) / 1000; /* setup tuner buffer */ tuner_buf[0] = (tuner_frequency >> 8) & 0x7f; tuner_buf[1] = tuner_frequency & 0xff; tuner_buf[2] = 0xca; tuner_buf[3] = (cp << 5) | (filter << 3) | band; if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); if (i2c_transfer(&dev->i2c_adap, &tuner_msg, 1) != 1) { pr_warn("could not write to tuner at addr: 0x%02x\n", addr << 1); return -EIO; } msleep(1); return 0; } static int philips_tu1216_init(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; struct tda1004x_state *state = fe->demodulator_priv; u8 addr = state->config->tuner_address; static u8 tu1216_init[] = { 0x0b, 0xf5, 0x85, 0xab }; struct i2c_msg tuner_msg = {.addr = addr,.flags = 0,.buf = tu1216_init,.len = sizeof(tu1216_init) }; /* setup PLL configuration */ if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); if (i2c_transfer(&dev->i2c_adap, &tuner_msg, 1) != 1) return -EIO; msleep(1); return 0; } /* ------------------------------------------------------------------ */ static struct tda1004x_config philips_tu1216_60_config = { .demod_address = 0x8, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_4M, .agc_config = TDA10046_AGC_DEFAULT, .if_freq = TDA10046_FREQ_3617, .tuner_address = 0x60, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config philips_tu1216_61_config = { .demod_address = 0x8, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_4M, .agc_config = TDA10046_AGC_DEFAULT, .if_freq = TDA10046_FREQ_3617, .tuner_address = 0x61, .request_firmware = philips_tda1004x_request_firmware }; /* ------------------------------------------------------------------ */ static int philips_td1316_tuner_init(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; struct tda1004x_state *state = fe->demodulator_priv; u8 addr = state->config->tuner_address; static u8 msg[] = { 0x0b, 0xf5, 0x86, 0xab }; struct i2c_msg init_msg = {.addr = addr,.flags = 0,.buf = msg,.len = sizeof(msg) }; /* setup PLL configuration */ if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); if (i2c_transfer(&dev->i2c_adap, &init_msg, 1) != 1) return -EIO; return 0; } static int philips_td1316_tuner_set_params(struct dvb_frontend *fe) { return philips_tda6651_pll_set(fe); } static int philips_td1316_tuner_sleep(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; struct tda1004x_state *state = fe->demodulator_priv; u8 addr = state->config->tuner_address; static u8 msg[] = { 0x0b, 0xdc, 0x86, 0xa4 }; struct i2c_msg analog_msg = {.addr = addr,.flags = 0,.buf = msg,.len = sizeof(msg) }; /* switch the tuner to analog mode */ if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); if (i2c_transfer(&dev->i2c_adap, &analog_msg, 1) != 1) return -EIO; return 0; } /* ------------------------------------------------------------------ */ static int philips_europa_tuner_init(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; static u8 msg[] = { 0x00, 0x40}; struct i2c_msg init_msg = {.addr = 0x43,.flags = 0,.buf = msg,.len = sizeof(msg) }; if (philips_td1316_tuner_init(fe)) return -EIO; msleep(1); if (i2c_transfer(&dev->i2c_adap, &init_msg, 1) != 1) return -EIO; return 0; } static int philips_europa_tuner_sleep(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; static u8 msg[] = { 0x00, 0x14 }; struct i2c_msg analog_msg = {.addr = 0x43,.flags = 0,.buf = msg,.len = sizeof(msg) }; if (philips_td1316_tuner_sleep(fe)) return -EIO; /* switch the board to analog mode */ if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); i2c_transfer(&dev->i2c_adap, &analog_msg, 1); return 0; } static int philips_europa_demod_sleep(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; if (dev->original_demod_sleep) dev->original_demod_sleep(fe); fe->ops.i2c_gate_ctrl(fe, 1); return 0; } static struct tda1004x_config philips_europa_config = { .demod_address = 0x8, .invert = 0, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_4M, .agc_config = TDA10046_AGC_IFO_AUTO_POS, .if_freq = TDA10046_FREQ_052, .tuner_address = 0x61, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config medion_cardbus = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_IFO_AUTO_NEG, .if_freq = TDA10046_FREQ_3613, .tuner_address = 0x61, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config technotrend_budget_t3000_config = { .demod_address = 0x8, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_4M, .agc_config = TDA10046_AGC_DEFAULT, .if_freq = TDA10046_FREQ_3617, .tuner_address = 0x63, .request_firmware = philips_tda1004x_request_firmware }; /* ------------------------------------------------------------------ * tda 1004x based cards with philips silicon tuner */ static int tda8290_i2c_gate_ctrl( struct dvb_frontend* fe, int enable) { struct tda1004x_state *state = fe->demodulator_priv; u8 addr = state->config->i2c_gate; static u8 tda8290_close[] = { 0x21, 0xc0}; static u8 tda8290_open[] = { 0x21, 0x80}; struct i2c_msg tda8290_msg = {.addr = addr,.flags = 0, .len = 2}; if (enable) { tda8290_msg.buf = tda8290_close; } else { tda8290_msg.buf = tda8290_open; } if (i2c_transfer(state->i2c, &tda8290_msg, 1) != 1) { pr_warn("could not access tda8290 I2C gate\n"); return -EIO; } msleep(20); return 0; } static int philips_tda827x_tuner_init(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; struct tda1004x_state *state = fe->demodulator_priv; switch (state->config->antenna_switch) { case 0: break; case 1: pr_debug("setting GPIO21 to 0 (TV antenna?)\n"); saa7134_set_gpio(dev, 21, 0); break; case 2: pr_debug("setting GPIO21 to 1 (Radio antenna?)\n"); saa7134_set_gpio(dev, 21, 1); break; } return 0; } static int philips_tda827x_tuner_sleep(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; struct tda1004x_state *state = fe->demodulator_priv; switch (state->config->antenna_switch) { case 0: break; case 1: pr_debug("setting GPIO21 to 1 (Radio antenna?)\n"); saa7134_set_gpio(dev, 21, 1); break; case 2: pr_debug("setting GPIO21 to 0 (TV antenna?)\n"); saa7134_set_gpio(dev, 21, 0); break; } return 0; } static int configure_tda827x_fe(struct saa7134_dev *dev, struct tda1004x_config *cdec_conf, struct tda827x_config *tuner_conf) { struct vb2_dvb_frontend *fe0; /* Get the first frontend */ fe0 = vb2_dvb_get_frontend(&dev->frontends, 1); if (!fe0) return -EINVAL; fe0->dvb.frontend = dvb_attach(tda10046_attach, cdec_conf, &dev->i2c_adap); if (fe0->dvb.frontend) { if (cdec_conf->i2c_gate) fe0->dvb.frontend->ops.i2c_gate_ctrl = tda8290_i2c_gate_ctrl; if (dvb_attach(tda827x_attach, fe0->dvb.frontend, cdec_conf->tuner_address, &dev->i2c_adap, tuner_conf)) return 0; pr_warn("no tda827x tuner found at addr: %02x\n", cdec_conf->tuner_address); } return -EINVAL; } /* ------------------------------------------------------------------ */ static struct tda827x_config tda827x_cfg_0 = { .init = philips_tda827x_tuner_init, .sleep = philips_tda827x_tuner_sleep, .config = 0, .switch_addr = 0 }; static struct tda827x_config tda827x_cfg_1 = { .init = philips_tda827x_tuner_init, .sleep = philips_tda827x_tuner_sleep, .config = 1, .switch_addr = 0x4b }; static struct tda827x_config tda827x_cfg_2 = { .init = philips_tda827x_tuner_init, .sleep = philips_tda827x_tuner_sleep, .config = 2, .switch_addr = 0x4b }; static struct tda827x_config tda827x_cfg_2_sw42 = { .init = philips_tda827x_tuner_init, .sleep = philips_tda827x_tuner_sleep, .config = 2, .switch_addr = 0x42 }; /* ------------------------------------------------------------------ */ static struct tda1004x_config tda827x_lifeview_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .tuner_address = 0x60, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config philips_tiger_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .antenna_switch= 1, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config cinergy_ht_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP01_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config cinergy_ht_pci_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP01_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x60, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config philips_tiger_s_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP01_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .antenna_switch= 1, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config pinnacle_pctv_310i_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config hauppauge_hvr_1110_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config asus_p7131_dual_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .antenna_switch= 2, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config lifeview_trio_config = { .demod_address = 0x09, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP00_I, .if_freq = TDA10046_FREQ_045, .tuner_address = 0x60, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config tevion_dvbt220rf_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .tuner_address = 0x60, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config md8800_dvbt_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP01_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x60, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config asus_p7131_4871_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP01_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .antenna_switch= 2, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config asus_p7131_hybrid_lna_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .antenna_switch= 2, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config kworld_dvb_t_210_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .antenna_switch= 1, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config avermedia_super_007_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP01_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x60, .antenna_switch= 1, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config twinhan_dtv_dvb_3056_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP01_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x42, .tuner_address = 0x61, .antenna_switch = 1, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config asus_tiger_3in1_config = { .demod_address = 0x0b, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .antenna_switch = 1, .request_firmware = philips_tda1004x_request_firmware }; static struct tda1004x_config asus_ps3_100_config = { .demod_address = 0x0b, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP11_I, .if_freq = TDA10046_FREQ_045, .i2c_gate = 0x4b, .tuner_address = 0x61, .antenna_switch = 1, .request_firmware = philips_tda1004x_request_firmware }; /* ------------------------------------------------------------------ * special case: this card uses saa713x GPIO22 for the mode switch */ static int ads_duo_tuner_init(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; philips_tda827x_tuner_init(fe); /* route TDA8275a AGC input to the channel decoder */ saa7134_set_gpio(dev, 22, 1); return 0; } static int ads_duo_tuner_sleep(struct dvb_frontend *fe) { struct saa7134_dev *dev = fe->dvb->priv; /* route TDA8275a AGC input to the analog IF chip*/ saa7134_set_gpio(dev, 22, 0); philips_tda827x_tuner_sleep(fe); return 0; } static struct tda827x_config ads_duo_cfg = { .init = ads_duo_tuner_init, .sleep = ads_duo_tuner_sleep, .config = 0 }; static struct tda1004x_config ads_tech_duo_config = { .demod_address = 0x08, .invert = 1, .invert_oclk = 0, .xtal_freq = TDA10046_XTAL_16M, .agc_config = TDA10046_AGC_TDA827X, .gpio_config = TDA10046_GP00_I, .if_freq = TDA10046_FREQ_045, .tuner_address = 0x61, .request_firmware = philips_tda1004x_request_firmware }; static struct zl10353_config behold_h6_config = { .demod_address = 0x1e>>1, .no_tuner = 1, .parallel_ts = 1, .disable_i2c_gate_ctrl = 1, }; static struct xc5000_config behold_x7_tunerconfig = { .i2c_address = 0xc2>>1, .if_khz = 4560, .radio_input = XC5000_RADIO_FM1, }; static struct zl10353_config behold_x7_config = { .demod_address = 0x1e>>1, .if2 = 45600, .no_tuner = 1, .parallel_ts = 1, .disable_i2c_gate_ctrl = 1, }; static struct zl10353_config videomate_t750_zl10353_config = { .demod_address = 0x0f, .no_tuner = 1, .parallel_ts = 1, .disable_i2c_gate_ctrl = 1, }; static struct qt1010_config videomate_t750_qt1010_config = { .i2c_address = 0x62 }; /* ================================================================== * tda10086 based DVB-S cards, helper functions */ static struct tda10086_config flydvbs = { .demod_address = 0x0e, .invert = 0, .diseqc_tone = 0, .xtal_freq = TDA10086_XTAL_16M, }; static struct tda10086_config sd1878_4m = { .demod_address = 0x0e, .invert = 0, .diseqc_tone = 0, .xtal_freq = TDA10086_XTAL_4M, }; /* ------------------------------------------------------------------ * special case: lnb supply is connected to the gated i2c */ static int md8800_set_voltage(struct dvb_frontend *fe, enum fe_sec_voltage voltage) { int res = -EIO; struct saa7134_dev *dev = fe->dvb->priv; if (fe->ops.i2c_gate_ctrl) { fe->ops.i2c_gate_ctrl(fe, 1); if (dev->original_set_voltage) res = dev->original_set_voltage(fe, voltage); fe->ops.i2c_gate_ctrl(fe, 0); } return res; }; static int md8800_set_high_voltage(struct dvb_frontend *fe, long arg) { int res = -EIO; struct saa7134_dev *dev = fe->dvb->priv; if (fe->ops.i2c_gate_ctrl) { fe->ops.i2c_gate_ctrl(fe, 1); if (dev->original_set_high_voltage) res = dev->original_set_high_voltage(fe, arg); fe->ops.i2c_gate_ctrl(fe, 0); } return res; }; static int md8800_set_voltage2(struct dvb_frontend *fe, enum fe_sec_voltage voltage) { struct saa7134_dev *dev = fe->dvb->priv; u8 wbuf[2] = { 0x1f, 00 }; u8 rbuf; struct i2c_msg msg[] = { { .addr = 0x08, .flags = 0, .buf = wbuf, .len = 1 }, { .addr = 0x08, .flags = I2C_M_RD, .buf = &rbuf, .len = 1 } }; if (i2c_transfer(&dev->i2c_adap, msg, 2) != 2) return -EIO; /* NOTE: this assumes that gpo1 is used, it might be bit 5 (gpo2) */ if (voltage == SEC_VOLTAGE_18) wbuf[1] = rbuf | 0x10; else wbuf[1] = rbuf & 0xef; msg[0].len = 2; i2c_transfer(&dev->i2c_adap, msg, 1); return 0; } static int md8800_set_high_voltage2(struct dvb_frontend *fe, long arg) { pr_warn("%s: sorry can't set high LNB supply voltage from here\n", __func__); return -EIO; } /* ================================================================== * nxt200x based ATSC cards, helper functions */ static struct nxt200x_config avertvhda180 = { .demod_address = 0x0a, }; static struct nxt200x_config kworldatsc110 = { .demod_address = 0x0a, }; /* ------------------------------------------------------------------ */ static struct mt312_config avertv_a700_mt312 = { .demod_address = 0x0e, .voltage_inverted = 1, }; static struct zl10036_config avertv_a700_tuner = { .tuner_address = 0x60, }; static struct mt312_config zl10313_compro_s350_config = { .demod_address = 0x0e, }; static struct mt312_config zl10313_avermedia_a706_config = { .demod_address = 0x0e, }; static struct lgdt3305_config hcw_lgdt3305_config = { .i2c_addr = 0x0e, .mpeg_mode = LGDT3305_MPEG_SERIAL, .tpclk_edge = LGDT3305_TPCLK_RISING_EDGE, .tpvalid_polarity = LGDT3305_TP_VALID_HIGH, .deny_i2c_rptr = 1, .spectral_inversion = 1, .qam_if_khz = 4000, .vsb_if_khz = 3250, }; static struct tda10048_config hcw_tda10048_config = { .demod_address = 0x10 >> 1, .output_mode = TDA10048_SERIAL_OUTPUT, .fwbulkwritelen = TDA10048_BULKWRITE_200, .inversion = TDA10048_INVERSION_ON, .dtv6_if_freq_khz = TDA10048_IF_3300, .dtv7_if_freq_khz = TDA10048_IF_3500, .dtv8_if_freq_khz = TDA10048_IF_4000, .clk_freq_khz = TDA10048_CLK_16000, .disable_gate_access = 1, }; static struct tda18271_std_map hauppauge_tda18271_std_map = { .atsc_6 = { .if_freq = 3250, .agc_mode = 3, .std = 4, .if_lvl = 1, .rfagc_top = 0x58, }, .qam_6 = { .if_freq = 4000, .agc_mode = 3, .std = 5, .if_lvl = 1, .rfagc_top = 0x58, }, }; static struct tda18271_config hcw_tda18271_config = { .std_map = &hauppauge_tda18271_std_map, .gate = TDA18271_GATE_ANALOG, .config = 3, .output_opt = TDA18271_OUTPUT_LT_OFF, }; static struct tda829x_config tda829x_no_probe = { .probe_tuner = TDA829X_DONT_PROBE, }; static struct tda10048_config zolid_tda10048_config = { .demod_address = 0x10 >> 1, .output_mode = TDA10048_PARALLEL_OUTPUT, .fwbulkwritelen = TDA10048_BULKWRITE_200, .inversion = TDA10048_INVERSION_ON, .dtv6_if_freq_khz = TDA10048_IF_3300, .dtv7_if_freq_khz = TDA10048_IF_3500, .dtv8_if_freq_khz = TDA10048_IF_4000, .clk_freq_khz = TDA10048_CLK_16000, .disable_gate_access = 1, }; static struct tda18271_config zolid_tda18271_config = { .gate = TDA18271_GATE_ANALOG, }; static struct tda10048_config dtv1000s_tda10048_config = { .demod_address = 0x10 >> 1, .output_mode = TDA10048_PARALLEL_OUTPUT, .fwbulkwritelen = TDA10048_BULKWRITE_200, .inversion = TDA10048_INVERSION_ON, .dtv6_if_freq_khz = TDA10048_IF_3300, .dtv7_if_freq_khz = TDA10048_IF_3800, .dtv8_if_freq_khz = TDA10048_IF_4300, .clk_freq_khz = TDA10048_CLK_16000, .disable_gate_access = 1, }; static struct tda18271_std_map dtv1000s_tda18271_std_map = { .dvbt_6 = { .if_freq = 3300, .agc_mode = 3, .std = 4, .if_lvl = 1, .rfagc_top = 0x37, }, .dvbt_7 = { .if_freq = 3800, .agc_mode = 3, .std = 5, .if_lvl = 1, .rfagc_top = 0x37, }, .dvbt_8 = { .if_freq = 4300, .agc_mode = 3, .std = 6, .if_lvl = 1, .rfagc_top = 0x37, }, }; static struct tda18271_config dtv1000s_tda18271_config = { .std_map = &dtv1000s_tda18271_std_map, .gate = TDA18271_GATE_ANALOG, }; static struct lgs8gxx_config prohdtv_pro2_lgs8g75_config = { .prod = LGS8GXX_PROD_LGS8G75, .demod_address = 0x1d, .serial_ts = 0, .ts_clk_pol = 1, .ts_clk_gated = 0, .if_clk_freq = 30400, /* 30.4 MHz */ .if_freq = 4000, /* 4.00 MHz */ .if_neg_center = 0, .ext_adc = 0, .adc_signed = 1, .adc_vpp = 3, /* 2.0 Vpp */ .if_neg_edge = 1, }; static struct tda18271_config prohdtv_pro2_tda18271_config = { .gate = TDA18271_GATE_ANALOG, .output_opt = TDA18271_OUTPUT_LT_OFF, }; static struct tda18271_std_map kworld_tda18271_std_map = { .atsc_6 = { .if_freq = 3250, .agc_mode = 3, .std = 3, .if_lvl = 6, .rfagc_top = 0x37 }, .qam_6 = { .if_freq = 4000, .agc_mode = 3, .std = 0, .if_lvl = 6, .rfagc_top = 0x37 }, }; static struct tda18271_config kworld_pc150u_tda18271_config = { .std_map = &kworld_tda18271_std_map, .gate = TDA18271_GATE_ANALOG, .output_opt = TDA18271_OUTPUT_LT_OFF, .config = 3, /* Use tuner callback for AGC */ .rf_cal_on_startup = 1 }; static struct s5h1411_config kworld_s5h1411_config = { .output_mode = S5H1411_PARALLEL_OUTPUT, .gpio = S5H1411_GPIO_OFF, .qam_if = S5H1411_IF_4000, .vsb_if = S5H1411_IF_3250, .inversion = S5H1411_INVERSION_ON, .status_mode = S5H1411_DEMODLOCKING, .mpeg_timing = S5H1411_MPEGTIMING_CONTINOUS_NONINVERTING_CLOCK, }; /* ================================================================== * Core code */ static int dvb_init(struct saa7134_dev *dev) { int ret; int attach_xc3028 = 0; struct vb2_dvb_frontend *fe0; struct vb2_queue *q; /* FIXME: add support for multi-frontend */ mutex_init(&dev->frontends.lock); INIT_LIST_HEAD(&dev->frontends.felist); pr_info("%s() allocating 1 frontend\n", __func__); fe0 = vb2_dvb_alloc_frontend(&dev->frontends, 1); if (!fe0) { pr_err("%s() failed to alloc\n", __func__); return -ENOMEM; } /* init struct vb2_dvb */ dev->ts.nr_bufs = 32; dev->ts.nr_packets = 32*4; fe0->dvb.name = dev->name; q = &fe0->dvb.dvbq; q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; q->io_modes = VB2_MMAP | VB2_READ; q->drv_priv = &dev->ts_q; q->ops = &saa7134_ts_qops; q->mem_ops = &vb2_dma_sg_memops; q->buf_struct_size = sizeof(struct saa7134_buf); q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC; q->lock = &dev->lock; q->dev = &dev->pci->dev; ret = vb2_queue_init(q); if (ret) { vb2_dvb_dealloc_frontends(&dev->frontends); return ret; } switch (dev->board) { case SAA7134_BOARD_PINNACLE_300I_DVBT_PAL: pr_debug("pinnacle 300i dvb setup\n"); fe0->dvb.frontend = dvb_attach(mt352_attach, &pinnacle_300i, &dev->i2c_adap); if (fe0->dvb.frontend) { fe0->dvb.frontend->ops.tuner_ops.set_params = mt352_pinnacle_tuner_set_params; } break; case SAA7134_BOARD_AVERMEDIA_777: case SAA7134_BOARD_AVERMEDIA_A16AR: pr_debug("avertv 777 dvb setup\n"); fe0->dvb.frontend = dvb_attach(mt352_attach, &avermedia_777, &dev->i2c_adap); if (fe0->dvb.frontend) { dvb_attach(simple_tuner_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x61, TUNER_PHILIPS_TD1316); } break; case SAA7134_BOARD_AVERMEDIA_A16D: pr_debug("AverMedia A16D dvb setup\n"); fe0->dvb.frontend = dvb_attach(mt352_attach, &avermedia_xc3028_mt352_dev, &dev->i2c_adap); attach_xc3028 = 1; break; case SAA7134_BOARD_MD7134: fe0->dvb.frontend = dvb_attach(tda10046_attach, &medion_cardbus, &dev->i2c_adap); if (fe0->dvb.frontend) { dvb_attach(simple_tuner_attach, fe0->dvb.frontend, &dev->i2c_adap, medion_cardbus.tuner_address, TUNER_PHILIPS_FMD1216ME_MK3); } break; case SAA7134_BOARD_PHILIPS_TOUGH: fe0->dvb.frontend = dvb_attach(tda10046_attach, &philips_tu1216_60_config, &dev->i2c_adap); if (fe0->dvb.frontend) { fe0->dvb.frontend->ops.tuner_ops.init = philips_tu1216_init; fe0->dvb.frontend->ops.tuner_ops.set_params = philips_tda6651_pll_set; } break; case SAA7134_BOARD_FLYDVBTDUO: case SAA7134_BOARD_FLYDVBT_DUO_CARDBUS: if (configure_tda827x_fe(dev, &tda827x_lifeview_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_PHILIPS_EUROPA: case SAA7134_BOARD_VIDEOMATE_DVBT_300: case SAA7134_BOARD_ASUS_EUROPA_HYBRID: fe0->dvb.frontend = dvb_attach(tda10046_attach, &philips_europa_config, &dev->i2c_adap); if (fe0->dvb.frontend) { dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep; fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep; fe0->dvb.frontend->ops.tuner_ops.init = philips_europa_tuner_init; fe0->dvb.frontend->ops.tuner_ops.sleep = philips_europa_tuner_sleep; fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params; } break; case SAA7134_BOARD_TECHNOTREND_BUDGET_T3000: fe0->dvb.frontend = dvb_attach(tda10046_attach, &technotrend_budget_t3000_config, &dev->i2c_adap); if (fe0->dvb.frontend) { dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep; fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep; fe0->dvb.frontend->ops.tuner_ops.init = philips_europa_tuner_init; fe0->dvb.frontend->ops.tuner_ops.sleep = philips_europa_tuner_sleep; fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params; } break; case SAA7134_BOARD_VIDEOMATE_DVBT_200: fe0->dvb.frontend = dvb_attach(tda10046_attach, &philips_tu1216_61_config, &dev->i2c_adap); if (fe0->dvb.frontend) { fe0->dvb.frontend->ops.tuner_ops.init = philips_tu1216_init; fe0->dvb.frontend->ops.tuner_ops.set_params = philips_tda6651_pll_set; } break; case SAA7134_BOARD_KWORLD_DVBT_210: if (configure_tda827x_fe(dev, &kworld_dvb_t_210_config, &tda827x_cfg_2) < 0) goto detach_frontend; break; case SAA7134_BOARD_HAUPPAUGE_HVR1120: fe0->dvb.frontend = dvb_attach(tda10048_attach, &hcw_tda10048_config, &dev->i2c_adap); if (fe0->dvb.frontend != NULL) { dvb_attach(tda829x_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x4b, &tda829x_no_probe); dvb_attach(tda18271_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, &hcw_tda18271_config); } break; case SAA7134_BOARD_PHILIPS_TIGER: if (configure_tda827x_fe(dev, &philips_tiger_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_PINNACLE_PCTV_310i: if (configure_tda827x_fe(dev, &pinnacle_pctv_310i_config, &tda827x_cfg_1) < 0) goto detach_frontend; break; case SAA7134_BOARD_HAUPPAUGE_HVR1110: if (configure_tda827x_fe(dev, &hauppauge_hvr_1110_config, &tda827x_cfg_1) < 0) goto detach_frontend; break; case SAA7134_BOARD_HAUPPAUGE_HVR1150: fe0->dvb.frontend = dvb_attach(lgdt3305_attach, &hcw_lgdt3305_config, &dev->i2c_adap); if (fe0->dvb.frontend) { dvb_attach(tda829x_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x4b, &tda829x_no_probe); dvb_attach(tda18271_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, &hcw_tda18271_config); } break; case SAA7134_BOARD_ASUSTeK_P7131_DUAL: if (configure_tda827x_fe(dev, &asus_p7131_dual_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_FLYDVBT_LR301: if (configure_tda827x_fe(dev, &tda827x_lifeview_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_FLYDVB_TRIO: if (!use_frontend) { /* terrestrial */ if (configure_tda827x_fe(dev, &lifeview_trio_config, &tda827x_cfg_0) < 0) goto detach_frontend; } else { /* satellite */ fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs, &dev->i2c_adap); if (fe0->dvb.frontend) { if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x63, &dev->i2c_adap, 0) == NULL) { pr_warn("%s: Lifeview Trio, No tda826x found!\n", __func__); goto detach_frontend; } if (dvb_attach(isl6421_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x08, 0, 0, false) == NULL) { pr_warn("%s: Lifeview Trio, No ISL6421 found!\n", __func__); goto detach_frontend; } } } break; case SAA7134_BOARD_ADS_DUO_CARDBUS_PTV331: case SAA7134_BOARD_FLYDVBT_HYBRID_CARDBUS: fe0->dvb.frontend = dvb_attach(tda10046_attach, &ads_tech_duo_config, &dev->i2c_adap); if (fe0->dvb.frontend) { if (dvb_attach(tda827x_attach,fe0->dvb.frontend, ads_tech_duo_config.tuner_address, &dev->i2c_adap, &ads_duo_cfg) == NULL) { pr_warn("no tda827x tuner found at addr: %02x\n", ads_tech_duo_config.tuner_address); goto detach_frontend; } } else pr_warn("failed to attach tda10046\n"); break; case SAA7134_BOARD_TEVION_DVBT_220RF: if (configure_tda827x_fe(dev, &tevion_dvbt220rf_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_MEDION_MD8800_QUADRO: if (!use_frontend) { /* terrestrial */ if (configure_tda827x_fe(dev, &md8800_dvbt_config, &tda827x_cfg_0) < 0) goto detach_frontend; } else { /* satellite */ fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs, &dev->i2c_adap); if (fe0->dvb.frontend) { struct dvb_frontend *fe = fe0->dvb.frontend; u8 dev_id = dev->eedata[2]; u8 data = 0xc4; struct i2c_msg msg = {.addr = 0x08, .flags = 0, .len = 1}; if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, 0) == NULL) { pr_warn("%s: Medion Quadro, no tda826x found !\n", __func__); goto detach_frontend; } if (dev_id != 0x08) { /* we need to open the i2c gate (we know it exists) */ fe->ops.i2c_gate_ctrl(fe, 1); if (dvb_attach(isl6405_attach, fe, &dev->i2c_adap, 0x08, 0, 0) == NULL) { pr_warn("%s: Medion Quadro, no ISL6405 found !\n", __func__); goto detach_frontend; } if (dev_id == 0x07) { /* fire up the 2nd section of the LNB supply since we can't do this from the other section */ msg.buf = &data; i2c_transfer(&dev->i2c_adap, &msg, 1); } fe->ops.i2c_gate_ctrl(fe, 0); dev->original_set_voltage = fe->ops.set_voltage; fe->ops.set_voltage = md8800_set_voltage; dev->original_set_high_voltage = fe->ops.enable_high_lnb_voltage; fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage; } else { fe->ops.set_voltage = md8800_set_voltage2; fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage2; } } } break; case SAA7134_BOARD_AVERMEDIA_AVERTVHD_A180: fe0->dvb.frontend = dvb_attach(nxt200x_attach, &avertvhda180, &dev->i2c_adap); if (fe0->dvb.frontend) dvb_attach(dvb_pll_attach, fe0->dvb.frontend, 0x61, NULL, DVB_PLL_TDHU2); break; case SAA7134_BOARD_ADS_INSTANT_HDTV_PCI: case SAA7134_BOARD_KWORLD_ATSC110: fe0->dvb.frontend = dvb_attach(nxt200x_attach, &kworldatsc110, &dev->i2c_adap); if (fe0->dvb.frontend) dvb_attach(simple_tuner_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x61, TUNER_PHILIPS_TUV1236D); break; case SAA7134_BOARD_KWORLD_PC150U: saa7134_set_gpio(dev, 18, 1); /* Switch to digital mode */ saa7134_tuner_callback(dev, 0, TDA18271_CALLBACK_CMD_AGC_ENABLE, 1); fe0->dvb.frontend = dvb_attach(s5h1411_attach, &kworld_s5h1411_config, &dev->i2c_adap); if (fe0->dvb.frontend != NULL) { dvb_attach(tda829x_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x4b, &tda829x_no_probe); dvb_attach(tda18271_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, &kworld_pc150u_tda18271_config); } break; case SAA7134_BOARD_FLYDVBS_LR300: fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs, &dev->i2c_adap); if (fe0->dvb.frontend) { if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, 0) == NULL) { pr_warn("%s: No tda826x found!\n", __func__); goto detach_frontend; } if (dvb_attach(isl6421_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x08, 0, 0, false) == NULL) { pr_warn("%s: No ISL6421 found!\n", __func__); goto detach_frontend; } } break; case SAA7134_BOARD_ASUS_EUROPA2_HYBRID: fe0->dvb.frontend = dvb_attach(tda10046_attach, &medion_cardbus, &dev->i2c_adap); if (fe0->dvb.frontend) { dev->original_demod_sleep = fe0->dvb.frontend->ops.sleep; fe0->dvb.frontend->ops.sleep = philips_europa_demod_sleep; dvb_attach(simple_tuner_attach, fe0->dvb.frontend, &dev->i2c_adap, medion_cardbus.tuner_address, TUNER_PHILIPS_FMD1216ME_MK3); } break; case SAA7134_BOARD_VIDEOMATE_DVBT_200A: fe0->dvb.frontend = dvb_attach(tda10046_attach, &philips_europa_config, &dev->i2c_adap); if (fe0->dvb.frontend) { fe0->dvb.frontend->ops.tuner_ops.init = philips_td1316_tuner_init; fe0->dvb.frontend->ops.tuner_ops.set_params = philips_td1316_tuner_set_params; } break; case SAA7134_BOARD_CINERGY_HT_PCMCIA: if (configure_tda827x_fe(dev, &cinergy_ht_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_CINERGY_HT_PCI: if (configure_tda827x_fe(dev, &cinergy_ht_pci_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_PHILIPS_TIGER_S: if (configure_tda827x_fe(dev, &philips_tiger_s_config, &tda827x_cfg_2) < 0) goto detach_frontend; break; case SAA7134_BOARD_ASUS_P7131_4871: if (configure_tda827x_fe(dev, &asus_p7131_4871_config, &tda827x_cfg_2) < 0) goto detach_frontend; break; case SAA7134_BOARD_ASUSTeK_P7131_HYBRID_LNA: if (configure_tda827x_fe(dev, &asus_p7131_hybrid_lna_config, &tda827x_cfg_2) < 0) goto detach_frontend; break; case SAA7134_BOARD_AVERMEDIA_SUPER_007: if (configure_tda827x_fe(dev, &avermedia_super_007_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_TWINHAN_DTV_DVB_3056: if (configure_tda827x_fe(dev, &twinhan_dtv_dvb_3056_config, &tda827x_cfg_2_sw42) < 0) goto detach_frontend; break; case SAA7134_BOARD_PHILIPS_SNAKE: fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs, &dev->i2c_adap); if (fe0->dvb.frontend) { if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, 0) == NULL) { pr_warn("%s: No tda826x found!\n", __func__); goto detach_frontend; } if (dvb_attach(lnbp21_attach, fe0->dvb.frontend, &dev->i2c_adap, 0, 0) == NULL) { pr_warn("%s: No lnbp21 found!\n", __func__); goto detach_frontend; } } break; case SAA7134_BOARD_CREATIX_CTX953: if (configure_tda827x_fe(dev, &md8800_dvbt_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_MSI_TVANYWHERE_AD11: if (configure_tda827x_fe(dev, &philips_tiger_s_config, &tda827x_cfg_2) < 0) goto detach_frontend; break; case SAA7134_BOARD_AVERMEDIA_CARDBUS_506: pr_debug("AverMedia E506R dvb setup\n"); saa7134_set_gpio(dev, 25, 0); msleep(10); saa7134_set_gpio(dev, 25, 1); fe0->dvb.frontend = dvb_attach(mt352_attach, &avermedia_xc3028_mt352_dev, &dev->i2c_adap); attach_xc3028 = 1; break; case SAA7134_BOARD_MD7134_BRIDGE_2: fe0->dvb.frontend = dvb_attach(tda10086_attach, &sd1878_4m, &dev->i2c_adap); if (fe0->dvb.frontend) { struct dvb_frontend *fe; if (dvb_attach(dvb_pll_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, DVB_PLL_PHILIPS_SD1878_TDA8261) == NULL) { pr_warn("%s: MD7134 DVB-S, no SD1878 found !\n", __func__); goto detach_frontend; } /* we need to open the i2c gate (we know it exists) */ fe = fe0->dvb.frontend; fe->ops.i2c_gate_ctrl(fe, 1); if (dvb_attach(isl6405_attach, fe, &dev->i2c_adap, 0x08, 0, 0) == NULL) { pr_warn("%s: MD7134 DVB-S, no ISL6405 found !\n", __func__); goto detach_frontend; } fe->ops.i2c_gate_ctrl(fe, 0); dev->original_set_voltage = fe->ops.set_voltage; fe->ops.set_voltage = md8800_set_voltage; dev->original_set_high_voltage = fe->ops.enable_high_lnb_voltage; fe->ops.enable_high_lnb_voltage = md8800_set_high_voltage; } break; case SAA7134_BOARD_AVERMEDIA_M103: saa7134_set_gpio(dev, 25, 0); msleep(10); saa7134_set_gpio(dev, 25, 1); fe0->dvb.frontend = dvb_attach(mt352_attach, &avermedia_xc3028_mt352_dev, &dev->i2c_adap); attach_xc3028 = 1; break; case SAA7134_BOARD_ASUSTeK_TIGER_3IN1: if (!use_frontend) { /* terrestrial */ if (configure_tda827x_fe(dev, &asus_tiger_3in1_config, &tda827x_cfg_2) < 0) goto detach_frontend; } else { /* satellite */ fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs, &dev->i2c_adap); if (fe0->dvb.frontend) { if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, 0) == NULL) { pr_warn("%s: Asus Tiger 3in1, no tda826x found!\n", __func__); goto detach_frontend; } if (dvb_attach(lnbp21_attach, fe0->dvb.frontend, &dev->i2c_adap, 0, 0) == NULL) { pr_warn("%s: Asus Tiger 3in1, no lnbp21 found!\n", __func__); goto detach_frontend; } } } break; case SAA7134_BOARD_ASUSTeK_PS3_100: if (!use_frontend) { /* terrestrial */ if (configure_tda827x_fe(dev, &asus_ps3_100_config, &tda827x_cfg_2) < 0) goto detach_frontend; } else { /* satellite */ fe0->dvb.frontend = dvb_attach(tda10086_attach, &flydvbs, &dev->i2c_adap); if (fe0->dvb.frontend) { if (dvb_attach(tda826x_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, 0) == NULL) { pr_warn("%s: Asus My Cinema PS3-100, no tda826x found!\n", __func__); goto detach_frontend; } if (dvb_attach(lnbp21_attach, fe0->dvb.frontend, &dev->i2c_adap, 0, 0) == NULL) { pr_warn("%s: Asus My Cinema PS3-100, no lnbp21 found!\n", __func__); goto detach_frontend; } } } break; case SAA7134_BOARD_ASUSTeK_TIGER: if (configure_tda827x_fe(dev, &philips_tiger_config, &tda827x_cfg_0) < 0) goto detach_frontend; break; case SAA7134_BOARD_BEHOLD_H6: fe0->dvb.frontend = dvb_attach(zl10353_attach, &behold_h6_config, &dev->i2c_adap); if (fe0->dvb.frontend) { dvb_attach(simple_tuner_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x61, TUNER_PHILIPS_FMD1216MEX_MK3); } break; case SAA7134_BOARD_BEHOLD_X7: fe0->dvb.frontend = dvb_attach(zl10353_attach, &behold_x7_config, &dev->i2c_adap); if (fe0->dvb.frontend) { dvb_attach(xc5000_attach, fe0->dvb.frontend, &dev->i2c_adap, &behold_x7_tunerconfig); } break; case SAA7134_BOARD_BEHOLD_H7: fe0->dvb.frontend = dvb_attach(zl10353_attach, &behold_x7_config, &dev->i2c_adap); if (fe0->dvb.frontend) { dvb_attach(xc5000_attach, fe0->dvb.frontend, &dev->i2c_adap, &behold_x7_tunerconfig); } break; case SAA7134_BOARD_AVERMEDIA_A700_PRO: case SAA7134_BOARD_AVERMEDIA_A700_HYBRID: /* Zarlink ZL10313 */ fe0->dvb.frontend = dvb_attach(mt312_attach, &avertv_a700_mt312, &dev->i2c_adap); if (fe0->dvb.frontend) { if (dvb_attach(zl10036_attach, fe0->dvb.frontend, &avertv_a700_tuner, &dev->i2c_adap) == NULL) { pr_warn("%s: No zl10036 found!\n", __func__); } } break; case SAA7134_BOARD_VIDEOMATE_S350: fe0->dvb.frontend = dvb_attach(mt312_attach, &zl10313_compro_s350_config, &dev->i2c_adap); if (fe0->dvb.frontend) if (dvb_attach(zl10039_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap) == NULL) pr_warn("%s: No zl10039 found!\n", __func__); break; case SAA7134_BOARD_VIDEOMATE_T750: fe0->dvb.frontend = dvb_attach(zl10353_attach, &videomate_t750_zl10353_config, &dev->i2c_adap); if (fe0->dvb.frontend != NULL) { if (dvb_attach(qt1010_attach, fe0->dvb.frontend, &dev->i2c_adap, &videomate_t750_qt1010_config) == NULL) pr_warn("error attaching QT1010\n"); } break; case SAA7134_BOARD_ZOLID_HYBRID_PCI: fe0->dvb.frontend = dvb_attach(tda10048_attach, &zolid_tda10048_config, &dev->i2c_adap); if (fe0->dvb.frontend != NULL) { dvb_attach(tda829x_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x4b, &tda829x_no_probe); dvb_attach(tda18271_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, &zolid_tda18271_config); } break; case SAA7134_BOARD_LEADTEK_WINFAST_DTV1000S: fe0->dvb.frontend = dvb_attach(tda10048_attach, &dtv1000s_tda10048_config, &dev->i2c_adap); if (fe0->dvb.frontend != NULL) { dvb_attach(tda829x_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x4b, &tda829x_no_probe); dvb_attach(tda18271_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, &dtv1000s_tda18271_config); } break; case SAA7134_BOARD_KWORLD_PCI_SBTVD_FULLSEG: /* Switch to digital mode */ saa7134_tuner_callback(dev, 0, TDA18271_CALLBACK_CMD_AGC_ENABLE, 1); fe0->dvb.frontend = dvb_attach(mb86a20s_attach, &kworld_mb86a20s_config, &dev->i2c_adap); if (fe0->dvb.frontend != NULL) { dvb_attach(tda829x_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x4b, &tda829x_no_probe); fe0->dvb.frontend->ops.i2c_gate_ctrl = kworld_sbtvd_gate_ctrl; dvb_attach(tda18271_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, &kworld_tda18271_config); } /* mb86a20s need to use the I2C gateway */ break; case SAA7134_BOARD_MAGICPRO_PROHDTV_PRO2: fe0->dvb.frontend = dvb_attach(lgs8gxx_attach, &prohdtv_pro2_lgs8g75_config, &dev->i2c_adap); if (fe0->dvb.frontend != NULL) { dvb_attach(tda829x_attach, fe0->dvb.frontend, &dev->i2c_adap, 0x4b, &tda829x_no_probe); dvb_attach(tda18271_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap, &prohdtv_pro2_tda18271_config); } break; case SAA7134_BOARD_AVERMEDIA_A706: /* Enable all DVB-S devices now */ /* CE5039 DVB-S tuner SLEEP pin low */ saa7134_set_gpio(dev, 23, 0); /* CE6313 DVB-S demod SLEEP pin low */ saa7134_set_gpio(dev, 9, 0); /* CE6313 DVB-S demod RESET# pin high */ saa7134_set_gpio(dev, 25, 1); msleep(1); fe0->dvb.frontend = dvb_attach(mt312_attach, &zl10313_avermedia_a706_config, &dev->i2c_adap); if (fe0->dvb.frontend) { fe0->dvb.frontend->ops.i2c_gate_ctrl = NULL; if (dvb_attach(zl10039_attach, fe0->dvb.frontend, 0x60, &dev->i2c_adap) == NULL) pr_warn("%s: No zl10039 found!\n", __func__); } break; default: pr_warn("Huh? unknown DVB card?\n"); break; } if (attach_xc3028) { struct dvb_frontend *fe; struct xc2028_config cfg = { .i2c_adap = &dev->i2c_adap, .i2c_addr = 0x61, }; if (!fe0->dvb.frontend) goto detach_frontend; fe = dvb_attach(xc2028_attach, fe0->dvb.frontend, &cfg); if (!fe) { pr_err("%s/2: xc3028 attach failed\n", dev->name); goto detach_frontend; } } if (NULL == fe0->dvb.frontend) { pr_err("%s/dvb: frontend initialization failed\n", dev->name); goto detach_frontend; } /* define general-purpose callback pointer */ fe0->dvb.frontend->callback = saa7134_tuner_callback; /* register everything else */ #ifndef CONFIG_MEDIA_CONTROLLER_DVB ret = vb2_dvb_register_bus(&dev->frontends, THIS_MODULE, dev, &dev->pci->dev, NULL, adapter_nr, 0); #else ret = vb2_dvb_register_bus(&dev->frontends, THIS_MODULE, dev, &dev->pci->dev, dev->media_dev, adapter_nr, 0); #endif /* this sequence is necessary to make the tda1004x load its firmware * and to enter analog mode of hybrid boards */ if (!ret) { if (fe0->dvb.frontend->ops.init) fe0->dvb.frontend->ops.init(fe0->dvb.frontend); if (fe0->dvb.frontend->ops.sleep) fe0->dvb.frontend->ops.sleep(fe0->dvb.frontend); if (fe0->dvb.frontend->ops.tuner_ops.sleep) fe0->dvb.frontend->ops.tuner_ops.sleep(fe0->dvb.frontend); } return ret; detach_frontend: vb2_dvb_dealloc_frontends(&dev->frontends); vb2_queue_release(&fe0->dvb.dvbq); return -EINVAL; } static int dvb_fini(struct saa7134_dev *dev) { struct vb2_dvb_frontend *fe0; /* Get the first frontend */ fe0 = vb2_dvb_get_frontend(&dev->frontends, 1); if (!fe0) return -EINVAL; /* FIXME: I suspect that this code is bogus, since the entry for Pinnacle 300I DVB-T PAL already defines the proper init to allow the detection of mt2032 (TDA9887_PORT2_INACTIVE) */ if (dev->board == SAA7134_BOARD_PINNACLE_300I_DVBT_PAL) { struct v4l2_priv_tun_config tda9887_cfg; static int on = TDA9887_PRESENT | TDA9887_PORT2_INACTIVE; tda9887_cfg.tuner = TUNER_TDA9887; tda9887_cfg.priv = &on; /* otherwise we don't detect the tuner on next insmod */ saa_call_all(dev, tuner, s_config, &tda9887_cfg); } else if (dev->board == SAA7134_BOARD_MEDION_MD8800_QUADRO) { if ((dev->eedata[2] == 0x07) && use_frontend) { /* turn off the 2nd lnb supply */ u8 data = 0x80; struct i2c_msg msg = {.addr = 0x08, .buf = &data, .flags = 0, .len = 1}; struct dvb_frontend *fe; fe = fe0->dvb.frontend; if (fe->ops.i2c_gate_ctrl) { fe->ops.i2c_gate_ctrl(fe, 1); i2c_transfer(&dev->i2c_adap, &msg, 1); fe->ops.i2c_gate_ctrl(fe, 0); } } } vb2_dvb_unregister_bus(&dev->frontends); vb2_queue_release(&fe0->dvb.dvbq); return 0; } static struct saa7134_mpeg_ops dvb_ops = { .type = SAA7134_MPEG_DVB, .init = dvb_init, .fini = dvb_fini, }; static int __init dvb_register(void) { return saa7134_ts_register(&dvb_ops); } static void __exit dvb_unregister(void) { saa7134_ts_unregister(&dvb_ops); } module_init(dvb_register); module_exit(dvb_unregister);
null
null
null
null
107,384
38,157
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
38,157
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h" #include "SkTypes.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_display_item_list.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_recorder.h" #include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h" #include "third_party/blink/renderer/platform/testing/fake_display_item_client.h" namespace blink { namespace { using testing::_; class DrawingDisplayItemTest : public testing::Test { protected: FakeDisplayItemClient client_; }; class MockWebDisplayItemList : public WebDisplayItemList { public: MOCK_METHOD2(AppendDrawingItem, void(const WebRect& visual_rect, sk_sp<const cc::PaintRecord>)); }; static sk_sp<PaintRecord> CreateRectRecord(const FloatRect& record_bounds) { PaintRecorder recorder; PaintCanvas* canvas = recorder.beginRecording(record_bounds.Width(), record_bounds.Height()); canvas->drawRect(record_bounds, PaintFlags()); return recorder.finishRecordingAsPicture(); } static sk_sp<PaintRecord> CreateRectRecordWithTranslate( const FloatRect& record_bounds, float dx, float dy) { PaintRecorder recorder; PaintCanvas* canvas = recorder.beginRecording(record_bounds.Width(), record_bounds.Height()); canvas->save(); canvas->translate(dx, dy); canvas->drawRect(record_bounds, PaintFlags()); canvas->restore(); return recorder.finishRecordingAsPicture(); } TEST_F(DrawingDisplayItemTest, VisualRectAndDrawingBounds) { FloatRect record_bounds(5.5, 6.6, 7.7, 8.8); LayoutRect drawing_bounds(record_bounds); client_.SetVisualRect(drawing_bounds); DrawingDisplayItem item(client_, DisplayItem::Type::kDocumentBackground, CreateRectRecord(record_bounds)); EXPECT_EQ(FloatRect(drawing_bounds), item.VisualRect()); MockWebDisplayItemList list1; WebRect expected_rect = EnclosingIntRect(drawing_bounds); EXPECT_CALL(list1, AppendDrawingItem(expected_rect, _)).Times(1); item.AppendToWebDisplayItemList(FloatSize(), &list1); FloatSize offset(2.1, 3.6); FloatRect visual_rect_with_offset(drawing_bounds); visual_rect_with_offset.Move(-offset); WebRect expected_visual_rect = EnclosingIntRect(visual_rect_with_offset); MockWebDisplayItemList list2; EXPECT_CALL(list2, AppendDrawingItem(expected_visual_rect, _)).Times(1); item.AppendToWebDisplayItemList(offset, &list2); } TEST_F(DrawingDisplayItemTest, Equals) { FloatRect bounds1(100.1, 100.2, 100.3, 100.4); client_.SetVisualRect(LayoutRect(bounds1)); DrawingDisplayItem item1(client_, DisplayItem::kDocumentBackground, CreateRectRecord(bounds1)); DrawingDisplayItem translated(client_, DisplayItem::kDocumentBackground, CreateRectRecordWithTranslate(bounds1, 10, 20)); // This item contains a DrawingRecord that is different from but visually // equivalent to item1's. DrawingDisplayItem zero_translated( client_, DisplayItem::kDocumentBackground, CreateRectRecordWithTranslate(bounds1, 0, 0)); FloatRect bounds2(100.5, 100.6, 100.7, 100.8); client_.SetVisualRect(LayoutRect(bounds2)); DrawingDisplayItem item2(client_, DisplayItem::kDocumentBackground, CreateRectRecord(bounds2)); DrawingDisplayItem empty_item(client_, DisplayItem::kDocumentBackground, nullptr); EXPECT_TRUE(item1.Equals(item1)); EXPECT_FALSE(item1.Equals(item2)); EXPECT_FALSE(item1.Equals(translated)); EXPECT_TRUE(item1.Equals(zero_translated)); EXPECT_FALSE(item1.Equals(empty_item)); EXPECT_FALSE(item2.Equals(item1)); EXPECT_TRUE(item2.Equals(item2)); EXPECT_FALSE(item2.Equals(translated)); EXPECT_FALSE(item2.Equals(zero_translated)); EXPECT_FALSE(item2.Equals(empty_item)); EXPECT_FALSE(translated.Equals(item1)); EXPECT_FALSE(translated.Equals(item2)); EXPECT_TRUE(translated.Equals(translated)); EXPECT_FALSE(translated.Equals(zero_translated)); EXPECT_FALSE(translated.Equals(empty_item)); EXPECT_TRUE(zero_translated.Equals(item1)); EXPECT_FALSE(zero_translated.Equals(item2)); EXPECT_FALSE(zero_translated.Equals(translated)); EXPECT_TRUE(zero_translated.Equals(zero_translated)); EXPECT_FALSE(zero_translated.Equals(empty_item)); EXPECT_FALSE(empty_item.Equals(item1)); EXPECT_FALSE(empty_item.Equals(item2)); EXPECT_FALSE(empty_item.Equals(translated)); EXPECT_FALSE(empty_item.Equals(zero_translated)); EXPECT_TRUE(empty_item.Equals(empty_item)); } } // namespace } // namespace blink
null
null
null
null
35,020
2,202
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
155,259
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * Generate a header file for hardcoded sine windows * * Copyright (c) 2009 Reimar Döffinger <Reimar.Doeffinger@gmx.de> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define USE_FIXED 1 #include "sinewin_tablegen_template.c"
null
null
null
null
71,314
67,662
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
67,662
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ipc/handle_win.h" #include <utility> #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "ipc/handle_attachment_win.h" #include "ipc/ipc_message.h" namespace IPC { HandleWin::HandleWin() : handle_(INVALID_HANDLE_VALUE) {} HandleWin::HandleWin(const HANDLE& handle) : handle_(handle) {} // static void ParamTraits<HandleWin>::Write(base::Pickle* m, const param_type& p) { scoped_refptr<IPC::internal::HandleAttachmentWin> attachment( new IPC::internal::HandleAttachmentWin(p.get_handle())); if (!m->WriteAttachment(std::move(attachment))) NOTREACHED(); } // static bool ParamTraits<HandleWin>::Read(const base::Pickle* m, base::PickleIterator* iter, param_type* r) { scoped_refptr<base::Pickle::Attachment> base_attachment; if (!m->ReadAttachment(iter, &base_attachment)) return false; MessageAttachment* attachment = static_cast<MessageAttachment*>(base_attachment.get()); if (attachment->GetType() != MessageAttachment::Type::WIN_HANDLE) return false; IPC::internal::HandleAttachmentWin* handle_attachment = static_cast<IPC::internal::HandleAttachmentWin*>(attachment); r->set_handle(handle_attachment->Take()); return true; } // static void ParamTraits<HandleWin>::Log(const param_type& p, std::string* l) { l->append(base::StringPrintf("0x%p", p.get_handle())); } } // namespace IPC
null
null
null
null
64,525
16,683
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
181,678
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * arch/sh/boards/dreamcast/rtc.c * * Dreamcast AICA RTC routines. * * Copyright (c) 2001, 2002 M. R. Brown <mrbrown@0xd6.org> * Copyright (c) 2002 Paul Mundt <lethal@chaoticdreams.org> * * Released under the terms of the GNU GPL v2.0. * */ #include <linux/time.h> #include <asm/rtc.h> #include <asm/io.h> /* The AICA RTC has an Epoch of 1/1/1950, so we must subtract 20 years (in seconds) to get the standard Unix Epoch when getting the time, and add 20 years when setting the time. */ #define TWENTY_YEARS ((20 * 365LU + 5) * 86400) /* The AICA RTC is represented by a 32-bit seconds counter stored in 2 16-bit registers.*/ #define AICA_RTC_SECS_H 0xa0710000 #define AICA_RTC_SECS_L 0xa0710004 /** * aica_rtc_gettimeofday - Get the time from the AICA RTC * @ts: pointer to resulting timespec * * Grabs the current RTC seconds counter and adjusts it to the Unix Epoch. */ static void aica_rtc_gettimeofday(struct timespec *ts) { unsigned long val1, val2; do { val1 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) | (__raw_readl(AICA_RTC_SECS_L) & 0xffff); val2 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) | (__raw_readl(AICA_RTC_SECS_L) & 0xffff); } while (val1 != val2); ts->tv_sec = val1 - TWENTY_YEARS; /* Can't get nanoseconds with just a seconds counter. */ ts->tv_nsec = 0; } /** * aica_rtc_settimeofday - Set the AICA RTC to the current time * @secs: contains the time_t to set * * Adjusts the given @tv to the AICA Epoch and sets the RTC seconds counter. */ static int aica_rtc_settimeofday(const time_t secs) { unsigned long val1, val2; unsigned long adj = secs + TWENTY_YEARS; do { __raw_writel((adj & 0xffff0000) >> 16, AICA_RTC_SECS_H); __raw_writel((adj & 0xffff), AICA_RTC_SECS_L); val1 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) | (__raw_readl(AICA_RTC_SECS_L) & 0xffff); val2 = ((__raw_readl(AICA_RTC_SECS_H) & 0xffff) << 16) | (__raw_readl(AICA_RTC_SECS_L) & 0xffff); } while (val1 != val2); return 0; } void aica_time_init(void) { rtc_sh_get_time = aica_rtc_gettimeofday; rtc_sh_set_time = aica_rtc_settimeofday; }
null
null
null
null
90,025
22,173
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
187,168
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (c) 2005-2011 Atheros Communications Inc. * Copyright (c) 2011-2013 Qualcomm Atheros, Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <linux/skbuff.h> #include <linux/ctype.h> #include "core.h" #include "htc.h" #include "debug.h" #include "wmi.h" #include "wmi-tlv.h" #include "mac.h" #include "testmode.h" #include "wmi-ops.h" #include "p2p.h" #include "hw.h" #include "hif.h" #define ATH10K_WMI_BARRIER_ECHO_ID 0xBA991E9 #define ATH10K_WMI_BARRIER_TIMEOUT_HZ (3 * HZ) /* MAIN WMI cmd track */ static struct wmi_cmd_map wmi_cmd_map = { .init_cmdid = WMI_INIT_CMDID, .start_scan_cmdid = WMI_START_SCAN_CMDID, .stop_scan_cmdid = WMI_STOP_SCAN_CMDID, .scan_chan_list_cmdid = WMI_SCAN_CHAN_LIST_CMDID, .scan_sch_prio_tbl_cmdid = WMI_SCAN_SCH_PRIO_TBL_CMDID, .pdev_set_regdomain_cmdid = WMI_PDEV_SET_REGDOMAIN_CMDID, .pdev_set_channel_cmdid = WMI_PDEV_SET_CHANNEL_CMDID, .pdev_set_param_cmdid = WMI_PDEV_SET_PARAM_CMDID, .pdev_pktlog_enable_cmdid = WMI_PDEV_PKTLOG_ENABLE_CMDID, .pdev_pktlog_disable_cmdid = WMI_PDEV_PKTLOG_DISABLE_CMDID, .pdev_set_wmm_params_cmdid = WMI_PDEV_SET_WMM_PARAMS_CMDID, .pdev_set_ht_cap_ie_cmdid = WMI_PDEV_SET_HT_CAP_IE_CMDID, .pdev_set_vht_cap_ie_cmdid = WMI_PDEV_SET_VHT_CAP_IE_CMDID, .pdev_set_dscp_tid_map_cmdid = WMI_PDEV_SET_DSCP_TID_MAP_CMDID, .pdev_set_quiet_mode_cmdid = WMI_PDEV_SET_QUIET_MODE_CMDID, .pdev_green_ap_ps_enable_cmdid = WMI_PDEV_GREEN_AP_PS_ENABLE_CMDID, .pdev_get_tpc_config_cmdid = WMI_PDEV_GET_TPC_CONFIG_CMDID, .pdev_set_base_macaddr_cmdid = WMI_PDEV_SET_BASE_MACADDR_CMDID, .vdev_create_cmdid = WMI_VDEV_CREATE_CMDID, .vdev_delete_cmdid = WMI_VDEV_DELETE_CMDID, .vdev_start_request_cmdid = WMI_VDEV_START_REQUEST_CMDID, .vdev_restart_request_cmdid = WMI_VDEV_RESTART_REQUEST_CMDID, .vdev_up_cmdid = WMI_VDEV_UP_CMDID, .vdev_stop_cmdid = WMI_VDEV_STOP_CMDID, .vdev_down_cmdid = WMI_VDEV_DOWN_CMDID, .vdev_set_param_cmdid = WMI_VDEV_SET_PARAM_CMDID, .vdev_install_key_cmdid = WMI_VDEV_INSTALL_KEY_CMDID, .peer_create_cmdid = WMI_PEER_CREATE_CMDID, .peer_delete_cmdid = WMI_PEER_DELETE_CMDID, .peer_flush_tids_cmdid = WMI_PEER_FLUSH_TIDS_CMDID, .peer_set_param_cmdid = WMI_PEER_SET_PARAM_CMDID, .peer_assoc_cmdid = WMI_PEER_ASSOC_CMDID, .peer_add_wds_entry_cmdid = WMI_PEER_ADD_WDS_ENTRY_CMDID, .peer_remove_wds_entry_cmdid = WMI_PEER_REMOVE_WDS_ENTRY_CMDID, .peer_mcast_group_cmdid = WMI_PEER_MCAST_GROUP_CMDID, .bcn_tx_cmdid = WMI_BCN_TX_CMDID, .pdev_send_bcn_cmdid = WMI_PDEV_SEND_BCN_CMDID, .bcn_tmpl_cmdid = WMI_BCN_TMPL_CMDID, .bcn_filter_rx_cmdid = WMI_BCN_FILTER_RX_CMDID, .prb_req_filter_rx_cmdid = WMI_PRB_REQ_FILTER_RX_CMDID, .mgmt_tx_cmdid = WMI_MGMT_TX_CMDID, .prb_tmpl_cmdid = WMI_PRB_TMPL_CMDID, .addba_clear_resp_cmdid = WMI_ADDBA_CLEAR_RESP_CMDID, .addba_send_cmdid = WMI_ADDBA_SEND_CMDID, .addba_status_cmdid = WMI_ADDBA_STATUS_CMDID, .delba_send_cmdid = WMI_DELBA_SEND_CMDID, .addba_set_resp_cmdid = WMI_ADDBA_SET_RESP_CMDID, .send_singleamsdu_cmdid = WMI_SEND_SINGLEAMSDU_CMDID, .sta_powersave_mode_cmdid = WMI_STA_POWERSAVE_MODE_CMDID, .sta_powersave_param_cmdid = WMI_STA_POWERSAVE_PARAM_CMDID, .sta_mimo_ps_mode_cmdid = WMI_STA_MIMO_PS_MODE_CMDID, .pdev_dfs_enable_cmdid = WMI_PDEV_DFS_ENABLE_CMDID, .pdev_dfs_disable_cmdid = WMI_PDEV_DFS_DISABLE_CMDID, .roam_scan_mode = WMI_ROAM_SCAN_MODE, .roam_scan_rssi_threshold = WMI_ROAM_SCAN_RSSI_THRESHOLD, .roam_scan_period = WMI_ROAM_SCAN_PERIOD, .roam_scan_rssi_change_threshold = WMI_ROAM_SCAN_RSSI_CHANGE_THRESHOLD, .roam_ap_profile = WMI_ROAM_AP_PROFILE, .ofl_scan_add_ap_profile = WMI_ROAM_AP_PROFILE, .ofl_scan_remove_ap_profile = WMI_OFL_SCAN_REMOVE_AP_PROFILE, .ofl_scan_period = WMI_OFL_SCAN_PERIOD, .p2p_dev_set_device_info = WMI_P2P_DEV_SET_DEVICE_INFO, .p2p_dev_set_discoverability = WMI_P2P_DEV_SET_DISCOVERABILITY, .p2p_go_set_beacon_ie = WMI_P2P_GO_SET_BEACON_IE, .p2p_go_set_probe_resp_ie = WMI_P2P_GO_SET_PROBE_RESP_IE, .p2p_set_vendor_ie_data_cmdid = WMI_P2P_SET_VENDOR_IE_DATA_CMDID, .ap_ps_peer_param_cmdid = WMI_AP_PS_PEER_PARAM_CMDID, .ap_ps_peer_uapsd_coex_cmdid = WMI_AP_PS_PEER_UAPSD_COEX_CMDID, .peer_rate_retry_sched_cmdid = WMI_PEER_RATE_RETRY_SCHED_CMDID, .wlan_profile_trigger_cmdid = WMI_WLAN_PROFILE_TRIGGER_CMDID, .wlan_profile_set_hist_intvl_cmdid = WMI_WLAN_PROFILE_SET_HIST_INTVL_CMDID, .wlan_profile_get_profile_data_cmdid = WMI_WLAN_PROFILE_GET_PROFILE_DATA_CMDID, .wlan_profile_enable_profile_id_cmdid = WMI_WLAN_PROFILE_ENABLE_PROFILE_ID_CMDID, .wlan_profile_list_profile_id_cmdid = WMI_WLAN_PROFILE_LIST_PROFILE_ID_CMDID, .pdev_suspend_cmdid = WMI_PDEV_SUSPEND_CMDID, .pdev_resume_cmdid = WMI_PDEV_RESUME_CMDID, .add_bcn_filter_cmdid = WMI_ADD_BCN_FILTER_CMDID, .rmv_bcn_filter_cmdid = WMI_RMV_BCN_FILTER_CMDID, .wow_add_wake_pattern_cmdid = WMI_WOW_ADD_WAKE_PATTERN_CMDID, .wow_del_wake_pattern_cmdid = WMI_WOW_DEL_WAKE_PATTERN_CMDID, .wow_enable_disable_wake_event_cmdid = WMI_WOW_ENABLE_DISABLE_WAKE_EVENT_CMDID, .wow_enable_cmdid = WMI_WOW_ENABLE_CMDID, .wow_hostwakeup_from_sleep_cmdid = WMI_WOW_HOSTWAKEUP_FROM_SLEEP_CMDID, .rtt_measreq_cmdid = WMI_RTT_MEASREQ_CMDID, .rtt_tsf_cmdid = WMI_RTT_TSF_CMDID, .vdev_spectral_scan_configure_cmdid = WMI_VDEV_SPECTRAL_SCAN_CONFIGURE_CMDID, .vdev_spectral_scan_enable_cmdid = WMI_VDEV_SPECTRAL_SCAN_ENABLE_CMDID, .request_stats_cmdid = WMI_REQUEST_STATS_CMDID, .set_arp_ns_offload_cmdid = WMI_SET_ARP_NS_OFFLOAD_CMDID, .network_list_offload_config_cmdid = WMI_NETWORK_LIST_OFFLOAD_CONFIG_CMDID, .gtk_offload_cmdid = WMI_GTK_OFFLOAD_CMDID, .csa_offload_enable_cmdid = WMI_CSA_OFFLOAD_ENABLE_CMDID, .csa_offload_chanswitch_cmdid = WMI_CSA_OFFLOAD_CHANSWITCH_CMDID, .chatter_set_mode_cmdid = WMI_CHATTER_SET_MODE_CMDID, .peer_tid_addba_cmdid = WMI_PEER_TID_ADDBA_CMDID, .peer_tid_delba_cmdid = WMI_PEER_TID_DELBA_CMDID, .sta_dtim_ps_method_cmdid = WMI_STA_DTIM_PS_METHOD_CMDID, .sta_uapsd_auto_trig_cmdid = WMI_STA_UAPSD_AUTO_TRIG_CMDID, .sta_keepalive_cmd = WMI_STA_KEEPALIVE_CMD, .echo_cmdid = WMI_ECHO_CMDID, .pdev_utf_cmdid = WMI_PDEV_UTF_CMDID, .dbglog_cfg_cmdid = WMI_DBGLOG_CFG_CMDID, .pdev_qvit_cmdid = WMI_PDEV_QVIT_CMDID, .pdev_ftm_intg_cmdid = WMI_PDEV_FTM_INTG_CMDID, .vdev_set_keepalive_cmdid = WMI_VDEV_SET_KEEPALIVE_CMDID, .vdev_get_keepalive_cmdid = WMI_VDEV_GET_KEEPALIVE_CMDID, .force_fw_hang_cmdid = WMI_FORCE_FW_HANG_CMDID, .gpio_config_cmdid = WMI_GPIO_CONFIG_CMDID, .gpio_output_cmdid = WMI_GPIO_OUTPUT_CMDID, .pdev_get_temperature_cmdid = WMI_CMD_UNSUPPORTED, .pdev_enable_adaptive_cca_cmdid = WMI_CMD_UNSUPPORTED, .scan_update_request_cmdid = WMI_CMD_UNSUPPORTED, .vdev_standby_response_cmdid = WMI_CMD_UNSUPPORTED, .vdev_resume_response_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_add_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_evict_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_restore_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_print_all_peers_info_cmdid = WMI_CMD_UNSUPPORTED, .peer_update_wds_entry_cmdid = WMI_CMD_UNSUPPORTED, .peer_add_proxy_sta_entry_cmdid = WMI_CMD_UNSUPPORTED, .rtt_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .oem_req_cmdid = WMI_CMD_UNSUPPORTED, .nan_cmdid = WMI_CMD_UNSUPPORTED, .vdev_ratemask_cmdid = WMI_CMD_UNSUPPORTED, .qboost_cfg_cmdid = WMI_CMD_UNSUPPORTED, .pdev_smart_ant_enable_cmdid = WMI_CMD_UNSUPPORTED, .pdev_smart_ant_set_rx_antenna_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_tx_antenna_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_train_info_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_node_config_ops_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_antenna_switch_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_ctl_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_mimogain_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_ratepwr_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_ratepwr_chainmsk_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_fips_cmdid = WMI_CMD_UNSUPPORTED, .tt_set_conf_cmdid = WMI_CMD_UNSUPPORTED, .fwtest_cmdid = WMI_CMD_UNSUPPORTED, .vdev_atf_request_cmdid = WMI_CMD_UNSUPPORTED, .peer_atf_request_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ani_cck_config_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ani_ofdm_config_cmdid = WMI_CMD_UNSUPPORTED, .pdev_reserve_ast_entry_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_nfcal_power_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_tpc_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ast_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_set_dscp_tid_map_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_get_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_filter_neighbor_rx_packets_cmdid = WMI_CMD_UNSUPPORTED, .mu_cal_start_cmdid = WMI_CMD_UNSUPPORTED, .set_cca_params_cmdid = WMI_CMD_UNSUPPORTED, .pdev_bss_chan_info_request_cmdid = WMI_CMD_UNSUPPORTED, }; /* 10.X WMI cmd track */ static struct wmi_cmd_map wmi_10x_cmd_map = { .init_cmdid = WMI_10X_INIT_CMDID, .start_scan_cmdid = WMI_10X_START_SCAN_CMDID, .stop_scan_cmdid = WMI_10X_STOP_SCAN_CMDID, .scan_chan_list_cmdid = WMI_10X_SCAN_CHAN_LIST_CMDID, .scan_sch_prio_tbl_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_regdomain_cmdid = WMI_10X_PDEV_SET_REGDOMAIN_CMDID, .pdev_set_channel_cmdid = WMI_10X_PDEV_SET_CHANNEL_CMDID, .pdev_set_param_cmdid = WMI_10X_PDEV_SET_PARAM_CMDID, .pdev_pktlog_enable_cmdid = WMI_10X_PDEV_PKTLOG_ENABLE_CMDID, .pdev_pktlog_disable_cmdid = WMI_10X_PDEV_PKTLOG_DISABLE_CMDID, .pdev_set_wmm_params_cmdid = WMI_10X_PDEV_SET_WMM_PARAMS_CMDID, .pdev_set_ht_cap_ie_cmdid = WMI_10X_PDEV_SET_HT_CAP_IE_CMDID, .pdev_set_vht_cap_ie_cmdid = WMI_10X_PDEV_SET_VHT_CAP_IE_CMDID, .pdev_set_dscp_tid_map_cmdid = WMI_10X_PDEV_SET_DSCP_TID_MAP_CMDID, .pdev_set_quiet_mode_cmdid = WMI_10X_PDEV_SET_QUIET_MODE_CMDID, .pdev_green_ap_ps_enable_cmdid = WMI_10X_PDEV_GREEN_AP_PS_ENABLE_CMDID, .pdev_get_tpc_config_cmdid = WMI_10X_PDEV_GET_TPC_CONFIG_CMDID, .pdev_set_base_macaddr_cmdid = WMI_10X_PDEV_SET_BASE_MACADDR_CMDID, .vdev_create_cmdid = WMI_10X_VDEV_CREATE_CMDID, .vdev_delete_cmdid = WMI_10X_VDEV_DELETE_CMDID, .vdev_start_request_cmdid = WMI_10X_VDEV_START_REQUEST_CMDID, .vdev_restart_request_cmdid = WMI_10X_VDEV_RESTART_REQUEST_CMDID, .vdev_up_cmdid = WMI_10X_VDEV_UP_CMDID, .vdev_stop_cmdid = WMI_10X_VDEV_STOP_CMDID, .vdev_down_cmdid = WMI_10X_VDEV_DOWN_CMDID, .vdev_set_param_cmdid = WMI_10X_VDEV_SET_PARAM_CMDID, .vdev_install_key_cmdid = WMI_10X_VDEV_INSTALL_KEY_CMDID, .peer_create_cmdid = WMI_10X_PEER_CREATE_CMDID, .peer_delete_cmdid = WMI_10X_PEER_DELETE_CMDID, .peer_flush_tids_cmdid = WMI_10X_PEER_FLUSH_TIDS_CMDID, .peer_set_param_cmdid = WMI_10X_PEER_SET_PARAM_CMDID, .peer_assoc_cmdid = WMI_10X_PEER_ASSOC_CMDID, .peer_add_wds_entry_cmdid = WMI_10X_PEER_ADD_WDS_ENTRY_CMDID, .peer_remove_wds_entry_cmdid = WMI_10X_PEER_REMOVE_WDS_ENTRY_CMDID, .peer_mcast_group_cmdid = WMI_10X_PEER_MCAST_GROUP_CMDID, .bcn_tx_cmdid = WMI_10X_BCN_TX_CMDID, .pdev_send_bcn_cmdid = WMI_10X_PDEV_SEND_BCN_CMDID, .bcn_tmpl_cmdid = WMI_CMD_UNSUPPORTED, .bcn_filter_rx_cmdid = WMI_10X_BCN_FILTER_RX_CMDID, .prb_req_filter_rx_cmdid = WMI_10X_PRB_REQ_FILTER_RX_CMDID, .mgmt_tx_cmdid = WMI_10X_MGMT_TX_CMDID, .prb_tmpl_cmdid = WMI_CMD_UNSUPPORTED, .addba_clear_resp_cmdid = WMI_10X_ADDBA_CLEAR_RESP_CMDID, .addba_send_cmdid = WMI_10X_ADDBA_SEND_CMDID, .addba_status_cmdid = WMI_10X_ADDBA_STATUS_CMDID, .delba_send_cmdid = WMI_10X_DELBA_SEND_CMDID, .addba_set_resp_cmdid = WMI_10X_ADDBA_SET_RESP_CMDID, .send_singleamsdu_cmdid = WMI_10X_SEND_SINGLEAMSDU_CMDID, .sta_powersave_mode_cmdid = WMI_10X_STA_POWERSAVE_MODE_CMDID, .sta_powersave_param_cmdid = WMI_10X_STA_POWERSAVE_PARAM_CMDID, .sta_mimo_ps_mode_cmdid = WMI_10X_STA_MIMO_PS_MODE_CMDID, .pdev_dfs_enable_cmdid = WMI_10X_PDEV_DFS_ENABLE_CMDID, .pdev_dfs_disable_cmdid = WMI_10X_PDEV_DFS_DISABLE_CMDID, .roam_scan_mode = WMI_10X_ROAM_SCAN_MODE, .roam_scan_rssi_threshold = WMI_10X_ROAM_SCAN_RSSI_THRESHOLD, .roam_scan_period = WMI_10X_ROAM_SCAN_PERIOD, .roam_scan_rssi_change_threshold = WMI_10X_ROAM_SCAN_RSSI_CHANGE_THRESHOLD, .roam_ap_profile = WMI_10X_ROAM_AP_PROFILE, .ofl_scan_add_ap_profile = WMI_10X_OFL_SCAN_ADD_AP_PROFILE, .ofl_scan_remove_ap_profile = WMI_10X_OFL_SCAN_REMOVE_AP_PROFILE, .ofl_scan_period = WMI_10X_OFL_SCAN_PERIOD, .p2p_dev_set_device_info = WMI_10X_P2P_DEV_SET_DEVICE_INFO, .p2p_dev_set_discoverability = WMI_10X_P2P_DEV_SET_DISCOVERABILITY, .p2p_go_set_beacon_ie = WMI_10X_P2P_GO_SET_BEACON_IE, .p2p_go_set_probe_resp_ie = WMI_10X_P2P_GO_SET_PROBE_RESP_IE, .p2p_set_vendor_ie_data_cmdid = WMI_CMD_UNSUPPORTED, .ap_ps_peer_param_cmdid = WMI_10X_AP_PS_PEER_PARAM_CMDID, .ap_ps_peer_uapsd_coex_cmdid = WMI_CMD_UNSUPPORTED, .peer_rate_retry_sched_cmdid = WMI_10X_PEER_RATE_RETRY_SCHED_CMDID, .wlan_profile_trigger_cmdid = WMI_10X_WLAN_PROFILE_TRIGGER_CMDID, .wlan_profile_set_hist_intvl_cmdid = WMI_10X_WLAN_PROFILE_SET_HIST_INTVL_CMDID, .wlan_profile_get_profile_data_cmdid = WMI_10X_WLAN_PROFILE_GET_PROFILE_DATA_CMDID, .wlan_profile_enable_profile_id_cmdid = WMI_10X_WLAN_PROFILE_ENABLE_PROFILE_ID_CMDID, .wlan_profile_list_profile_id_cmdid = WMI_10X_WLAN_PROFILE_LIST_PROFILE_ID_CMDID, .pdev_suspend_cmdid = WMI_10X_PDEV_SUSPEND_CMDID, .pdev_resume_cmdid = WMI_10X_PDEV_RESUME_CMDID, .add_bcn_filter_cmdid = WMI_10X_ADD_BCN_FILTER_CMDID, .rmv_bcn_filter_cmdid = WMI_10X_RMV_BCN_FILTER_CMDID, .wow_add_wake_pattern_cmdid = WMI_10X_WOW_ADD_WAKE_PATTERN_CMDID, .wow_del_wake_pattern_cmdid = WMI_10X_WOW_DEL_WAKE_PATTERN_CMDID, .wow_enable_disable_wake_event_cmdid = WMI_10X_WOW_ENABLE_DISABLE_WAKE_EVENT_CMDID, .wow_enable_cmdid = WMI_10X_WOW_ENABLE_CMDID, .wow_hostwakeup_from_sleep_cmdid = WMI_10X_WOW_HOSTWAKEUP_FROM_SLEEP_CMDID, .rtt_measreq_cmdid = WMI_10X_RTT_MEASREQ_CMDID, .rtt_tsf_cmdid = WMI_10X_RTT_TSF_CMDID, .vdev_spectral_scan_configure_cmdid = WMI_10X_VDEV_SPECTRAL_SCAN_CONFIGURE_CMDID, .vdev_spectral_scan_enable_cmdid = WMI_10X_VDEV_SPECTRAL_SCAN_ENABLE_CMDID, .request_stats_cmdid = WMI_10X_REQUEST_STATS_CMDID, .set_arp_ns_offload_cmdid = WMI_CMD_UNSUPPORTED, .network_list_offload_config_cmdid = WMI_CMD_UNSUPPORTED, .gtk_offload_cmdid = WMI_CMD_UNSUPPORTED, .csa_offload_enable_cmdid = WMI_CMD_UNSUPPORTED, .csa_offload_chanswitch_cmdid = WMI_CMD_UNSUPPORTED, .chatter_set_mode_cmdid = WMI_CMD_UNSUPPORTED, .peer_tid_addba_cmdid = WMI_CMD_UNSUPPORTED, .peer_tid_delba_cmdid = WMI_CMD_UNSUPPORTED, .sta_dtim_ps_method_cmdid = WMI_CMD_UNSUPPORTED, .sta_uapsd_auto_trig_cmdid = WMI_CMD_UNSUPPORTED, .sta_keepalive_cmd = WMI_CMD_UNSUPPORTED, .echo_cmdid = WMI_10X_ECHO_CMDID, .pdev_utf_cmdid = WMI_10X_PDEV_UTF_CMDID, .dbglog_cfg_cmdid = WMI_10X_DBGLOG_CFG_CMDID, .pdev_qvit_cmdid = WMI_10X_PDEV_QVIT_CMDID, .pdev_ftm_intg_cmdid = WMI_CMD_UNSUPPORTED, .vdev_set_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .vdev_get_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .force_fw_hang_cmdid = WMI_CMD_UNSUPPORTED, .gpio_config_cmdid = WMI_10X_GPIO_CONFIG_CMDID, .gpio_output_cmdid = WMI_10X_GPIO_OUTPUT_CMDID, .pdev_get_temperature_cmdid = WMI_CMD_UNSUPPORTED, .pdev_enable_adaptive_cca_cmdid = WMI_CMD_UNSUPPORTED, .scan_update_request_cmdid = WMI_CMD_UNSUPPORTED, .vdev_standby_response_cmdid = WMI_CMD_UNSUPPORTED, .vdev_resume_response_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_add_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_evict_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_restore_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_print_all_peers_info_cmdid = WMI_CMD_UNSUPPORTED, .peer_update_wds_entry_cmdid = WMI_CMD_UNSUPPORTED, .peer_add_proxy_sta_entry_cmdid = WMI_CMD_UNSUPPORTED, .rtt_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .oem_req_cmdid = WMI_CMD_UNSUPPORTED, .nan_cmdid = WMI_CMD_UNSUPPORTED, .vdev_ratemask_cmdid = WMI_CMD_UNSUPPORTED, .qboost_cfg_cmdid = WMI_CMD_UNSUPPORTED, .pdev_smart_ant_enable_cmdid = WMI_CMD_UNSUPPORTED, .pdev_smart_ant_set_rx_antenna_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_tx_antenna_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_train_info_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_node_config_ops_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_antenna_switch_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_ctl_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_mimogain_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_ratepwr_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_ratepwr_chainmsk_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_fips_cmdid = WMI_CMD_UNSUPPORTED, .tt_set_conf_cmdid = WMI_CMD_UNSUPPORTED, .fwtest_cmdid = WMI_CMD_UNSUPPORTED, .vdev_atf_request_cmdid = WMI_CMD_UNSUPPORTED, .peer_atf_request_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ani_cck_config_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ani_ofdm_config_cmdid = WMI_CMD_UNSUPPORTED, .pdev_reserve_ast_entry_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_nfcal_power_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_tpc_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ast_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_set_dscp_tid_map_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_get_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_filter_neighbor_rx_packets_cmdid = WMI_CMD_UNSUPPORTED, .mu_cal_start_cmdid = WMI_CMD_UNSUPPORTED, .set_cca_params_cmdid = WMI_CMD_UNSUPPORTED, .pdev_bss_chan_info_request_cmdid = WMI_CMD_UNSUPPORTED, }; /* 10.2.4 WMI cmd track */ static struct wmi_cmd_map wmi_10_2_4_cmd_map = { .init_cmdid = WMI_10_2_INIT_CMDID, .start_scan_cmdid = WMI_10_2_START_SCAN_CMDID, .stop_scan_cmdid = WMI_10_2_STOP_SCAN_CMDID, .scan_chan_list_cmdid = WMI_10_2_SCAN_CHAN_LIST_CMDID, .scan_sch_prio_tbl_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_regdomain_cmdid = WMI_10_2_PDEV_SET_REGDOMAIN_CMDID, .pdev_set_channel_cmdid = WMI_10_2_PDEV_SET_CHANNEL_CMDID, .pdev_set_param_cmdid = WMI_10_2_PDEV_SET_PARAM_CMDID, .pdev_pktlog_enable_cmdid = WMI_10_2_PDEV_PKTLOG_ENABLE_CMDID, .pdev_pktlog_disable_cmdid = WMI_10_2_PDEV_PKTLOG_DISABLE_CMDID, .pdev_set_wmm_params_cmdid = WMI_10_2_PDEV_SET_WMM_PARAMS_CMDID, .pdev_set_ht_cap_ie_cmdid = WMI_10_2_PDEV_SET_HT_CAP_IE_CMDID, .pdev_set_vht_cap_ie_cmdid = WMI_10_2_PDEV_SET_VHT_CAP_IE_CMDID, .pdev_set_quiet_mode_cmdid = WMI_10_2_PDEV_SET_QUIET_MODE_CMDID, .pdev_green_ap_ps_enable_cmdid = WMI_10_2_PDEV_GREEN_AP_PS_ENABLE_CMDID, .pdev_get_tpc_config_cmdid = WMI_10_2_PDEV_GET_TPC_CONFIG_CMDID, .pdev_set_base_macaddr_cmdid = WMI_10_2_PDEV_SET_BASE_MACADDR_CMDID, .vdev_create_cmdid = WMI_10_2_VDEV_CREATE_CMDID, .vdev_delete_cmdid = WMI_10_2_VDEV_DELETE_CMDID, .vdev_start_request_cmdid = WMI_10_2_VDEV_START_REQUEST_CMDID, .vdev_restart_request_cmdid = WMI_10_2_VDEV_RESTART_REQUEST_CMDID, .vdev_up_cmdid = WMI_10_2_VDEV_UP_CMDID, .vdev_stop_cmdid = WMI_10_2_VDEV_STOP_CMDID, .vdev_down_cmdid = WMI_10_2_VDEV_DOWN_CMDID, .vdev_set_param_cmdid = WMI_10_2_VDEV_SET_PARAM_CMDID, .vdev_install_key_cmdid = WMI_10_2_VDEV_INSTALL_KEY_CMDID, .peer_create_cmdid = WMI_10_2_PEER_CREATE_CMDID, .peer_delete_cmdid = WMI_10_2_PEER_DELETE_CMDID, .peer_flush_tids_cmdid = WMI_10_2_PEER_FLUSH_TIDS_CMDID, .peer_set_param_cmdid = WMI_10_2_PEER_SET_PARAM_CMDID, .peer_assoc_cmdid = WMI_10_2_PEER_ASSOC_CMDID, .peer_add_wds_entry_cmdid = WMI_10_2_PEER_ADD_WDS_ENTRY_CMDID, .peer_remove_wds_entry_cmdid = WMI_10_2_PEER_REMOVE_WDS_ENTRY_CMDID, .peer_mcast_group_cmdid = WMI_10_2_PEER_MCAST_GROUP_CMDID, .bcn_tx_cmdid = WMI_10_2_BCN_TX_CMDID, .pdev_send_bcn_cmdid = WMI_10_2_PDEV_SEND_BCN_CMDID, .bcn_tmpl_cmdid = WMI_CMD_UNSUPPORTED, .bcn_filter_rx_cmdid = WMI_10_2_BCN_FILTER_RX_CMDID, .prb_req_filter_rx_cmdid = WMI_10_2_PRB_REQ_FILTER_RX_CMDID, .mgmt_tx_cmdid = WMI_10_2_MGMT_TX_CMDID, .prb_tmpl_cmdid = WMI_CMD_UNSUPPORTED, .addba_clear_resp_cmdid = WMI_10_2_ADDBA_CLEAR_RESP_CMDID, .addba_send_cmdid = WMI_10_2_ADDBA_SEND_CMDID, .addba_status_cmdid = WMI_10_2_ADDBA_STATUS_CMDID, .delba_send_cmdid = WMI_10_2_DELBA_SEND_CMDID, .addba_set_resp_cmdid = WMI_10_2_ADDBA_SET_RESP_CMDID, .send_singleamsdu_cmdid = WMI_10_2_SEND_SINGLEAMSDU_CMDID, .sta_powersave_mode_cmdid = WMI_10_2_STA_POWERSAVE_MODE_CMDID, .sta_powersave_param_cmdid = WMI_10_2_STA_POWERSAVE_PARAM_CMDID, .sta_mimo_ps_mode_cmdid = WMI_10_2_STA_MIMO_PS_MODE_CMDID, .pdev_dfs_enable_cmdid = WMI_10_2_PDEV_DFS_ENABLE_CMDID, .pdev_dfs_disable_cmdid = WMI_10_2_PDEV_DFS_DISABLE_CMDID, .roam_scan_mode = WMI_10_2_ROAM_SCAN_MODE, .roam_scan_rssi_threshold = WMI_10_2_ROAM_SCAN_RSSI_THRESHOLD, .roam_scan_period = WMI_10_2_ROAM_SCAN_PERIOD, .roam_scan_rssi_change_threshold = WMI_10_2_ROAM_SCAN_RSSI_CHANGE_THRESHOLD, .roam_ap_profile = WMI_10_2_ROAM_AP_PROFILE, .ofl_scan_add_ap_profile = WMI_10_2_OFL_SCAN_ADD_AP_PROFILE, .ofl_scan_remove_ap_profile = WMI_10_2_OFL_SCAN_REMOVE_AP_PROFILE, .ofl_scan_period = WMI_10_2_OFL_SCAN_PERIOD, .p2p_dev_set_device_info = WMI_10_2_P2P_DEV_SET_DEVICE_INFO, .p2p_dev_set_discoverability = WMI_10_2_P2P_DEV_SET_DISCOVERABILITY, .p2p_go_set_beacon_ie = WMI_10_2_P2P_GO_SET_BEACON_IE, .p2p_go_set_probe_resp_ie = WMI_10_2_P2P_GO_SET_PROBE_RESP_IE, .p2p_set_vendor_ie_data_cmdid = WMI_CMD_UNSUPPORTED, .ap_ps_peer_param_cmdid = WMI_10_2_AP_PS_PEER_PARAM_CMDID, .ap_ps_peer_uapsd_coex_cmdid = WMI_CMD_UNSUPPORTED, .peer_rate_retry_sched_cmdid = WMI_10_2_PEER_RATE_RETRY_SCHED_CMDID, .wlan_profile_trigger_cmdid = WMI_10_2_WLAN_PROFILE_TRIGGER_CMDID, .wlan_profile_set_hist_intvl_cmdid = WMI_10_2_WLAN_PROFILE_SET_HIST_INTVL_CMDID, .wlan_profile_get_profile_data_cmdid = WMI_10_2_WLAN_PROFILE_GET_PROFILE_DATA_CMDID, .wlan_profile_enable_profile_id_cmdid = WMI_10_2_WLAN_PROFILE_ENABLE_PROFILE_ID_CMDID, .wlan_profile_list_profile_id_cmdid = WMI_10_2_WLAN_PROFILE_LIST_PROFILE_ID_CMDID, .pdev_suspend_cmdid = WMI_10_2_PDEV_SUSPEND_CMDID, .pdev_resume_cmdid = WMI_10_2_PDEV_RESUME_CMDID, .add_bcn_filter_cmdid = WMI_10_2_ADD_BCN_FILTER_CMDID, .rmv_bcn_filter_cmdid = WMI_10_2_RMV_BCN_FILTER_CMDID, .wow_add_wake_pattern_cmdid = WMI_10_2_WOW_ADD_WAKE_PATTERN_CMDID, .wow_del_wake_pattern_cmdid = WMI_10_2_WOW_DEL_WAKE_PATTERN_CMDID, .wow_enable_disable_wake_event_cmdid = WMI_10_2_WOW_ENABLE_DISABLE_WAKE_EVENT_CMDID, .wow_enable_cmdid = WMI_10_2_WOW_ENABLE_CMDID, .wow_hostwakeup_from_sleep_cmdid = WMI_10_2_WOW_HOSTWAKEUP_FROM_SLEEP_CMDID, .rtt_measreq_cmdid = WMI_10_2_RTT_MEASREQ_CMDID, .rtt_tsf_cmdid = WMI_10_2_RTT_TSF_CMDID, .vdev_spectral_scan_configure_cmdid = WMI_10_2_VDEV_SPECTRAL_SCAN_CONFIGURE_CMDID, .vdev_spectral_scan_enable_cmdid = WMI_10_2_VDEV_SPECTRAL_SCAN_ENABLE_CMDID, .request_stats_cmdid = WMI_10_2_REQUEST_STATS_CMDID, .set_arp_ns_offload_cmdid = WMI_CMD_UNSUPPORTED, .network_list_offload_config_cmdid = WMI_CMD_UNSUPPORTED, .gtk_offload_cmdid = WMI_CMD_UNSUPPORTED, .csa_offload_enable_cmdid = WMI_CMD_UNSUPPORTED, .csa_offload_chanswitch_cmdid = WMI_CMD_UNSUPPORTED, .chatter_set_mode_cmdid = WMI_CMD_UNSUPPORTED, .peer_tid_addba_cmdid = WMI_CMD_UNSUPPORTED, .peer_tid_delba_cmdid = WMI_CMD_UNSUPPORTED, .sta_dtim_ps_method_cmdid = WMI_CMD_UNSUPPORTED, .sta_uapsd_auto_trig_cmdid = WMI_CMD_UNSUPPORTED, .sta_keepalive_cmd = WMI_CMD_UNSUPPORTED, .echo_cmdid = WMI_10_2_ECHO_CMDID, .pdev_utf_cmdid = WMI_10_2_PDEV_UTF_CMDID, .dbglog_cfg_cmdid = WMI_10_2_DBGLOG_CFG_CMDID, .pdev_qvit_cmdid = WMI_10_2_PDEV_QVIT_CMDID, .pdev_ftm_intg_cmdid = WMI_CMD_UNSUPPORTED, .vdev_set_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .vdev_get_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .force_fw_hang_cmdid = WMI_CMD_UNSUPPORTED, .gpio_config_cmdid = WMI_10_2_GPIO_CONFIG_CMDID, .gpio_output_cmdid = WMI_10_2_GPIO_OUTPUT_CMDID, .pdev_get_temperature_cmdid = WMI_10_2_PDEV_GET_TEMPERATURE_CMDID, .pdev_enable_adaptive_cca_cmdid = WMI_10_2_SET_CCA_PARAMS, .scan_update_request_cmdid = WMI_CMD_UNSUPPORTED, .vdev_standby_response_cmdid = WMI_CMD_UNSUPPORTED, .vdev_resume_response_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_add_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_evict_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_restore_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_print_all_peers_info_cmdid = WMI_CMD_UNSUPPORTED, .peer_update_wds_entry_cmdid = WMI_CMD_UNSUPPORTED, .peer_add_proxy_sta_entry_cmdid = WMI_CMD_UNSUPPORTED, .rtt_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .oem_req_cmdid = WMI_CMD_UNSUPPORTED, .nan_cmdid = WMI_CMD_UNSUPPORTED, .vdev_ratemask_cmdid = WMI_CMD_UNSUPPORTED, .qboost_cfg_cmdid = WMI_CMD_UNSUPPORTED, .pdev_smart_ant_enable_cmdid = WMI_CMD_UNSUPPORTED, .pdev_smart_ant_set_rx_antenna_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_tx_antenna_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_train_info_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_node_config_ops_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_antenna_switch_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_ctl_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_mimogain_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_ratepwr_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_ratepwr_chainmsk_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_fips_cmdid = WMI_CMD_UNSUPPORTED, .tt_set_conf_cmdid = WMI_CMD_UNSUPPORTED, .fwtest_cmdid = WMI_CMD_UNSUPPORTED, .vdev_atf_request_cmdid = WMI_CMD_UNSUPPORTED, .peer_atf_request_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ani_cck_config_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ani_ofdm_config_cmdid = WMI_CMD_UNSUPPORTED, .pdev_reserve_ast_entry_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_nfcal_power_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_tpc_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ast_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_set_dscp_tid_map_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_get_info_cmdid = WMI_CMD_UNSUPPORTED, .vdev_filter_neighbor_rx_packets_cmdid = WMI_CMD_UNSUPPORTED, .mu_cal_start_cmdid = WMI_CMD_UNSUPPORTED, .set_cca_params_cmdid = WMI_CMD_UNSUPPORTED, .pdev_bss_chan_info_request_cmdid = WMI_10_2_PDEV_BSS_CHAN_INFO_REQUEST_CMDID, }; /* 10.4 WMI cmd track */ static struct wmi_cmd_map wmi_10_4_cmd_map = { .init_cmdid = WMI_10_4_INIT_CMDID, .start_scan_cmdid = WMI_10_4_START_SCAN_CMDID, .stop_scan_cmdid = WMI_10_4_STOP_SCAN_CMDID, .scan_chan_list_cmdid = WMI_10_4_SCAN_CHAN_LIST_CMDID, .scan_sch_prio_tbl_cmdid = WMI_10_4_SCAN_SCH_PRIO_TBL_CMDID, .pdev_set_regdomain_cmdid = WMI_10_4_PDEV_SET_REGDOMAIN_CMDID, .pdev_set_channel_cmdid = WMI_10_4_PDEV_SET_CHANNEL_CMDID, .pdev_set_param_cmdid = WMI_10_4_PDEV_SET_PARAM_CMDID, .pdev_pktlog_enable_cmdid = WMI_10_4_PDEV_PKTLOG_ENABLE_CMDID, .pdev_pktlog_disable_cmdid = WMI_10_4_PDEV_PKTLOG_DISABLE_CMDID, .pdev_set_wmm_params_cmdid = WMI_10_4_PDEV_SET_WMM_PARAMS_CMDID, .pdev_set_ht_cap_ie_cmdid = WMI_10_4_PDEV_SET_HT_CAP_IE_CMDID, .pdev_set_vht_cap_ie_cmdid = WMI_10_4_PDEV_SET_VHT_CAP_IE_CMDID, .pdev_set_dscp_tid_map_cmdid = WMI_10_4_PDEV_SET_DSCP_TID_MAP_CMDID, .pdev_set_quiet_mode_cmdid = WMI_10_4_PDEV_SET_QUIET_MODE_CMDID, .pdev_green_ap_ps_enable_cmdid = WMI_10_4_PDEV_GREEN_AP_PS_ENABLE_CMDID, .pdev_get_tpc_config_cmdid = WMI_10_4_PDEV_GET_TPC_CONFIG_CMDID, .pdev_set_base_macaddr_cmdid = WMI_10_4_PDEV_SET_BASE_MACADDR_CMDID, .vdev_create_cmdid = WMI_10_4_VDEV_CREATE_CMDID, .vdev_delete_cmdid = WMI_10_4_VDEV_DELETE_CMDID, .vdev_start_request_cmdid = WMI_10_4_VDEV_START_REQUEST_CMDID, .vdev_restart_request_cmdid = WMI_10_4_VDEV_RESTART_REQUEST_CMDID, .vdev_up_cmdid = WMI_10_4_VDEV_UP_CMDID, .vdev_stop_cmdid = WMI_10_4_VDEV_STOP_CMDID, .vdev_down_cmdid = WMI_10_4_VDEV_DOWN_CMDID, .vdev_set_param_cmdid = WMI_10_4_VDEV_SET_PARAM_CMDID, .vdev_install_key_cmdid = WMI_10_4_VDEV_INSTALL_KEY_CMDID, .peer_create_cmdid = WMI_10_4_PEER_CREATE_CMDID, .peer_delete_cmdid = WMI_10_4_PEER_DELETE_CMDID, .peer_flush_tids_cmdid = WMI_10_4_PEER_FLUSH_TIDS_CMDID, .peer_set_param_cmdid = WMI_10_4_PEER_SET_PARAM_CMDID, .peer_assoc_cmdid = WMI_10_4_PEER_ASSOC_CMDID, .peer_add_wds_entry_cmdid = WMI_10_4_PEER_ADD_WDS_ENTRY_CMDID, .peer_remove_wds_entry_cmdid = WMI_10_4_PEER_REMOVE_WDS_ENTRY_CMDID, .peer_mcast_group_cmdid = WMI_10_4_PEER_MCAST_GROUP_CMDID, .bcn_tx_cmdid = WMI_10_4_BCN_TX_CMDID, .pdev_send_bcn_cmdid = WMI_10_4_PDEV_SEND_BCN_CMDID, .bcn_tmpl_cmdid = WMI_10_4_BCN_PRB_TMPL_CMDID, .bcn_filter_rx_cmdid = WMI_10_4_BCN_FILTER_RX_CMDID, .prb_req_filter_rx_cmdid = WMI_10_4_PRB_REQ_FILTER_RX_CMDID, .mgmt_tx_cmdid = WMI_10_4_MGMT_TX_CMDID, .prb_tmpl_cmdid = WMI_10_4_PRB_TMPL_CMDID, .addba_clear_resp_cmdid = WMI_10_4_ADDBA_CLEAR_RESP_CMDID, .addba_send_cmdid = WMI_10_4_ADDBA_SEND_CMDID, .addba_status_cmdid = WMI_10_4_ADDBA_STATUS_CMDID, .delba_send_cmdid = WMI_10_4_DELBA_SEND_CMDID, .addba_set_resp_cmdid = WMI_10_4_ADDBA_SET_RESP_CMDID, .send_singleamsdu_cmdid = WMI_10_4_SEND_SINGLEAMSDU_CMDID, .sta_powersave_mode_cmdid = WMI_10_4_STA_POWERSAVE_MODE_CMDID, .sta_powersave_param_cmdid = WMI_10_4_STA_POWERSAVE_PARAM_CMDID, .sta_mimo_ps_mode_cmdid = WMI_10_4_STA_MIMO_PS_MODE_CMDID, .pdev_dfs_enable_cmdid = WMI_10_4_PDEV_DFS_ENABLE_CMDID, .pdev_dfs_disable_cmdid = WMI_10_4_PDEV_DFS_DISABLE_CMDID, .roam_scan_mode = WMI_10_4_ROAM_SCAN_MODE, .roam_scan_rssi_threshold = WMI_10_4_ROAM_SCAN_RSSI_THRESHOLD, .roam_scan_period = WMI_10_4_ROAM_SCAN_PERIOD, .roam_scan_rssi_change_threshold = WMI_10_4_ROAM_SCAN_RSSI_CHANGE_THRESHOLD, .roam_ap_profile = WMI_10_4_ROAM_AP_PROFILE, .ofl_scan_add_ap_profile = WMI_10_4_OFL_SCAN_ADD_AP_PROFILE, .ofl_scan_remove_ap_profile = WMI_10_4_OFL_SCAN_REMOVE_AP_PROFILE, .ofl_scan_period = WMI_10_4_OFL_SCAN_PERIOD, .p2p_dev_set_device_info = WMI_10_4_P2P_DEV_SET_DEVICE_INFO, .p2p_dev_set_discoverability = WMI_10_4_P2P_DEV_SET_DISCOVERABILITY, .p2p_go_set_beacon_ie = WMI_10_4_P2P_GO_SET_BEACON_IE, .p2p_go_set_probe_resp_ie = WMI_10_4_P2P_GO_SET_PROBE_RESP_IE, .p2p_set_vendor_ie_data_cmdid = WMI_10_4_P2P_SET_VENDOR_IE_DATA_CMDID, .ap_ps_peer_param_cmdid = WMI_10_4_AP_PS_PEER_PARAM_CMDID, .ap_ps_peer_uapsd_coex_cmdid = WMI_10_4_AP_PS_PEER_UAPSD_COEX_CMDID, .peer_rate_retry_sched_cmdid = WMI_10_4_PEER_RATE_RETRY_SCHED_CMDID, .wlan_profile_trigger_cmdid = WMI_10_4_WLAN_PROFILE_TRIGGER_CMDID, .wlan_profile_set_hist_intvl_cmdid = WMI_10_4_WLAN_PROFILE_SET_HIST_INTVL_CMDID, .wlan_profile_get_profile_data_cmdid = WMI_10_4_WLAN_PROFILE_GET_PROFILE_DATA_CMDID, .wlan_profile_enable_profile_id_cmdid = WMI_10_4_WLAN_PROFILE_ENABLE_PROFILE_ID_CMDID, .wlan_profile_list_profile_id_cmdid = WMI_10_4_WLAN_PROFILE_LIST_PROFILE_ID_CMDID, .pdev_suspend_cmdid = WMI_10_4_PDEV_SUSPEND_CMDID, .pdev_resume_cmdid = WMI_10_4_PDEV_RESUME_CMDID, .add_bcn_filter_cmdid = WMI_10_4_ADD_BCN_FILTER_CMDID, .rmv_bcn_filter_cmdid = WMI_10_4_RMV_BCN_FILTER_CMDID, .wow_add_wake_pattern_cmdid = WMI_10_4_WOW_ADD_WAKE_PATTERN_CMDID, .wow_del_wake_pattern_cmdid = WMI_10_4_WOW_DEL_WAKE_PATTERN_CMDID, .wow_enable_disable_wake_event_cmdid = WMI_10_4_WOW_ENABLE_DISABLE_WAKE_EVENT_CMDID, .wow_enable_cmdid = WMI_10_4_WOW_ENABLE_CMDID, .wow_hostwakeup_from_sleep_cmdid = WMI_10_4_WOW_HOSTWAKEUP_FROM_SLEEP_CMDID, .rtt_measreq_cmdid = WMI_10_4_RTT_MEASREQ_CMDID, .rtt_tsf_cmdid = WMI_10_4_RTT_TSF_CMDID, .vdev_spectral_scan_configure_cmdid = WMI_10_4_VDEV_SPECTRAL_SCAN_CONFIGURE_CMDID, .vdev_spectral_scan_enable_cmdid = WMI_10_4_VDEV_SPECTRAL_SCAN_ENABLE_CMDID, .request_stats_cmdid = WMI_10_4_REQUEST_STATS_CMDID, .set_arp_ns_offload_cmdid = WMI_CMD_UNSUPPORTED, .network_list_offload_config_cmdid = WMI_CMD_UNSUPPORTED, .gtk_offload_cmdid = WMI_10_4_GTK_OFFLOAD_CMDID, .csa_offload_enable_cmdid = WMI_10_4_CSA_OFFLOAD_ENABLE_CMDID, .csa_offload_chanswitch_cmdid = WMI_10_4_CSA_OFFLOAD_CHANSWITCH_CMDID, .chatter_set_mode_cmdid = WMI_CMD_UNSUPPORTED, .peer_tid_addba_cmdid = WMI_CMD_UNSUPPORTED, .peer_tid_delba_cmdid = WMI_CMD_UNSUPPORTED, .sta_dtim_ps_method_cmdid = WMI_CMD_UNSUPPORTED, .sta_uapsd_auto_trig_cmdid = WMI_CMD_UNSUPPORTED, .sta_keepalive_cmd = WMI_CMD_UNSUPPORTED, .echo_cmdid = WMI_10_4_ECHO_CMDID, .pdev_utf_cmdid = WMI_10_4_PDEV_UTF_CMDID, .dbglog_cfg_cmdid = WMI_10_4_DBGLOG_CFG_CMDID, .pdev_qvit_cmdid = WMI_10_4_PDEV_QVIT_CMDID, .pdev_ftm_intg_cmdid = WMI_CMD_UNSUPPORTED, .vdev_set_keepalive_cmdid = WMI_10_4_VDEV_SET_KEEPALIVE_CMDID, .vdev_get_keepalive_cmdid = WMI_10_4_VDEV_GET_KEEPALIVE_CMDID, .force_fw_hang_cmdid = WMI_10_4_FORCE_FW_HANG_CMDID, .gpio_config_cmdid = WMI_10_4_GPIO_CONFIG_CMDID, .gpio_output_cmdid = WMI_10_4_GPIO_OUTPUT_CMDID, .pdev_get_temperature_cmdid = WMI_10_4_PDEV_GET_TEMPERATURE_CMDID, .vdev_set_wmm_params_cmdid = WMI_CMD_UNSUPPORTED, .tdls_set_state_cmdid = WMI_CMD_UNSUPPORTED, .tdls_peer_update_cmdid = WMI_CMD_UNSUPPORTED, .adaptive_qcs_cmdid = WMI_CMD_UNSUPPORTED, .scan_update_request_cmdid = WMI_10_4_SCAN_UPDATE_REQUEST_CMDID, .vdev_standby_response_cmdid = WMI_10_4_VDEV_STANDBY_RESPONSE_CMDID, .vdev_resume_response_cmdid = WMI_10_4_VDEV_RESUME_RESPONSE_CMDID, .wlan_peer_caching_add_peer_cmdid = WMI_10_4_WLAN_PEER_CACHING_ADD_PEER_CMDID, .wlan_peer_caching_evict_peer_cmdid = WMI_10_4_WLAN_PEER_CACHING_EVICT_PEER_CMDID, .wlan_peer_caching_restore_peer_cmdid = WMI_10_4_WLAN_PEER_CACHING_RESTORE_PEER_CMDID, .wlan_peer_caching_print_all_peers_info_cmdid = WMI_10_4_WLAN_PEER_CACHING_PRINT_ALL_PEERS_INFO_CMDID, .peer_update_wds_entry_cmdid = WMI_10_4_PEER_UPDATE_WDS_ENTRY_CMDID, .peer_add_proxy_sta_entry_cmdid = WMI_10_4_PEER_ADD_PROXY_STA_ENTRY_CMDID, .rtt_keepalive_cmdid = WMI_10_4_RTT_KEEPALIVE_CMDID, .oem_req_cmdid = WMI_10_4_OEM_REQ_CMDID, .nan_cmdid = WMI_10_4_NAN_CMDID, .vdev_ratemask_cmdid = WMI_10_4_VDEV_RATEMASK_CMDID, .qboost_cfg_cmdid = WMI_10_4_QBOOST_CFG_CMDID, .pdev_smart_ant_enable_cmdid = WMI_10_4_PDEV_SMART_ANT_ENABLE_CMDID, .pdev_smart_ant_set_rx_antenna_cmdid = WMI_10_4_PDEV_SMART_ANT_SET_RX_ANTENNA_CMDID, .peer_smart_ant_set_tx_antenna_cmdid = WMI_10_4_PEER_SMART_ANT_SET_TX_ANTENNA_CMDID, .peer_smart_ant_set_train_info_cmdid = WMI_10_4_PEER_SMART_ANT_SET_TRAIN_INFO_CMDID, .peer_smart_ant_set_node_config_ops_cmdid = WMI_10_4_PEER_SMART_ANT_SET_NODE_CONFIG_OPS_CMDID, .pdev_set_antenna_switch_table_cmdid = WMI_10_4_PDEV_SET_ANTENNA_SWITCH_TABLE_CMDID, .pdev_set_ctl_table_cmdid = WMI_10_4_PDEV_SET_CTL_TABLE_CMDID, .pdev_set_mimogain_table_cmdid = WMI_10_4_PDEV_SET_MIMOGAIN_TABLE_CMDID, .pdev_ratepwr_table_cmdid = WMI_10_4_PDEV_RATEPWR_TABLE_CMDID, .pdev_ratepwr_chainmsk_table_cmdid = WMI_10_4_PDEV_RATEPWR_CHAINMSK_TABLE_CMDID, .pdev_fips_cmdid = WMI_10_4_PDEV_FIPS_CMDID, .tt_set_conf_cmdid = WMI_10_4_TT_SET_CONF_CMDID, .fwtest_cmdid = WMI_10_4_FWTEST_CMDID, .vdev_atf_request_cmdid = WMI_10_4_VDEV_ATF_REQUEST_CMDID, .peer_atf_request_cmdid = WMI_10_4_PEER_ATF_REQUEST_CMDID, .pdev_get_ani_cck_config_cmdid = WMI_10_4_PDEV_GET_ANI_CCK_CONFIG_CMDID, .pdev_get_ani_ofdm_config_cmdid = WMI_10_4_PDEV_GET_ANI_OFDM_CONFIG_CMDID, .pdev_reserve_ast_entry_cmdid = WMI_10_4_PDEV_RESERVE_AST_ENTRY_CMDID, .pdev_get_nfcal_power_cmdid = WMI_10_4_PDEV_GET_NFCAL_POWER_CMDID, .pdev_get_tpc_cmdid = WMI_10_4_PDEV_GET_TPC_CMDID, .pdev_get_ast_info_cmdid = WMI_10_4_PDEV_GET_AST_INFO_CMDID, .vdev_set_dscp_tid_map_cmdid = WMI_10_4_VDEV_SET_DSCP_TID_MAP_CMDID, .pdev_get_info_cmdid = WMI_10_4_PDEV_GET_INFO_CMDID, .vdev_get_info_cmdid = WMI_10_4_VDEV_GET_INFO_CMDID, .vdev_filter_neighbor_rx_packets_cmdid = WMI_10_4_VDEV_FILTER_NEIGHBOR_RX_PACKETS_CMDID, .mu_cal_start_cmdid = WMI_10_4_MU_CAL_START_CMDID, .set_cca_params_cmdid = WMI_10_4_SET_CCA_PARAMS_CMDID, .pdev_bss_chan_info_request_cmdid = WMI_10_4_PDEV_BSS_CHAN_INFO_REQUEST_CMDID, .ext_resource_cfg_cmdid = WMI_10_4_EXT_RESOURCE_CFG_CMDID, }; /* MAIN WMI VDEV param map */ static struct wmi_vdev_param_map wmi_vdev_param_map = { .rts_threshold = WMI_VDEV_PARAM_RTS_THRESHOLD, .fragmentation_threshold = WMI_VDEV_PARAM_FRAGMENTATION_THRESHOLD, .beacon_interval = WMI_VDEV_PARAM_BEACON_INTERVAL, .listen_interval = WMI_VDEV_PARAM_LISTEN_INTERVAL, .multicast_rate = WMI_VDEV_PARAM_MULTICAST_RATE, .mgmt_tx_rate = WMI_VDEV_PARAM_MGMT_TX_RATE, .slot_time = WMI_VDEV_PARAM_SLOT_TIME, .preamble = WMI_VDEV_PARAM_PREAMBLE, .swba_time = WMI_VDEV_PARAM_SWBA_TIME, .wmi_vdev_stats_update_period = WMI_VDEV_STATS_UPDATE_PERIOD, .wmi_vdev_pwrsave_ageout_time = WMI_VDEV_PWRSAVE_AGEOUT_TIME, .wmi_vdev_host_swba_interval = WMI_VDEV_HOST_SWBA_INTERVAL, .dtim_period = WMI_VDEV_PARAM_DTIM_PERIOD, .wmi_vdev_oc_scheduler_air_time_limit = WMI_VDEV_OC_SCHEDULER_AIR_TIME_LIMIT, .wds = WMI_VDEV_PARAM_WDS, .atim_window = WMI_VDEV_PARAM_ATIM_WINDOW, .bmiss_count_max = WMI_VDEV_PARAM_BMISS_COUNT_MAX, .bmiss_first_bcnt = WMI_VDEV_PARAM_BMISS_FIRST_BCNT, .bmiss_final_bcnt = WMI_VDEV_PARAM_BMISS_FINAL_BCNT, .feature_wmm = WMI_VDEV_PARAM_FEATURE_WMM, .chwidth = WMI_VDEV_PARAM_CHWIDTH, .chextoffset = WMI_VDEV_PARAM_CHEXTOFFSET, .disable_htprotection = WMI_VDEV_PARAM_DISABLE_HTPROTECTION, .sta_quickkickout = WMI_VDEV_PARAM_STA_QUICKKICKOUT, .mgmt_rate = WMI_VDEV_PARAM_MGMT_RATE, .protection_mode = WMI_VDEV_PARAM_PROTECTION_MODE, .fixed_rate = WMI_VDEV_PARAM_FIXED_RATE, .sgi = WMI_VDEV_PARAM_SGI, .ldpc = WMI_VDEV_PARAM_LDPC, .tx_stbc = WMI_VDEV_PARAM_TX_STBC, .rx_stbc = WMI_VDEV_PARAM_RX_STBC, .intra_bss_fwd = WMI_VDEV_PARAM_INTRA_BSS_FWD, .def_keyid = WMI_VDEV_PARAM_DEF_KEYID, .nss = WMI_VDEV_PARAM_NSS, .bcast_data_rate = WMI_VDEV_PARAM_BCAST_DATA_RATE, .mcast_data_rate = WMI_VDEV_PARAM_MCAST_DATA_RATE, .mcast_indicate = WMI_VDEV_PARAM_MCAST_INDICATE, .dhcp_indicate = WMI_VDEV_PARAM_DHCP_INDICATE, .unknown_dest_indicate = WMI_VDEV_PARAM_UNKNOWN_DEST_INDICATE, .ap_keepalive_min_idle_inactive_time_secs = WMI_VDEV_PARAM_AP_KEEPALIVE_MIN_IDLE_INACTIVE_TIME_SECS, .ap_keepalive_max_idle_inactive_time_secs = WMI_VDEV_PARAM_AP_KEEPALIVE_MAX_IDLE_INACTIVE_TIME_SECS, .ap_keepalive_max_unresponsive_time_secs = WMI_VDEV_PARAM_AP_KEEPALIVE_MAX_UNRESPONSIVE_TIME_SECS, .ap_enable_nawds = WMI_VDEV_PARAM_AP_ENABLE_NAWDS, .mcast2ucast_set = WMI_VDEV_PARAM_UNSUPPORTED, .enable_rtscts = WMI_VDEV_PARAM_ENABLE_RTSCTS, .txbf = WMI_VDEV_PARAM_TXBF, .packet_powersave = WMI_VDEV_PARAM_PACKET_POWERSAVE, .drop_unencry = WMI_VDEV_PARAM_DROP_UNENCRY, .tx_encap_type = WMI_VDEV_PARAM_TX_ENCAP_TYPE, .ap_detect_out_of_sync_sleeping_sta_time_secs = WMI_VDEV_PARAM_UNSUPPORTED, .rc_num_retries = WMI_VDEV_PARAM_UNSUPPORTED, .cabq_maxdur = WMI_VDEV_PARAM_UNSUPPORTED, .mfptest_set = WMI_VDEV_PARAM_UNSUPPORTED, .rts_fixed_rate = WMI_VDEV_PARAM_UNSUPPORTED, .vht_sgimask = WMI_VDEV_PARAM_UNSUPPORTED, .vht80_ratemask = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_adjust_enable = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_tgt_bmiss_num = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_bmiss_sample_cycle = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_slop_step = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_init_slop = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_adjust_pause = WMI_VDEV_PARAM_UNSUPPORTED, .proxy_sta = WMI_VDEV_PARAM_UNSUPPORTED, .meru_vc = WMI_VDEV_PARAM_UNSUPPORTED, .rx_decap_type = WMI_VDEV_PARAM_UNSUPPORTED, .bw_nss_ratemask = WMI_VDEV_PARAM_UNSUPPORTED, }; /* 10.X WMI VDEV param map */ static struct wmi_vdev_param_map wmi_10x_vdev_param_map = { .rts_threshold = WMI_10X_VDEV_PARAM_RTS_THRESHOLD, .fragmentation_threshold = WMI_10X_VDEV_PARAM_FRAGMENTATION_THRESHOLD, .beacon_interval = WMI_10X_VDEV_PARAM_BEACON_INTERVAL, .listen_interval = WMI_10X_VDEV_PARAM_LISTEN_INTERVAL, .multicast_rate = WMI_10X_VDEV_PARAM_MULTICAST_RATE, .mgmt_tx_rate = WMI_10X_VDEV_PARAM_MGMT_TX_RATE, .slot_time = WMI_10X_VDEV_PARAM_SLOT_TIME, .preamble = WMI_10X_VDEV_PARAM_PREAMBLE, .swba_time = WMI_10X_VDEV_PARAM_SWBA_TIME, .wmi_vdev_stats_update_period = WMI_10X_VDEV_STATS_UPDATE_PERIOD, .wmi_vdev_pwrsave_ageout_time = WMI_10X_VDEV_PWRSAVE_AGEOUT_TIME, .wmi_vdev_host_swba_interval = WMI_10X_VDEV_HOST_SWBA_INTERVAL, .dtim_period = WMI_10X_VDEV_PARAM_DTIM_PERIOD, .wmi_vdev_oc_scheduler_air_time_limit = WMI_10X_VDEV_OC_SCHEDULER_AIR_TIME_LIMIT, .wds = WMI_10X_VDEV_PARAM_WDS, .atim_window = WMI_10X_VDEV_PARAM_ATIM_WINDOW, .bmiss_count_max = WMI_10X_VDEV_PARAM_BMISS_COUNT_MAX, .bmiss_first_bcnt = WMI_VDEV_PARAM_UNSUPPORTED, .bmiss_final_bcnt = WMI_VDEV_PARAM_UNSUPPORTED, .feature_wmm = WMI_10X_VDEV_PARAM_FEATURE_WMM, .chwidth = WMI_10X_VDEV_PARAM_CHWIDTH, .chextoffset = WMI_10X_VDEV_PARAM_CHEXTOFFSET, .disable_htprotection = WMI_10X_VDEV_PARAM_DISABLE_HTPROTECTION, .sta_quickkickout = WMI_10X_VDEV_PARAM_STA_QUICKKICKOUT, .mgmt_rate = WMI_10X_VDEV_PARAM_MGMT_RATE, .protection_mode = WMI_10X_VDEV_PARAM_PROTECTION_MODE, .fixed_rate = WMI_10X_VDEV_PARAM_FIXED_RATE, .sgi = WMI_10X_VDEV_PARAM_SGI, .ldpc = WMI_10X_VDEV_PARAM_LDPC, .tx_stbc = WMI_10X_VDEV_PARAM_TX_STBC, .rx_stbc = WMI_10X_VDEV_PARAM_RX_STBC, .intra_bss_fwd = WMI_10X_VDEV_PARAM_INTRA_BSS_FWD, .def_keyid = WMI_10X_VDEV_PARAM_DEF_KEYID, .nss = WMI_10X_VDEV_PARAM_NSS, .bcast_data_rate = WMI_10X_VDEV_PARAM_BCAST_DATA_RATE, .mcast_data_rate = WMI_10X_VDEV_PARAM_MCAST_DATA_RATE, .mcast_indicate = WMI_10X_VDEV_PARAM_MCAST_INDICATE, .dhcp_indicate = WMI_10X_VDEV_PARAM_DHCP_INDICATE, .unknown_dest_indicate = WMI_10X_VDEV_PARAM_UNKNOWN_DEST_INDICATE, .ap_keepalive_min_idle_inactive_time_secs = WMI_10X_VDEV_PARAM_AP_KEEPALIVE_MIN_IDLE_INACTIVE_TIME_SECS, .ap_keepalive_max_idle_inactive_time_secs = WMI_10X_VDEV_PARAM_AP_KEEPALIVE_MAX_IDLE_INACTIVE_TIME_SECS, .ap_keepalive_max_unresponsive_time_secs = WMI_10X_VDEV_PARAM_AP_KEEPALIVE_MAX_UNRESPONSIVE_TIME_SECS, .ap_enable_nawds = WMI_10X_VDEV_PARAM_AP_ENABLE_NAWDS, .mcast2ucast_set = WMI_10X_VDEV_PARAM_MCAST2UCAST_SET, .enable_rtscts = WMI_10X_VDEV_PARAM_ENABLE_RTSCTS, .txbf = WMI_VDEV_PARAM_UNSUPPORTED, .packet_powersave = WMI_VDEV_PARAM_UNSUPPORTED, .drop_unencry = WMI_VDEV_PARAM_UNSUPPORTED, .tx_encap_type = WMI_VDEV_PARAM_UNSUPPORTED, .ap_detect_out_of_sync_sleeping_sta_time_secs = WMI_10X_VDEV_PARAM_AP_DETECT_OUT_OF_SYNC_SLEEPING_STA_TIME_SECS, .rc_num_retries = WMI_VDEV_PARAM_UNSUPPORTED, .cabq_maxdur = WMI_VDEV_PARAM_UNSUPPORTED, .mfptest_set = WMI_VDEV_PARAM_UNSUPPORTED, .rts_fixed_rate = WMI_VDEV_PARAM_UNSUPPORTED, .vht_sgimask = WMI_VDEV_PARAM_UNSUPPORTED, .vht80_ratemask = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_adjust_enable = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_tgt_bmiss_num = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_bmiss_sample_cycle = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_slop_step = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_init_slop = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_adjust_pause = WMI_VDEV_PARAM_UNSUPPORTED, .proxy_sta = WMI_VDEV_PARAM_UNSUPPORTED, .meru_vc = WMI_VDEV_PARAM_UNSUPPORTED, .rx_decap_type = WMI_VDEV_PARAM_UNSUPPORTED, .bw_nss_ratemask = WMI_VDEV_PARAM_UNSUPPORTED, }; static struct wmi_vdev_param_map wmi_10_2_4_vdev_param_map = { .rts_threshold = WMI_10X_VDEV_PARAM_RTS_THRESHOLD, .fragmentation_threshold = WMI_10X_VDEV_PARAM_FRAGMENTATION_THRESHOLD, .beacon_interval = WMI_10X_VDEV_PARAM_BEACON_INTERVAL, .listen_interval = WMI_10X_VDEV_PARAM_LISTEN_INTERVAL, .multicast_rate = WMI_10X_VDEV_PARAM_MULTICAST_RATE, .mgmt_tx_rate = WMI_10X_VDEV_PARAM_MGMT_TX_RATE, .slot_time = WMI_10X_VDEV_PARAM_SLOT_TIME, .preamble = WMI_10X_VDEV_PARAM_PREAMBLE, .swba_time = WMI_10X_VDEV_PARAM_SWBA_TIME, .wmi_vdev_stats_update_period = WMI_10X_VDEV_STATS_UPDATE_PERIOD, .wmi_vdev_pwrsave_ageout_time = WMI_10X_VDEV_PWRSAVE_AGEOUT_TIME, .wmi_vdev_host_swba_interval = WMI_10X_VDEV_HOST_SWBA_INTERVAL, .dtim_period = WMI_10X_VDEV_PARAM_DTIM_PERIOD, .wmi_vdev_oc_scheduler_air_time_limit = WMI_10X_VDEV_OC_SCHEDULER_AIR_TIME_LIMIT, .wds = WMI_10X_VDEV_PARAM_WDS, .atim_window = WMI_10X_VDEV_PARAM_ATIM_WINDOW, .bmiss_count_max = WMI_10X_VDEV_PARAM_BMISS_COUNT_MAX, .bmiss_first_bcnt = WMI_VDEV_PARAM_UNSUPPORTED, .bmiss_final_bcnt = WMI_VDEV_PARAM_UNSUPPORTED, .feature_wmm = WMI_10X_VDEV_PARAM_FEATURE_WMM, .chwidth = WMI_10X_VDEV_PARAM_CHWIDTH, .chextoffset = WMI_10X_VDEV_PARAM_CHEXTOFFSET, .disable_htprotection = WMI_10X_VDEV_PARAM_DISABLE_HTPROTECTION, .sta_quickkickout = WMI_10X_VDEV_PARAM_STA_QUICKKICKOUT, .mgmt_rate = WMI_10X_VDEV_PARAM_MGMT_RATE, .protection_mode = WMI_10X_VDEV_PARAM_PROTECTION_MODE, .fixed_rate = WMI_10X_VDEV_PARAM_FIXED_RATE, .sgi = WMI_10X_VDEV_PARAM_SGI, .ldpc = WMI_10X_VDEV_PARAM_LDPC, .tx_stbc = WMI_10X_VDEV_PARAM_TX_STBC, .rx_stbc = WMI_10X_VDEV_PARAM_RX_STBC, .intra_bss_fwd = WMI_10X_VDEV_PARAM_INTRA_BSS_FWD, .def_keyid = WMI_10X_VDEV_PARAM_DEF_KEYID, .nss = WMI_10X_VDEV_PARAM_NSS, .bcast_data_rate = WMI_10X_VDEV_PARAM_BCAST_DATA_RATE, .mcast_data_rate = WMI_10X_VDEV_PARAM_MCAST_DATA_RATE, .mcast_indicate = WMI_10X_VDEV_PARAM_MCAST_INDICATE, .dhcp_indicate = WMI_10X_VDEV_PARAM_DHCP_INDICATE, .unknown_dest_indicate = WMI_10X_VDEV_PARAM_UNKNOWN_DEST_INDICATE, .ap_keepalive_min_idle_inactive_time_secs = WMI_10X_VDEV_PARAM_AP_KEEPALIVE_MIN_IDLE_INACTIVE_TIME_SECS, .ap_keepalive_max_idle_inactive_time_secs = WMI_10X_VDEV_PARAM_AP_KEEPALIVE_MAX_IDLE_INACTIVE_TIME_SECS, .ap_keepalive_max_unresponsive_time_secs = WMI_10X_VDEV_PARAM_AP_KEEPALIVE_MAX_UNRESPONSIVE_TIME_SECS, .ap_enable_nawds = WMI_10X_VDEV_PARAM_AP_ENABLE_NAWDS, .mcast2ucast_set = WMI_10X_VDEV_PARAM_MCAST2UCAST_SET, .enable_rtscts = WMI_10X_VDEV_PARAM_ENABLE_RTSCTS, .txbf = WMI_VDEV_PARAM_UNSUPPORTED, .packet_powersave = WMI_VDEV_PARAM_UNSUPPORTED, .drop_unencry = WMI_VDEV_PARAM_UNSUPPORTED, .tx_encap_type = WMI_VDEV_PARAM_UNSUPPORTED, .ap_detect_out_of_sync_sleeping_sta_time_secs = WMI_10X_VDEV_PARAM_AP_DETECT_OUT_OF_SYNC_SLEEPING_STA_TIME_SECS, .rc_num_retries = WMI_VDEV_PARAM_UNSUPPORTED, .cabq_maxdur = WMI_VDEV_PARAM_UNSUPPORTED, .mfptest_set = WMI_VDEV_PARAM_UNSUPPORTED, .rts_fixed_rate = WMI_VDEV_PARAM_UNSUPPORTED, .vht_sgimask = WMI_VDEV_PARAM_UNSUPPORTED, .vht80_ratemask = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_adjust_enable = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_tgt_bmiss_num = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_bmiss_sample_cycle = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_slop_step = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_init_slop = WMI_VDEV_PARAM_UNSUPPORTED, .early_rx_adjust_pause = WMI_VDEV_PARAM_UNSUPPORTED, .proxy_sta = WMI_VDEV_PARAM_UNSUPPORTED, .meru_vc = WMI_VDEV_PARAM_UNSUPPORTED, .rx_decap_type = WMI_VDEV_PARAM_UNSUPPORTED, .bw_nss_ratemask = WMI_VDEV_PARAM_UNSUPPORTED, }; static struct wmi_vdev_param_map wmi_10_4_vdev_param_map = { .rts_threshold = WMI_10_4_VDEV_PARAM_RTS_THRESHOLD, .fragmentation_threshold = WMI_10_4_VDEV_PARAM_FRAGMENTATION_THRESHOLD, .beacon_interval = WMI_10_4_VDEV_PARAM_BEACON_INTERVAL, .listen_interval = WMI_10_4_VDEV_PARAM_LISTEN_INTERVAL, .multicast_rate = WMI_10_4_VDEV_PARAM_MULTICAST_RATE, .mgmt_tx_rate = WMI_10_4_VDEV_PARAM_MGMT_TX_RATE, .slot_time = WMI_10_4_VDEV_PARAM_SLOT_TIME, .preamble = WMI_10_4_VDEV_PARAM_PREAMBLE, .swba_time = WMI_10_4_VDEV_PARAM_SWBA_TIME, .wmi_vdev_stats_update_period = WMI_10_4_VDEV_STATS_UPDATE_PERIOD, .wmi_vdev_pwrsave_ageout_time = WMI_10_4_VDEV_PWRSAVE_AGEOUT_TIME, .wmi_vdev_host_swba_interval = WMI_10_4_VDEV_HOST_SWBA_INTERVAL, .dtim_period = WMI_10_4_VDEV_PARAM_DTIM_PERIOD, .wmi_vdev_oc_scheduler_air_time_limit = WMI_10_4_VDEV_OC_SCHEDULER_AIR_TIME_LIMIT, .wds = WMI_10_4_VDEV_PARAM_WDS, .atim_window = WMI_10_4_VDEV_PARAM_ATIM_WINDOW, .bmiss_count_max = WMI_10_4_VDEV_PARAM_BMISS_COUNT_MAX, .bmiss_first_bcnt = WMI_10_4_VDEV_PARAM_BMISS_FIRST_BCNT, .bmiss_final_bcnt = WMI_10_4_VDEV_PARAM_BMISS_FINAL_BCNT, .feature_wmm = WMI_10_4_VDEV_PARAM_FEATURE_WMM, .chwidth = WMI_10_4_VDEV_PARAM_CHWIDTH, .chextoffset = WMI_10_4_VDEV_PARAM_CHEXTOFFSET, .disable_htprotection = WMI_10_4_VDEV_PARAM_DISABLE_HTPROTECTION, .sta_quickkickout = WMI_10_4_VDEV_PARAM_STA_QUICKKICKOUT, .mgmt_rate = WMI_10_4_VDEV_PARAM_MGMT_RATE, .protection_mode = WMI_10_4_VDEV_PARAM_PROTECTION_MODE, .fixed_rate = WMI_10_4_VDEV_PARAM_FIXED_RATE, .sgi = WMI_10_4_VDEV_PARAM_SGI, .ldpc = WMI_10_4_VDEV_PARAM_LDPC, .tx_stbc = WMI_10_4_VDEV_PARAM_TX_STBC, .rx_stbc = WMI_10_4_VDEV_PARAM_RX_STBC, .intra_bss_fwd = WMI_10_4_VDEV_PARAM_INTRA_BSS_FWD, .def_keyid = WMI_10_4_VDEV_PARAM_DEF_KEYID, .nss = WMI_10_4_VDEV_PARAM_NSS, .bcast_data_rate = WMI_10_4_VDEV_PARAM_BCAST_DATA_RATE, .mcast_data_rate = WMI_10_4_VDEV_PARAM_MCAST_DATA_RATE, .mcast_indicate = WMI_10_4_VDEV_PARAM_MCAST_INDICATE, .dhcp_indicate = WMI_10_4_VDEV_PARAM_DHCP_INDICATE, .unknown_dest_indicate = WMI_10_4_VDEV_PARAM_UNKNOWN_DEST_INDICATE, .ap_keepalive_min_idle_inactive_time_secs = WMI_10_4_VDEV_PARAM_AP_KEEPALIVE_MIN_IDLE_INACTIVE_TIME_SECS, .ap_keepalive_max_idle_inactive_time_secs = WMI_10_4_VDEV_PARAM_AP_KEEPALIVE_MAX_IDLE_INACTIVE_TIME_SECS, .ap_keepalive_max_unresponsive_time_secs = WMI_10_4_VDEV_PARAM_AP_KEEPALIVE_MAX_UNRESPONSIVE_TIME_SECS, .ap_enable_nawds = WMI_10_4_VDEV_PARAM_AP_ENABLE_NAWDS, .mcast2ucast_set = WMI_10_4_VDEV_PARAM_MCAST2UCAST_SET, .enable_rtscts = WMI_10_4_VDEV_PARAM_ENABLE_RTSCTS, .txbf = WMI_10_4_VDEV_PARAM_TXBF, .packet_powersave = WMI_10_4_VDEV_PARAM_PACKET_POWERSAVE, .drop_unencry = WMI_10_4_VDEV_PARAM_DROP_UNENCRY, .tx_encap_type = WMI_10_4_VDEV_PARAM_TX_ENCAP_TYPE, .ap_detect_out_of_sync_sleeping_sta_time_secs = WMI_10_4_VDEV_PARAM_AP_DETECT_OUT_OF_SYNC_SLEEPING_STA_TIME_SECS, .rc_num_retries = WMI_10_4_VDEV_PARAM_RC_NUM_RETRIES, .cabq_maxdur = WMI_10_4_VDEV_PARAM_CABQ_MAXDUR, .mfptest_set = WMI_10_4_VDEV_PARAM_MFPTEST_SET, .rts_fixed_rate = WMI_10_4_VDEV_PARAM_RTS_FIXED_RATE, .vht_sgimask = WMI_10_4_VDEV_PARAM_VHT_SGIMASK, .vht80_ratemask = WMI_10_4_VDEV_PARAM_VHT80_RATEMASK, .early_rx_adjust_enable = WMI_10_4_VDEV_PARAM_EARLY_RX_ADJUST_ENABLE, .early_rx_tgt_bmiss_num = WMI_10_4_VDEV_PARAM_EARLY_RX_TGT_BMISS_NUM, .early_rx_bmiss_sample_cycle = WMI_10_4_VDEV_PARAM_EARLY_RX_BMISS_SAMPLE_CYCLE, .early_rx_slop_step = WMI_10_4_VDEV_PARAM_EARLY_RX_SLOP_STEP, .early_rx_init_slop = WMI_10_4_VDEV_PARAM_EARLY_RX_INIT_SLOP, .early_rx_adjust_pause = WMI_10_4_VDEV_PARAM_EARLY_RX_ADJUST_PAUSE, .proxy_sta = WMI_10_4_VDEV_PARAM_PROXY_STA, .meru_vc = WMI_10_4_VDEV_PARAM_MERU_VC, .rx_decap_type = WMI_10_4_VDEV_PARAM_RX_DECAP_TYPE, .bw_nss_ratemask = WMI_10_4_VDEV_PARAM_BW_NSS_RATEMASK, .inc_tsf = WMI_10_4_VDEV_PARAM_TSF_INCREMENT, .dec_tsf = WMI_10_4_VDEV_PARAM_TSF_DECREMENT, }; static struct wmi_pdev_param_map wmi_pdev_param_map = { .tx_chain_mask = WMI_PDEV_PARAM_TX_CHAIN_MASK, .rx_chain_mask = WMI_PDEV_PARAM_RX_CHAIN_MASK, .txpower_limit2g = WMI_PDEV_PARAM_TXPOWER_LIMIT2G, .txpower_limit5g = WMI_PDEV_PARAM_TXPOWER_LIMIT5G, .txpower_scale = WMI_PDEV_PARAM_TXPOWER_SCALE, .beacon_gen_mode = WMI_PDEV_PARAM_BEACON_GEN_MODE, .beacon_tx_mode = WMI_PDEV_PARAM_BEACON_TX_MODE, .resmgr_offchan_mode = WMI_PDEV_PARAM_RESMGR_OFFCHAN_MODE, .protection_mode = WMI_PDEV_PARAM_PROTECTION_MODE, .dynamic_bw = WMI_PDEV_PARAM_DYNAMIC_BW, .non_agg_sw_retry_th = WMI_PDEV_PARAM_NON_AGG_SW_RETRY_TH, .agg_sw_retry_th = WMI_PDEV_PARAM_AGG_SW_RETRY_TH, .sta_kickout_th = WMI_PDEV_PARAM_STA_KICKOUT_TH, .ac_aggrsize_scaling = WMI_PDEV_PARAM_AC_AGGRSIZE_SCALING, .ltr_enable = WMI_PDEV_PARAM_LTR_ENABLE, .ltr_ac_latency_be = WMI_PDEV_PARAM_LTR_AC_LATENCY_BE, .ltr_ac_latency_bk = WMI_PDEV_PARAM_LTR_AC_LATENCY_BK, .ltr_ac_latency_vi = WMI_PDEV_PARAM_LTR_AC_LATENCY_VI, .ltr_ac_latency_vo = WMI_PDEV_PARAM_LTR_AC_LATENCY_VO, .ltr_ac_latency_timeout = WMI_PDEV_PARAM_LTR_AC_LATENCY_TIMEOUT, .ltr_sleep_override = WMI_PDEV_PARAM_LTR_SLEEP_OVERRIDE, .ltr_rx_override = WMI_PDEV_PARAM_LTR_RX_OVERRIDE, .ltr_tx_activity_timeout = WMI_PDEV_PARAM_LTR_TX_ACTIVITY_TIMEOUT, .l1ss_enable = WMI_PDEV_PARAM_L1SS_ENABLE, .dsleep_enable = WMI_PDEV_PARAM_DSLEEP_ENABLE, .pcielp_txbuf_flush = WMI_PDEV_PARAM_PCIELP_TXBUF_FLUSH, .pcielp_txbuf_watermark = WMI_PDEV_PARAM_PCIELP_TXBUF_TMO_EN, .pcielp_txbuf_tmo_en = WMI_PDEV_PARAM_PCIELP_TXBUF_TMO_EN, .pcielp_txbuf_tmo_value = WMI_PDEV_PARAM_PCIELP_TXBUF_TMO_VALUE, .pdev_stats_update_period = WMI_PDEV_PARAM_PDEV_STATS_UPDATE_PERIOD, .vdev_stats_update_period = WMI_PDEV_PARAM_VDEV_STATS_UPDATE_PERIOD, .peer_stats_update_period = WMI_PDEV_PARAM_PEER_STATS_UPDATE_PERIOD, .bcnflt_stats_update_period = WMI_PDEV_PARAM_BCNFLT_STATS_UPDATE_PERIOD, .pmf_qos = WMI_PDEV_PARAM_PMF_QOS, .arp_ac_override = WMI_PDEV_PARAM_ARP_AC_OVERRIDE, .dcs = WMI_PDEV_PARAM_DCS, .ani_enable = WMI_PDEV_PARAM_ANI_ENABLE, .ani_poll_period = WMI_PDEV_PARAM_ANI_POLL_PERIOD, .ani_listen_period = WMI_PDEV_PARAM_ANI_LISTEN_PERIOD, .ani_ofdm_level = WMI_PDEV_PARAM_ANI_OFDM_LEVEL, .ani_cck_level = WMI_PDEV_PARAM_ANI_CCK_LEVEL, .dyntxchain = WMI_PDEV_PARAM_DYNTXCHAIN, .proxy_sta = WMI_PDEV_PARAM_PROXY_STA, .idle_ps_config = WMI_PDEV_PARAM_IDLE_PS_CONFIG, .power_gating_sleep = WMI_PDEV_PARAM_POWER_GATING_SLEEP, .fast_channel_reset = WMI_PDEV_PARAM_UNSUPPORTED, .burst_dur = WMI_PDEV_PARAM_UNSUPPORTED, .burst_enable = WMI_PDEV_PARAM_UNSUPPORTED, .cal_period = WMI_PDEV_PARAM_UNSUPPORTED, .aggr_burst = WMI_PDEV_PARAM_UNSUPPORTED, .rx_decap_mode = WMI_PDEV_PARAM_UNSUPPORTED, .smart_antenna_default_antenna = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_override = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_tid = WMI_PDEV_PARAM_UNSUPPORTED, .antenna_gain = WMI_PDEV_PARAM_UNSUPPORTED, .rx_filter = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast_to_ucast_tid = WMI_PDEV_PARAM_UNSUPPORTED, .proxy_sta_mode = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast2ucast_mode = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast2ucast_buffer = WMI_PDEV_PARAM_UNSUPPORTED, .remove_mcast2ucast_buffer = WMI_PDEV_PARAM_UNSUPPORTED, .peer_sta_ps_statechg_enable = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_ac_override = WMI_PDEV_PARAM_UNSUPPORTED, .block_interbss = WMI_PDEV_PARAM_UNSUPPORTED, .set_disable_reset_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_msdu_ttl_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_ppdu_duration_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .txbf_sound_period_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_promisc_mode_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_burst_mode_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .en_stats = WMI_PDEV_PARAM_UNSUPPORTED, .mu_group_policy = WMI_PDEV_PARAM_UNSUPPORTED, .noise_detection = WMI_PDEV_PARAM_UNSUPPORTED, .noise_threshold = WMI_PDEV_PARAM_UNSUPPORTED, .dpd_enable = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast_bcast_echo = WMI_PDEV_PARAM_UNSUPPORTED, .atf_strict_sch = WMI_PDEV_PARAM_UNSUPPORTED, .atf_sched_duration = WMI_PDEV_PARAM_UNSUPPORTED, .ant_plzn = WMI_PDEV_PARAM_UNSUPPORTED, .mgmt_retry_limit = WMI_PDEV_PARAM_UNSUPPORTED, .sensitivity_level = WMI_PDEV_PARAM_UNSUPPORTED, .signed_txpower_2g = WMI_PDEV_PARAM_UNSUPPORTED, .signed_txpower_5g = WMI_PDEV_PARAM_UNSUPPORTED, .enable_per_tid_amsdu = WMI_PDEV_PARAM_UNSUPPORTED, .enable_per_tid_ampdu = WMI_PDEV_PARAM_UNSUPPORTED, .cca_threshold = WMI_PDEV_PARAM_UNSUPPORTED, .rts_fixed_rate = WMI_PDEV_PARAM_UNSUPPORTED, .pdev_reset = WMI_PDEV_PARAM_UNSUPPORTED, .wapi_mbssid_offset = WMI_PDEV_PARAM_UNSUPPORTED, .arp_srcaddr = WMI_PDEV_PARAM_UNSUPPORTED, .arp_dstaddr = WMI_PDEV_PARAM_UNSUPPORTED, .enable_btcoex = WMI_PDEV_PARAM_UNSUPPORTED, }; static struct wmi_pdev_param_map wmi_10x_pdev_param_map = { .tx_chain_mask = WMI_10X_PDEV_PARAM_TX_CHAIN_MASK, .rx_chain_mask = WMI_10X_PDEV_PARAM_RX_CHAIN_MASK, .txpower_limit2g = WMI_10X_PDEV_PARAM_TXPOWER_LIMIT2G, .txpower_limit5g = WMI_10X_PDEV_PARAM_TXPOWER_LIMIT5G, .txpower_scale = WMI_10X_PDEV_PARAM_TXPOWER_SCALE, .beacon_gen_mode = WMI_10X_PDEV_PARAM_BEACON_GEN_MODE, .beacon_tx_mode = WMI_10X_PDEV_PARAM_BEACON_TX_MODE, .resmgr_offchan_mode = WMI_10X_PDEV_PARAM_RESMGR_OFFCHAN_MODE, .protection_mode = WMI_10X_PDEV_PARAM_PROTECTION_MODE, .dynamic_bw = WMI_10X_PDEV_PARAM_DYNAMIC_BW, .non_agg_sw_retry_th = WMI_10X_PDEV_PARAM_NON_AGG_SW_RETRY_TH, .agg_sw_retry_th = WMI_10X_PDEV_PARAM_AGG_SW_RETRY_TH, .sta_kickout_th = WMI_10X_PDEV_PARAM_STA_KICKOUT_TH, .ac_aggrsize_scaling = WMI_10X_PDEV_PARAM_AC_AGGRSIZE_SCALING, .ltr_enable = WMI_10X_PDEV_PARAM_LTR_ENABLE, .ltr_ac_latency_be = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_BE, .ltr_ac_latency_bk = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_BK, .ltr_ac_latency_vi = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_VI, .ltr_ac_latency_vo = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_VO, .ltr_ac_latency_timeout = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_TIMEOUT, .ltr_sleep_override = WMI_10X_PDEV_PARAM_LTR_SLEEP_OVERRIDE, .ltr_rx_override = WMI_10X_PDEV_PARAM_LTR_RX_OVERRIDE, .ltr_tx_activity_timeout = WMI_10X_PDEV_PARAM_LTR_TX_ACTIVITY_TIMEOUT, .l1ss_enable = WMI_10X_PDEV_PARAM_L1SS_ENABLE, .dsleep_enable = WMI_10X_PDEV_PARAM_DSLEEP_ENABLE, .pcielp_txbuf_flush = WMI_PDEV_PARAM_UNSUPPORTED, .pcielp_txbuf_watermark = WMI_PDEV_PARAM_UNSUPPORTED, .pcielp_txbuf_tmo_en = WMI_PDEV_PARAM_UNSUPPORTED, .pcielp_txbuf_tmo_value = WMI_PDEV_PARAM_UNSUPPORTED, .pdev_stats_update_period = WMI_10X_PDEV_PARAM_PDEV_STATS_UPDATE_PERIOD, .vdev_stats_update_period = WMI_10X_PDEV_PARAM_VDEV_STATS_UPDATE_PERIOD, .peer_stats_update_period = WMI_10X_PDEV_PARAM_PEER_STATS_UPDATE_PERIOD, .bcnflt_stats_update_period = WMI_10X_PDEV_PARAM_BCNFLT_STATS_UPDATE_PERIOD, .pmf_qos = WMI_10X_PDEV_PARAM_PMF_QOS, .arp_ac_override = WMI_10X_PDEV_PARAM_ARPDHCP_AC_OVERRIDE, .dcs = WMI_10X_PDEV_PARAM_DCS, .ani_enable = WMI_10X_PDEV_PARAM_ANI_ENABLE, .ani_poll_period = WMI_10X_PDEV_PARAM_ANI_POLL_PERIOD, .ani_listen_period = WMI_10X_PDEV_PARAM_ANI_LISTEN_PERIOD, .ani_ofdm_level = WMI_10X_PDEV_PARAM_ANI_OFDM_LEVEL, .ani_cck_level = WMI_10X_PDEV_PARAM_ANI_CCK_LEVEL, .dyntxchain = WMI_10X_PDEV_PARAM_DYNTXCHAIN, .proxy_sta = WMI_PDEV_PARAM_UNSUPPORTED, .idle_ps_config = WMI_PDEV_PARAM_UNSUPPORTED, .power_gating_sleep = WMI_PDEV_PARAM_UNSUPPORTED, .fast_channel_reset = WMI_10X_PDEV_PARAM_FAST_CHANNEL_RESET, .burst_dur = WMI_10X_PDEV_PARAM_BURST_DUR, .burst_enable = WMI_10X_PDEV_PARAM_BURST_ENABLE, .cal_period = WMI_10X_PDEV_PARAM_CAL_PERIOD, .aggr_burst = WMI_PDEV_PARAM_UNSUPPORTED, .rx_decap_mode = WMI_PDEV_PARAM_UNSUPPORTED, .smart_antenna_default_antenna = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_override = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_tid = WMI_PDEV_PARAM_UNSUPPORTED, .antenna_gain = WMI_PDEV_PARAM_UNSUPPORTED, .rx_filter = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast_to_ucast_tid = WMI_PDEV_PARAM_UNSUPPORTED, .proxy_sta_mode = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast2ucast_mode = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast2ucast_buffer = WMI_PDEV_PARAM_UNSUPPORTED, .remove_mcast2ucast_buffer = WMI_PDEV_PARAM_UNSUPPORTED, .peer_sta_ps_statechg_enable = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_ac_override = WMI_PDEV_PARAM_UNSUPPORTED, .block_interbss = WMI_PDEV_PARAM_UNSUPPORTED, .set_disable_reset_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_msdu_ttl_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_ppdu_duration_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .txbf_sound_period_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_promisc_mode_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_burst_mode_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .en_stats = WMI_PDEV_PARAM_UNSUPPORTED, .mu_group_policy = WMI_PDEV_PARAM_UNSUPPORTED, .noise_detection = WMI_PDEV_PARAM_UNSUPPORTED, .noise_threshold = WMI_PDEV_PARAM_UNSUPPORTED, .dpd_enable = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast_bcast_echo = WMI_PDEV_PARAM_UNSUPPORTED, .atf_strict_sch = WMI_PDEV_PARAM_UNSUPPORTED, .atf_sched_duration = WMI_PDEV_PARAM_UNSUPPORTED, .ant_plzn = WMI_PDEV_PARAM_UNSUPPORTED, .mgmt_retry_limit = WMI_PDEV_PARAM_UNSUPPORTED, .sensitivity_level = WMI_PDEV_PARAM_UNSUPPORTED, .signed_txpower_2g = WMI_PDEV_PARAM_UNSUPPORTED, .signed_txpower_5g = WMI_PDEV_PARAM_UNSUPPORTED, .enable_per_tid_amsdu = WMI_PDEV_PARAM_UNSUPPORTED, .enable_per_tid_ampdu = WMI_PDEV_PARAM_UNSUPPORTED, .cca_threshold = WMI_PDEV_PARAM_UNSUPPORTED, .rts_fixed_rate = WMI_PDEV_PARAM_UNSUPPORTED, .pdev_reset = WMI_PDEV_PARAM_UNSUPPORTED, .wapi_mbssid_offset = WMI_PDEV_PARAM_UNSUPPORTED, .arp_srcaddr = WMI_PDEV_PARAM_UNSUPPORTED, .arp_dstaddr = WMI_PDEV_PARAM_UNSUPPORTED, .enable_btcoex = WMI_PDEV_PARAM_UNSUPPORTED, }; static struct wmi_pdev_param_map wmi_10_2_4_pdev_param_map = { .tx_chain_mask = WMI_10X_PDEV_PARAM_TX_CHAIN_MASK, .rx_chain_mask = WMI_10X_PDEV_PARAM_RX_CHAIN_MASK, .txpower_limit2g = WMI_10X_PDEV_PARAM_TXPOWER_LIMIT2G, .txpower_limit5g = WMI_10X_PDEV_PARAM_TXPOWER_LIMIT5G, .txpower_scale = WMI_10X_PDEV_PARAM_TXPOWER_SCALE, .beacon_gen_mode = WMI_10X_PDEV_PARAM_BEACON_GEN_MODE, .beacon_tx_mode = WMI_10X_PDEV_PARAM_BEACON_TX_MODE, .resmgr_offchan_mode = WMI_10X_PDEV_PARAM_RESMGR_OFFCHAN_MODE, .protection_mode = WMI_10X_PDEV_PARAM_PROTECTION_MODE, .dynamic_bw = WMI_10X_PDEV_PARAM_DYNAMIC_BW, .non_agg_sw_retry_th = WMI_10X_PDEV_PARAM_NON_AGG_SW_RETRY_TH, .agg_sw_retry_th = WMI_10X_PDEV_PARAM_AGG_SW_RETRY_TH, .sta_kickout_th = WMI_10X_PDEV_PARAM_STA_KICKOUT_TH, .ac_aggrsize_scaling = WMI_10X_PDEV_PARAM_AC_AGGRSIZE_SCALING, .ltr_enable = WMI_10X_PDEV_PARAM_LTR_ENABLE, .ltr_ac_latency_be = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_BE, .ltr_ac_latency_bk = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_BK, .ltr_ac_latency_vi = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_VI, .ltr_ac_latency_vo = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_VO, .ltr_ac_latency_timeout = WMI_10X_PDEV_PARAM_LTR_AC_LATENCY_TIMEOUT, .ltr_sleep_override = WMI_10X_PDEV_PARAM_LTR_SLEEP_OVERRIDE, .ltr_rx_override = WMI_10X_PDEV_PARAM_LTR_RX_OVERRIDE, .ltr_tx_activity_timeout = WMI_10X_PDEV_PARAM_LTR_TX_ACTIVITY_TIMEOUT, .l1ss_enable = WMI_10X_PDEV_PARAM_L1SS_ENABLE, .dsleep_enable = WMI_10X_PDEV_PARAM_DSLEEP_ENABLE, .pcielp_txbuf_flush = WMI_PDEV_PARAM_UNSUPPORTED, .pcielp_txbuf_watermark = WMI_PDEV_PARAM_UNSUPPORTED, .pcielp_txbuf_tmo_en = WMI_PDEV_PARAM_UNSUPPORTED, .pcielp_txbuf_tmo_value = WMI_PDEV_PARAM_UNSUPPORTED, .pdev_stats_update_period = WMI_10X_PDEV_PARAM_PDEV_STATS_UPDATE_PERIOD, .vdev_stats_update_period = WMI_10X_PDEV_PARAM_VDEV_STATS_UPDATE_PERIOD, .peer_stats_update_period = WMI_10X_PDEV_PARAM_PEER_STATS_UPDATE_PERIOD, .bcnflt_stats_update_period = WMI_10X_PDEV_PARAM_BCNFLT_STATS_UPDATE_PERIOD, .pmf_qos = WMI_10X_PDEV_PARAM_PMF_QOS, .arp_ac_override = WMI_10X_PDEV_PARAM_ARPDHCP_AC_OVERRIDE, .dcs = WMI_10X_PDEV_PARAM_DCS, .ani_enable = WMI_10X_PDEV_PARAM_ANI_ENABLE, .ani_poll_period = WMI_10X_PDEV_PARAM_ANI_POLL_PERIOD, .ani_listen_period = WMI_10X_PDEV_PARAM_ANI_LISTEN_PERIOD, .ani_ofdm_level = WMI_10X_PDEV_PARAM_ANI_OFDM_LEVEL, .ani_cck_level = WMI_10X_PDEV_PARAM_ANI_CCK_LEVEL, .dyntxchain = WMI_10X_PDEV_PARAM_DYNTXCHAIN, .proxy_sta = WMI_PDEV_PARAM_UNSUPPORTED, .idle_ps_config = WMI_PDEV_PARAM_UNSUPPORTED, .power_gating_sleep = WMI_PDEV_PARAM_UNSUPPORTED, .fast_channel_reset = WMI_10X_PDEV_PARAM_FAST_CHANNEL_RESET, .burst_dur = WMI_10X_PDEV_PARAM_BURST_DUR, .burst_enable = WMI_10X_PDEV_PARAM_BURST_ENABLE, .cal_period = WMI_10X_PDEV_PARAM_CAL_PERIOD, .aggr_burst = WMI_PDEV_PARAM_UNSUPPORTED, .rx_decap_mode = WMI_PDEV_PARAM_UNSUPPORTED, .smart_antenna_default_antenna = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_override = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_tid = WMI_PDEV_PARAM_UNSUPPORTED, .antenna_gain = WMI_PDEV_PARAM_UNSUPPORTED, .rx_filter = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast_to_ucast_tid = WMI_PDEV_PARAM_UNSUPPORTED, .proxy_sta_mode = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast2ucast_mode = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast2ucast_buffer = WMI_PDEV_PARAM_UNSUPPORTED, .remove_mcast2ucast_buffer = WMI_PDEV_PARAM_UNSUPPORTED, .peer_sta_ps_statechg_enable = WMI_PDEV_PARAM_UNSUPPORTED, .igmpmld_ac_override = WMI_PDEV_PARAM_UNSUPPORTED, .block_interbss = WMI_PDEV_PARAM_UNSUPPORTED, .set_disable_reset_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_msdu_ttl_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_ppdu_duration_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .txbf_sound_period_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_promisc_mode_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .set_burst_mode_cmdid = WMI_PDEV_PARAM_UNSUPPORTED, .en_stats = WMI_PDEV_PARAM_UNSUPPORTED, .mu_group_policy = WMI_PDEV_PARAM_UNSUPPORTED, .noise_detection = WMI_PDEV_PARAM_UNSUPPORTED, .noise_threshold = WMI_PDEV_PARAM_UNSUPPORTED, .dpd_enable = WMI_PDEV_PARAM_UNSUPPORTED, .set_mcast_bcast_echo = WMI_PDEV_PARAM_UNSUPPORTED, .atf_strict_sch = WMI_PDEV_PARAM_UNSUPPORTED, .atf_sched_duration = WMI_PDEV_PARAM_UNSUPPORTED, .ant_plzn = WMI_PDEV_PARAM_UNSUPPORTED, .mgmt_retry_limit = WMI_PDEV_PARAM_UNSUPPORTED, .sensitivity_level = WMI_PDEV_PARAM_UNSUPPORTED, .signed_txpower_2g = WMI_PDEV_PARAM_UNSUPPORTED, .signed_txpower_5g = WMI_PDEV_PARAM_UNSUPPORTED, .enable_per_tid_amsdu = WMI_PDEV_PARAM_UNSUPPORTED, .enable_per_tid_ampdu = WMI_PDEV_PARAM_UNSUPPORTED, .cca_threshold = WMI_PDEV_PARAM_UNSUPPORTED, .rts_fixed_rate = WMI_PDEV_PARAM_UNSUPPORTED, .pdev_reset = WMI_PDEV_PARAM_UNSUPPORTED, .wapi_mbssid_offset = WMI_PDEV_PARAM_UNSUPPORTED, .arp_srcaddr = WMI_PDEV_PARAM_UNSUPPORTED, .arp_dstaddr = WMI_PDEV_PARAM_UNSUPPORTED, .enable_btcoex = WMI_PDEV_PARAM_UNSUPPORTED, }; /* firmware 10.2 specific mappings */ static struct wmi_cmd_map wmi_10_2_cmd_map = { .init_cmdid = WMI_10_2_INIT_CMDID, .start_scan_cmdid = WMI_10_2_START_SCAN_CMDID, .stop_scan_cmdid = WMI_10_2_STOP_SCAN_CMDID, .scan_chan_list_cmdid = WMI_10_2_SCAN_CHAN_LIST_CMDID, .scan_sch_prio_tbl_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_regdomain_cmdid = WMI_10_2_PDEV_SET_REGDOMAIN_CMDID, .pdev_set_channel_cmdid = WMI_10_2_PDEV_SET_CHANNEL_CMDID, .pdev_set_param_cmdid = WMI_10_2_PDEV_SET_PARAM_CMDID, .pdev_pktlog_enable_cmdid = WMI_10_2_PDEV_PKTLOG_ENABLE_CMDID, .pdev_pktlog_disable_cmdid = WMI_10_2_PDEV_PKTLOG_DISABLE_CMDID, .pdev_set_wmm_params_cmdid = WMI_10_2_PDEV_SET_WMM_PARAMS_CMDID, .pdev_set_ht_cap_ie_cmdid = WMI_10_2_PDEV_SET_HT_CAP_IE_CMDID, .pdev_set_vht_cap_ie_cmdid = WMI_10_2_PDEV_SET_VHT_CAP_IE_CMDID, .pdev_set_quiet_mode_cmdid = WMI_10_2_PDEV_SET_QUIET_MODE_CMDID, .pdev_green_ap_ps_enable_cmdid = WMI_10_2_PDEV_GREEN_AP_PS_ENABLE_CMDID, .pdev_get_tpc_config_cmdid = WMI_10_2_PDEV_GET_TPC_CONFIG_CMDID, .pdev_set_base_macaddr_cmdid = WMI_10_2_PDEV_SET_BASE_MACADDR_CMDID, .vdev_create_cmdid = WMI_10_2_VDEV_CREATE_CMDID, .vdev_delete_cmdid = WMI_10_2_VDEV_DELETE_CMDID, .vdev_start_request_cmdid = WMI_10_2_VDEV_START_REQUEST_CMDID, .vdev_restart_request_cmdid = WMI_10_2_VDEV_RESTART_REQUEST_CMDID, .vdev_up_cmdid = WMI_10_2_VDEV_UP_CMDID, .vdev_stop_cmdid = WMI_10_2_VDEV_STOP_CMDID, .vdev_down_cmdid = WMI_10_2_VDEV_DOWN_CMDID, .vdev_set_param_cmdid = WMI_10_2_VDEV_SET_PARAM_CMDID, .vdev_install_key_cmdid = WMI_10_2_VDEV_INSTALL_KEY_CMDID, .peer_create_cmdid = WMI_10_2_PEER_CREATE_CMDID, .peer_delete_cmdid = WMI_10_2_PEER_DELETE_CMDID, .peer_flush_tids_cmdid = WMI_10_2_PEER_FLUSH_TIDS_CMDID, .peer_set_param_cmdid = WMI_10_2_PEER_SET_PARAM_CMDID, .peer_assoc_cmdid = WMI_10_2_PEER_ASSOC_CMDID, .peer_add_wds_entry_cmdid = WMI_10_2_PEER_ADD_WDS_ENTRY_CMDID, .peer_remove_wds_entry_cmdid = WMI_10_2_PEER_REMOVE_WDS_ENTRY_CMDID, .peer_mcast_group_cmdid = WMI_10_2_PEER_MCAST_GROUP_CMDID, .bcn_tx_cmdid = WMI_10_2_BCN_TX_CMDID, .pdev_send_bcn_cmdid = WMI_10_2_PDEV_SEND_BCN_CMDID, .bcn_tmpl_cmdid = WMI_CMD_UNSUPPORTED, .bcn_filter_rx_cmdid = WMI_10_2_BCN_FILTER_RX_CMDID, .prb_req_filter_rx_cmdid = WMI_10_2_PRB_REQ_FILTER_RX_CMDID, .mgmt_tx_cmdid = WMI_10_2_MGMT_TX_CMDID, .prb_tmpl_cmdid = WMI_CMD_UNSUPPORTED, .addba_clear_resp_cmdid = WMI_10_2_ADDBA_CLEAR_RESP_CMDID, .addba_send_cmdid = WMI_10_2_ADDBA_SEND_CMDID, .addba_status_cmdid = WMI_10_2_ADDBA_STATUS_CMDID, .delba_send_cmdid = WMI_10_2_DELBA_SEND_CMDID, .addba_set_resp_cmdid = WMI_10_2_ADDBA_SET_RESP_CMDID, .send_singleamsdu_cmdid = WMI_10_2_SEND_SINGLEAMSDU_CMDID, .sta_powersave_mode_cmdid = WMI_10_2_STA_POWERSAVE_MODE_CMDID, .sta_powersave_param_cmdid = WMI_10_2_STA_POWERSAVE_PARAM_CMDID, .sta_mimo_ps_mode_cmdid = WMI_10_2_STA_MIMO_PS_MODE_CMDID, .pdev_dfs_enable_cmdid = WMI_10_2_PDEV_DFS_ENABLE_CMDID, .pdev_dfs_disable_cmdid = WMI_10_2_PDEV_DFS_DISABLE_CMDID, .roam_scan_mode = WMI_10_2_ROAM_SCAN_MODE, .roam_scan_rssi_threshold = WMI_10_2_ROAM_SCAN_RSSI_THRESHOLD, .roam_scan_period = WMI_10_2_ROAM_SCAN_PERIOD, .roam_scan_rssi_change_threshold = WMI_10_2_ROAM_SCAN_RSSI_CHANGE_THRESHOLD, .roam_ap_profile = WMI_10_2_ROAM_AP_PROFILE, .ofl_scan_add_ap_profile = WMI_10_2_OFL_SCAN_ADD_AP_PROFILE, .ofl_scan_remove_ap_profile = WMI_10_2_OFL_SCAN_REMOVE_AP_PROFILE, .ofl_scan_period = WMI_10_2_OFL_SCAN_PERIOD, .p2p_dev_set_device_info = WMI_10_2_P2P_DEV_SET_DEVICE_INFO, .p2p_dev_set_discoverability = WMI_10_2_P2P_DEV_SET_DISCOVERABILITY, .p2p_go_set_beacon_ie = WMI_10_2_P2P_GO_SET_BEACON_IE, .p2p_go_set_probe_resp_ie = WMI_10_2_P2P_GO_SET_PROBE_RESP_IE, .p2p_set_vendor_ie_data_cmdid = WMI_CMD_UNSUPPORTED, .ap_ps_peer_param_cmdid = WMI_10_2_AP_PS_PEER_PARAM_CMDID, .ap_ps_peer_uapsd_coex_cmdid = WMI_CMD_UNSUPPORTED, .peer_rate_retry_sched_cmdid = WMI_10_2_PEER_RATE_RETRY_SCHED_CMDID, .wlan_profile_trigger_cmdid = WMI_10_2_WLAN_PROFILE_TRIGGER_CMDID, .wlan_profile_set_hist_intvl_cmdid = WMI_10_2_WLAN_PROFILE_SET_HIST_INTVL_CMDID, .wlan_profile_get_profile_data_cmdid = WMI_10_2_WLAN_PROFILE_GET_PROFILE_DATA_CMDID, .wlan_profile_enable_profile_id_cmdid = WMI_10_2_WLAN_PROFILE_ENABLE_PROFILE_ID_CMDID, .wlan_profile_list_profile_id_cmdid = WMI_10_2_WLAN_PROFILE_LIST_PROFILE_ID_CMDID, .pdev_suspend_cmdid = WMI_10_2_PDEV_SUSPEND_CMDID, .pdev_resume_cmdid = WMI_10_2_PDEV_RESUME_CMDID, .add_bcn_filter_cmdid = WMI_10_2_ADD_BCN_FILTER_CMDID, .rmv_bcn_filter_cmdid = WMI_10_2_RMV_BCN_FILTER_CMDID, .wow_add_wake_pattern_cmdid = WMI_10_2_WOW_ADD_WAKE_PATTERN_CMDID, .wow_del_wake_pattern_cmdid = WMI_10_2_WOW_DEL_WAKE_PATTERN_CMDID, .wow_enable_disable_wake_event_cmdid = WMI_10_2_WOW_ENABLE_DISABLE_WAKE_EVENT_CMDID, .wow_enable_cmdid = WMI_10_2_WOW_ENABLE_CMDID, .wow_hostwakeup_from_sleep_cmdid = WMI_10_2_WOW_HOSTWAKEUP_FROM_SLEEP_CMDID, .rtt_measreq_cmdid = WMI_10_2_RTT_MEASREQ_CMDID, .rtt_tsf_cmdid = WMI_10_2_RTT_TSF_CMDID, .vdev_spectral_scan_configure_cmdid = WMI_10_2_VDEV_SPECTRAL_SCAN_CONFIGURE_CMDID, .vdev_spectral_scan_enable_cmdid = WMI_10_2_VDEV_SPECTRAL_SCAN_ENABLE_CMDID, .request_stats_cmdid = WMI_10_2_REQUEST_STATS_CMDID, .set_arp_ns_offload_cmdid = WMI_CMD_UNSUPPORTED, .network_list_offload_config_cmdid = WMI_CMD_UNSUPPORTED, .gtk_offload_cmdid = WMI_CMD_UNSUPPORTED, .csa_offload_enable_cmdid = WMI_CMD_UNSUPPORTED, .csa_offload_chanswitch_cmdid = WMI_CMD_UNSUPPORTED, .chatter_set_mode_cmdid = WMI_CMD_UNSUPPORTED, .peer_tid_addba_cmdid = WMI_CMD_UNSUPPORTED, .peer_tid_delba_cmdid = WMI_CMD_UNSUPPORTED, .sta_dtim_ps_method_cmdid = WMI_CMD_UNSUPPORTED, .sta_uapsd_auto_trig_cmdid = WMI_CMD_UNSUPPORTED, .sta_keepalive_cmd = WMI_CMD_UNSUPPORTED, .echo_cmdid = WMI_10_2_ECHO_CMDID, .pdev_utf_cmdid = WMI_10_2_PDEV_UTF_CMDID, .dbglog_cfg_cmdid = WMI_10_2_DBGLOG_CFG_CMDID, .pdev_qvit_cmdid = WMI_10_2_PDEV_QVIT_CMDID, .pdev_ftm_intg_cmdid = WMI_CMD_UNSUPPORTED, .vdev_set_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .vdev_get_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .force_fw_hang_cmdid = WMI_CMD_UNSUPPORTED, .gpio_config_cmdid = WMI_10_2_GPIO_CONFIG_CMDID, .gpio_output_cmdid = WMI_10_2_GPIO_OUTPUT_CMDID, .pdev_get_temperature_cmdid = WMI_CMD_UNSUPPORTED, .pdev_enable_adaptive_cca_cmdid = WMI_CMD_UNSUPPORTED, .scan_update_request_cmdid = WMI_CMD_UNSUPPORTED, .vdev_standby_response_cmdid = WMI_CMD_UNSUPPORTED, .vdev_resume_response_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_add_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_evict_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_restore_peer_cmdid = WMI_CMD_UNSUPPORTED, .wlan_peer_caching_print_all_peers_info_cmdid = WMI_CMD_UNSUPPORTED, .peer_update_wds_entry_cmdid = WMI_CMD_UNSUPPORTED, .peer_add_proxy_sta_entry_cmdid = WMI_CMD_UNSUPPORTED, .rtt_keepalive_cmdid = WMI_CMD_UNSUPPORTED, .oem_req_cmdid = WMI_CMD_UNSUPPORTED, .nan_cmdid = WMI_CMD_UNSUPPORTED, .vdev_ratemask_cmdid = WMI_CMD_UNSUPPORTED, .qboost_cfg_cmdid = WMI_CMD_UNSUPPORTED, .pdev_smart_ant_enable_cmdid = WMI_CMD_UNSUPPORTED, .pdev_smart_ant_set_rx_antenna_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_tx_antenna_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_train_info_cmdid = WMI_CMD_UNSUPPORTED, .peer_smart_ant_set_node_config_ops_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_antenna_switch_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_ctl_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_set_mimogain_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_ratepwr_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_ratepwr_chainmsk_table_cmdid = WMI_CMD_UNSUPPORTED, .pdev_fips_cmdid = WMI_CMD_UNSUPPORTED, .tt_set_conf_cmdid = WMI_CMD_UNSUPPORTED, .fwtest_cmdid = WMI_CMD_UNSUPPORTED, .vdev_atf_request_cmdid = WMI_CMD_UNSUPPORTED, .peer_atf_request_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ani_cck_config_cmdid = WMI_CMD_UNSUPPORTED, .pdev_get_ani_ofdm_config_cmdid = WMI_CMD_UNSUPPORTED, .pdev_reserve_ast_entry_cmdid = WMI_CMD_UNSUPPORTED, }; static struct wmi_pdev_param_map wmi_10_4_pdev_param_map = { .tx_chain_mask = WMI_10_4_PDEV_PARAM_TX_CHAIN_MASK, .rx_chain_mask = WMI_10_4_PDEV_PARAM_RX_CHAIN_MASK, .txpower_limit2g = WMI_10_4_PDEV_PARAM_TXPOWER_LIMIT2G, .txpower_limit5g = WMI_10_4_PDEV_PARAM_TXPOWER_LIMIT5G, .txpower_scale = WMI_10_4_PDEV_PARAM_TXPOWER_SCALE, .beacon_gen_mode = WMI_10_4_PDEV_PARAM_BEACON_GEN_MODE, .beacon_tx_mode = WMI_10_4_PDEV_PARAM_BEACON_TX_MODE, .resmgr_offchan_mode = WMI_10_4_PDEV_PARAM_RESMGR_OFFCHAN_MODE, .protection_mode = WMI_10_4_PDEV_PARAM_PROTECTION_MODE, .dynamic_bw = WMI_10_4_PDEV_PARAM_DYNAMIC_BW, .non_agg_sw_retry_th = WMI_10_4_PDEV_PARAM_NON_AGG_SW_RETRY_TH, .agg_sw_retry_th = WMI_10_4_PDEV_PARAM_AGG_SW_RETRY_TH, .sta_kickout_th = WMI_10_4_PDEV_PARAM_STA_KICKOUT_TH, .ac_aggrsize_scaling = WMI_10_4_PDEV_PARAM_AC_AGGRSIZE_SCALING, .ltr_enable = WMI_10_4_PDEV_PARAM_LTR_ENABLE, .ltr_ac_latency_be = WMI_10_4_PDEV_PARAM_LTR_AC_LATENCY_BE, .ltr_ac_latency_bk = WMI_10_4_PDEV_PARAM_LTR_AC_LATENCY_BK, .ltr_ac_latency_vi = WMI_10_4_PDEV_PARAM_LTR_AC_LATENCY_VI, .ltr_ac_latency_vo = WMI_10_4_PDEV_PARAM_LTR_AC_LATENCY_VO, .ltr_ac_latency_timeout = WMI_10_4_PDEV_PARAM_LTR_AC_LATENCY_TIMEOUT, .ltr_sleep_override = WMI_10_4_PDEV_PARAM_LTR_SLEEP_OVERRIDE, .ltr_rx_override = WMI_10_4_PDEV_PARAM_LTR_RX_OVERRIDE, .ltr_tx_activity_timeout = WMI_10_4_PDEV_PARAM_LTR_TX_ACTIVITY_TIMEOUT, .l1ss_enable = WMI_10_4_PDEV_PARAM_L1SS_ENABLE, .dsleep_enable = WMI_10_4_PDEV_PARAM_DSLEEP_ENABLE, .pcielp_txbuf_flush = WMI_10_4_PDEV_PARAM_PCIELP_TXBUF_FLUSH, .pcielp_txbuf_watermark = WMI_10_4_PDEV_PARAM_PCIELP_TXBUF_WATERMARK, .pcielp_txbuf_tmo_en = WMI_10_4_PDEV_PARAM_PCIELP_TXBUF_TMO_EN, .pcielp_txbuf_tmo_value = WMI_10_4_PDEV_PARAM_PCIELP_TXBUF_TMO_VALUE, .pdev_stats_update_period = WMI_10_4_PDEV_PARAM_PDEV_STATS_UPDATE_PERIOD, .vdev_stats_update_period = WMI_10_4_PDEV_PARAM_VDEV_STATS_UPDATE_PERIOD, .peer_stats_update_period = WMI_10_4_PDEV_PARAM_PEER_STATS_UPDATE_PERIOD, .bcnflt_stats_update_period = WMI_10_4_PDEV_PARAM_BCNFLT_STATS_UPDATE_PERIOD, .pmf_qos = WMI_10_4_PDEV_PARAM_PMF_QOS, .arp_ac_override = WMI_10_4_PDEV_PARAM_ARP_AC_OVERRIDE, .dcs = WMI_10_4_PDEV_PARAM_DCS, .ani_enable = WMI_10_4_PDEV_PARAM_ANI_ENABLE, .ani_poll_period = WMI_10_4_PDEV_PARAM_ANI_POLL_PERIOD, .ani_listen_period = WMI_10_4_PDEV_PARAM_ANI_LISTEN_PERIOD, .ani_ofdm_level = WMI_10_4_PDEV_PARAM_ANI_OFDM_LEVEL, .ani_cck_level = WMI_10_4_PDEV_PARAM_ANI_CCK_LEVEL, .dyntxchain = WMI_10_4_PDEV_PARAM_DYNTXCHAIN, .proxy_sta = WMI_10_4_PDEV_PARAM_PROXY_STA, .idle_ps_config = WMI_10_4_PDEV_PARAM_IDLE_PS_CONFIG, .power_gating_sleep = WMI_10_4_PDEV_PARAM_POWER_GATING_SLEEP, .fast_channel_reset = WMI_10_4_PDEV_PARAM_FAST_CHANNEL_RESET, .burst_dur = WMI_10_4_PDEV_PARAM_BURST_DUR, .burst_enable = WMI_10_4_PDEV_PARAM_BURST_ENABLE, .cal_period = WMI_10_4_PDEV_PARAM_CAL_PERIOD, .aggr_burst = WMI_10_4_PDEV_PARAM_AGGR_BURST, .rx_decap_mode = WMI_10_4_PDEV_PARAM_RX_DECAP_MODE, .smart_antenna_default_antenna = WMI_10_4_PDEV_PARAM_SMART_ANTENNA_DEFAULT_ANTENNA, .igmpmld_override = WMI_10_4_PDEV_PARAM_IGMPMLD_OVERRIDE, .igmpmld_tid = WMI_10_4_PDEV_PARAM_IGMPMLD_TID, .antenna_gain = WMI_10_4_PDEV_PARAM_ANTENNA_GAIN, .rx_filter = WMI_10_4_PDEV_PARAM_RX_FILTER, .set_mcast_to_ucast_tid = WMI_10_4_PDEV_SET_MCAST_TO_UCAST_TID, .proxy_sta_mode = WMI_10_4_PDEV_PARAM_PROXY_STA_MODE, .set_mcast2ucast_mode = WMI_10_4_PDEV_PARAM_SET_MCAST2UCAST_MODE, .set_mcast2ucast_buffer = WMI_10_4_PDEV_PARAM_SET_MCAST2UCAST_BUFFER, .remove_mcast2ucast_buffer = WMI_10_4_PDEV_PARAM_REMOVE_MCAST2UCAST_BUFFER, .peer_sta_ps_statechg_enable = WMI_10_4_PDEV_PEER_STA_PS_STATECHG_ENABLE, .igmpmld_ac_override = WMI_10_4_PDEV_PARAM_IGMPMLD_AC_OVERRIDE, .block_interbss = WMI_10_4_PDEV_PARAM_BLOCK_INTERBSS, .set_disable_reset_cmdid = WMI_10_4_PDEV_PARAM_SET_DISABLE_RESET_CMDID, .set_msdu_ttl_cmdid = WMI_10_4_PDEV_PARAM_SET_MSDU_TTL_CMDID, .set_ppdu_duration_cmdid = WMI_10_4_PDEV_PARAM_SET_PPDU_DURATION_CMDID, .txbf_sound_period_cmdid = WMI_10_4_PDEV_PARAM_TXBF_SOUND_PERIOD_CMDID, .set_promisc_mode_cmdid = WMI_10_4_PDEV_PARAM_SET_PROMISC_MODE_CMDID, .set_burst_mode_cmdid = WMI_10_4_PDEV_PARAM_SET_BURST_MODE_CMDID, .en_stats = WMI_10_4_PDEV_PARAM_EN_STATS, .mu_group_policy = WMI_10_4_PDEV_PARAM_MU_GROUP_POLICY, .noise_detection = WMI_10_4_PDEV_PARAM_NOISE_DETECTION, .noise_threshold = WMI_10_4_PDEV_PARAM_NOISE_THRESHOLD, .dpd_enable = WMI_10_4_PDEV_PARAM_DPD_ENABLE, .set_mcast_bcast_echo = WMI_10_4_PDEV_PARAM_SET_MCAST_BCAST_ECHO, .atf_strict_sch = WMI_10_4_PDEV_PARAM_ATF_STRICT_SCH, .atf_sched_duration = WMI_10_4_PDEV_PARAM_ATF_SCHED_DURATION, .ant_plzn = WMI_10_4_PDEV_PARAM_ANT_PLZN, .mgmt_retry_limit = WMI_10_4_PDEV_PARAM_MGMT_RETRY_LIMIT, .sensitivity_level = WMI_10_4_PDEV_PARAM_SENSITIVITY_LEVEL, .signed_txpower_2g = WMI_10_4_PDEV_PARAM_SIGNED_TXPOWER_2G, .signed_txpower_5g = WMI_10_4_PDEV_PARAM_SIGNED_TXPOWER_5G, .enable_per_tid_amsdu = WMI_10_4_PDEV_PARAM_ENABLE_PER_TID_AMSDU, .enable_per_tid_ampdu = WMI_10_4_PDEV_PARAM_ENABLE_PER_TID_AMPDU, .cca_threshold = WMI_10_4_PDEV_PARAM_CCA_THRESHOLD, .rts_fixed_rate = WMI_10_4_PDEV_PARAM_RTS_FIXED_RATE, .pdev_reset = WMI_10_4_PDEV_PARAM_PDEV_RESET, .wapi_mbssid_offset = WMI_10_4_PDEV_PARAM_WAPI_MBSSID_OFFSET, .arp_srcaddr = WMI_10_4_PDEV_PARAM_ARP_SRCADDR, .arp_dstaddr = WMI_10_4_PDEV_PARAM_ARP_DSTADDR, .enable_btcoex = WMI_10_4_PDEV_PARAM_ENABLE_BTCOEX, }; static const struct wmi_peer_flags_map wmi_peer_flags_map = { .auth = WMI_PEER_AUTH, .qos = WMI_PEER_QOS, .need_ptk_4_way = WMI_PEER_NEED_PTK_4_WAY, .need_gtk_2_way = WMI_PEER_NEED_GTK_2_WAY, .apsd = WMI_PEER_APSD, .ht = WMI_PEER_HT, .bw40 = WMI_PEER_40MHZ, .stbc = WMI_PEER_STBC, .ldbc = WMI_PEER_LDPC, .dyn_mimops = WMI_PEER_DYN_MIMOPS, .static_mimops = WMI_PEER_STATIC_MIMOPS, .spatial_mux = WMI_PEER_SPATIAL_MUX, .vht = WMI_PEER_VHT, .bw80 = WMI_PEER_80MHZ, .vht_2g = WMI_PEER_VHT_2G, .pmf = WMI_PEER_PMF, .bw160 = WMI_PEER_160MHZ, }; static const struct wmi_peer_flags_map wmi_10x_peer_flags_map = { .auth = WMI_10X_PEER_AUTH, .qos = WMI_10X_PEER_QOS, .need_ptk_4_way = WMI_10X_PEER_NEED_PTK_4_WAY, .need_gtk_2_way = WMI_10X_PEER_NEED_GTK_2_WAY, .apsd = WMI_10X_PEER_APSD, .ht = WMI_10X_PEER_HT, .bw40 = WMI_10X_PEER_40MHZ, .stbc = WMI_10X_PEER_STBC, .ldbc = WMI_10X_PEER_LDPC, .dyn_mimops = WMI_10X_PEER_DYN_MIMOPS, .static_mimops = WMI_10X_PEER_STATIC_MIMOPS, .spatial_mux = WMI_10X_PEER_SPATIAL_MUX, .vht = WMI_10X_PEER_VHT, .bw80 = WMI_10X_PEER_80MHZ, .bw160 = WMI_10X_PEER_160MHZ, }; static const struct wmi_peer_flags_map wmi_10_2_peer_flags_map = { .auth = WMI_10_2_PEER_AUTH, .qos = WMI_10_2_PEER_QOS, .need_ptk_4_way = WMI_10_2_PEER_NEED_PTK_4_WAY, .need_gtk_2_way = WMI_10_2_PEER_NEED_GTK_2_WAY, .apsd = WMI_10_2_PEER_APSD, .ht = WMI_10_2_PEER_HT, .bw40 = WMI_10_2_PEER_40MHZ, .stbc = WMI_10_2_PEER_STBC, .ldbc = WMI_10_2_PEER_LDPC, .dyn_mimops = WMI_10_2_PEER_DYN_MIMOPS, .static_mimops = WMI_10_2_PEER_STATIC_MIMOPS, .spatial_mux = WMI_10_2_PEER_SPATIAL_MUX, .vht = WMI_10_2_PEER_VHT, .bw80 = WMI_10_2_PEER_80MHZ, .vht_2g = WMI_10_2_PEER_VHT_2G, .pmf = WMI_10_2_PEER_PMF, .bw160 = WMI_10_2_PEER_160MHZ, }; void ath10k_wmi_put_wmi_channel(struct wmi_channel *ch, const struct wmi_channel_arg *arg) { u32 flags = 0; memset(ch, 0, sizeof(*ch)); if (arg->passive) flags |= WMI_CHAN_FLAG_PASSIVE; if (arg->allow_ibss) flags |= WMI_CHAN_FLAG_ADHOC_ALLOWED; if (arg->allow_ht) flags |= WMI_CHAN_FLAG_ALLOW_HT; if (arg->allow_vht) flags |= WMI_CHAN_FLAG_ALLOW_VHT; if (arg->ht40plus) flags |= WMI_CHAN_FLAG_HT40_PLUS; if (arg->chan_radar) flags |= WMI_CHAN_FLAG_DFS; ch->mhz = __cpu_to_le32(arg->freq); ch->band_center_freq1 = __cpu_to_le32(arg->band_center_freq1); if (arg->mode == MODE_11AC_VHT80_80) ch->band_center_freq2 = __cpu_to_le32(arg->band_center_freq2); else ch->band_center_freq2 = 0; ch->min_power = arg->min_power; ch->max_power = arg->max_power; ch->reg_power = arg->max_reg_power; ch->antenna_max = arg->max_antenna_gain; ch->max_tx_power = arg->max_power; /* mode & flags share storage */ ch->mode = arg->mode; ch->flags |= __cpu_to_le32(flags); } int ath10k_wmi_wait_for_service_ready(struct ath10k *ar) { unsigned long time_left; time_left = wait_for_completion_timeout(&ar->wmi.service_ready, WMI_SERVICE_READY_TIMEOUT_HZ); if (!time_left) return -ETIMEDOUT; return 0; } int ath10k_wmi_wait_for_unified_ready(struct ath10k *ar) { unsigned long time_left; time_left = wait_for_completion_timeout(&ar->wmi.unified_ready, WMI_UNIFIED_READY_TIMEOUT_HZ); if (!time_left) return -ETIMEDOUT; return 0; } struct sk_buff *ath10k_wmi_alloc_skb(struct ath10k *ar, u32 len) { struct sk_buff *skb; u32 round_len = roundup(len, 4); skb = ath10k_htc_alloc_skb(ar, WMI_SKB_HEADROOM + round_len); if (!skb) return NULL; skb_reserve(skb, WMI_SKB_HEADROOM); if (!IS_ALIGNED((unsigned long)skb->data, 4)) ath10k_warn(ar, "Unaligned WMI skb\n"); skb_put(skb, round_len); memset(skb->data, 0, round_len); return skb; } static void ath10k_wmi_htc_tx_complete(struct ath10k *ar, struct sk_buff *skb) { dev_kfree_skb(skb); } int ath10k_wmi_cmd_send_nowait(struct ath10k *ar, struct sk_buff *skb, u32 cmd_id) { struct ath10k_skb_cb *skb_cb = ATH10K_SKB_CB(skb); struct wmi_cmd_hdr *cmd_hdr; int ret; u32 cmd = 0; if (skb_push(skb, sizeof(struct wmi_cmd_hdr)) == NULL) return -ENOMEM; cmd |= SM(cmd_id, WMI_CMD_HDR_CMD_ID); cmd_hdr = (struct wmi_cmd_hdr *)skb->data; cmd_hdr->cmd_id = __cpu_to_le32(cmd); memset(skb_cb, 0, sizeof(*skb_cb)); ret = ath10k_htc_send(&ar->htc, ar->wmi.eid, skb); trace_ath10k_wmi_cmd(ar, cmd_id, skb->data, skb->len, ret); if (ret) goto err_pull; return 0; err_pull: skb_pull(skb, sizeof(struct wmi_cmd_hdr)); return ret; } static void ath10k_wmi_tx_beacon_nowait(struct ath10k_vif *arvif) { struct ath10k *ar = arvif->ar; struct ath10k_skb_cb *cb; struct sk_buff *bcn; bool dtim_zero; bool deliver_cab; int ret; spin_lock_bh(&ar->data_lock); bcn = arvif->beacon; if (!bcn) goto unlock; cb = ATH10K_SKB_CB(bcn); switch (arvif->beacon_state) { case ATH10K_BEACON_SENDING: case ATH10K_BEACON_SENT: break; case ATH10K_BEACON_SCHEDULED: arvif->beacon_state = ATH10K_BEACON_SENDING; spin_unlock_bh(&ar->data_lock); dtim_zero = !!(cb->flags & ATH10K_SKB_F_DTIM_ZERO); deliver_cab = !!(cb->flags & ATH10K_SKB_F_DELIVER_CAB); ret = ath10k_wmi_beacon_send_ref_nowait(arvif->ar, arvif->vdev_id, bcn->data, bcn->len, cb->paddr, dtim_zero, deliver_cab); spin_lock_bh(&ar->data_lock); if (ret == 0) arvif->beacon_state = ATH10K_BEACON_SENT; else arvif->beacon_state = ATH10K_BEACON_SCHEDULED; } unlock: spin_unlock_bh(&ar->data_lock); } static void ath10k_wmi_tx_beacons_iter(void *data, u8 *mac, struct ieee80211_vif *vif) { struct ath10k_vif *arvif = (void *)vif->drv_priv; ath10k_wmi_tx_beacon_nowait(arvif); } static void ath10k_wmi_tx_beacons_nowait(struct ath10k *ar) { ieee80211_iterate_active_interfaces_atomic(ar->hw, IEEE80211_IFACE_ITER_NORMAL, ath10k_wmi_tx_beacons_iter, NULL); } static void ath10k_wmi_op_ep_tx_credits(struct ath10k *ar) { /* try to send pending beacons first. they take priority */ ath10k_wmi_tx_beacons_nowait(ar); wake_up(&ar->wmi.tx_credits_wq); } int ath10k_wmi_cmd_send(struct ath10k *ar, struct sk_buff *skb, u32 cmd_id) { int ret = -EOPNOTSUPP; might_sleep(); if (cmd_id == WMI_CMD_UNSUPPORTED) { ath10k_warn(ar, "wmi command %d is not supported by firmware\n", cmd_id); return ret; } wait_event_timeout(ar->wmi.tx_credits_wq, ({ /* try to send pending beacons first. they take priority */ ath10k_wmi_tx_beacons_nowait(ar); ret = ath10k_wmi_cmd_send_nowait(ar, skb, cmd_id); if (ret && test_bit(ATH10K_FLAG_CRASH_FLUSH, &ar->dev_flags)) ret = -ESHUTDOWN; (ret != -EAGAIN); }), 3 * HZ); if (ret) dev_kfree_skb_any(skb); return ret; } static struct sk_buff * ath10k_wmi_op_gen_mgmt_tx(struct ath10k *ar, struct sk_buff *msdu) { struct ath10k_skb_cb *cb = ATH10K_SKB_CB(msdu); struct ath10k_vif *arvif; struct wmi_mgmt_tx_cmd *cmd; struct ieee80211_hdr *hdr; struct sk_buff *skb; int len; u32 vdev_id; u32 buf_len = msdu->len; u16 fc; hdr = (struct ieee80211_hdr *)msdu->data; fc = le16_to_cpu(hdr->frame_control); if (cb->vif) { arvif = (void *)cb->vif->drv_priv; vdev_id = arvif->vdev_id; } else { vdev_id = 0; } if (WARN_ON_ONCE(!ieee80211_is_mgmt(hdr->frame_control))) return ERR_PTR(-EINVAL); len = sizeof(cmd->hdr) + msdu->len; if ((ieee80211_is_action(hdr->frame_control) || ieee80211_is_deauth(hdr->frame_control) || ieee80211_is_disassoc(hdr->frame_control)) && ieee80211_has_protected(hdr->frame_control)) { len += IEEE80211_CCMP_MIC_LEN; buf_len += IEEE80211_CCMP_MIC_LEN; } len = round_up(len, 4); skb = ath10k_wmi_alloc_skb(ar, len); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_mgmt_tx_cmd *)skb->data; cmd->hdr.vdev_id = __cpu_to_le32(vdev_id); cmd->hdr.tx_rate = 0; cmd->hdr.tx_power = 0; cmd->hdr.buf_len = __cpu_to_le32(buf_len); ether_addr_copy(cmd->hdr.peer_macaddr.addr, ieee80211_get_DA(hdr)); memcpy(cmd->buf, msdu->data, msdu->len); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi mgmt tx skb %pK len %d ftype %02x stype %02x\n", msdu, skb->len, fc & IEEE80211_FCTL_FTYPE, fc & IEEE80211_FCTL_STYPE); trace_ath10k_tx_hdr(ar, skb->data, skb->len); trace_ath10k_tx_payload(ar, skb->data, skb->len); return skb; } static void ath10k_wmi_event_scan_started(struct ath10k *ar) { lockdep_assert_held(&ar->data_lock); switch (ar->scan.state) { case ATH10K_SCAN_IDLE: case ATH10K_SCAN_RUNNING: case ATH10K_SCAN_ABORTING: ath10k_warn(ar, "received scan started event in an invalid scan state: %s (%d)\n", ath10k_scan_state_str(ar->scan.state), ar->scan.state); break; case ATH10K_SCAN_STARTING: ar->scan.state = ATH10K_SCAN_RUNNING; if (ar->scan.is_roc) ieee80211_ready_on_channel(ar->hw); complete(&ar->scan.started); break; } } static void ath10k_wmi_event_scan_start_failed(struct ath10k *ar) { lockdep_assert_held(&ar->data_lock); switch (ar->scan.state) { case ATH10K_SCAN_IDLE: case ATH10K_SCAN_RUNNING: case ATH10K_SCAN_ABORTING: ath10k_warn(ar, "received scan start failed event in an invalid scan state: %s (%d)\n", ath10k_scan_state_str(ar->scan.state), ar->scan.state); break; case ATH10K_SCAN_STARTING: complete(&ar->scan.started); __ath10k_scan_finish(ar); break; } } static void ath10k_wmi_event_scan_completed(struct ath10k *ar) { lockdep_assert_held(&ar->data_lock); switch (ar->scan.state) { case ATH10K_SCAN_IDLE: case ATH10K_SCAN_STARTING: /* One suspected reason scan can be completed while starting is * if firmware fails to deliver all scan events to the host, * e.g. when transport pipe is full. This has been observed * with spectral scan phyerr events starving wmi transport * pipe. In such case the "scan completed" event should be (and * is) ignored by the host as it may be just firmware's scan * state machine recovering. */ ath10k_warn(ar, "received scan completed event in an invalid scan state: %s (%d)\n", ath10k_scan_state_str(ar->scan.state), ar->scan.state); break; case ATH10K_SCAN_RUNNING: case ATH10K_SCAN_ABORTING: __ath10k_scan_finish(ar); break; } } static void ath10k_wmi_event_scan_bss_chan(struct ath10k *ar) { lockdep_assert_held(&ar->data_lock); switch (ar->scan.state) { case ATH10K_SCAN_IDLE: case ATH10K_SCAN_STARTING: ath10k_warn(ar, "received scan bss chan event in an invalid scan state: %s (%d)\n", ath10k_scan_state_str(ar->scan.state), ar->scan.state); break; case ATH10K_SCAN_RUNNING: case ATH10K_SCAN_ABORTING: ar->scan_channel = NULL; break; } } static void ath10k_wmi_event_scan_foreign_chan(struct ath10k *ar, u32 freq) { lockdep_assert_held(&ar->data_lock); switch (ar->scan.state) { case ATH10K_SCAN_IDLE: case ATH10K_SCAN_STARTING: ath10k_warn(ar, "received scan foreign chan event in an invalid scan state: %s (%d)\n", ath10k_scan_state_str(ar->scan.state), ar->scan.state); break; case ATH10K_SCAN_RUNNING: case ATH10K_SCAN_ABORTING: ar->scan_channel = ieee80211_get_channel(ar->hw->wiphy, freq); if (ar->scan.is_roc && ar->scan.roc_freq == freq) complete(&ar->scan.on_channel); break; } } static const char * ath10k_wmi_event_scan_type_str(enum wmi_scan_event_type type, enum wmi_scan_completion_reason reason) { switch (type) { case WMI_SCAN_EVENT_STARTED: return "started"; case WMI_SCAN_EVENT_COMPLETED: switch (reason) { case WMI_SCAN_REASON_COMPLETED: return "completed"; case WMI_SCAN_REASON_CANCELLED: return "completed [cancelled]"; case WMI_SCAN_REASON_PREEMPTED: return "completed [preempted]"; case WMI_SCAN_REASON_TIMEDOUT: return "completed [timedout]"; case WMI_SCAN_REASON_INTERNAL_FAILURE: return "completed [internal err]"; case WMI_SCAN_REASON_MAX: break; } return "completed [unknown]"; case WMI_SCAN_EVENT_BSS_CHANNEL: return "bss channel"; case WMI_SCAN_EVENT_FOREIGN_CHANNEL: return "foreign channel"; case WMI_SCAN_EVENT_DEQUEUED: return "dequeued"; case WMI_SCAN_EVENT_PREEMPTED: return "preempted"; case WMI_SCAN_EVENT_START_FAILED: return "start failed"; case WMI_SCAN_EVENT_RESTARTED: return "restarted"; case WMI_SCAN_EVENT_FOREIGN_CHANNEL_EXIT: return "foreign channel exit"; default: return "unknown"; } } static int ath10k_wmi_op_pull_scan_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_scan_ev_arg *arg) { struct wmi_scan_event *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->event_type = ev->event_type; arg->reason = ev->reason; arg->channel_freq = ev->channel_freq; arg->scan_req_id = ev->scan_req_id; arg->scan_id = ev->scan_id; arg->vdev_id = ev->vdev_id; return 0; } int ath10k_wmi_event_scan(struct ath10k *ar, struct sk_buff *skb) { struct wmi_scan_ev_arg arg = {}; enum wmi_scan_event_type event_type; enum wmi_scan_completion_reason reason; u32 freq; u32 req_id; u32 scan_id; u32 vdev_id; int ret; ret = ath10k_wmi_pull_scan(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse scan event: %d\n", ret); return ret; } event_type = __le32_to_cpu(arg.event_type); reason = __le32_to_cpu(arg.reason); freq = __le32_to_cpu(arg.channel_freq); req_id = __le32_to_cpu(arg.scan_req_id); scan_id = __le32_to_cpu(arg.scan_id); vdev_id = __le32_to_cpu(arg.vdev_id); spin_lock_bh(&ar->data_lock); ath10k_dbg(ar, ATH10K_DBG_WMI, "scan event %s type %d reason %d freq %d req_id %d scan_id %d vdev_id %d state %s (%d)\n", ath10k_wmi_event_scan_type_str(event_type, reason), event_type, reason, freq, req_id, scan_id, vdev_id, ath10k_scan_state_str(ar->scan.state), ar->scan.state); switch (event_type) { case WMI_SCAN_EVENT_STARTED: ath10k_wmi_event_scan_started(ar); break; case WMI_SCAN_EVENT_COMPLETED: ath10k_wmi_event_scan_completed(ar); break; case WMI_SCAN_EVENT_BSS_CHANNEL: ath10k_wmi_event_scan_bss_chan(ar); break; case WMI_SCAN_EVENT_FOREIGN_CHANNEL: ath10k_wmi_event_scan_foreign_chan(ar, freq); break; case WMI_SCAN_EVENT_START_FAILED: ath10k_warn(ar, "received scan start failure event\n"); ath10k_wmi_event_scan_start_failed(ar); break; case WMI_SCAN_EVENT_DEQUEUED: case WMI_SCAN_EVENT_PREEMPTED: case WMI_SCAN_EVENT_RESTARTED: case WMI_SCAN_EVENT_FOREIGN_CHANNEL_EXIT: default: break; } spin_unlock_bh(&ar->data_lock); return 0; } /* If keys are configured, HW decrypts all frames * with protected bit set. Mark such frames as decrypted. */ static void ath10k_wmi_handle_wep_reauth(struct ath10k *ar, struct sk_buff *skb, struct ieee80211_rx_status *status) { struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data; unsigned int hdrlen; bool peer_key; u8 *addr, keyidx; if (!ieee80211_is_auth(hdr->frame_control) || !ieee80211_has_protected(hdr->frame_control)) return; hdrlen = ieee80211_hdrlen(hdr->frame_control); if (skb->len < (hdrlen + IEEE80211_WEP_IV_LEN)) return; keyidx = skb->data[hdrlen + (IEEE80211_WEP_IV_LEN - 1)] >> WEP_KEYID_SHIFT; addr = ieee80211_get_SA(hdr); spin_lock_bh(&ar->data_lock); peer_key = ath10k_mac_is_peer_wep_key_set(ar, addr, keyidx); spin_unlock_bh(&ar->data_lock); if (peer_key) { ath10k_dbg(ar, ATH10K_DBG_MAC, "mac wep key present for peer %pM\n", addr); status->flag |= RX_FLAG_DECRYPTED; } } static int ath10k_wmi_op_pull_mgmt_rx_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_mgmt_rx_ev_arg *arg) { struct wmi_mgmt_rx_event_v1 *ev_v1; struct wmi_mgmt_rx_event_v2 *ev_v2; struct wmi_mgmt_rx_hdr_v1 *ev_hdr; struct wmi_mgmt_rx_ext_info *ext_info; size_t pull_len; u32 msdu_len; u32 len; if (test_bit(ATH10K_FW_FEATURE_EXT_WMI_MGMT_RX, ar->running_fw->fw_file.fw_features)) { ev_v2 = (struct wmi_mgmt_rx_event_v2 *)skb->data; ev_hdr = &ev_v2->hdr.v1; pull_len = sizeof(*ev_v2); } else { ev_v1 = (struct wmi_mgmt_rx_event_v1 *)skb->data; ev_hdr = &ev_v1->hdr; pull_len = sizeof(*ev_v1); } if (skb->len < pull_len) return -EPROTO; skb_pull(skb, pull_len); arg->channel = ev_hdr->channel; arg->buf_len = ev_hdr->buf_len; arg->status = ev_hdr->status; arg->snr = ev_hdr->snr; arg->phy_mode = ev_hdr->phy_mode; arg->rate = ev_hdr->rate; msdu_len = __le32_to_cpu(arg->buf_len); if (skb->len < msdu_len) return -EPROTO; if (le32_to_cpu(arg->status) & WMI_RX_STATUS_EXT_INFO) { len = ALIGN(le32_to_cpu(arg->buf_len), 4); ext_info = (struct wmi_mgmt_rx_ext_info *)(skb->data + len); memcpy(&arg->ext_info, ext_info, sizeof(struct wmi_mgmt_rx_ext_info)); } /* the WMI buffer might've ended up being padded to 4 bytes due to HTC * trailer with credit update. Trim the excess garbage. */ skb_trim(skb, msdu_len); return 0; } static int ath10k_wmi_10_4_op_pull_mgmt_rx_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_mgmt_rx_ev_arg *arg) { struct wmi_10_4_mgmt_rx_event *ev; struct wmi_10_4_mgmt_rx_hdr *ev_hdr; size_t pull_len; u32 msdu_len; struct wmi_mgmt_rx_ext_info *ext_info; u32 len; ev = (struct wmi_10_4_mgmt_rx_event *)skb->data; ev_hdr = &ev->hdr; pull_len = sizeof(*ev); if (skb->len < pull_len) return -EPROTO; skb_pull(skb, pull_len); arg->channel = ev_hdr->channel; arg->buf_len = ev_hdr->buf_len; arg->status = ev_hdr->status; arg->snr = ev_hdr->snr; arg->phy_mode = ev_hdr->phy_mode; arg->rate = ev_hdr->rate; msdu_len = __le32_to_cpu(arg->buf_len); if (skb->len < msdu_len) return -EPROTO; if (le32_to_cpu(arg->status) & WMI_RX_STATUS_EXT_INFO) { len = ALIGN(le32_to_cpu(arg->buf_len), 4); ext_info = (struct wmi_mgmt_rx_ext_info *)(skb->data + len); memcpy(&arg->ext_info, ext_info, sizeof(struct wmi_mgmt_rx_ext_info)); } /* Make sure bytes added for padding are removed. */ skb_trim(skb, msdu_len); return 0; } static bool ath10k_wmi_rx_is_decrypted(struct ath10k *ar, struct ieee80211_hdr *hdr) { if (!ieee80211_has_protected(hdr->frame_control)) return false; /* FW delivers WEP Shared Auth frame with Protected Bit set and * encrypted payload. However in case of PMF it delivers decrypted * frames with Protected Bit set. */ if (ieee80211_is_auth(hdr->frame_control)) return false; /* qca99x0 based FW delivers broadcast or multicast management frames * (ex: group privacy action frames in mesh) as encrypted payload. */ if (is_multicast_ether_addr(ieee80211_get_DA(hdr)) && ar->hw_params.sw_decrypt_mcast_mgmt) return false; return true; } int ath10k_wmi_event_mgmt_rx(struct ath10k *ar, struct sk_buff *skb) { struct wmi_mgmt_rx_ev_arg arg = {}; struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb); struct ieee80211_hdr *hdr; struct ieee80211_supported_band *sband; u32 rx_status; u32 channel; u32 phy_mode; u32 snr; u32 rate; u32 buf_len; u16 fc; int ret; ret = ath10k_wmi_pull_mgmt_rx(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse mgmt rx event: %d\n", ret); dev_kfree_skb(skb); return ret; } channel = __le32_to_cpu(arg.channel); buf_len = __le32_to_cpu(arg.buf_len); rx_status = __le32_to_cpu(arg.status); snr = __le32_to_cpu(arg.snr); phy_mode = __le32_to_cpu(arg.phy_mode); rate = __le32_to_cpu(arg.rate); memset(status, 0, sizeof(*status)); ath10k_dbg(ar, ATH10K_DBG_MGMT, "event mgmt rx status %08x\n", rx_status); if ((test_bit(ATH10K_CAC_RUNNING, &ar->dev_flags)) || (rx_status & (WMI_RX_STATUS_ERR_DECRYPT | WMI_RX_STATUS_ERR_KEY_CACHE_MISS | WMI_RX_STATUS_ERR_CRC))) { dev_kfree_skb(skb); return 0; } if (rx_status & WMI_RX_STATUS_ERR_MIC) status->flag |= RX_FLAG_MMIC_ERROR; if (rx_status & WMI_RX_STATUS_EXT_INFO) { status->mactime = __le64_to_cpu(arg.ext_info.rx_mac_timestamp); status->flag |= RX_FLAG_MACTIME_END; } /* Hardware can Rx CCK rates on 5GHz. In that case phy_mode is set to * MODE_11B. This means phy_mode is not a reliable source for the band * of mgmt rx. */ if (channel >= 1 && channel <= 14) { status->band = NL80211_BAND_2GHZ; } else if (channel >= 36 && channel <= 169) { status->band = NL80211_BAND_5GHZ; } else { /* Shouldn't happen unless list of advertised channels to * mac80211 has been changed. */ WARN_ON_ONCE(1); dev_kfree_skb(skb); return 0; } if (phy_mode == MODE_11B && status->band == NL80211_BAND_5GHZ) ath10k_dbg(ar, ATH10K_DBG_MGMT, "wmi mgmt rx 11b (CCK) on 5GHz\n"); sband = &ar->mac.sbands[status->band]; status->freq = ieee80211_channel_to_frequency(channel, status->band); status->signal = snr + ATH10K_DEFAULT_NOISE_FLOOR; status->rate_idx = ath10k_mac_bitrate_to_idx(sband, rate / 100); hdr = (struct ieee80211_hdr *)skb->data; fc = le16_to_cpu(hdr->frame_control); /* Firmware is guaranteed to report all essential management frames via * WMI while it can deliver some extra via HTT. Since there can be * duplicates split the reporting wrt monitor/sniffing. */ status->flag |= RX_FLAG_SKIP_MONITOR; ath10k_wmi_handle_wep_reauth(ar, skb, status); if (ath10k_wmi_rx_is_decrypted(ar, hdr)) { status->flag |= RX_FLAG_DECRYPTED; if (!ieee80211_is_action(hdr->frame_control) && !ieee80211_is_deauth(hdr->frame_control) && !ieee80211_is_disassoc(hdr->frame_control)) { status->flag |= RX_FLAG_IV_STRIPPED | RX_FLAG_MMIC_STRIPPED; hdr->frame_control = __cpu_to_le16(fc & ~IEEE80211_FCTL_PROTECTED); } } if (ieee80211_is_beacon(hdr->frame_control)) ath10k_mac_handle_beacon(ar, skb); ath10k_dbg(ar, ATH10K_DBG_MGMT, "event mgmt rx skb %pK len %d ftype %02x stype %02x\n", skb, skb->len, fc & IEEE80211_FCTL_FTYPE, fc & IEEE80211_FCTL_STYPE); ath10k_dbg(ar, ATH10K_DBG_MGMT, "event mgmt rx freq %d band %d snr %d, rate_idx %d\n", status->freq, status->band, status->signal, status->rate_idx); ieee80211_rx(ar->hw, skb); return 0; } static int freq_to_idx(struct ath10k *ar, int freq) { struct ieee80211_supported_band *sband; int band, ch, idx = 0; for (band = NL80211_BAND_2GHZ; band < NUM_NL80211_BANDS; band++) { sband = ar->hw->wiphy->bands[band]; if (!sband) continue; for (ch = 0; ch < sband->n_channels; ch++, idx++) if (sband->channels[ch].center_freq == freq) goto exit; } exit: return idx; } static int ath10k_wmi_op_pull_ch_info_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_ch_info_ev_arg *arg) { struct wmi_chan_info_event *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->err_code = ev->err_code; arg->freq = ev->freq; arg->cmd_flags = ev->cmd_flags; arg->noise_floor = ev->noise_floor; arg->rx_clear_count = ev->rx_clear_count; arg->cycle_count = ev->cycle_count; return 0; } static int ath10k_wmi_10_4_op_pull_ch_info_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_ch_info_ev_arg *arg) { struct wmi_10_4_chan_info_event *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->err_code = ev->err_code; arg->freq = ev->freq; arg->cmd_flags = ev->cmd_flags; arg->noise_floor = ev->noise_floor; arg->rx_clear_count = ev->rx_clear_count; arg->cycle_count = ev->cycle_count; arg->chan_tx_pwr_range = ev->chan_tx_pwr_range; arg->chan_tx_pwr_tp = ev->chan_tx_pwr_tp; arg->rx_frame_count = ev->rx_frame_count; return 0; } void ath10k_wmi_event_chan_info(struct ath10k *ar, struct sk_buff *skb) { struct wmi_ch_info_ev_arg arg = {}; struct survey_info *survey; u32 err_code, freq, cmd_flags, noise_floor, rx_clear_count, cycle_count; int idx, ret; ret = ath10k_wmi_pull_ch_info(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse chan info event: %d\n", ret); return; } err_code = __le32_to_cpu(arg.err_code); freq = __le32_to_cpu(arg.freq); cmd_flags = __le32_to_cpu(arg.cmd_flags); noise_floor = __le32_to_cpu(arg.noise_floor); rx_clear_count = __le32_to_cpu(arg.rx_clear_count); cycle_count = __le32_to_cpu(arg.cycle_count); ath10k_dbg(ar, ATH10K_DBG_WMI, "chan info err_code %d freq %d cmd_flags %d noise_floor %d rx_clear_count %d cycle_count %d\n", err_code, freq, cmd_flags, noise_floor, rx_clear_count, cycle_count); spin_lock_bh(&ar->data_lock); switch (ar->scan.state) { case ATH10K_SCAN_IDLE: case ATH10K_SCAN_STARTING: ath10k_warn(ar, "received chan info event without a scan request, ignoring\n"); goto exit; case ATH10K_SCAN_RUNNING: case ATH10K_SCAN_ABORTING: break; } idx = freq_to_idx(ar, freq); if (idx >= ARRAY_SIZE(ar->survey)) { ath10k_warn(ar, "chan info: invalid frequency %d (idx %d out of bounds)\n", freq, idx); goto exit; } if (cmd_flags & WMI_CHAN_INFO_FLAG_COMPLETE) { if (ar->ch_info_can_report_survey) { survey = &ar->survey[idx]; survey->noise = noise_floor; survey->filled = SURVEY_INFO_NOISE_DBM; ath10k_hw_fill_survey_time(ar, survey, cycle_count, rx_clear_count, ar->survey_last_cycle_count, ar->survey_last_rx_clear_count); } ar->ch_info_can_report_survey = false; } else { ar->ch_info_can_report_survey = true; } if (!(cmd_flags & WMI_CHAN_INFO_FLAG_PRE_COMPLETE)) { ar->survey_last_rx_clear_count = rx_clear_count; ar->survey_last_cycle_count = cycle_count; } exit: spin_unlock_bh(&ar->data_lock); } void ath10k_wmi_event_echo(struct ath10k *ar, struct sk_buff *skb) { struct wmi_echo_ev_arg arg = {}; int ret; ret = ath10k_wmi_pull_echo_ev(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse echo: %d\n", ret); return; } ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi event echo value 0x%08x\n", le32_to_cpu(arg.value)); if (le32_to_cpu(arg.value) == ATH10K_WMI_BARRIER_ECHO_ID) complete(&ar->wmi.barrier); } int ath10k_wmi_event_debug_mesg(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi event debug mesg len %d\n", skb->len); trace_ath10k_wmi_dbglog(ar, skb->data, skb->len); return 0; } void ath10k_wmi_pull_pdev_stats_base(const struct wmi_pdev_stats_base *src, struct ath10k_fw_stats_pdev *dst) { dst->ch_noise_floor = __le32_to_cpu(src->chan_nf); dst->tx_frame_count = __le32_to_cpu(src->tx_frame_count); dst->rx_frame_count = __le32_to_cpu(src->rx_frame_count); dst->rx_clear_count = __le32_to_cpu(src->rx_clear_count); dst->cycle_count = __le32_to_cpu(src->cycle_count); dst->phy_err_count = __le32_to_cpu(src->phy_err_count); dst->chan_tx_power = __le32_to_cpu(src->chan_tx_pwr); } void ath10k_wmi_pull_pdev_stats_tx(const struct wmi_pdev_stats_tx *src, struct ath10k_fw_stats_pdev *dst) { dst->comp_queued = __le32_to_cpu(src->comp_queued); dst->comp_delivered = __le32_to_cpu(src->comp_delivered); dst->msdu_enqued = __le32_to_cpu(src->msdu_enqued); dst->mpdu_enqued = __le32_to_cpu(src->mpdu_enqued); dst->wmm_drop = __le32_to_cpu(src->wmm_drop); dst->local_enqued = __le32_to_cpu(src->local_enqued); dst->local_freed = __le32_to_cpu(src->local_freed); dst->hw_queued = __le32_to_cpu(src->hw_queued); dst->hw_reaped = __le32_to_cpu(src->hw_reaped); dst->underrun = __le32_to_cpu(src->underrun); dst->tx_abort = __le32_to_cpu(src->tx_abort); dst->mpdus_requed = __le32_to_cpu(src->mpdus_requed); dst->tx_ko = __le32_to_cpu(src->tx_ko); dst->data_rc = __le32_to_cpu(src->data_rc); dst->self_triggers = __le32_to_cpu(src->self_triggers); dst->sw_retry_failure = __le32_to_cpu(src->sw_retry_failure); dst->illgl_rate_phy_err = __le32_to_cpu(src->illgl_rate_phy_err); dst->pdev_cont_xretry = __le32_to_cpu(src->pdev_cont_xretry); dst->pdev_tx_timeout = __le32_to_cpu(src->pdev_tx_timeout); dst->pdev_resets = __le32_to_cpu(src->pdev_resets); dst->phy_underrun = __le32_to_cpu(src->phy_underrun); dst->txop_ovf = __le32_to_cpu(src->txop_ovf); } static void ath10k_wmi_10_4_pull_pdev_stats_tx(const struct wmi_10_4_pdev_stats_tx *src, struct ath10k_fw_stats_pdev *dst) { dst->comp_queued = __le32_to_cpu(src->comp_queued); dst->comp_delivered = __le32_to_cpu(src->comp_delivered); dst->msdu_enqued = __le32_to_cpu(src->msdu_enqued); dst->mpdu_enqued = __le32_to_cpu(src->mpdu_enqued); dst->wmm_drop = __le32_to_cpu(src->wmm_drop); dst->local_enqued = __le32_to_cpu(src->local_enqued); dst->local_freed = __le32_to_cpu(src->local_freed); dst->hw_queued = __le32_to_cpu(src->hw_queued); dst->hw_reaped = __le32_to_cpu(src->hw_reaped); dst->underrun = __le32_to_cpu(src->underrun); dst->tx_abort = __le32_to_cpu(src->tx_abort); dst->mpdus_requed = __le32_to_cpu(src->mpdus_requed); dst->tx_ko = __le32_to_cpu(src->tx_ko); dst->data_rc = __le32_to_cpu(src->data_rc); dst->self_triggers = __le32_to_cpu(src->self_triggers); dst->sw_retry_failure = __le32_to_cpu(src->sw_retry_failure); dst->illgl_rate_phy_err = __le32_to_cpu(src->illgl_rate_phy_err); dst->pdev_cont_xretry = __le32_to_cpu(src->pdev_cont_xretry); dst->pdev_tx_timeout = __le32_to_cpu(src->pdev_tx_timeout); dst->pdev_resets = __le32_to_cpu(src->pdev_resets); dst->phy_underrun = __le32_to_cpu(src->phy_underrun); dst->txop_ovf = __le32_to_cpu(src->txop_ovf); dst->hw_paused = __le32_to_cpu(src->hw_paused); dst->seq_posted = __le32_to_cpu(src->seq_posted); dst->seq_failed_queueing = __le32_to_cpu(src->seq_failed_queueing); dst->seq_completed = __le32_to_cpu(src->seq_completed); dst->seq_restarted = __le32_to_cpu(src->seq_restarted); dst->mu_seq_posted = __le32_to_cpu(src->mu_seq_posted); dst->mpdus_sw_flush = __le32_to_cpu(src->mpdus_sw_flush); dst->mpdus_hw_filter = __le32_to_cpu(src->mpdus_hw_filter); dst->mpdus_truncated = __le32_to_cpu(src->mpdus_truncated); dst->mpdus_ack_failed = __le32_to_cpu(src->mpdus_ack_failed); dst->mpdus_hw_filter = __le32_to_cpu(src->mpdus_hw_filter); dst->mpdus_expired = __le32_to_cpu(src->mpdus_expired); } void ath10k_wmi_pull_pdev_stats_rx(const struct wmi_pdev_stats_rx *src, struct ath10k_fw_stats_pdev *dst) { dst->mid_ppdu_route_change = __le32_to_cpu(src->mid_ppdu_route_change); dst->status_rcvd = __le32_to_cpu(src->status_rcvd); dst->r0_frags = __le32_to_cpu(src->r0_frags); dst->r1_frags = __le32_to_cpu(src->r1_frags); dst->r2_frags = __le32_to_cpu(src->r2_frags); dst->r3_frags = __le32_to_cpu(src->r3_frags); dst->htt_msdus = __le32_to_cpu(src->htt_msdus); dst->htt_mpdus = __le32_to_cpu(src->htt_mpdus); dst->loc_msdus = __le32_to_cpu(src->loc_msdus); dst->loc_mpdus = __le32_to_cpu(src->loc_mpdus); dst->oversize_amsdu = __le32_to_cpu(src->oversize_amsdu); dst->phy_errs = __le32_to_cpu(src->phy_errs); dst->phy_err_drop = __le32_to_cpu(src->phy_err_drop); dst->mpdu_errs = __le32_to_cpu(src->mpdu_errs); } void ath10k_wmi_pull_pdev_stats_extra(const struct wmi_pdev_stats_extra *src, struct ath10k_fw_stats_pdev *dst) { dst->ack_rx_bad = __le32_to_cpu(src->ack_rx_bad); dst->rts_bad = __le32_to_cpu(src->rts_bad); dst->rts_good = __le32_to_cpu(src->rts_good); dst->fcs_bad = __le32_to_cpu(src->fcs_bad); dst->no_beacons = __le32_to_cpu(src->no_beacons); dst->mib_int_count = __le32_to_cpu(src->mib_int_count); } void ath10k_wmi_pull_peer_stats(const struct wmi_peer_stats *src, struct ath10k_fw_stats_peer *dst) { ether_addr_copy(dst->peer_macaddr, src->peer_macaddr.addr); dst->peer_rssi = __le32_to_cpu(src->peer_rssi); dst->peer_tx_rate = __le32_to_cpu(src->peer_tx_rate); } static void ath10k_wmi_10_4_pull_peer_stats(const struct wmi_10_4_peer_stats *src, struct ath10k_fw_stats_peer *dst) { ether_addr_copy(dst->peer_macaddr, src->peer_macaddr.addr); dst->peer_rssi = __le32_to_cpu(src->peer_rssi); dst->peer_tx_rate = __le32_to_cpu(src->peer_tx_rate); dst->peer_rx_rate = __le32_to_cpu(src->peer_rx_rate); } static int ath10k_wmi_main_op_pull_fw_stats(struct ath10k *ar, struct sk_buff *skb, struct ath10k_fw_stats *stats) { const struct wmi_stats_event *ev = (void *)skb->data; u32 num_pdev_stats, num_vdev_stats, num_peer_stats; int i; if (!skb_pull(skb, sizeof(*ev))) return -EPROTO; num_pdev_stats = __le32_to_cpu(ev->num_pdev_stats); num_vdev_stats = __le32_to_cpu(ev->num_vdev_stats); num_peer_stats = __le32_to_cpu(ev->num_peer_stats); for (i = 0; i < num_pdev_stats; i++) { const struct wmi_pdev_stats *src; struct ath10k_fw_stats_pdev *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_pdev_stats_base(&src->base, dst); ath10k_wmi_pull_pdev_stats_tx(&src->tx, dst); ath10k_wmi_pull_pdev_stats_rx(&src->rx, dst); list_add_tail(&dst->list, &stats->pdevs); } /* fw doesn't implement vdev stats */ for (i = 0; i < num_peer_stats; i++) { const struct wmi_peer_stats *src; struct ath10k_fw_stats_peer *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_peer_stats(src, dst); list_add_tail(&dst->list, &stats->peers); } return 0; } static int ath10k_wmi_10x_op_pull_fw_stats(struct ath10k *ar, struct sk_buff *skb, struct ath10k_fw_stats *stats) { const struct wmi_stats_event *ev = (void *)skb->data; u32 num_pdev_stats, num_vdev_stats, num_peer_stats; int i; if (!skb_pull(skb, sizeof(*ev))) return -EPROTO; num_pdev_stats = __le32_to_cpu(ev->num_pdev_stats); num_vdev_stats = __le32_to_cpu(ev->num_vdev_stats); num_peer_stats = __le32_to_cpu(ev->num_peer_stats); for (i = 0; i < num_pdev_stats; i++) { const struct wmi_10x_pdev_stats *src; struct ath10k_fw_stats_pdev *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_pdev_stats_base(&src->base, dst); ath10k_wmi_pull_pdev_stats_tx(&src->tx, dst); ath10k_wmi_pull_pdev_stats_rx(&src->rx, dst); ath10k_wmi_pull_pdev_stats_extra(&src->extra, dst); list_add_tail(&dst->list, &stats->pdevs); } /* fw doesn't implement vdev stats */ for (i = 0; i < num_peer_stats; i++) { const struct wmi_10x_peer_stats *src; struct ath10k_fw_stats_peer *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_peer_stats(&src->old, dst); dst->peer_rx_rate = __le32_to_cpu(src->peer_rx_rate); list_add_tail(&dst->list, &stats->peers); } return 0; } static int ath10k_wmi_10_2_op_pull_fw_stats(struct ath10k *ar, struct sk_buff *skb, struct ath10k_fw_stats *stats) { const struct wmi_10_2_stats_event *ev = (void *)skb->data; u32 num_pdev_stats; u32 num_pdev_ext_stats; u32 num_vdev_stats; u32 num_peer_stats; int i; if (!skb_pull(skb, sizeof(*ev))) return -EPROTO; num_pdev_stats = __le32_to_cpu(ev->num_pdev_stats); num_pdev_ext_stats = __le32_to_cpu(ev->num_pdev_ext_stats); num_vdev_stats = __le32_to_cpu(ev->num_vdev_stats); num_peer_stats = __le32_to_cpu(ev->num_peer_stats); for (i = 0; i < num_pdev_stats; i++) { const struct wmi_10_2_pdev_stats *src; struct ath10k_fw_stats_pdev *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_pdev_stats_base(&src->base, dst); ath10k_wmi_pull_pdev_stats_tx(&src->tx, dst); ath10k_wmi_pull_pdev_stats_rx(&src->rx, dst); ath10k_wmi_pull_pdev_stats_extra(&src->extra, dst); /* FIXME: expose 10.2 specific values */ list_add_tail(&dst->list, &stats->pdevs); } for (i = 0; i < num_pdev_ext_stats; i++) { const struct wmi_10_2_pdev_ext_stats *src; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; /* FIXME: expose values to userspace * * Note: Even though this loop seems to do nothing it is * required to parse following sub-structures properly. */ } /* fw doesn't implement vdev stats */ for (i = 0; i < num_peer_stats; i++) { const struct wmi_10_2_peer_stats *src; struct ath10k_fw_stats_peer *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_peer_stats(&src->old, dst); dst->peer_rx_rate = __le32_to_cpu(src->peer_rx_rate); /* FIXME: expose 10.2 specific values */ list_add_tail(&dst->list, &stats->peers); } return 0; } static int ath10k_wmi_10_2_4_op_pull_fw_stats(struct ath10k *ar, struct sk_buff *skb, struct ath10k_fw_stats *stats) { const struct wmi_10_2_stats_event *ev = (void *)skb->data; u32 num_pdev_stats; u32 num_pdev_ext_stats; u32 num_vdev_stats; u32 num_peer_stats; int i; if (!skb_pull(skb, sizeof(*ev))) return -EPROTO; num_pdev_stats = __le32_to_cpu(ev->num_pdev_stats); num_pdev_ext_stats = __le32_to_cpu(ev->num_pdev_ext_stats); num_vdev_stats = __le32_to_cpu(ev->num_vdev_stats); num_peer_stats = __le32_to_cpu(ev->num_peer_stats); for (i = 0; i < num_pdev_stats; i++) { const struct wmi_10_2_pdev_stats *src; struct ath10k_fw_stats_pdev *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_pdev_stats_base(&src->base, dst); ath10k_wmi_pull_pdev_stats_tx(&src->tx, dst); ath10k_wmi_pull_pdev_stats_rx(&src->rx, dst); ath10k_wmi_pull_pdev_stats_extra(&src->extra, dst); /* FIXME: expose 10.2 specific values */ list_add_tail(&dst->list, &stats->pdevs); } for (i = 0; i < num_pdev_ext_stats; i++) { const struct wmi_10_2_pdev_ext_stats *src; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; /* FIXME: expose values to userspace * * Note: Even though this loop seems to do nothing it is * required to parse following sub-structures properly. */ } /* fw doesn't implement vdev stats */ for (i = 0; i < num_peer_stats; i++) { const struct wmi_10_2_4_ext_peer_stats *src; struct ath10k_fw_stats_peer *dst; int stats_len; if (test_bit(WMI_SERVICE_PEER_STATS, ar->wmi.svc_map)) stats_len = sizeof(struct wmi_10_2_4_ext_peer_stats); else stats_len = sizeof(struct wmi_10_2_4_peer_stats); src = (void *)skb->data; if (!skb_pull(skb, stats_len)) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_peer_stats(&src->common.old, dst); dst->peer_rx_rate = __le32_to_cpu(src->common.peer_rx_rate); if (ath10k_peer_stats_enabled(ar)) dst->rx_duration = __le32_to_cpu(src->rx_duration); /* FIXME: expose 10.2 specific values */ list_add_tail(&dst->list, &stats->peers); } return 0; } static int ath10k_wmi_10_4_op_pull_fw_stats(struct ath10k *ar, struct sk_buff *skb, struct ath10k_fw_stats *stats) { const struct wmi_10_2_stats_event *ev = (void *)skb->data; u32 num_pdev_stats; u32 num_pdev_ext_stats; u32 num_vdev_stats; u32 num_peer_stats; u32 num_bcnflt_stats; u32 stats_id; int i; if (!skb_pull(skb, sizeof(*ev))) return -EPROTO; num_pdev_stats = __le32_to_cpu(ev->num_pdev_stats); num_pdev_ext_stats = __le32_to_cpu(ev->num_pdev_ext_stats); num_vdev_stats = __le32_to_cpu(ev->num_vdev_stats); num_peer_stats = __le32_to_cpu(ev->num_peer_stats); num_bcnflt_stats = __le32_to_cpu(ev->num_bcnflt_stats); stats_id = __le32_to_cpu(ev->stats_id); for (i = 0; i < num_pdev_stats; i++) { const struct wmi_10_4_pdev_stats *src; struct ath10k_fw_stats_pdev *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_pull_pdev_stats_base(&src->base, dst); ath10k_wmi_10_4_pull_pdev_stats_tx(&src->tx, dst); ath10k_wmi_pull_pdev_stats_rx(&src->rx, dst); dst->rx_ovfl_errs = __le32_to_cpu(src->rx_ovfl_errs); ath10k_wmi_pull_pdev_stats_extra(&src->extra, dst); list_add_tail(&dst->list, &stats->pdevs); } for (i = 0; i < num_pdev_ext_stats; i++) { const struct wmi_10_2_pdev_ext_stats *src; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; /* FIXME: expose values to userspace * * Note: Even though this loop seems to do nothing it is * required to parse following sub-structures properly. */ } /* fw doesn't implement vdev stats */ for (i = 0; i < num_peer_stats; i++) { const struct wmi_10_4_peer_stats *src; struct ath10k_fw_stats_peer *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ath10k_wmi_10_4_pull_peer_stats(src, dst); list_add_tail(&dst->list, &stats->peers); } for (i = 0; i < num_bcnflt_stats; i++) { const struct wmi_10_4_bss_bcn_filter_stats *src; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; /* FIXME: expose values to userspace * * Note: Even though this loop seems to do nothing it is * required to parse following sub-structures properly. */ } if ((stats_id & WMI_10_4_STAT_PEER_EXTD) == 0) return 0; stats->extended = true; for (i = 0; i < num_peer_stats; i++) { const struct wmi_10_4_peer_extd_stats *src; struct ath10k_fw_extd_stats_peer *dst; src = (void *)skb->data; if (!skb_pull(skb, sizeof(*src))) return -EPROTO; dst = kzalloc(sizeof(*dst), GFP_ATOMIC); if (!dst) continue; ether_addr_copy(dst->peer_macaddr, src->peer_macaddr.addr); dst->rx_duration = __le32_to_cpu(src->rx_duration); list_add_tail(&dst->list, &stats->peers_extd); } return 0; } void ath10k_wmi_event_update_stats(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_UPDATE_STATS_EVENTID\n"); ath10k_debug_fw_stats_process(ar, skb); } static int ath10k_wmi_op_pull_vdev_start_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_vdev_start_ev_arg *arg) { struct wmi_vdev_start_response_event *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->vdev_id = ev->vdev_id; arg->req_id = ev->req_id; arg->resp_type = ev->resp_type; arg->status = ev->status; return 0; } void ath10k_wmi_event_vdev_start_resp(struct ath10k *ar, struct sk_buff *skb) { struct wmi_vdev_start_ev_arg arg = {}; int ret; ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_VDEV_START_RESP_EVENTID\n"); ret = ath10k_wmi_pull_vdev_start(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse vdev start event: %d\n", ret); return; } if (WARN_ON(__le32_to_cpu(arg.status))) return; complete(&ar->vdev_setup_done); } void ath10k_wmi_event_vdev_stopped(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_VDEV_STOPPED_EVENTID\n"); complete(&ar->vdev_setup_done); } static int ath10k_wmi_op_pull_peer_kick_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_peer_kick_ev_arg *arg) { struct wmi_peer_sta_kickout_event *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->mac_addr = ev->peer_macaddr.addr; return 0; } void ath10k_wmi_event_peer_sta_kickout(struct ath10k *ar, struct sk_buff *skb) { struct wmi_peer_kick_ev_arg arg = {}; struct ieee80211_sta *sta; int ret; ret = ath10k_wmi_pull_peer_kick(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse peer kickout event: %d\n", ret); return; } ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi event peer sta kickout %pM\n", arg.mac_addr); rcu_read_lock(); sta = ieee80211_find_sta_by_ifaddr(ar->hw, arg.mac_addr, NULL); if (!sta) { ath10k_warn(ar, "Spurious quick kickout for STA %pM\n", arg.mac_addr); goto exit; } ieee80211_report_low_ack(sta, 10); exit: rcu_read_unlock(); } /* * FIXME * * We don't report to mac80211 sleep state of connected * stations. Due to this mac80211 can't fill in TIM IE * correctly. * * I know of no way of getting nullfunc frames that contain * sleep transition from connected stations - these do not * seem to be sent from the target to the host. There also * doesn't seem to be a dedicated event for that. So the * only way left to do this would be to read tim_bitmap * during SWBA. * * We could probably try using tim_bitmap from SWBA to tell * mac80211 which stations are asleep and which are not. The * problem here is calling mac80211 functions so many times * could take too long and make us miss the time to submit * the beacon to the target. * * So as a workaround we try to extend the TIM IE if there * is unicast buffered for stations with aid > 7 and fill it * in ourselves. */ static void ath10k_wmi_update_tim(struct ath10k *ar, struct ath10k_vif *arvif, struct sk_buff *bcn, const struct wmi_tim_info_arg *tim_info) { struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)bcn->data; struct ieee80211_tim_ie *tim; u8 *ies, *ie; u8 ie_len, pvm_len; __le32 t; u32 v, tim_len; /* When FW reports 0 in tim_len, ensure atleast first byte * in tim_bitmap is considered for pvm calculation. */ tim_len = tim_info->tim_len ? __le32_to_cpu(tim_info->tim_len) : 1; /* if next SWBA has no tim_changed the tim_bitmap is garbage. * we must copy the bitmap upon change and reuse it later */ if (__le32_to_cpu(tim_info->tim_changed)) { int i; if (sizeof(arvif->u.ap.tim_bitmap) < tim_len) { ath10k_warn(ar, "SWBA TIM field is too big (%u), truncated it to %zu", tim_len, sizeof(arvif->u.ap.tim_bitmap)); tim_len = sizeof(arvif->u.ap.tim_bitmap); } for (i = 0; i < tim_len; i++) { t = tim_info->tim_bitmap[i / 4]; v = __le32_to_cpu(t); arvif->u.ap.tim_bitmap[i] = (v >> ((i % 4) * 8)) & 0xFF; } /* FW reports either length 0 or length based on max supported * station. so we calculate this on our own */ arvif->u.ap.tim_len = 0; for (i = 0; i < tim_len; i++) if (arvif->u.ap.tim_bitmap[i]) arvif->u.ap.tim_len = i; arvif->u.ap.tim_len++; } ies = bcn->data; ies += ieee80211_hdrlen(hdr->frame_control); ies += 12; /* fixed parameters */ ie = (u8 *)cfg80211_find_ie(WLAN_EID_TIM, ies, (u8 *)skb_tail_pointer(bcn) - ies); if (!ie) { if (arvif->vdev_type != WMI_VDEV_TYPE_IBSS) ath10k_warn(ar, "no tim ie found;\n"); return; } tim = (void *)ie + 2; ie_len = ie[1]; pvm_len = ie_len - 3; /* exclude dtim count, dtim period, bmap ctl */ if (pvm_len < arvif->u.ap.tim_len) { int expand_size = tim_len - pvm_len; int move_size = skb_tail_pointer(bcn) - (ie + 2 + ie_len); void *next_ie = ie + 2 + ie_len; if (skb_put(bcn, expand_size)) { memmove(next_ie + expand_size, next_ie, move_size); ie[1] += expand_size; ie_len += expand_size; pvm_len += expand_size; } else { ath10k_warn(ar, "tim expansion failed\n"); } } if (pvm_len > tim_len) { ath10k_warn(ar, "tim pvm length is too great (%d)\n", pvm_len); return; } tim->bitmap_ctrl = !!__le32_to_cpu(tim_info->tim_mcast); memcpy(tim->virtual_map, arvif->u.ap.tim_bitmap, pvm_len); if (tim->dtim_count == 0) { ATH10K_SKB_CB(bcn)->flags |= ATH10K_SKB_F_DTIM_ZERO; if (__le32_to_cpu(tim_info->tim_mcast) == 1) ATH10K_SKB_CB(bcn)->flags |= ATH10K_SKB_F_DELIVER_CAB; } ath10k_dbg(ar, ATH10K_DBG_MGMT, "dtim %d/%d mcast %d pvmlen %d\n", tim->dtim_count, tim->dtim_period, tim->bitmap_ctrl, pvm_len); } static void ath10k_wmi_update_noa(struct ath10k *ar, struct ath10k_vif *arvif, struct sk_buff *bcn, const struct wmi_p2p_noa_info *noa) { if (!arvif->vif->p2p) return; ath10k_dbg(ar, ATH10K_DBG_MGMT, "noa changed: %d\n", noa->changed); if (noa->changed & WMI_P2P_NOA_CHANGED_BIT) ath10k_p2p_noa_update(arvif, noa); if (arvif->u.ap.noa_data) if (!pskb_expand_head(bcn, 0, arvif->u.ap.noa_len, GFP_ATOMIC)) memcpy(skb_put(bcn, arvif->u.ap.noa_len), arvif->u.ap.noa_data, arvif->u.ap.noa_len); } static int ath10k_wmi_op_pull_swba_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_swba_ev_arg *arg) { struct wmi_host_swba_event *ev = (void *)skb->data; u32 map; size_t i; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->vdev_map = ev->vdev_map; for (i = 0, map = __le32_to_cpu(ev->vdev_map); map; map >>= 1) { if (!(map & BIT(0))) continue; /* If this happens there were some changes in firmware and * ath10k should update the max size of tim_info array. */ if (WARN_ON_ONCE(i == ARRAY_SIZE(arg->tim_info))) break; if (__le32_to_cpu(ev->bcn_info[i].tim_info.tim_len) > sizeof(ev->bcn_info[i].tim_info.tim_bitmap)) { ath10k_warn(ar, "refusing to parse invalid swba structure\n"); return -EPROTO; } arg->tim_info[i].tim_len = ev->bcn_info[i].tim_info.tim_len; arg->tim_info[i].tim_mcast = ev->bcn_info[i].tim_info.tim_mcast; arg->tim_info[i].tim_bitmap = ev->bcn_info[i].tim_info.tim_bitmap; arg->tim_info[i].tim_changed = ev->bcn_info[i].tim_info.tim_changed; arg->tim_info[i].tim_num_ps_pending = ev->bcn_info[i].tim_info.tim_num_ps_pending; arg->noa_info[i] = &ev->bcn_info[i].p2p_noa_info; i++; } return 0; } static int ath10k_wmi_10_2_4_op_pull_swba_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_swba_ev_arg *arg) { struct wmi_10_2_4_host_swba_event *ev = (void *)skb->data; u32 map; size_t i; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->vdev_map = ev->vdev_map; for (i = 0, map = __le32_to_cpu(ev->vdev_map); map; map >>= 1) { if (!(map & BIT(0))) continue; /* If this happens there were some changes in firmware and * ath10k should update the max size of tim_info array. */ if (WARN_ON_ONCE(i == ARRAY_SIZE(arg->tim_info))) break; if (__le32_to_cpu(ev->bcn_info[i].tim_info.tim_len) > sizeof(ev->bcn_info[i].tim_info.tim_bitmap)) { ath10k_warn(ar, "refusing to parse invalid swba structure\n"); return -EPROTO; } arg->tim_info[i].tim_len = ev->bcn_info[i].tim_info.tim_len; arg->tim_info[i].tim_mcast = ev->bcn_info[i].tim_info.tim_mcast; arg->tim_info[i].tim_bitmap = ev->bcn_info[i].tim_info.tim_bitmap; arg->tim_info[i].tim_changed = ev->bcn_info[i].tim_info.tim_changed; arg->tim_info[i].tim_num_ps_pending = ev->bcn_info[i].tim_info.tim_num_ps_pending; i++; } return 0; } static int ath10k_wmi_10_4_op_pull_swba_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_swba_ev_arg *arg) { struct wmi_10_4_host_swba_event *ev = (void *)skb->data; u32 map, tim_len; size_t i; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->vdev_map = ev->vdev_map; for (i = 0, map = __le32_to_cpu(ev->vdev_map); map; map >>= 1) { if (!(map & BIT(0))) continue; /* If this happens there were some changes in firmware and * ath10k should update the max size of tim_info array. */ if (WARN_ON_ONCE(i == ARRAY_SIZE(arg->tim_info))) break; if (__le32_to_cpu(ev->bcn_info[i].tim_info.tim_len) > sizeof(ev->bcn_info[i].tim_info.tim_bitmap)) { ath10k_warn(ar, "refusing to parse invalid swba structure\n"); return -EPROTO; } tim_len = __le32_to_cpu(ev->bcn_info[i].tim_info.tim_len); if (tim_len) { /* Exclude 4 byte guard length */ tim_len -= 4; arg->tim_info[i].tim_len = __cpu_to_le32(tim_len); } else { arg->tim_info[i].tim_len = 0; } arg->tim_info[i].tim_mcast = ev->bcn_info[i].tim_info.tim_mcast; arg->tim_info[i].tim_bitmap = ev->bcn_info[i].tim_info.tim_bitmap; arg->tim_info[i].tim_changed = ev->bcn_info[i].tim_info.tim_changed; arg->tim_info[i].tim_num_ps_pending = ev->bcn_info[i].tim_info.tim_num_ps_pending; /* 10.4 firmware doesn't have p2p support. notice of absence * info can be ignored for now. */ i++; } return 0; } static enum wmi_txbf_conf ath10k_wmi_10_4_txbf_conf_scheme(struct ath10k *ar) { return WMI_TXBF_CONF_BEFORE_ASSOC; } void ath10k_wmi_event_host_swba(struct ath10k *ar, struct sk_buff *skb) { struct wmi_swba_ev_arg arg = {}; u32 map; int i = -1; const struct wmi_tim_info_arg *tim_info; const struct wmi_p2p_noa_info *noa_info; struct ath10k_vif *arvif; struct sk_buff *bcn; dma_addr_t paddr; int ret, vdev_id = 0; ret = ath10k_wmi_pull_swba(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse swba event: %d\n", ret); return; } map = __le32_to_cpu(arg.vdev_map); ath10k_dbg(ar, ATH10K_DBG_MGMT, "mgmt swba vdev_map 0x%x\n", map); for (; map; map >>= 1, vdev_id++) { if (!(map & 0x1)) continue; i++; if (i >= WMI_MAX_AP_VDEV) { ath10k_warn(ar, "swba has corrupted vdev map\n"); break; } tim_info = &arg.tim_info[i]; noa_info = arg.noa_info[i]; ath10k_dbg(ar, ATH10K_DBG_MGMT, "mgmt event bcn_info %d tim_len %d mcast %d changed %d num_ps_pending %d bitmap 0x%08x%08x%08x%08x\n", i, __le32_to_cpu(tim_info->tim_len), __le32_to_cpu(tim_info->tim_mcast), __le32_to_cpu(tim_info->tim_changed), __le32_to_cpu(tim_info->tim_num_ps_pending), __le32_to_cpu(tim_info->tim_bitmap[3]), __le32_to_cpu(tim_info->tim_bitmap[2]), __le32_to_cpu(tim_info->tim_bitmap[1]), __le32_to_cpu(tim_info->tim_bitmap[0])); /* TODO: Only first 4 word from tim_bitmap is dumped. * Extend debug code to dump full tim_bitmap. */ arvif = ath10k_get_arvif(ar, vdev_id); if (arvif == NULL) { ath10k_warn(ar, "no vif for vdev_id %d found\n", vdev_id); continue; } /* mac80211 would have already asked us to stop beaconing and * bring the vdev down, so continue in that case */ if (!arvif->is_up) continue; /* There are no completions for beacons so wait for next SWBA * before telling mac80211 to decrement CSA counter * * Once CSA counter is completed stop sending beacons until * actual channel switch is done */ if (arvif->vif->csa_active && ieee80211_csa_is_complete(arvif->vif)) { ieee80211_csa_finish(arvif->vif); continue; } bcn = ieee80211_beacon_get(ar->hw, arvif->vif); if (!bcn) { ath10k_warn(ar, "could not get mac80211 beacon\n"); continue; } ath10k_tx_h_seq_no(arvif->vif, bcn); ath10k_wmi_update_tim(ar, arvif, bcn, tim_info); ath10k_wmi_update_noa(ar, arvif, bcn, noa_info); spin_lock_bh(&ar->data_lock); if (arvif->beacon) { switch (arvif->beacon_state) { case ATH10K_BEACON_SENT: break; case ATH10K_BEACON_SCHEDULED: ath10k_warn(ar, "SWBA overrun on vdev %d, skipped old beacon\n", arvif->vdev_id); break; case ATH10K_BEACON_SENDING: ath10k_warn(ar, "SWBA overrun on vdev %d, skipped new beacon\n", arvif->vdev_id); dev_kfree_skb(bcn); goto skip; } ath10k_mac_vif_beacon_free(arvif); } if (!arvif->beacon_buf) { paddr = dma_map_single(arvif->ar->dev, bcn->data, bcn->len, DMA_TO_DEVICE); ret = dma_mapping_error(arvif->ar->dev, paddr); if (ret) { ath10k_warn(ar, "failed to map beacon: %d\n", ret); dev_kfree_skb_any(bcn); goto skip; } ATH10K_SKB_CB(bcn)->paddr = paddr; } else { if (bcn->len > IEEE80211_MAX_FRAME_LEN) { ath10k_warn(ar, "trimming beacon %d -> %d bytes!\n", bcn->len, IEEE80211_MAX_FRAME_LEN); skb_trim(bcn, IEEE80211_MAX_FRAME_LEN); } memcpy(arvif->beacon_buf, bcn->data, bcn->len); ATH10K_SKB_CB(bcn)->paddr = arvif->beacon_paddr; } arvif->beacon = bcn; arvif->beacon_state = ATH10K_BEACON_SCHEDULED; trace_ath10k_tx_hdr(ar, bcn->data, bcn->len); trace_ath10k_tx_payload(ar, bcn->data, bcn->len); skip: spin_unlock_bh(&ar->data_lock); } ath10k_wmi_tx_beacons_nowait(ar); } void ath10k_wmi_event_tbttoffset_update(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_TBTTOFFSET_UPDATE_EVENTID\n"); } static void ath10k_dfs_radar_report(struct ath10k *ar, struct wmi_phyerr_ev_arg *phyerr, const struct phyerr_radar_report *rr, u64 tsf) { u32 reg0, reg1, tsf32l; struct ieee80211_channel *ch; struct pulse_event pe; u64 tsf64; u8 rssi, width; reg0 = __le32_to_cpu(rr->reg0); reg1 = __le32_to_cpu(rr->reg1); ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "wmi phyerr radar report chirp %d max_width %d agc_total_gain %d pulse_delta_diff %d\n", MS(reg0, RADAR_REPORT_REG0_PULSE_IS_CHIRP), MS(reg0, RADAR_REPORT_REG0_PULSE_IS_MAX_WIDTH), MS(reg0, RADAR_REPORT_REG0_AGC_TOTAL_GAIN), MS(reg0, RADAR_REPORT_REG0_PULSE_DELTA_DIFF)); ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "wmi phyerr radar report pulse_delta_pean %d pulse_sidx %d fft_valid %d agc_mb_gain %d subchan_mask %d\n", MS(reg0, RADAR_REPORT_REG0_PULSE_DELTA_PEAK), MS(reg0, RADAR_REPORT_REG0_PULSE_SIDX), MS(reg1, RADAR_REPORT_REG1_PULSE_SRCH_FFT_VALID), MS(reg1, RADAR_REPORT_REG1_PULSE_AGC_MB_GAIN), MS(reg1, RADAR_REPORT_REG1_PULSE_SUBCHAN_MASK)); ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "wmi phyerr radar report pulse_tsf_offset 0x%X pulse_dur: %d\n", MS(reg1, RADAR_REPORT_REG1_PULSE_TSF_OFFSET), MS(reg1, RADAR_REPORT_REG1_PULSE_DUR)); if (!ar->dfs_detector) return; spin_lock_bh(&ar->data_lock); ch = ar->rx_channel; spin_unlock_bh(&ar->data_lock); if (!ch) { ath10k_warn(ar, "failed to derive channel for radar pulse, treating as radar\n"); goto radar_detected; } /* report event to DFS pattern detector */ tsf32l = phyerr->tsf_timestamp; tsf64 = tsf & (~0xFFFFFFFFULL); tsf64 |= tsf32l; width = MS(reg1, RADAR_REPORT_REG1_PULSE_DUR); rssi = phyerr->rssi_combined; /* hardware store this as 8 bit signed value, * set to zero if negative number */ if (rssi & 0x80) rssi = 0; pe.ts = tsf64; pe.freq = ch->center_freq; pe.width = width; pe.rssi = rssi; pe.chirp = (MS(reg0, RADAR_REPORT_REG0_PULSE_IS_CHIRP) != 0); ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "dfs add pulse freq: %d, width: %d, rssi %d, tsf: %llX\n", pe.freq, pe.width, pe.rssi, pe.ts); ATH10K_DFS_STAT_INC(ar, pulses_detected); if (!ar->dfs_detector->add_pulse(ar->dfs_detector, &pe)) { ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "dfs no pulse pattern detected, yet\n"); return; } radar_detected: ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "dfs radar detected\n"); ATH10K_DFS_STAT_INC(ar, radar_detected); /* Control radar events reporting in debugfs file dfs_block_radar_events */ if (ar->dfs_block_radar_events) { ath10k_info(ar, "DFS Radar detected, but ignored as requested\n"); return; } ieee80211_radar_detected(ar->hw); } static int ath10k_dfs_fft_report(struct ath10k *ar, struct wmi_phyerr_ev_arg *phyerr, const struct phyerr_fft_report *fftr, u64 tsf) { u32 reg0, reg1; u8 rssi, peak_mag; reg0 = __le32_to_cpu(fftr->reg0); reg1 = __le32_to_cpu(fftr->reg1); rssi = phyerr->rssi_combined; ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "wmi phyerr fft report total_gain_db %d base_pwr_db %d fft_chn_idx %d peak_sidx %d\n", MS(reg0, SEARCH_FFT_REPORT_REG0_TOTAL_GAIN_DB), MS(reg0, SEARCH_FFT_REPORT_REG0_BASE_PWR_DB), MS(reg0, SEARCH_FFT_REPORT_REG0_FFT_CHN_IDX), MS(reg0, SEARCH_FFT_REPORT_REG0_PEAK_SIDX)); ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "wmi phyerr fft report rel_pwr_db %d avgpwr_db %d peak_mag %d num_store_bin %d\n", MS(reg1, SEARCH_FFT_REPORT_REG1_RELPWR_DB), MS(reg1, SEARCH_FFT_REPORT_REG1_AVGPWR_DB), MS(reg1, SEARCH_FFT_REPORT_REG1_PEAK_MAG), MS(reg1, SEARCH_FFT_REPORT_REG1_NUM_STR_BINS_IB)); peak_mag = MS(reg1, SEARCH_FFT_REPORT_REG1_PEAK_MAG); /* false event detection */ if (rssi == DFS_RSSI_POSSIBLY_FALSE && peak_mag < 2 * DFS_PEAK_MAG_THOLD_POSSIBLY_FALSE) { ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "dfs false pulse detected\n"); ATH10K_DFS_STAT_INC(ar, pulses_discarded); return -EINVAL; } return 0; } void ath10k_wmi_event_dfs(struct ath10k *ar, struct wmi_phyerr_ev_arg *phyerr, u64 tsf) { int buf_len, tlv_len, res, i = 0; const struct phyerr_tlv *tlv; const struct phyerr_radar_report *rr; const struct phyerr_fft_report *fftr; const u8 *tlv_buf; buf_len = phyerr->buf_len; ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "wmi event dfs err_code %d rssi %d tsfl 0x%X tsf64 0x%llX len %d\n", phyerr->phy_err_code, phyerr->rssi_combined, phyerr->tsf_timestamp, tsf, buf_len); /* Skip event if DFS disabled */ if (!IS_ENABLED(CONFIG_ATH10K_DFS_CERTIFIED)) return; ATH10K_DFS_STAT_INC(ar, pulses_total); while (i < buf_len) { if (i + sizeof(*tlv) > buf_len) { ath10k_warn(ar, "too short buf for tlv header (%d)\n", i); return; } tlv = (struct phyerr_tlv *)&phyerr->buf[i]; tlv_len = __le16_to_cpu(tlv->len); tlv_buf = &phyerr->buf[i + sizeof(*tlv)]; ath10k_dbg(ar, ATH10K_DBG_REGULATORY, "wmi event dfs tlv_len %d tlv_tag 0x%02X tlv_sig 0x%02X\n", tlv_len, tlv->tag, tlv->sig); switch (tlv->tag) { case PHYERR_TLV_TAG_RADAR_PULSE_SUMMARY: if (i + sizeof(*tlv) + sizeof(*rr) > buf_len) { ath10k_warn(ar, "too short radar pulse summary (%d)\n", i); return; } rr = (struct phyerr_radar_report *)tlv_buf; ath10k_dfs_radar_report(ar, phyerr, rr, tsf); break; case PHYERR_TLV_TAG_SEARCH_FFT_REPORT: if (i + sizeof(*tlv) + sizeof(*fftr) > buf_len) { ath10k_warn(ar, "too short fft report (%d)\n", i); return; } fftr = (struct phyerr_fft_report *)tlv_buf; res = ath10k_dfs_fft_report(ar, phyerr, fftr, tsf); if (res) return; break; } i += sizeof(*tlv) + tlv_len; } } void ath10k_wmi_event_spectral_scan(struct ath10k *ar, struct wmi_phyerr_ev_arg *phyerr, u64 tsf) { int buf_len, tlv_len, res, i = 0; struct phyerr_tlv *tlv; const void *tlv_buf; const struct phyerr_fft_report *fftr; size_t fftr_len; buf_len = phyerr->buf_len; while (i < buf_len) { if (i + sizeof(*tlv) > buf_len) { ath10k_warn(ar, "failed to parse phyerr tlv header at byte %d\n", i); return; } tlv = (struct phyerr_tlv *)&phyerr->buf[i]; tlv_len = __le16_to_cpu(tlv->len); tlv_buf = &phyerr->buf[i + sizeof(*tlv)]; if (i + sizeof(*tlv) + tlv_len > buf_len) { ath10k_warn(ar, "failed to parse phyerr tlv payload at byte %d\n", i); return; } switch (tlv->tag) { case PHYERR_TLV_TAG_SEARCH_FFT_REPORT: if (sizeof(*fftr) > tlv_len) { ath10k_warn(ar, "failed to parse fft report at byte %d\n", i); return; } fftr_len = tlv_len - sizeof(*fftr); fftr = tlv_buf; res = ath10k_spectral_process_fft(ar, phyerr, fftr, fftr_len, tsf); if (res < 0) { ath10k_dbg(ar, ATH10K_DBG_WMI, "failed to process fft report: %d\n", res); return; } break; } i += sizeof(*tlv) + tlv_len; } } static int ath10k_wmi_op_pull_phyerr_ev_hdr(struct ath10k *ar, struct sk_buff *skb, struct wmi_phyerr_hdr_arg *arg) { struct wmi_phyerr_event *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; arg->num_phyerrs = __le32_to_cpu(ev->num_phyerrs); arg->tsf_l32 = __le32_to_cpu(ev->tsf_l32); arg->tsf_u32 = __le32_to_cpu(ev->tsf_u32); arg->buf_len = skb->len - sizeof(*ev); arg->phyerrs = ev->phyerrs; return 0; } static int ath10k_wmi_10_4_op_pull_phyerr_ev_hdr(struct ath10k *ar, struct sk_buff *skb, struct wmi_phyerr_hdr_arg *arg) { struct wmi_10_4_phyerr_event *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; /* 10.4 firmware always reports only one phyerr */ arg->num_phyerrs = 1; arg->tsf_l32 = __le32_to_cpu(ev->tsf_l32); arg->tsf_u32 = __le32_to_cpu(ev->tsf_u32); arg->buf_len = skb->len; arg->phyerrs = skb->data; return 0; } int ath10k_wmi_op_pull_phyerr_ev(struct ath10k *ar, const void *phyerr_buf, int left_len, struct wmi_phyerr_ev_arg *arg) { const struct wmi_phyerr *phyerr = phyerr_buf; int i; if (left_len < sizeof(*phyerr)) { ath10k_warn(ar, "wrong phyerr event head len %d (need: >=%zd)\n", left_len, sizeof(*phyerr)); return -EINVAL; } arg->tsf_timestamp = __le32_to_cpu(phyerr->tsf_timestamp); arg->freq1 = __le16_to_cpu(phyerr->freq1); arg->freq2 = __le16_to_cpu(phyerr->freq2); arg->rssi_combined = phyerr->rssi_combined; arg->chan_width_mhz = phyerr->chan_width_mhz; arg->buf_len = __le32_to_cpu(phyerr->buf_len); arg->buf = phyerr->buf; arg->hdr_len = sizeof(*phyerr); for (i = 0; i < 4; i++) arg->nf_chains[i] = __le16_to_cpu(phyerr->nf_chains[i]); switch (phyerr->phy_err_code) { case PHY_ERROR_GEN_SPECTRAL_SCAN: arg->phy_err_code = PHY_ERROR_SPECTRAL_SCAN; break; case PHY_ERROR_GEN_FALSE_RADAR_EXT: arg->phy_err_code = PHY_ERROR_FALSE_RADAR_EXT; break; case PHY_ERROR_GEN_RADAR: arg->phy_err_code = PHY_ERROR_RADAR; break; default: arg->phy_err_code = PHY_ERROR_UNKNOWN; break; } return 0; } static int ath10k_wmi_10_4_op_pull_phyerr_ev(struct ath10k *ar, const void *phyerr_buf, int left_len, struct wmi_phyerr_ev_arg *arg) { const struct wmi_10_4_phyerr_event *phyerr = phyerr_buf; u32 phy_err_mask; int i; if (left_len < sizeof(*phyerr)) { ath10k_warn(ar, "wrong phyerr event head len %d (need: >=%zd)\n", left_len, sizeof(*phyerr)); return -EINVAL; } arg->tsf_timestamp = __le32_to_cpu(phyerr->tsf_timestamp); arg->freq1 = __le16_to_cpu(phyerr->freq1); arg->freq2 = __le16_to_cpu(phyerr->freq2); arg->rssi_combined = phyerr->rssi_combined; arg->chan_width_mhz = phyerr->chan_width_mhz; arg->buf_len = __le32_to_cpu(phyerr->buf_len); arg->buf = phyerr->buf; arg->hdr_len = sizeof(*phyerr); for (i = 0; i < 4; i++) arg->nf_chains[i] = __le16_to_cpu(phyerr->nf_chains[i]); phy_err_mask = __le32_to_cpu(phyerr->phy_err_mask[0]); if (phy_err_mask & PHY_ERROR_10_4_SPECTRAL_SCAN_MASK) arg->phy_err_code = PHY_ERROR_SPECTRAL_SCAN; else if (phy_err_mask & PHY_ERROR_10_4_RADAR_MASK) arg->phy_err_code = PHY_ERROR_RADAR; else arg->phy_err_code = PHY_ERROR_UNKNOWN; return 0; } void ath10k_wmi_event_phyerr(struct ath10k *ar, struct sk_buff *skb) { struct wmi_phyerr_hdr_arg hdr_arg = {}; struct wmi_phyerr_ev_arg phyerr_arg = {}; const void *phyerr; u32 count, i, buf_len, phy_err_code; u64 tsf; int left_len, ret; ATH10K_DFS_STAT_INC(ar, phy_errors); ret = ath10k_wmi_pull_phyerr_hdr(ar, skb, &hdr_arg); if (ret) { ath10k_warn(ar, "failed to parse phyerr event hdr: %d\n", ret); return; } /* Check number of included events */ count = hdr_arg.num_phyerrs; left_len = hdr_arg.buf_len; tsf = hdr_arg.tsf_u32; tsf <<= 32; tsf |= hdr_arg.tsf_l32; ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi event phyerr count %d tsf64 0x%llX\n", count, tsf); phyerr = hdr_arg.phyerrs; for (i = 0; i < count; i++) { ret = ath10k_wmi_pull_phyerr(ar, phyerr, left_len, &phyerr_arg); if (ret) { ath10k_warn(ar, "failed to parse phyerr event (%d)\n", i); return; } left_len -= phyerr_arg.hdr_len; buf_len = phyerr_arg.buf_len; phy_err_code = phyerr_arg.phy_err_code; if (left_len < buf_len) { ath10k_warn(ar, "single event (%d) wrong buf len\n", i); return; } left_len -= buf_len; switch (phy_err_code) { case PHY_ERROR_RADAR: ath10k_wmi_event_dfs(ar, &phyerr_arg, tsf); break; case PHY_ERROR_SPECTRAL_SCAN: ath10k_wmi_event_spectral_scan(ar, &phyerr_arg, tsf); break; case PHY_ERROR_FALSE_RADAR_EXT: ath10k_wmi_event_dfs(ar, &phyerr_arg, tsf); ath10k_wmi_event_spectral_scan(ar, &phyerr_arg, tsf); break; default: break; } phyerr = phyerr + phyerr_arg.hdr_len + buf_len; } } void ath10k_wmi_event_roam(struct ath10k *ar, struct sk_buff *skb) { struct wmi_roam_ev_arg arg = {}; int ret; u32 vdev_id; u32 reason; s32 rssi; ret = ath10k_wmi_pull_roam_ev(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse roam event: %d\n", ret); return; } vdev_id = __le32_to_cpu(arg.vdev_id); reason = __le32_to_cpu(arg.reason); rssi = __le32_to_cpu(arg.rssi); rssi += WMI_SPECTRAL_NOISE_FLOOR_REF_DEFAULT; ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi roam event vdev %u reason 0x%08x rssi %d\n", vdev_id, reason, rssi); if (reason >= WMI_ROAM_REASON_MAX) ath10k_warn(ar, "ignoring unknown roam event reason %d on vdev %i\n", reason, vdev_id); switch (reason) { case WMI_ROAM_REASON_BEACON_MISS: ath10k_mac_handle_beacon_miss(ar, vdev_id); break; case WMI_ROAM_REASON_BETTER_AP: case WMI_ROAM_REASON_LOW_RSSI: case WMI_ROAM_REASON_SUITABLE_AP_FOUND: case WMI_ROAM_REASON_HO_FAILED: ath10k_warn(ar, "ignoring not implemented roam event reason %d on vdev %i\n", reason, vdev_id); break; } } void ath10k_wmi_event_profile_match(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_PROFILE_MATCH\n"); } void ath10k_wmi_event_debug_print(struct ath10k *ar, struct sk_buff *skb) { char buf[101], c; int i; for (i = 0; i < sizeof(buf) - 1; i++) { if (i >= skb->len) break; c = skb->data[i]; if (c == '\0') break; if (isascii(c) && isprint(c)) buf[i] = c; else buf[i] = '.'; } if (i == sizeof(buf) - 1) ath10k_warn(ar, "wmi debug print truncated: %d\n", skb->len); /* for some reason the debug prints end with \n, remove that */ if (skb->data[i - 1] == '\n') i--; /* the last byte is always reserved for the null character */ buf[i] = '\0'; ath10k_dbg(ar, ATH10K_DBG_WMI_PRINT, "wmi print '%s'\n", buf); } void ath10k_wmi_event_pdev_qvit(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_PDEV_QVIT_EVENTID\n"); } void ath10k_wmi_event_wlan_profile_data(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_WLAN_PROFILE_DATA_EVENTID\n"); } void ath10k_wmi_event_rtt_measurement_report(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_RTT_MEASUREMENT_REPORT_EVENTID\n"); } void ath10k_wmi_event_tsf_measurement_report(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_TSF_MEASUREMENT_REPORT_EVENTID\n"); } void ath10k_wmi_event_rtt_error_report(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_RTT_ERROR_REPORT_EVENTID\n"); } void ath10k_wmi_event_wow_wakeup_host(struct ath10k *ar, struct sk_buff *skb) { struct wmi_wow_ev_arg ev = {}; int ret; complete(&ar->wow.wakeup_completed); ret = ath10k_wmi_pull_wow_event(ar, skb, &ev); if (ret) { ath10k_warn(ar, "failed to parse wow wakeup event: %d\n", ret); return; } ath10k_dbg(ar, ATH10K_DBG_WMI, "wow wakeup host reason %s\n", wow_reason(ev.wake_reason)); } void ath10k_wmi_event_dcs_interference(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_DCS_INTERFERENCE_EVENTID\n"); } static u8 ath10k_tpc_config_get_rate(struct ath10k *ar, struct wmi_pdev_tpc_config_event *ev, u32 rate_idx, u32 num_chains, u32 rate_code, u8 type) { u8 tpc, num_streams, preamble, ch, stm_idx; num_streams = ATH10K_HW_NSS(rate_code); preamble = ATH10K_HW_PREAMBLE(rate_code); ch = num_chains - 1; tpc = min_t(u8, ev->rates_array[rate_idx], ev->max_reg_allow_pow[ch]); if (__le32_to_cpu(ev->num_tx_chain) <= 1) goto out; if (preamble == WMI_RATE_PREAMBLE_CCK) goto out; stm_idx = num_streams - 1; if (num_chains <= num_streams) goto out; switch (type) { case WMI_TPC_TABLE_TYPE_STBC: tpc = min_t(u8, tpc, ev->max_reg_allow_pow_agstbc[ch - 1][stm_idx]); break; case WMI_TPC_TABLE_TYPE_TXBF: tpc = min_t(u8, tpc, ev->max_reg_allow_pow_agtxbf[ch - 1][stm_idx]); break; case WMI_TPC_TABLE_TYPE_CDD: tpc = min_t(u8, tpc, ev->max_reg_allow_pow_agcdd[ch - 1][stm_idx]); break; default: ath10k_warn(ar, "unknown wmi tpc table type: %d\n", type); tpc = 0; break; } out: return tpc; } static void ath10k_tpc_config_disp_tables(struct ath10k *ar, struct wmi_pdev_tpc_config_event *ev, struct ath10k_tpc_stats *tpc_stats, u8 *rate_code, u16 *pream_table, u8 type) { u32 i, j, pream_idx, flags; u8 tpc[WMI_TPC_TX_N_CHAIN]; char tpc_value[WMI_TPC_TX_N_CHAIN * WMI_TPC_BUF_SIZE]; char buff[WMI_TPC_BUF_SIZE]; flags = __le32_to_cpu(ev->flags); switch (type) { case WMI_TPC_TABLE_TYPE_CDD: if (!(flags & WMI_TPC_CONFIG_EVENT_FLAG_TABLE_CDD)) { ath10k_dbg(ar, ATH10K_DBG_WMI, "CDD not supported\n"); tpc_stats->flag[type] = ATH10K_TPC_TABLE_TYPE_FLAG; return; } break; case WMI_TPC_TABLE_TYPE_STBC: if (!(flags & WMI_TPC_CONFIG_EVENT_FLAG_TABLE_STBC)) { ath10k_dbg(ar, ATH10K_DBG_WMI, "STBC not supported\n"); tpc_stats->flag[type] = ATH10K_TPC_TABLE_TYPE_FLAG; return; } break; case WMI_TPC_TABLE_TYPE_TXBF: if (!(flags & WMI_TPC_CONFIG_EVENT_FLAG_TABLE_TXBF)) { ath10k_dbg(ar, ATH10K_DBG_WMI, "TXBF not supported\n"); tpc_stats->flag[type] = ATH10K_TPC_TABLE_TYPE_FLAG; return; } break; default: ath10k_dbg(ar, ATH10K_DBG_WMI, "invalid table type in wmi tpc event: %d\n", type); return; } pream_idx = 0; for (i = 0; i < __le32_to_cpu(ev->rate_max); i++) { memset(tpc_value, 0, sizeof(tpc_value)); memset(buff, 0, sizeof(buff)); if (i == pream_table[pream_idx]) pream_idx++; for (j = 0; j < WMI_TPC_TX_N_CHAIN; j++) { if (j >= __le32_to_cpu(ev->num_tx_chain)) break; tpc[j] = ath10k_tpc_config_get_rate(ar, ev, i, j + 1, rate_code[i], type); snprintf(buff, sizeof(buff), "%8d ", tpc[j]); strncat(tpc_value, buff, strlen(buff)); } tpc_stats->tpc_table[type].pream_idx[i] = pream_idx; tpc_stats->tpc_table[type].rate_code[i] = rate_code[i]; memcpy(tpc_stats->tpc_table[type].tpc_value[i], tpc_value, sizeof(tpc_value)); } } void ath10k_wmi_event_pdev_tpc_config(struct ath10k *ar, struct sk_buff *skb) { u32 i, j, pream_idx, num_tx_chain; u8 rate_code[WMI_TPC_RATE_MAX], rate_idx; u16 pream_table[WMI_TPC_PREAM_TABLE_MAX]; struct wmi_pdev_tpc_config_event *ev; struct ath10k_tpc_stats *tpc_stats; ev = (struct wmi_pdev_tpc_config_event *)skb->data; tpc_stats = kzalloc(sizeof(*tpc_stats), GFP_ATOMIC); if (!tpc_stats) return; /* Create the rate code table based on the chains supported */ rate_idx = 0; pream_idx = 0; /* Fill CCK rate code */ for (i = 0; i < 4; i++) { rate_code[rate_idx] = ATH10K_HW_RATECODE(i, 0, WMI_RATE_PREAMBLE_CCK); rate_idx++; } pream_table[pream_idx] = rate_idx; pream_idx++; /* Fill OFDM rate code */ for (i = 0; i < 8; i++) { rate_code[rate_idx] = ATH10K_HW_RATECODE(i, 0, WMI_RATE_PREAMBLE_OFDM); rate_idx++; } pream_table[pream_idx] = rate_idx; pream_idx++; num_tx_chain = __le32_to_cpu(ev->num_tx_chain); /* Fill HT20 rate code */ for (i = 0; i < num_tx_chain; i++) { for (j = 0; j < 8; j++) { rate_code[rate_idx] = ATH10K_HW_RATECODE(j, i, WMI_RATE_PREAMBLE_HT); rate_idx++; } } pream_table[pream_idx] = rate_idx; pream_idx++; /* Fill HT40 rate code */ for (i = 0; i < num_tx_chain; i++) { for (j = 0; j < 8; j++) { rate_code[rate_idx] = ATH10K_HW_RATECODE(j, i, WMI_RATE_PREAMBLE_HT); rate_idx++; } } pream_table[pream_idx] = rate_idx; pream_idx++; /* Fill VHT20 rate code */ for (i = 0; i < __le32_to_cpu(ev->num_tx_chain); i++) { for (j = 0; j < 10; j++) { rate_code[rate_idx] = ATH10K_HW_RATECODE(j, i, WMI_RATE_PREAMBLE_VHT); rate_idx++; } } pream_table[pream_idx] = rate_idx; pream_idx++; /* Fill VHT40 rate code */ for (i = 0; i < num_tx_chain; i++) { for (j = 0; j < 10; j++) { rate_code[rate_idx] = ATH10K_HW_RATECODE(j, i, WMI_RATE_PREAMBLE_VHT); rate_idx++; } } pream_table[pream_idx] = rate_idx; pream_idx++; /* Fill VHT80 rate code */ for (i = 0; i < num_tx_chain; i++) { for (j = 0; j < 10; j++) { rate_code[rate_idx] = ATH10K_HW_RATECODE(j, i, WMI_RATE_PREAMBLE_VHT); rate_idx++; } } pream_table[pream_idx] = rate_idx; pream_idx++; rate_code[rate_idx++] = ATH10K_HW_RATECODE(0, 0, WMI_RATE_PREAMBLE_CCK); rate_code[rate_idx++] = ATH10K_HW_RATECODE(0, 0, WMI_RATE_PREAMBLE_OFDM); rate_code[rate_idx++] = ATH10K_HW_RATECODE(0, 0, WMI_RATE_PREAMBLE_CCK); rate_code[rate_idx++] = ATH10K_HW_RATECODE(0, 0, WMI_RATE_PREAMBLE_OFDM); rate_code[rate_idx++] = ATH10K_HW_RATECODE(0, 0, WMI_RATE_PREAMBLE_OFDM); pream_table[pream_idx] = ATH10K_TPC_PREAM_TABLE_END; tpc_stats->chan_freq = __le32_to_cpu(ev->chan_freq); tpc_stats->phy_mode = __le32_to_cpu(ev->phy_mode); tpc_stats->ctl = __le32_to_cpu(ev->ctl); tpc_stats->reg_domain = __le32_to_cpu(ev->reg_domain); tpc_stats->twice_antenna_gain = a_sle32_to_cpu(ev->twice_antenna_gain); tpc_stats->twice_antenna_reduction = __le32_to_cpu(ev->twice_antenna_reduction); tpc_stats->power_limit = __le32_to_cpu(ev->power_limit); tpc_stats->twice_max_rd_power = __le32_to_cpu(ev->twice_max_rd_power); tpc_stats->num_tx_chain = __le32_to_cpu(ev->num_tx_chain); tpc_stats->rate_max = __le32_to_cpu(ev->rate_max); ath10k_tpc_config_disp_tables(ar, ev, tpc_stats, rate_code, pream_table, WMI_TPC_TABLE_TYPE_CDD); ath10k_tpc_config_disp_tables(ar, ev, tpc_stats, rate_code, pream_table, WMI_TPC_TABLE_TYPE_STBC); ath10k_tpc_config_disp_tables(ar, ev, tpc_stats, rate_code, pream_table, WMI_TPC_TABLE_TYPE_TXBF); ath10k_debug_tpc_stats_process(ar, tpc_stats); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi event tpc config channel %d mode %d ctl %d regd %d gain %d %d limit %d max_power %d tx_chanins %d rates %d\n", __le32_to_cpu(ev->chan_freq), __le32_to_cpu(ev->phy_mode), __le32_to_cpu(ev->ctl), __le32_to_cpu(ev->reg_domain), a_sle32_to_cpu(ev->twice_antenna_gain), __le32_to_cpu(ev->twice_antenna_reduction), __le32_to_cpu(ev->power_limit), __le32_to_cpu(ev->twice_max_rd_power) / 2, __le32_to_cpu(ev->num_tx_chain), __le32_to_cpu(ev->rate_max)); } void ath10k_wmi_event_pdev_ftm_intg(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_PDEV_FTM_INTG_EVENTID\n"); } void ath10k_wmi_event_gtk_offload_status(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_GTK_OFFLOAD_STATUS_EVENTID\n"); } void ath10k_wmi_event_gtk_rekey_fail(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_GTK_REKEY_FAIL_EVENTID\n"); } void ath10k_wmi_event_delba_complete(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_TX_DELBA_COMPLETE_EVENTID\n"); } void ath10k_wmi_event_addba_complete(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_TX_ADDBA_COMPLETE_EVENTID\n"); } void ath10k_wmi_event_vdev_install_key_complete(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_VDEV_INSTALL_KEY_COMPLETE_EVENTID\n"); } void ath10k_wmi_event_inst_rssi_stats(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_INST_RSSI_STATS_EVENTID\n"); } void ath10k_wmi_event_vdev_standby_req(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_VDEV_STANDBY_REQ_EVENTID\n"); } void ath10k_wmi_event_vdev_resume_req(struct ath10k *ar, struct sk_buff *skb) { ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI_VDEV_RESUME_REQ_EVENTID\n"); } static int ath10k_wmi_alloc_chunk(struct ath10k *ar, u32 req_id, u32 num_units, u32 unit_len) { dma_addr_t paddr; u32 pool_size = 0; int idx = ar->wmi.num_mem_chunks; void *vaddr = NULL; if (ar->wmi.num_mem_chunks == ARRAY_SIZE(ar->wmi.mem_chunks)) return -ENOMEM; while (!vaddr && num_units) { pool_size = num_units * round_up(unit_len, 4); if (!pool_size) return -EINVAL; vaddr = kzalloc(pool_size, GFP_KERNEL | __GFP_NOWARN); if (!vaddr) num_units /= 2; } if (!num_units) return -ENOMEM; paddr = dma_map_single(ar->dev, vaddr, pool_size, DMA_BIDIRECTIONAL); if (dma_mapping_error(ar->dev, paddr)) { kfree(vaddr); return -ENOMEM; } ar->wmi.mem_chunks[idx].vaddr = vaddr; ar->wmi.mem_chunks[idx].paddr = paddr; ar->wmi.mem_chunks[idx].len = pool_size; ar->wmi.mem_chunks[idx].req_id = req_id; ar->wmi.num_mem_chunks++; return num_units; } static int ath10k_wmi_alloc_host_mem(struct ath10k *ar, u32 req_id, u32 num_units, u32 unit_len) { int ret; while (num_units) { ret = ath10k_wmi_alloc_chunk(ar, req_id, num_units, unit_len); if (ret < 0) return ret; num_units -= ret; } return 0; } static bool ath10k_wmi_is_host_mem_allocated(struct ath10k *ar, const struct wlan_host_mem_req **mem_reqs, u32 num_mem_reqs) { u32 req_id, num_units, unit_size, num_unit_info; u32 pool_size; int i, j; bool found; if (ar->wmi.num_mem_chunks != num_mem_reqs) return false; for (i = 0; i < num_mem_reqs; ++i) { req_id = __le32_to_cpu(mem_reqs[i]->req_id); num_units = __le32_to_cpu(mem_reqs[i]->num_units); unit_size = __le32_to_cpu(mem_reqs[i]->unit_size); num_unit_info = __le32_to_cpu(mem_reqs[i]->num_unit_info); if (num_unit_info & NUM_UNITS_IS_NUM_ACTIVE_PEERS) { if (ar->num_active_peers) num_units = ar->num_active_peers + 1; else num_units = ar->max_num_peers + 1; } else if (num_unit_info & NUM_UNITS_IS_NUM_PEERS) { num_units = ar->max_num_peers + 1; } else if (num_unit_info & NUM_UNITS_IS_NUM_VDEVS) { num_units = ar->max_num_vdevs + 1; } found = false; for (j = 0; j < ar->wmi.num_mem_chunks; j++) { if (ar->wmi.mem_chunks[j].req_id == req_id) { pool_size = num_units * round_up(unit_size, 4); if (ar->wmi.mem_chunks[j].len == pool_size) { found = true; break; } } } if (!found) return false; } return true; } static int ath10k_wmi_main_op_pull_svc_rdy_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_svc_rdy_ev_arg *arg) { struct wmi_service_ready_event *ev; size_t i, n; if (skb->len < sizeof(*ev)) return -EPROTO; ev = (void *)skb->data; skb_pull(skb, sizeof(*ev)); arg->min_tx_power = ev->hw_min_tx_power; arg->max_tx_power = ev->hw_max_tx_power; arg->ht_cap = ev->ht_cap_info; arg->vht_cap = ev->vht_cap_info; arg->sw_ver0 = ev->sw_version; arg->sw_ver1 = ev->sw_version_1; arg->phy_capab = ev->phy_capability; arg->num_rf_chains = ev->num_rf_chains; arg->eeprom_rd = ev->hal_reg_capabilities.eeprom_rd; arg->num_mem_reqs = ev->num_mem_reqs; arg->service_map = ev->wmi_service_bitmap; arg->service_map_len = sizeof(ev->wmi_service_bitmap); n = min_t(size_t, __le32_to_cpu(arg->num_mem_reqs), ARRAY_SIZE(arg->mem_reqs)); for (i = 0; i < n; i++) arg->mem_reqs[i] = &ev->mem_reqs[i]; if (skb->len < __le32_to_cpu(arg->num_mem_reqs) * sizeof(arg->mem_reqs[0])) return -EPROTO; return 0; } static int ath10k_wmi_10x_op_pull_svc_rdy_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_svc_rdy_ev_arg *arg) { struct wmi_10x_service_ready_event *ev; int i, n; if (skb->len < sizeof(*ev)) return -EPROTO; ev = (void *)skb->data; skb_pull(skb, sizeof(*ev)); arg->min_tx_power = ev->hw_min_tx_power; arg->max_tx_power = ev->hw_max_tx_power; arg->ht_cap = ev->ht_cap_info; arg->vht_cap = ev->vht_cap_info; arg->sw_ver0 = ev->sw_version; arg->phy_capab = ev->phy_capability; arg->num_rf_chains = ev->num_rf_chains; arg->eeprom_rd = ev->hal_reg_capabilities.eeprom_rd; arg->num_mem_reqs = ev->num_mem_reqs; arg->service_map = ev->wmi_service_bitmap; arg->service_map_len = sizeof(ev->wmi_service_bitmap); n = min_t(size_t, __le32_to_cpu(arg->num_mem_reqs), ARRAY_SIZE(arg->mem_reqs)); for (i = 0; i < n; i++) arg->mem_reqs[i] = &ev->mem_reqs[i]; if (skb->len < __le32_to_cpu(arg->num_mem_reqs) * sizeof(arg->mem_reqs[0])) return -EPROTO; return 0; } static void ath10k_wmi_event_service_ready_work(struct work_struct *work) { struct ath10k *ar = container_of(work, struct ath10k, svc_rdy_work); struct sk_buff *skb = ar->svc_rdy_skb; struct wmi_svc_rdy_ev_arg arg = {}; u32 num_units, req_id, unit_size, num_mem_reqs, num_unit_info, i; int ret; bool allocated; if (!skb) { ath10k_warn(ar, "invalid service ready event skb\n"); return; } ret = ath10k_wmi_pull_svc_rdy(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse service ready: %d\n", ret); return; } memset(&ar->wmi.svc_map, 0, sizeof(ar->wmi.svc_map)); ath10k_wmi_map_svc(ar, arg.service_map, ar->wmi.svc_map, arg.service_map_len); ar->hw_min_tx_power = __le32_to_cpu(arg.min_tx_power); ar->hw_max_tx_power = __le32_to_cpu(arg.max_tx_power); ar->ht_cap_info = __le32_to_cpu(arg.ht_cap); ar->vht_cap_info = __le32_to_cpu(arg.vht_cap); ar->fw_version_major = (__le32_to_cpu(arg.sw_ver0) & 0xff000000) >> 24; ar->fw_version_minor = (__le32_to_cpu(arg.sw_ver0) & 0x00ffffff); ar->fw_version_release = (__le32_to_cpu(arg.sw_ver1) & 0xffff0000) >> 16; ar->fw_version_build = (__le32_to_cpu(arg.sw_ver1) & 0x0000ffff); ar->phy_capability = __le32_to_cpu(arg.phy_capab); ar->num_rf_chains = __le32_to_cpu(arg.num_rf_chains); ar->hw_eeprom_rd = __le32_to_cpu(arg.eeprom_rd); ath10k_dbg_dump(ar, ATH10K_DBG_WMI, NULL, "wmi svc: ", arg.service_map, arg.service_map_len); if (ar->num_rf_chains > ar->max_spatial_stream) { ath10k_warn(ar, "hardware advertises support for more spatial streams than it should (%d > %d)\n", ar->num_rf_chains, ar->max_spatial_stream); ar->num_rf_chains = ar->max_spatial_stream; } if (!ar->cfg_tx_chainmask) { ar->cfg_tx_chainmask = (1 << ar->num_rf_chains) - 1; ar->cfg_rx_chainmask = (1 << ar->num_rf_chains) - 1; } if (strlen(ar->hw->wiphy->fw_version) == 0) { snprintf(ar->hw->wiphy->fw_version, sizeof(ar->hw->wiphy->fw_version), "%u.%u.%u.%u", ar->fw_version_major, ar->fw_version_minor, ar->fw_version_release, ar->fw_version_build); } num_mem_reqs = __le32_to_cpu(arg.num_mem_reqs); if (num_mem_reqs > WMI_MAX_MEM_REQS) { ath10k_warn(ar, "requested memory chunks number (%d) exceeds the limit\n", num_mem_reqs); return; } if (test_bit(WMI_SERVICE_PEER_CACHING, ar->wmi.svc_map)) { if (test_bit(ATH10K_FW_FEATURE_PEER_FLOW_CONTROL, ar->running_fw->fw_file.fw_features)) ar->num_active_peers = TARGET_10_4_QCACHE_ACTIVE_PEERS_PFC + ar->max_num_vdevs; else ar->num_active_peers = TARGET_10_4_QCACHE_ACTIVE_PEERS + ar->max_num_vdevs; ar->max_num_peers = TARGET_10_4_NUM_QCACHE_PEERS_MAX + ar->max_num_vdevs; ar->num_tids = ar->num_active_peers * 2; ar->max_num_stations = TARGET_10_4_NUM_QCACHE_PEERS_MAX; } /* TODO: Adjust max peer count for cases like WMI_SERVICE_RATECTRL_CACHE * and WMI_SERVICE_IRAM_TIDS, etc. */ allocated = ath10k_wmi_is_host_mem_allocated(ar, arg.mem_reqs, num_mem_reqs); if (allocated) goto skip_mem_alloc; /* Either this event is received during boot time or there is a change * in memory requirement from firmware when compared to last request. * Free any old memory and do a fresh allocation based on the current * memory requirement. */ ath10k_wmi_free_host_mem(ar); for (i = 0; i < num_mem_reqs; ++i) { req_id = __le32_to_cpu(arg.mem_reqs[i]->req_id); num_units = __le32_to_cpu(arg.mem_reqs[i]->num_units); unit_size = __le32_to_cpu(arg.mem_reqs[i]->unit_size); num_unit_info = __le32_to_cpu(arg.mem_reqs[i]->num_unit_info); if (num_unit_info & NUM_UNITS_IS_NUM_ACTIVE_PEERS) { if (ar->num_active_peers) num_units = ar->num_active_peers + 1; else num_units = ar->max_num_peers + 1; } else if (num_unit_info & NUM_UNITS_IS_NUM_PEERS) { /* number of units to allocate is number of * peers, 1 extra for self peer on target */ /* this needs to be tied, host and target * can get out of sync */ num_units = ar->max_num_peers + 1; } else if (num_unit_info & NUM_UNITS_IS_NUM_VDEVS) { num_units = ar->max_num_vdevs + 1; } ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi mem_req_id %d num_units %d num_unit_info %d unit size %d actual units %d\n", req_id, __le32_to_cpu(arg.mem_reqs[i]->num_units), num_unit_info, unit_size, num_units); ret = ath10k_wmi_alloc_host_mem(ar, req_id, num_units, unit_size); if (ret) return; } skip_mem_alloc: ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi event service ready min_tx_power 0x%08x max_tx_power 0x%08x ht_cap 0x%08x vht_cap 0x%08x sw_ver0 0x%08x sw_ver1 0x%08x fw_build 0x%08x phy_capab 0x%08x num_rf_chains 0x%08x eeprom_rd 0x%08x num_mem_reqs 0x%08x\n", __le32_to_cpu(arg.min_tx_power), __le32_to_cpu(arg.max_tx_power), __le32_to_cpu(arg.ht_cap), __le32_to_cpu(arg.vht_cap), __le32_to_cpu(arg.sw_ver0), __le32_to_cpu(arg.sw_ver1), __le32_to_cpu(arg.fw_build), __le32_to_cpu(arg.phy_capab), __le32_to_cpu(arg.num_rf_chains), __le32_to_cpu(arg.eeprom_rd), __le32_to_cpu(arg.num_mem_reqs)); dev_kfree_skb(skb); ar->svc_rdy_skb = NULL; complete(&ar->wmi.service_ready); } void ath10k_wmi_event_service_ready(struct ath10k *ar, struct sk_buff *skb) { ar->svc_rdy_skb = skb; queue_work(ar->workqueue_aux, &ar->svc_rdy_work); } static int ath10k_wmi_op_pull_rdy_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_rdy_ev_arg *arg) { struct wmi_ready_event *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->sw_version = ev->sw_version; arg->abi_version = ev->abi_version; arg->status = ev->status; arg->mac_addr = ev->mac_addr.addr; return 0; } static int ath10k_wmi_op_pull_roam_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_roam_ev_arg *arg) { struct wmi_roam_ev *ev = (void *)skb->data; if (skb->len < sizeof(*ev)) return -EPROTO; skb_pull(skb, sizeof(*ev)); arg->vdev_id = ev->vdev_id; arg->reason = ev->reason; return 0; } static int ath10k_wmi_op_pull_echo_ev(struct ath10k *ar, struct sk_buff *skb, struct wmi_echo_ev_arg *arg) { struct wmi_echo_event *ev = (void *)skb->data; arg->value = ev->value; return 0; } int ath10k_wmi_event_ready(struct ath10k *ar, struct sk_buff *skb) { struct wmi_rdy_ev_arg arg = {}; int ret; ret = ath10k_wmi_pull_rdy(ar, skb, &arg); if (ret) { ath10k_warn(ar, "failed to parse ready event: %d\n", ret); return ret; } ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi event ready sw_version %u abi_version %u mac_addr %pM status %d\n", __le32_to_cpu(arg.sw_version), __le32_to_cpu(arg.abi_version), arg.mac_addr, __le32_to_cpu(arg.status)); ether_addr_copy(ar->mac_addr, arg.mac_addr); complete(&ar->wmi.unified_ready); return 0; } static int ath10k_wmi_event_temperature(struct ath10k *ar, struct sk_buff *skb) { const struct wmi_pdev_temperature_event *ev; ev = (struct wmi_pdev_temperature_event *)skb->data; if (WARN_ON(skb->len < sizeof(*ev))) return -EPROTO; ath10k_thermal_event_temperature(ar, __le32_to_cpu(ev->temperature)); return 0; } static int ath10k_wmi_event_pdev_bss_chan_info(struct ath10k *ar, struct sk_buff *skb) { struct wmi_pdev_bss_chan_info_event *ev; struct survey_info *survey; u64 busy, total, tx, rx, rx_bss; u32 freq, noise_floor; u32 cc_freq_hz = ar->hw_params.channel_counters_freq_hz; int idx; ev = (struct wmi_pdev_bss_chan_info_event *)skb->data; if (WARN_ON(skb->len < sizeof(*ev))) return -EPROTO; freq = __le32_to_cpu(ev->freq); noise_floor = __le32_to_cpu(ev->noise_floor); busy = __le64_to_cpu(ev->cycle_busy); total = __le64_to_cpu(ev->cycle_total); tx = __le64_to_cpu(ev->cycle_tx); rx = __le64_to_cpu(ev->cycle_rx); rx_bss = __le64_to_cpu(ev->cycle_rx_bss); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi event pdev bss chan info:\n freq: %d noise: %d cycle: busy %llu total %llu tx %llu rx %llu rx_bss %llu\n", freq, noise_floor, busy, total, tx, rx, rx_bss); spin_lock_bh(&ar->data_lock); idx = freq_to_idx(ar, freq); if (idx >= ARRAY_SIZE(ar->survey)) { ath10k_warn(ar, "bss chan info: invalid frequency %d (idx %d out of bounds)\n", freq, idx); goto exit; } survey = &ar->survey[idx]; survey->noise = noise_floor; survey->time = div_u64(total, cc_freq_hz); survey->time_busy = div_u64(busy, cc_freq_hz); survey->time_rx = div_u64(rx_bss, cc_freq_hz); survey->time_tx = div_u64(tx, cc_freq_hz); survey->filled |= (SURVEY_INFO_NOISE_DBM | SURVEY_INFO_TIME | SURVEY_INFO_TIME_BUSY | SURVEY_INFO_TIME_RX | SURVEY_INFO_TIME_TX); exit: spin_unlock_bh(&ar->data_lock); complete(&ar->bss_survey_done); return 0; } static inline void ath10k_wmi_queue_set_coverage_class_work(struct ath10k *ar) { if (ar->hw_params.hw_ops->set_coverage_class) { spin_lock_bh(&ar->data_lock); /* This call only ensures that the modified coverage class * persists in case the firmware sets the registers back to * their default value. So calling it is only necessary if the * coverage class has a non-zero value. */ if (ar->fw_coverage.coverage_class) queue_work(ar->workqueue, &ar->set_coverage_class_work); spin_unlock_bh(&ar->data_lock); } } static void ath10k_wmi_op_rx(struct ath10k *ar, struct sk_buff *skb) { struct wmi_cmd_hdr *cmd_hdr; enum wmi_event_id id; cmd_hdr = (struct wmi_cmd_hdr *)skb->data; id = MS(__le32_to_cpu(cmd_hdr->cmd_id), WMI_CMD_HDR_CMD_ID); if (skb_pull(skb, sizeof(struct wmi_cmd_hdr)) == NULL) goto out; trace_ath10k_wmi_event(ar, id, skb->data, skb->len); switch (id) { case WMI_MGMT_RX_EVENTID: ath10k_wmi_event_mgmt_rx(ar, skb); /* mgmt_rx() owns the skb now! */ return; case WMI_SCAN_EVENTID: ath10k_wmi_event_scan(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_CHAN_INFO_EVENTID: ath10k_wmi_event_chan_info(ar, skb); break; case WMI_ECHO_EVENTID: ath10k_wmi_event_echo(ar, skb); break; case WMI_DEBUG_MESG_EVENTID: ath10k_wmi_event_debug_mesg(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_UPDATE_STATS_EVENTID: ath10k_wmi_event_update_stats(ar, skb); break; case WMI_VDEV_START_RESP_EVENTID: ath10k_wmi_event_vdev_start_resp(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_VDEV_STOPPED_EVENTID: ath10k_wmi_event_vdev_stopped(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_PEER_STA_KICKOUT_EVENTID: ath10k_wmi_event_peer_sta_kickout(ar, skb); break; case WMI_HOST_SWBA_EVENTID: ath10k_wmi_event_host_swba(ar, skb); break; case WMI_TBTTOFFSET_UPDATE_EVENTID: ath10k_wmi_event_tbttoffset_update(ar, skb); break; case WMI_PHYERR_EVENTID: ath10k_wmi_event_phyerr(ar, skb); break; case WMI_ROAM_EVENTID: ath10k_wmi_event_roam(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_PROFILE_MATCH: ath10k_wmi_event_profile_match(ar, skb); break; case WMI_DEBUG_PRINT_EVENTID: ath10k_wmi_event_debug_print(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_PDEV_QVIT_EVENTID: ath10k_wmi_event_pdev_qvit(ar, skb); break; case WMI_WLAN_PROFILE_DATA_EVENTID: ath10k_wmi_event_wlan_profile_data(ar, skb); break; case WMI_RTT_MEASUREMENT_REPORT_EVENTID: ath10k_wmi_event_rtt_measurement_report(ar, skb); break; case WMI_TSF_MEASUREMENT_REPORT_EVENTID: ath10k_wmi_event_tsf_measurement_report(ar, skb); break; case WMI_RTT_ERROR_REPORT_EVENTID: ath10k_wmi_event_rtt_error_report(ar, skb); break; case WMI_WOW_WAKEUP_HOST_EVENTID: ath10k_wmi_event_wow_wakeup_host(ar, skb); break; case WMI_DCS_INTERFERENCE_EVENTID: ath10k_wmi_event_dcs_interference(ar, skb); break; case WMI_PDEV_TPC_CONFIG_EVENTID: ath10k_wmi_event_pdev_tpc_config(ar, skb); break; case WMI_PDEV_FTM_INTG_EVENTID: ath10k_wmi_event_pdev_ftm_intg(ar, skb); break; case WMI_GTK_OFFLOAD_STATUS_EVENTID: ath10k_wmi_event_gtk_offload_status(ar, skb); break; case WMI_GTK_REKEY_FAIL_EVENTID: ath10k_wmi_event_gtk_rekey_fail(ar, skb); break; case WMI_TX_DELBA_COMPLETE_EVENTID: ath10k_wmi_event_delba_complete(ar, skb); break; case WMI_TX_ADDBA_COMPLETE_EVENTID: ath10k_wmi_event_addba_complete(ar, skb); break; case WMI_VDEV_INSTALL_KEY_COMPLETE_EVENTID: ath10k_wmi_event_vdev_install_key_complete(ar, skb); break; case WMI_SERVICE_READY_EVENTID: ath10k_wmi_event_service_ready(ar, skb); return; case WMI_READY_EVENTID: ath10k_wmi_event_ready(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; default: ath10k_warn(ar, "Unknown eventid: %d\n", id); break; } out: dev_kfree_skb(skb); } static void ath10k_wmi_10_1_op_rx(struct ath10k *ar, struct sk_buff *skb) { struct wmi_cmd_hdr *cmd_hdr; enum wmi_10x_event_id id; bool consumed; cmd_hdr = (struct wmi_cmd_hdr *)skb->data; id = MS(__le32_to_cpu(cmd_hdr->cmd_id), WMI_CMD_HDR_CMD_ID); if (skb_pull(skb, sizeof(struct wmi_cmd_hdr)) == NULL) goto out; trace_ath10k_wmi_event(ar, id, skb->data, skb->len); consumed = ath10k_tm_event_wmi(ar, id, skb); /* Ready event must be handled normally also in UTF mode so that we * know the UTF firmware has booted, others we are just bypass WMI * events to testmode. */ if (consumed && id != WMI_10X_READY_EVENTID) { ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi testmode consumed 0x%x\n", id); goto out; } switch (id) { case WMI_10X_MGMT_RX_EVENTID: ath10k_wmi_event_mgmt_rx(ar, skb); /* mgmt_rx() owns the skb now! */ return; case WMI_10X_SCAN_EVENTID: ath10k_wmi_event_scan(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10X_CHAN_INFO_EVENTID: ath10k_wmi_event_chan_info(ar, skb); break; case WMI_10X_ECHO_EVENTID: ath10k_wmi_event_echo(ar, skb); break; case WMI_10X_DEBUG_MESG_EVENTID: ath10k_wmi_event_debug_mesg(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10X_UPDATE_STATS_EVENTID: ath10k_wmi_event_update_stats(ar, skb); break; case WMI_10X_VDEV_START_RESP_EVENTID: ath10k_wmi_event_vdev_start_resp(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10X_VDEV_STOPPED_EVENTID: ath10k_wmi_event_vdev_stopped(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10X_PEER_STA_KICKOUT_EVENTID: ath10k_wmi_event_peer_sta_kickout(ar, skb); break; case WMI_10X_HOST_SWBA_EVENTID: ath10k_wmi_event_host_swba(ar, skb); break; case WMI_10X_TBTTOFFSET_UPDATE_EVENTID: ath10k_wmi_event_tbttoffset_update(ar, skb); break; case WMI_10X_PHYERR_EVENTID: ath10k_wmi_event_phyerr(ar, skb); break; case WMI_10X_ROAM_EVENTID: ath10k_wmi_event_roam(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10X_PROFILE_MATCH: ath10k_wmi_event_profile_match(ar, skb); break; case WMI_10X_DEBUG_PRINT_EVENTID: ath10k_wmi_event_debug_print(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10X_PDEV_QVIT_EVENTID: ath10k_wmi_event_pdev_qvit(ar, skb); break; case WMI_10X_WLAN_PROFILE_DATA_EVENTID: ath10k_wmi_event_wlan_profile_data(ar, skb); break; case WMI_10X_RTT_MEASUREMENT_REPORT_EVENTID: ath10k_wmi_event_rtt_measurement_report(ar, skb); break; case WMI_10X_TSF_MEASUREMENT_REPORT_EVENTID: ath10k_wmi_event_tsf_measurement_report(ar, skb); break; case WMI_10X_RTT_ERROR_REPORT_EVENTID: ath10k_wmi_event_rtt_error_report(ar, skb); break; case WMI_10X_WOW_WAKEUP_HOST_EVENTID: ath10k_wmi_event_wow_wakeup_host(ar, skb); break; case WMI_10X_DCS_INTERFERENCE_EVENTID: ath10k_wmi_event_dcs_interference(ar, skb); break; case WMI_10X_PDEV_TPC_CONFIG_EVENTID: ath10k_wmi_event_pdev_tpc_config(ar, skb); break; case WMI_10X_INST_RSSI_STATS_EVENTID: ath10k_wmi_event_inst_rssi_stats(ar, skb); break; case WMI_10X_VDEV_STANDBY_REQ_EVENTID: ath10k_wmi_event_vdev_standby_req(ar, skb); break; case WMI_10X_VDEV_RESUME_REQ_EVENTID: ath10k_wmi_event_vdev_resume_req(ar, skb); break; case WMI_10X_SERVICE_READY_EVENTID: ath10k_wmi_event_service_ready(ar, skb); return; case WMI_10X_READY_EVENTID: ath10k_wmi_event_ready(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10X_PDEV_UTF_EVENTID: /* ignore utf events */ break; default: ath10k_warn(ar, "Unknown eventid: %d\n", id); break; } out: dev_kfree_skb(skb); } static void ath10k_wmi_10_2_op_rx(struct ath10k *ar, struct sk_buff *skb) { struct wmi_cmd_hdr *cmd_hdr; enum wmi_10_2_event_id id; bool consumed; cmd_hdr = (struct wmi_cmd_hdr *)skb->data; id = MS(__le32_to_cpu(cmd_hdr->cmd_id), WMI_CMD_HDR_CMD_ID); if (skb_pull(skb, sizeof(struct wmi_cmd_hdr)) == NULL) goto out; trace_ath10k_wmi_event(ar, id, skb->data, skb->len); consumed = ath10k_tm_event_wmi(ar, id, skb); /* Ready event must be handled normally also in UTF mode so that we * know the UTF firmware has booted, others we are just bypass WMI * events to testmode. */ if (consumed && id != WMI_10_2_READY_EVENTID) { ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi testmode consumed 0x%x\n", id); goto out; } switch (id) { case WMI_10_2_MGMT_RX_EVENTID: ath10k_wmi_event_mgmt_rx(ar, skb); /* mgmt_rx() owns the skb now! */ return; case WMI_10_2_SCAN_EVENTID: ath10k_wmi_event_scan(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_CHAN_INFO_EVENTID: ath10k_wmi_event_chan_info(ar, skb); break; case WMI_10_2_ECHO_EVENTID: ath10k_wmi_event_echo(ar, skb); break; case WMI_10_2_DEBUG_MESG_EVENTID: ath10k_wmi_event_debug_mesg(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_UPDATE_STATS_EVENTID: ath10k_wmi_event_update_stats(ar, skb); break; case WMI_10_2_VDEV_START_RESP_EVENTID: ath10k_wmi_event_vdev_start_resp(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_VDEV_STOPPED_EVENTID: ath10k_wmi_event_vdev_stopped(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_PEER_STA_KICKOUT_EVENTID: ath10k_wmi_event_peer_sta_kickout(ar, skb); break; case WMI_10_2_HOST_SWBA_EVENTID: ath10k_wmi_event_host_swba(ar, skb); break; case WMI_10_2_TBTTOFFSET_UPDATE_EVENTID: ath10k_wmi_event_tbttoffset_update(ar, skb); break; case WMI_10_2_PHYERR_EVENTID: ath10k_wmi_event_phyerr(ar, skb); break; case WMI_10_2_ROAM_EVENTID: ath10k_wmi_event_roam(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_PROFILE_MATCH: ath10k_wmi_event_profile_match(ar, skb); break; case WMI_10_2_DEBUG_PRINT_EVENTID: ath10k_wmi_event_debug_print(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_PDEV_QVIT_EVENTID: ath10k_wmi_event_pdev_qvit(ar, skb); break; case WMI_10_2_WLAN_PROFILE_DATA_EVENTID: ath10k_wmi_event_wlan_profile_data(ar, skb); break; case WMI_10_2_RTT_MEASUREMENT_REPORT_EVENTID: ath10k_wmi_event_rtt_measurement_report(ar, skb); break; case WMI_10_2_TSF_MEASUREMENT_REPORT_EVENTID: ath10k_wmi_event_tsf_measurement_report(ar, skb); break; case WMI_10_2_RTT_ERROR_REPORT_EVENTID: ath10k_wmi_event_rtt_error_report(ar, skb); break; case WMI_10_2_WOW_WAKEUP_HOST_EVENTID: ath10k_wmi_event_wow_wakeup_host(ar, skb); break; case WMI_10_2_DCS_INTERFERENCE_EVENTID: ath10k_wmi_event_dcs_interference(ar, skb); break; case WMI_10_2_PDEV_TPC_CONFIG_EVENTID: ath10k_wmi_event_pdev_tpc_config(ar, skb); break; case WMI_10_2_INST_RSSI_STATS_EVENTID: ath10k_wmi_event_inst_rssi_stats(ar, skb); break; case WMI_10_2_VDEV_STANDBY_REQ_EVENTID: ath10k_wmi_event_vdev_standby_req(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_VDEV_RESUME_REQ_EVENTID: ath10k_wmi_event_vdev_resume_req(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_SERVICE_READY_EVENTID: ath10k_wmi_event_service_ready(ar, skb); return; case WMI_10_2_READY_EVENTID: ath10k_wmi_event_ready(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_2_PDEV_TEMPERATURE_EVENTID: ath10k_wmi_event_temperature(ar, skb); break; case WMI_10_2_PDEV_BSS_CHAN_INFO_EVENTID: ath10k_wmi_event_pdev_bss_chan_info(ar, skb); break; case WMI_10_2_RTT_KEEPALIVE_EVENTID: case WMI_10_2_GPIO_INPUT_EVENTID: case WMI_10_2_PEER_RATECODE_LIST_EVENTID: case WMI_10_2_GENERIC_BUFFER_EVENTID: case WMI_10_2_MCAST_BUF_RELEASE_EVENTID: case WMI_10_2_MCAST_LIST_AGEOUT_EVENTID: case WMI_10_2_WDS_PEER_EVENTID: ath10k_dbg(ar, ATH10K_DBG_WMI, "received event id %d not implemented\n", id); break; default: ath10k_warn(ar, "Unknown eventid: %d\n", id); break; } out: dev_kfree_skb(skb); } static void ath10k_wmi_10_4_op_rx(struct ath10k *ar, struct sk_buff *skb) { struct wmi_cmd_hdr *cmd_hdr; enum wmi_10_4_event_id id; bool consumed; cmd_hdr = (struct wmi_cmd_hdr *)skb->data; id = MS(__le32_to_cpu(cmd_hdr->cmd_id), WMI_CMD_HDR_CMD_ID); if (!skb_pull(skb, sizeof(struct wmi_cmd_hdr))) goto out; trace_ath10k_wmi_event(ar, id, skb->data, skb->len); consumed = ath10k_tm_event_wmi(ar, id, skb); /* Ready event must be handled normally also in UTF mode so that we * know the UTF firmware has booted, others we are just bypass WMI * events to testmode. */ if (consumed && id != WMI_10_4_READY_EVENTID) { ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi testmode consumed 0x%x\n", id); goto out; } switch (id) { case WMI_10_4_MGMT_RX_EVENTID: ath10k_wmi_event_mgmt_rx(ar, skb); /* mgmt_rx() owns the skb now! */ return; case WMI_10_4_ECHO_EVENTID: ath10k_wmi_event_echo(ar, skb); break; case WMI_10_4_DEBUG_MESG_EVENTID: ath10k_wmi_event_debug_mesg(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_4_SERVICE_READY_EVENTID: ath10k_wmi_event_service_ready(ar, skb); return; case WMI_10_4_SCAN_EVENTID: ath10k_wmi_event_scan(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_4_CHAN_INFO_EVENTID: ath10k_wmi_event_chan_info(ar, skb); break; case WMI_10_4_PHYERR_EVENTID: ath10k_wmi_event_phyerr(ar, skb); break; case WMI_10_4_READY_EVENTID: ath10k_wmi_event_ready(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_4_PEER_STA_KICKOUT_EVENTID: ath10k_wmi_event_peer_sta_kickout(ar, skb); break; case WMI_10_4_ROAM_EVENTID: ath10k_wmi_event_roam(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_4_HOST_SWBA_EVENTID: ath10k_wmi_event_host_swba(ar, skb); break; case WMI_10_4_TBTTOFFSET_UPDATE_EVENTID: ath10k_wmi_event_tbttoffset_update(ar, skb); break; case WMI_10_4_DEBUG_PRINT_EVENTID: ath10k_wmi_event_debug_print(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_4_VDEV_START_RESP_EVENTID: ath10k_wmi_event_vdev_start_resp(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_4_VDEV_STOPPED_EVENTID: ath10k_wmi_event_vdev_stopped(ar, skb); ath10k_wmi_queue_set_coverage_class_work(ar); break; case WMI_10_4_WOW_WAKEUP_HOST_EVENTID: case WMI_10_4_PEER_RATECODE_LIST_EVENTID: case WMI_10_4_WDS_PEER_EVENTID: ath10k_dbg(ar, ATH10K_DBG_WMI, "received event id %d not implemented\n", id); break; case WMI_10_4_UPDATE_STATS_EVENTID: ath10k_wmi_event_update_stats(ar, skb); break; case WMI_10_4_PDEV_TEMPERATURE_EVENTID: ath10k_wmi_event_temperature(ar, skb); break; case WMI_10_4_PDEV_BSS_CHAN_INFO_EVENTID: ath10k_wmi_event_pdev_bss_chan_info(ar, skb); break; case WMI_10_4_PDEV_TPC_CONFIG_EVENTID: ath10k_wmi_event_pdev_tpc_config(ar, skb); break; default: ath10k_warn(ar, "Unknown eventid: %d\n", id); break; } out: dev_kfree_skb(skb); } static void ath10k_wmi_process_rx(struct ath10k *ar, struct sk_buff *skb) { int ret; ret = ath10k_wmi_rx(ar, skb); if (ret) ath10k_warn(ar, "failed to process wmi rx: %d\n", ret); } int ath10k_wmi_connect(struct ath10k *ar) { int status; struct ath10k_htc_svc_conn_req conn_req; struct ath10k_htc_svc_conn_resp conn_resp; memset(&conn_req, 0, sizeof(conn_req)); memset(&conn_resp, 0, sizeof(conn_resp)); /* these fields are the same for all service endpoints */ conn_req.ep_ops.ep_tx_complete = ath10k_wmi_htc_tx_complete; conn_req.ep_ops.ep_rx_complete = ath10k_wmi_process_rx; conn_req.ep_ops.ep_tx_credits = ath10k_wmi_op_ep_tx_credits; /* connect to control service */ conn_req.service_id = ATH10K_HTC_SVC_ID_WMI_CONTROL; status = ath10k_htc_connect_service(&ar->htc, &conn_req, &conn_resp); if (status) { ath10k_warn(ar, "failed to connect to WMI CONTROL service status: %d\n", status); return status; } ar->wmi.eid = conn_resp.eid; return 0; } static struct sk_buff * ath10k_wmi_op_gen_pdev_set_rd(struct ath10k *ar, u16 rd, u16 rd2g, u16 rd5g, u16 ctl2g, u16 ctl5g, enum wmi_dfs_region dfs_reg) { struct wmi_pdev_set_regdomain_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_set_regdomain_cmd *)skb->data; cmd->reg_domain = __cpu_to_le32(rd); cmd->reg_domain_2G = __cpu_to_le32(rd2g); cmd->reg_domain_5G = __cpu_to_le32(rd5g); cmd->conformance_test_limit_2G = __cpu_to_le32(ctl2g); cmd->conformance_test_limit_5G = __cpu_to_le32(ctl5g); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi pdev regdomain rd %x rd2g %x rd5g %x ctl2g %x ctl5g %x\n", rd, rd2g, rd5g, ctl2g, ctl5g); return skb; } static struct sk_buff * ath10k_wmi_10x_op_gen_pdev_set_rd(struct ath10k *ar, u16 rd, u16 rd2g, u16 rd5g, u16 ctl2g, u16 ctl5g, enum wmi_dfs_region dfs_reg) { struct wmi_pdev_set_regdomain_cmd_10x *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_set_regdomain_cmd_10x *)skb->data; cmd->reg_domain = __cpu_to_le32(rd); cmd->reg_domain_2G = __cpu_to_le32(rd2g); cmd->reg_domain_5G = __cpu_to_le32(rd5g); cmd->conformance_test_limit_2G = __cpu_to_le32(ctl2g); cmd->conformance_test_limit_5G = __cpu_to_le32(ctl5g); cmd->dfs_domain = __cpu_to_le32(dfs_reg); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi pdev regdomain rd %x rd2g %x rd5g %x ctl2g %x ctl5g %x dfs_region %x\n", rd, rd2g, rd5g, ctl2g, ctl5g, dfs_reg); return skb; } static struct sk_buff * ath10k_wmi_op_gen_pdev_suspend(struct ath10k *ar, u32 suspend_opt) { struct wmi_pdev_suspend_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_suspend_cmd *)skb->data; cmd->suspend_opt = __cpu_to_le32(suspend_opt); return skb; } static struct sk_buff * ath10k_wmi_op_gen_pdev_resume(struct ath10k *ar) { struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, 0); if (!skb) return ERR_PTR(-ENOMEM); return skb; } static struct sk_buff * ath10k_wmi_op_gen_pdev_set_param(struct ath10k *ar, u32 id, u32 value) { struct wmi_pdev_set_param_cmd *cmd; struct sk_buff *skb; if (id == WMI_PDEV_PARAM_UNSUPPORTED) { ath10k_warn(ar, "pdev param %d not supported by firmware\n", id); return ERR_PTR(-EOPNOTSUPP); } skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_set_param_cmd *)skb->data; cmd->param_id = __cpu_to_le32(id); cmd->param_value = __cpu_to_le32(value); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi pdev set param %d value %d\n", id, value); return skb; } void ath10k_wmi_put_host_mem_chunks(struct ath10k *ar, struct wmi_host_mem_chunks *chunks) { struct host_memory_chunk *chunk; int i; chunks->count = __cpu_to_le32(ar->wmi.num_mem_chunks); for (i = 0; i < ar->wmi.num_mem_chunks; i++) { chunk = &chunks->items[i]; chunk->ptr = __cpu_to_le32(ar->wmi.mem_chunks[i].paddr); chunk->size = __cpu_to_le32(ar->wmi.mem_chunks[i].len); chunk->req_id = __cpu_to_le32(ar->wmi.mem_chunks[i].req_id); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi chunk %d len %d requested, addr 0x%llx\n", i, ar->wmi.mem_chunks[i].len, (unsigned long long)ar->wmi.mem_chunks[i].paddr); } } static struct sk_buff *ath10k_wmi_op_gen_init(struct ath10k *ar) { struct wmi_init_cmd *cmd; struct sk_buff *buf; struct wmi_resource_config config = {}; u32 len, val; config.num_vdevs = __cpu_to_le32(TARGET_NUM_VDEVS); config.num_peers = __cpu_to_le32(TARGET_NUM_PEERS); config.num_offload_peers = __cpu_to_le32(TARGET_NUM_OFFLOAD_PEERS); config.num_offload_reorder_bufs = __cpu_to_le32(TARGET_NUM_OFFLOAD_REORDER_BUFS); config.num_peer_keys = __cpu_to_le32(TARGET_NUM_PEER_KEYS); config.num_tids = __cpu_to_le32(TARGET_NUM_TIDS); config.ast_skid_limit = __cpu_to_le32(TARGET_AST_SKID_LIMIT); config.tx_chain_mask = __cpu_to_le32(TARGET_TX_CHAIN_MASK); config.rx_chain_mask = __cpu_to_le32(TARGET_RX_CHAIN_MASK); config.rx_timeout_pri_vo = __cpu_to_le32(TARGET_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_vi = __cpu_to_le32(TARGET_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_be = __cpu_to_le32(TARGET_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_bk = __cpu_to_le32(TARGET_RX_TIMEOUT_HI_PRI); config.rx_decap_mode = __cpu_to_le32(ar->wmi.rx_decap_mode); config.scan_max_pending_reqs = __cpu_to_le32(TARGET_SCAN_MAX_PENDING_REQS); config.bmiss_offload_max_vdev = __cpu_to_le32(TARGET_BMISS_OFFLOAD_MAX_VDEV); config.roam_offload_max_vdev = __cpu_to_le32(TARGET_ROAM_OFFLOAD_MAX_VDEV); config.roam_offload_max_ap_profiles = __cpu_to_le32(TARGET_ROAM_OFFLOAD_MAX_AP_PROFILES); config.num_mcast_groups = __cpu_to_le32(TARGET_NUM_MCAST_GROUPS); config.num_mcast_table_elems = __cpu_to_le32(TARGET_NUM_MCAST_TABLE_ELEMS); config.mcast2ucast_mode = __cpu_to_le32(TARGET_MCAST2UCAST_MODE); config.tx_dbg_log_size = __cpu_to_le32(TARGET_TX_DBG_LOG_SIZE); config.num_wds_entries = __cpu_to_le32(TARGET_NUM_WDS_ENTRIES); config.dma_burst_size = __cpu_to_le32(TARGET_DMA_BURST_SIZE); config.mac_aggr_delim = __cpu_to_le32(TARGET_MAC_AGGR_DELIM); val = TARGET_RX_SKIP_DEFRAG_TIMEOUT_DUP_DETECTION_CHECK; config.rx_skip_defrag_timeout_dup_detection_check = __cpu_to_le32(val); config.vow_config = __cpu_to_le32(TARGET_VOW_CONFIG); config.gtk_offload_max_vdev = __cpu_to_le32(TARGET_GTK_OFFLOAD_MAX_VDEV); config.num_msdu_desc = __cpu_to_le32(TARGET_NUM_MSDU_DESC); config.max_frag_entries = __cpu_to_le32(TARGET_MAX_FRAG_ENTRIES); len = sizeof(*cmd) + (sizeof(struct host_memory_chunk) * ar->wmi.num_mem_chunks); buf = ath10k_wmi_alloc_skb(ar, len); if (!buf) return ERR_PTR(-ENOMEM); cmd = (struct wmi_init_cmd *)buf->data; memcpy(&cmd->resource_config, &config, sizeof(config)); ath10k_wmi_put_host_mem_chunks(ar, &cmd->mem_chunks); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi init\n"); return buf; } static struct sk_buff *ath10k_wmi_10_1_op_gen_init(struct ath10k *ar) { struct wmi_init_cmd_10x *cmd; struct sk_buff *buf; struct wmi_resource_config_10x config = {}; u32 len, val; config.num_vdevs = __cpu_to_le32(TARGET_10X_NUM_VDEVS); config.num_peers = __cpu_to_le32(TARGET_10X_NUM_PEERS); config.num_peer_keys = __cpu_to_le32(TARGET_10X_NUM_PEER_KEYS); config.num_tids = __cpu_to_le32(TARGET_10X_NUM_TIDS); config.ast_skid_limit = __cpu_to_le32(TARGET_10X_AST_SKID_LIMIT); config.tx_chain_mask = __cpu_to_le32(TARGET_10X_TX_CHAIN_MASK); config.rx_chain_mask = __cpu_to_le32(TARGET_10X_RX_CHAIN_MASK); config.rx_timeout_pri_vo = __cpu_to_le32(TARGET_10X_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_vi = __cpu_to_le32(TARGET_10X_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_be = __cpu_to_le32(TARGET_10X_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_bk = __cpu_to_le32(TARGET_10X_RX_TIMEOUT_HI_PRI); config.rx_decap_mode = __cpu_to_le32(ar->wmi.rx_decap_mode); config.scan_max_pending_reqs = __cpu_to_le32(TARGET_10X_SCAN_MAX_PENDING_REQS); config.bmiss_offload_max_vdev = __cpu_to_le32(TARGET_10X_BMISS_OFFLOAD_MAX_VDEV); config.roam_offload_max_vdev = __cpu_to_le32(TARGET_10X_ROAM_OFFLOAD_MAX_VDEV); config.roam_offload_max_ap_profiles = __cpu_to_le32(TARGET_10X_ROAM_OFFLOAD_MAX_AP_PROFILES); config.num_mcast_groups = __cpu_to_le32(TARGET_10X_NUM_MCAST_GROUPS); config.num_mcast_table_elems = __cpu_to_le32(TARGET_10X_NUM_MCAST_TABLE_ELEMS); config.mcast2ucast_mode = __cpu_to_le32(TARGET_10X_MCAST2UCAST_MODE); config.tx_dbg_log_size = __cpu_to_le32(TARGET_10X_TX_DBG_LOG_SIZE); config.num_wds_entries = __cpu_to_le32(TARGET_10X_NUM_WDS_ENTRIES); config.dma_burst_size = __cpu_to_le32(TARGET_10X_DMA_BURST_SIZE); config.mac_aggr_delim = __cpu_to_le32(TARGET_10X_MAC_AGGR_DELIM); val = TARGET_10X_RX_SKIP_DEFRAG_TIMEOUT_DUP_DETECTION_CHECK; config.rx_skip_defrag_timeout_dup_detection_check = __cpu_to_le32(val); config.vow_config = __cpu_to_le32(TARGET_10X_VOW_CONFIG); config.num_msdu_desc = __cpu_to_le32(TARGET_10X_NUM_MSDU_DESC); config.max_frag_entries = __cpu_to_le32(TARGET_10X_MAX_FRAG_ENTRIES); len = sizeof(*cmd) + (sizeof(struct host_memory_chunk) * ar->wmi.num_mem_chunks); buf = ath10k_wmi_alloc_skb(ar, len); if (!buf) return ERR_PTR(-ENOMEM); cmd = (struct wmi_init_cmd_10x *)buf->data; memcpy(&cmd->resource_config, &config, sizeof(config)); ath10k_wmi_put_host_mem_chunks(ar, &cmd->mem_chunks); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi init 10x\n"); return buf; } static struct sk_buff *ath10k_wmi_10_2_op_gen_init(struct ath10k *ar) { struct wmi_init_cmd_10_2 *cmd; struct sk_buff *buf; struct wmi_resource_config_10x config = {}; u32 len, val, features; config.num_vdevs = __cpu_to_le32(TARGET_10X_NUM_VDEVS); config.num_peer_keys = __cpu_to_le32(TARGET_10X_NUM_PEER_KEYS); if (ath10k_peer_stats_enabled(ar)) { config.num_peers = __cpu_to_le32(TARGET_10X_TX_STATS_NUM_PEERS); config.num_tids = __cpu_to_le32(TARGET_10X_TX_STATS_NUM_TIDS); } else { config.num_peers = __cpu_to_le32(TARGET_10X_NUM_PEERS); config.num_tids = __cpu_to_le32(TARGET_10X_NUM_TIDS); } config.ast_skid_limit = __cpu_to_le32(TARGET_10X_AST_SKID_LIMIT); config.tx_chain_mask = __cpu_to_le32(TARGET_10X_TX_CHAIN_MASK); config.rx_chain_mask = __cpu_to_le32(TARGET_10X_RX_CHAIN_MASK); config.rx_timeout_pri_vo = __cpu_to_le32(TARGET_10X_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_vi = __cpu_to_le32(TARGET_10X_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_be = __cpu_to_le32(TARGET_10X_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri_bk = __cpu_to_le32(TARGET_10X_RX_TIMEOUT_HI_PRI); config.rx_decap_mode = __cpu_to_le32(ar->wmi.rx_decap_mode); config.scan_max_pending_reqs = __cpu_to_le32(TARGET_10X_SCAN_MAX_PENDING_REQS); config.bmiss_offload_max_vdev = __cpu_to_le32(TARGET_10X_BMISS_OFFLOAD_MAX_VDEV); config.roam_offload_max_vdev = __cpu_to_le32(TARGET_10X_ROAM_OFFLOAD_MAX_VDEV); config.roam_offload_max_ap_profiles = __cpu_to_le32(TARGET_10X_ROAM_OFFLOAD_MAX_AP_PROFILES); config.num_mcast_groups = __cpu_to_le32(TARGET_10X_NUM_MCAST_GROUPS); config.num_mcast_table_elems = __cpu_to_le32(TARGET_10X_NUM_MCAST_TABLE_ELEMS); config.mcast2ucast_mode = __cpu_to_le32(TARGET_10X_MCAST2UCAST_MODE); config.tx_dbg_log_size = __cpu_to_le32(TARGET_10X_TX_DBG_LOG_SIZE); config.num_wds_entries = __cpu_to_le32(TARGET_10X_NUM_WDS_ENTRIES); config.dma_burst_size = __cpu_to_le32(TARGET_10_2_DMA_BURST_SIZE); config.mac_aggr_delim = __cpu_to_le32(TARGET_10X_MAC_AGGR_DELIM); val = TARGET_10X_RX_SKIP_DEFRAG_TIMEOUT_DUP_DETECTION_CHECK; config.rx_skip_defrag_timeout_dup_detection_check = __cpu_to_le32(val); config.vow_config = __cpu_to_le32(TARGET_10X_VOW_CONFIG); config.num_msdu_desc = __cpu_to_le32(TARGET_10X_NUM_MSDU_DESC); config.max_frag_entries = __cpu_to_le32(TARGET_10X_MAX_FRAG_ENTRIES); len = sizeof(*cmd) + (sizeof(struct host_memory_chunk) * ar->wmi.num_mem_chunks); buf = ath10k_wmi_alloc_skb(ar, len); if (!buf) return ERR_PTR(-ENOMEM); cmd = (struct wmi_init_cmd_10_2 *)buf->data; features = WMI_10_2_RX_BATCH_MODE; if (test_bit(ATH10K_FLAG_BTCOEX, &ar->dev_flags) && test_bit(WMI_SERVICE_COEX_GPIO, ar->wmi.svc_map)) features |= WMI_10_2_COEX_GPIO; if (ath10k_peer_stats_enabled(ar)) features |= WMI_10_2_PEER_STATS; if (test_bit(WMI_SERVICE_BSS_CHANNEL_INFO_64, ar->wmi.svc_map)) features |= WMI_10_2_BSS_CHAN_INFO; cmd->resource_config.feature_mask = __cpu_to_le32(features); memcpy(&cmd->resource_config.common, &config, sizeof(config)); ath10k_wmi_put_host_mem_chunks(ar, &cmd->mem_chunks); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi init 10.2\n"); return buf; } static struct sk_buff *ath10k_wmi_10_4_op_gen_init(struct ath10k *ar) { struct wmi_init_cmd_10_4 *cmd; struct sk_buff *buf; struct wmi_resource_config_10_4 config = {}; u32 len; config.num_vdevs = __cpu_to_le32(ar->max_num_vdevs); config.num_peers = __cpu_to_le32(ar->max_num_peers); config.num_active_peers = __cpu_to_le32(ar->num_active_peers); config.num_tids = __cpu_to_le32(ar->num_tids); config.num_offload_peers = __cpu_to_le32(TARGET_10_4_NUM_OFFLOAD_PEERS); config.num_offload_reorder_buffs = __cpu_to_le32(TARGET_10_4_NUM_OFFLOAD_REORDER_BUFFS); config.num_peer_keys = __cpu_to_le32(TARGET_10_4_NUM_PEER_KEYS); config.ast_skid_limit = __cpu_to_le32(TARGET_10_4_AST_SKID_LIMIT); config.tx_chain_mask = __cpu_to_le32(ar->hw_params.tx_chain_mask); config.rx_chain_mask = __cpu_to_le32(ar->hw_params.rx_chain_mask); config.rx_timeout_pri[0] = __cpu_to_le32(TARGET_10_4_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri[1] = __cpu_to_le32(TARGET_10_4_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri[2] = __cpu_to_le32(TARGET_10_4_RX_TIMEOUT_LO_PRI); config.rx_timeout_pri[3] = __cpu_to_le32(TARGET_10_4_RX_TIMEOUT_HI_PRI); config.rx_decap_mode = __cpu_to_le32(ar->wmi.rx_decap_mode); config.scan_max_pending_req = __cpu_to_le32(TARGET_10_4_SCAN_MAX_REQS); config.bmiss_offload_max_vdev = __cpu_to_le32(TARGET_10_4_BMISS_OFFLOAD_MAX_VDEV); config.roam_offload_max_vdev = __cpu_to_le32(TARGET_10_4_ROAM_OFFLOAD_MAX_VDEV); config.roam_offload_max_ap_profiles = __cpu_to_le32(TARGET_10_4_ROAM_OFFLOAD_MAX_PROFILES); config.num_mcast_groups = __cpu_to_le32(TARGET_10_4_NUM_MCAST_GROUPS); config.num_mcast_table_elems = __cpu_to_le32(TARGET_10_4_NUM_MCAST_TABLE_ELEMS); config.mcast2ucast_mode = __cpu_to_le32(TARGET_10_4_MCAST2UCAST_MODE); config.tx_dbg_log_size = __cpu_to_le32(TARGET_10_4_TX_DBG_LOG_SIZE); config.num_wds_entries = __cpu_to_le32(TARGET_10_4_NUM_WDS_ENTRIES); config.dma_burst_size = __cpu_to_le32(TARGET_10_4_DMA_BURST_SIZE); config.mac_aggr_delim = __cpu_to_le32(TARGET_10_4_MAC_AGGR_DELIM); config.rx_skip_defrag_timeout_dup_detection_check = __cpu_to_le32(TARGET_10_4_RX_SKIP_DEFRAG_TIMEOUT_DUP_DETECTION_CHECK); config.vow_config = __cpu_to_le32(TARGET_10_4_VOW_CONFIG); config.gtk_offload_max_vdev = __cpu_to_le32(TARGET_10_4_GTK_OFFLOAD_MAX_VDEV); config.num_msdu_desc = __cpu_to_le32(ar->htt.max_num_pending_tx); config.max_frag_entries = __cpu_to_le32(TARGET_10_4_11AC_TX_MAX_FRAGS); config.max_peer_ext_stats = __cpu_to_le32(TARGET_10_4_MAX_PEER_EXT_STATS); config.smart_ant_cap = __cpu_to_le32(TARGET_10_4_SMART_ANT_CAP); config.bk_minfree = __cpu_to_le32(TARGET_10_4_BK_MIN_FREE); config.be_minfree = __cpu_to_le32(TARGET_10_4_BE_MIN_FREE); config.vi_minfree = __cpu_to_le32(TARGET_10_4_VI_MIN_FREE); config.vo_minfree = __cpu_to_le32(TARGET_10_4_VO_MIN_FREE); config.rx_batchmode = __cpu_to_le32(TARGET_10_4_RX_BATCH_MODE); config.tt_support = __cpu_to_le32(TARGET_10_4_THERMAL_THROTTLING_CONFIG); config.atf_config = __cpu_to_le32(TARGET_10_4_ATF_CONFIG); config.iphdr_pad_config = __cpu_to_le32(TARGET_10_4_IPHDR_PAD_CONFIG); config.qwrap_config = __cpu_to_le32(TARGET_10_4_QWRAP_CONFIG); len = sizeof(*cmd) + (sizeof(struct host_memory_chunk) * ar->wmi.num_mem_chunks); buf = ath10k_wmi_alloc_skb(ar, len); if (!buf) return ERR_PTR(-ENOMEM); cmd = (struct wmi_init_cmd_10_4 *)buf->data; memcpy(&cmd->resource_config, &config, sizeof(config)); ath10k_wmi_put_host_mem_chunks(ar, &cmd->mem_chunks); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi init 10.4\n"); return buf; } int ath10k_wmi_start_scan_verify(const struct wmi_start_scan_arg *arg) { if (arg->ie_len && !arg->ie) return -EINVAL; if (arg->n_channels && !arg->channels) return -EINVAL; if (arg->n_ssids && !arg->ssids) return -EINVAL; if (arg->n_bssids && !arg->bssids) return -EINVAL; if (arg->ie_len > WLAN_SCAN_PARAMS_MAX_IE_LEN) return -EINVAL; if (arg->n_channels > ARRAY_SIZE(arg->channels)) return -EINVAL; if (arg->n_ssids > WLAN_SCAN_PARAMS_MAX_SSID) return -EINVAL; if (arg->n_bssids > WLAN_SCAN_PARAMS_MAX_BSSID) return -EINVAL; return 0; } static size_t ath10k_wmi_start_scan_tlvs_len(const struct wmi_start_scan_arg *arg) { int len = 0; if (arg->ie_len) { len += sizeof(struct wmi_ie_data); len += roundup(arg->ie_len, 4); } if (arg->n_channels) { len += sizeof(struct wmi_chan_list); len += sizeof(__le32) * arg->n_channels; } if (arg->n_ssids) { len += sizeof(struct wmi_ssid_list); len += sizeof(struct wmi_ssid) * arg->n_ssids; } if (arg->n_bssids) { len += sizeof(struct wmi_bssid_list); len += sizeof(struct wmi_mac_addr) * arg->n_bssids; } return len; } void ath10k_wmi_put_start_scan_common(struct wmi_start_scan_common *cmn, const struct wmi_start_scan_arg *arg) { u32 scan_id; u32 scan_req_id; scan_id = WMI_HOST_SCAN_REQ_ID_PREFIX; scan_id |= arg->scan_id; scan_req_id = WMI_HOST_SCAN_REQUESTOR_ID_PREFIX; scan_req_id |= arg->scan_req_id; cmn->scan_id = __cpu_to_le32(scan_id); cmn->scan_req_id = __cpu_to_le32(scan_req_id); cmn->vdev_id = __cpu_to_le32(arg->vdev_id); cmn->scan_priority = __cpu_to_le32(arg->scan_priority); cmn->notify_scan_events = __cpu_to_le32(arg->notify_scan_events); cmn->dwell_time_active = __cpu_to_le32(arg->dwell_time_active); cmn->dwell_time_passive = __cpu_to_le32(arg->dwell_time_passive); cmn->min_rest_time = __cpu_to_le32(arg->min_rest_time); cmn->max_rest_time = __cpu_to_le32(arg->max_rest_time); cmn->repeat_probe_time = __cpu_to_le32(arg->repeat_probe_time); cmn->probe_spacing_time = __cpu_to_le32(arg->probe_spacing_time); cmn->idle_time = __cpu_to_le32(arg->idle_time); cmn->max_scan_time = __cpu_to_le32(arg->max_scan_time); cmn->probe_delay = __cpu_to_le32(arg->probe_delay); cmn->scan_ctrl_flags = __cpu_to_le32(arg->scan_ctrl_flags); } static void ath10k_wmi_put_start_scan_tlvs(struct wmi_start_scan_tlvs *tlvs, const struct wmi_start_scan_arg *arg) { struct wmi_ie_data *ie; struct wmi_chan_list *channels; struct wmi_ssid_list *ssids; struct wmi_bssid_list *bssids; void *ptr = tlvs->tlvs; int i; if (arg->n_channels) { channels = ptr; channels->tag = __cpu_to_le32(WMI_CHAN_LIST_TAG); channels->num_chan = __cpu_to_le32(arg->n_channels); for (i = 0; i < arg->n_channels; i++) channels->channel_list[i].freq = __cpu_to_le16(arg->channels[i]); ptr += sizeof(*channels); ptr += sizeof(__le32) * arg->n_channels; } if (arg->n_ssids) { ssids = ptr; ssids->tag = __cpu_to_le32(WMI_SSID_LIST_TAG); ssids->num_ssids = __cpu_to_le32(arg->n_ssids); for (i = 0; i < arg->n_ssids; i++) { ssids->ssids[i].ssid_len = __cpu_to_le32(arg->ssids[i].len); memcpy(&ssids->ssids[i].ssid, arg->ssids[i].ssid, arg->ssids[i].len); } ptr += sizeof(*ssids); ptr += sizeof(struct wmi_ssid) * arg->n_ssids; } if (arg->n_bssids) { bssids = ptr; bssids->tag = __cpu_to_le32(WMI_BSSID_LIST_TAG); bssids->num_bssid = __cpu_to_le32(arg->n_bssids); for (i = 0; i < arg->n_bssids; i++) ether_addr_copy(bssids->bssid_list[i].addr, arg->bssids[i].bssid); ptr += sizeof(*bssids); ptr += sizeof(struct wmi_mac_addr) * arg->n_bssids; } if (arg->ie_len) { ie = ptr; ie->tag = __cpu_to_le32(WMI_IE_TAG); ie->ie_len = __cpu_to_le32(arg->ie_len); memcpy(ie->ie_data, arg->ie, arg->ie_len); ptr += sizeof(*ie); ptr += roundup(arg->ie_len, 4); } } static struct sk_buff * ath10k_wmi_op_gen_start_scan(struct ath10k *ar, const struct wmi_start_scan_arg *arg) { struct wmi_start_scan_cmd *cmd; struct sk_buff *skb; size_t len; int ret; ret = ath10k_wmi_start_scan_verify(arg); if (ret) return ERR_PTR(ret); len = sizeof(*cmd) + ath10k_wmi_start_scan_tlvs_len(arg); skb = ath10k_wmi_alloc_skb(ar, len); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_start_scan_cmd *)skb->data; ath10k_wmi_put_start_scan_common(&cmd->common, arg); ath10k_wmi_put_start_scan_tlvs(&cmd->tlvs, arg); cmd->burst_duration_ms = __cpu_to_le32(0); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi start scan\n"); return skb; } static struct sk_buff * ath10k_wmi_10x_op_gen_start_scan(struct ath10k *ar, const struct wmi_start_scan_arg *arg) { struct wmi_10x_start_scan_cmd *cmd; struct sk_buff *skb; size_t len; int ret; ret = ath10k_wmi_start_scan_verify(arg); if (ret) return ERR_PTR(ret); len = sizeof(*cmd) + ath10k_wmi_start_scan_tlvs_len(arg); skb = ath10k_wmi_alloc_skb(ar, len); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_10x_start_scan_cmd *)skb->data; ath10k_wmi_put_start_scan_common(&cmd->common, arg); ath10k_wmi_put_start_scan_tlvs(&cmd->tlvs, arg); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi 10x start scan\n"); return skb; } void ath10k_wmi_start_scan_init(struct ath10k *ar, struct wmi_start_scan_arg *arg) { /* setup commonly used values */ arg->scan_req_id = 1; arg->scan_priority = WMI_SCAN_PRIORITY_LOW; arg->dwell_time_active = 50; arg->dwell_time_passive = 150; arg->min_rest_time = 50; arg->max_rest_time = 500; arg->repeat_probe_time = 0; arg->probe_spacing_time = 0; arg->idle_time = 0; arg->max_scan_time = 20000; arg->probe_delay = 5; arg->notify_scan_events = WMI_SCAN_EVENT_STARTED | WMI_SCAN_EVENT_COMPLETED | WMI_SCAN_EVENT_BSS_CHANNEL | WMI_SCAN_EVENT_FOREIGN_CHANNEL | WMI_SCAN_EVENT_FOREIGN_CHANNEL_EXIT | WMI_SCAN_EVENT_DEQUEUED; arg->scan_ctrl_flags |= WMI_SCAN_CHAN_STAT_EVENT; arg->n_bssids = 1; arg->bssids[0].bssid = "\xFF\xFF\xFF\xFF\xFF\xFF"; } static struct sk_buff * ath10k_wmi_op_gen_stop_scan(struct ath10k *ar, const struct wmi_stop_scan_arg *arg) { struct wmi_stop_scan_cmd *cmd; struct sk_buff *skb; u32 scan_id; u32 req_id; if (arg->req_id > 0xFFF) return ERR_PTR(-EINVAL); if (arg->req_type == WMI_SCAN_STOP_ONE && arg->u.scan_id > 0xFFF) return ERR_PTR(-EINVAL); skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); scan_id = arg->u.scan_id; scan_id |= WMI_HOST_SCAN_REQ_ID_PREFIX; req_id = arg->req_id; req_id |= WMI_HOST_SCAN_REQUESTOR_ID_PREFIX; cmd = (struct wmi_stop_scan_cmd *)skb->data; cmd->req_type = __cpu_to_le32(arg->req_type); cmd->vdev_id = __cpu_to_le32(arg->u.vdev_id); cmd->scan_id = __cpu_to_le32(scan_id); cmd->scan_req_id = __cpu_to_le32(req_id); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi stop scan reqid %d req_type %d vdev/scan_id %d\n", arg->req_id, arg->req_type, arg->u.scan_id); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_create(struct ath10k *ar, u32 vdev_id, enum wmi_vdev_type type, enum wmi_vdev_subtype subtype, const u8 macaddr[ETH_ALEN]) { struct wmi_vdev_create_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_create_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->vdev_type = __cpu_to_le32(type); cmd->vdev_subtype = __cpu_to_le32(subtype); ether_addr_copy(cmd->vdev_macaddr.addr, macaddr); ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI vdev create: id %d type %d subtype %d macaddr %pM\n", vdev_id, type, subtype, macaddr); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_delete(struct ath10k *ar, u32 vdev_id) { struct wmi_vdev_delete_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_delete_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ath10k_dbg(ar, ATH10K_DBG_WMI, "WMI vdev delete id %d\n", vdev_id); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_start(struct ath10k *ar, const struct wmi_vdev_start_request_arg *arg, bool restart) { struct wmi_vdev_start_request_cmd *cmd; struct sk_buff *skb; const char *cmdname; u32 flags = 0; if (WARN_ON(arg->hidden_ssid && !arg->ssid)) return ERR_PTR(-EINVAL); if (WARN_ON(arg->ssid_len > sizeof(cmd->ssid.ssid))) return ERR_PTR(-EINVAL); if (restart) cmdname = "restart"; else cmdname = "start"; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); if (arg->hidden_ssid) flags |= WMI_VDEV_START_HIDDEN_SSID; if (arg->pmf_enabled) flags |= WMI_VDEV_START_PMF_ENABLED; cmd = (struct wmi_vdev_start_request_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(arg->vdev_id); cmd->disable_hw_ack = __cpu_to_le32(arg->disable_hw_ack); cmd->beacon_interval = __cpu_to_le32(arg->bcn_intval); cmd->dtim_period = __cpu_to_le32(arg->dtim_period); cmd->flags = __cpu_to_le32(flags); cmd->bcn_tx_rate = __cpu_to_le32(arg->bcn_tx_rate); cmd->bcn_tx_power = __cpu_to_le32(arg->bcn_tx_power); if (arg->ssid) { cmd->ssid.ssid_len = __cpu_to_le32(arg->ssid_len); memcpy(cmd->ssid.ssid, arg->ssid, arg->ssid_len); } ath10k_wmi_put_wmi_channel(&cmd->chan, &arg->channel); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi vdev %s id 0x%x flags: 0x%0X, freq %d, mode %d, ch_flags: 0x%0X, max_power: %d\n", cmdname, arg->vdev_id, flags, arg->channel.freq, arg->channel.mode, cmd->chan.flags, arg->channel.max_power); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_stop(struct ath10k *ar, u32 vdev_id) { struct wmi_vdev_stop_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_stop_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi vdev stop id 0x%x\n", vdev_id); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_up(struct ath10k *ar, u32 vdev_id, u32 aid, const u8 *bssid) { struct wmi_vdev_up_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_up_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->vdev_assoc_id = __cpu_to_le32(aid); ether_addr_copy(cmd->vdev_bssid.addr, bssid); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi mgmt vdev up id 0x%x assoc id %d bssid %pM\n", vdev_id, aid, bssid); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_down(struct ath10k *ar, u32 vdev_id) { struct wmi_vdev_down_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_down_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi mgmt vdev down id 0x%x\n", vdev_id); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_set_param(struct ath10k *ar, u32 vdev_id, u32 param_id, u32 param_value) { struct wmi_vdev_set_param_cmd *cmd; struct sk_buff *skb; if (param_id == WMI_VDEV_PARAM_UNSUPPORTED) { ath10k_dbg(ar, ATH10K_DBG_WMI, "vdev param %d not supported by firmware\n", param_id); return ERR_PTR(-EOPNOTSUPP); } skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_set_param_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->param_id = __cpu_to_le32(param_id); cmd->param_value = __cpu_to_le32(param_value); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi vdev id 0x%x set param %d value %d\n", vdev_id, param_id, param_value); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_install_key(struct ath10k *ar, const struct wmi_vdev_install_key_arg *arg) { struct wmi_vdev_install_key_cmd *cmd; struct sk_buff *skb; if (arg->key_cipher == WMI_CIPHER_NONE && arg->key_data != NULL) return ERR_PTR(-EINVAL); if (arg->key_cipher != WMI_CIPHER_NONE && arg->key_data == NULL) return ERR_PTR(-EINVAL); skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd) + arg->key_len); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_install_key_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(arg->vdev_id); cmd->key_idx = __cpu_to_le32(arg->key_idx); cmd->key_flags = __cpu_to_le32(arg->key_flags); cmd->key_cipher = __cpu_to_le32(arg->key_cipher); cmd->key_len = __cpu_to_le32(arg->key_len); cmd->key_txmic_len = __cpu_to_le32(arg->key_txmic_len); cmd->key_rxmic_len = __cpu_to_le32(arg->key_rxmic_len); if (arg->macaddr) ether_addr_copy(cmd->peer_macaddr.addr, arg->macaddr); if (arg->key_data) memcpy(cmd->key_data, arg->key_data, arg->key_len); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi vdev install key idx %d cipher %d len %d\n", arg->key_idx, arg->key_cipher, arg->key_len); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_spectral_conf(struct ath10k *ar, const struct wmi_vdev_spectral_conf_arg *arg) { struct wmi_vdev_spectral_conf_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_spectral_conf_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(arg->vdev_id); cmd->scan_count = __cpu_to_le32(arg->scan_count); cmd->scan_period = __cpu_to_le32(arg->scan_period); cmd->scan_priority = __cpu_to_le32(arg->scan_priority); cmd->scan_fft_size = __cpu_to_le32(arg->scan_fft_size); cmd->scan_gc_ena = __cpu_to_le32(arg->scan_gc_ena); cmd->scan_restart_ena = __cpu_to_le32(arg->scan_restart_ena); cmd->scan_noise_floor_ref = __cpu_to_le32(arg->scan_noise_floor_ref); cmd->scan_init_delay = __cpu_to_le32(arg->scan_init_delay); cmd->scan_nb_tone_thr = __cpu_to_le32(arg->scan_nb_tone_thr); cmd->scan_str_bin_thr = __cpu_to_le32(arg->scan_str_bin_thr); cmd->scan_wb_rpt_mode = __cpu_to_le32(arg->scan_wb_rpt_mode); cmd->scan_rssi_rpt_mode = __cpu_to_le32(arg->scan_rssi_rpt_mode); cmd->scan_rssi_thr = __cpu_to_le32(arg->scan_rssi_thr); cmd->scan_pwr_format = __cpu_to_le32(arg->scan_pwr_format); cmd->scan_rpt_mode = __cpu_to_le32(arg->scan_rpt_mode); cmd->scan_bin_scale = __cpu_to_le32(arg->scan_bin_scale); cmd->scan_dbm_adj = __cpu_to_le32(arg->scan_dbm_adj); cmd->scan_chn_mask = __cpu_to_le32(arg->scan_chn_mask); return skb; } static struct sk_buff * ath10k_wmi_op_gen_vdev_spectral_enable(struct ath10k *ar, u32 vdev_id, u32 trigger, u32 enable) { struct wmi_vdev_spectral_enable_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_vdev_spectral_enable_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->trigger_cmd = __cpu_to_le32(trigger); cmd->enable_cmd = __cpu_to_le32(enable); return skb; } static struct sk_buff * ath10k_wmi_op_gen_peer_create(struct ath10k *ar, u32 vdev_id, const u8 peer_addr[ETH_ALEN], enum wmi_peer_type peer_type) { struct wmi_peer_create_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_peer_create_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ether_addr_copy(cmd->peer_macaddr.addr, peer_addr); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi peer create vdev_id %d peer_addr %pM\n", vdev_id, peer_addr); return skb; } static struct sk_buff * ath10k_wmi_op_gen_peer_delete(struct ath10k *ar, u32 vdev_id, const u8 peer_addr[ETH_ALEN]) { struct wmi_peer_delete_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_peer_delete_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ether_addr_copy(cmd->peer_macaddr.addr, peer_addr); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi peer delete vdev_id %d peer_addr %pM\n", vdev_id, peer_addr); return skb; } static struct sk_buff * ath10k_wmi_op_gen_peer_flush(struct ath10k *ar, u32 vdev_id, const u8 peer_addr[ETH_ALEN], u32 tid_bitmap) { struct wmi_peer_flush_tids_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_peer_flush_tids_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->peer_tid_bitmap = __cpu_to_le32(tid_bitmap); ether_addr_copy(cmd->peer_macaddr.addr, peer_addr); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi peer flush vdev_id %d peer_addr %pM tids %08x\n", vdev_id, peer_addr, tid_bitmap); return skb; } static struct sk_buff * ath10k_wmi_op_gen_peer_set_param(struct ath10k *ar, u32 vdev_id, const u8 *peer_addr, enum wmi_peer_param param_id, u32 param_value) { struct wmi_peer_set_param_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_peer_set_param_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->param_id = __cpu_to_le32(param_id); cmd->param_value = __cpu_to_le32(param_value); ether_addr_copy(cmd->peer_macaddr.addr, peer_addr); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi vdev %d peer 0x%pM set param %d value %d\n", vdev_id, peer_addr, param_id, param_value); return skb; } static struct sk_buff * ath10k_wmi_op_gen_set_psmode(struct ath10k *ar, u32 vdev_id, enum wmi_sta_ps_mode psmode) { struct wmi_sta_powersave_mode_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_sta_powersave_mode_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->sta_ps_mode = __cpu_to_le32(psmode); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi set powersave id 0x%x mode %d\n", vdev_id, psmode); return skb; } static struct sk_buff * ath10k_wmi_op_gen_set_sta_ps(struct ath10k *ar, u32 vdev_id, enum wmi_sta_powersave_param param_id, u32 value) { struct wmi_sta_powersave_param_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_sta_powersave_param_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->param_id = __cpu_to_le32(param_id); cmd->param_value = __cpu_to_le32(value); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi sta ps param vdev_id 0x%x param %d value %d\n", vdev_id, param_id, value); return skb; } static struct sk_buff * ath10k_wmi_op_gen_set_ap_ps(struct ath10k *ar, u32 vdev_id, const u8 *mac, enum wmi_ap_ps_peer_param param_id, u32 value) { struct wmi_ap_ps_peer_cmd *cmd; struct sk_buff *skb; if (!mac) return ERR_PTR(-EINVAL); skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_ap_ps_peer_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->param_id = __cpu_to_le32(param_id); cmd->param_value = __cpu_to_le32(value); ether_addr_copy(cmd->peer_macaddr.addr, mac); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi ap ps param vdev_id 0x%X param %d value %d mac_addr %pM\n", vdev_id, param_id, value, mac); return skb; } static struct sk_buff * ath10k_wmi_op_gen_scan_chan_list(struct ath10k *ar, const struct wmi_scan_chan_list_arg *arg) { struct wmi_scan_chan_list_cmd *cmd; struct sk_buff *skb; struct wmi_channel_arg *ch; struct wmi_channel *ci; int len; int i; len = sizeof(*cmd) + arg->n_channels * sizeof(struct wmi_channel); skb = ath10k_wmi_alloc_skb(ar, len); if (!skb) return ERR_PTR(-EINVAL); cmd = (struct wmi_scan_chan_list_cmd *)skb->data; cmd->num_scan_chans = __cpu_to_le32(arg->n_channels); for (i = 0; i < arg->n_channels; i++) { ch = &arg->channels[i]; ci = &cmd->chan_info[i]; ath10k_wmi_put_wmi_channel(ci, ch); } return skb; } static void ath10k_wmi_peer_assoc_fill(struct ath10k *ar, void *buf, const struct wmi_peer_assoc_complete_arg *arg) { struct wmi_common_peer_assoc_complete_cmd *cmd = buf; cmd->vdev_id = __cpu_to_le32(arg->vdev_id); cmd->peer_new_assoc = __cpu_to_le32(arg->peer_reassoc ? 0 : 1); cmd->peer_associd = __cpu_to_le32(arg->peer_aid); cmd->peer_flags = __cpu_to_le32(arg->peer_flags); cmd->peer_caps = __cpu_to_le32(arg->peer_caps); cmd->peer_listen_intval = __cpu_to_le32(arg->peer_listen_intval); cmd->peer_ht_caps = __cpu_to_le32(arg->peer_ht_caps); cmd->peer_max_mpdu = __cpu_to_le32(arg->peer_max_mpdu); cmd->peer_mpdu_density = __cpu_to_le32(arg->peer_mpdu_density); cmd->peer_rate_caps = __cpu_to_le32(arg->peer_rate_caps); cmd->peer_nss = __cpu_to_le32(arg->peer_num_spatial_streams); cmd->peer_vht_caps = __cpu_to_le32(arg->peer_vht_caps); cmd->peer_phymode = __cpu_to_le32(arg->peer_phymode); ether_addr_copy(cmd->peer_macaddr.addr, arg->addr); cmd->peer_legacy_rates.num_rates = __cpu_to_le32(arg->peer_legacy_rates.num_rates); memcpy(cmd->peer_legacy_rates.rates, arg->peer_legacy_rates.rates, arg->peer_legacy_rates.num_rates); cmd->peer_ht_rates.num_rates = __cpu_to_le32(arg->peer_ht_rates.num_rates); memcpy(cmd->peer_ht_rates.rates, arg->peer_ht_rates.rates, arg->peer_ht_rates.num_rates); cmd->peer_vht_rates.rx_max_rate = __cpu_to_le32(arg->peer_vht_rates.rx_max_rate); cmd->peer_vht_rates.rx_mcs_set = __cpu_to_le32(arg->peer_vht_rates.rx_mcs_set); cmd->peer_vht_rates.tx_max_rate = __cpu_to_le32(arg->peer_vht_rates.tx_max_rate); cmd->peer_vht_rates.tx_mcs_set = __cpu_to_le32(arg->peer_vht_rates.tx_mcs_set); } static void ath10k_wmi_peer_assoc_fill_main(struct ath10k *ar, void *buf, const struct wmi_peer_assoc_complete_arg *arg) { struct wmi_main_peer_assoc_complete_cmd *cmd = buf; ath10k_wmi_peer_assoc_fill(ar, buf, arg); memset(cmd->peer_ht_info, 0, sizeof(cmd->peer_ht_info)); } static void ath10k_wmi_peer_assoc_fill_10_1(struct ath10k *ar, void *buf, const struct wmi_peer_assoc_complete_arg *arg) { ath10k_wmi_peer_assoc_fill(ar, buf, arg); } static void ath10k_wmi_peer_assoc_fill_10_2(struct ath10k *ar, void *buf, const struct wmi_peer_assoc_complete_arg *arg) { struct wmi_10_2_peer_assoc_complete_cmd *cmd = buf; int max_mcs, max_nss; u32 info0; /* TODO: Is using max values okay with firmware? */ max_mcs = 0xf; max_nss = 0xf; info0 = SM(max_mcs, WMI_PEER_ASSOC_INFO0_MAX_MCS_IDX) | SM(max_nss, WMI_PEER_ASSOC_INFO0_MAX_NSS); ath10k_wmi_peer_assoc_fill(ar, buf, arg); cmd->info0 = __cpu_to_le32(info0); } static void ath10k_wmi_peer_assoc_fill_10_4(struct ath10k *ar, void *buf, const struct wmi_peer_assoc_complete_arg *arg) { struct wmi_10_4_peer_assoc_complete_cmd *cmd = buf; ath10k_wmi_peer_assoc_fill_10_2(ar, buf, arg); cmd->peer_bw_rxnss_override = 0; } static int ath10k_wmi_peer_assoc_check_arg(const struct wmi_peer_assoc_complete_arg *arg) { if (arg->peer_mpdu_density > 16) return -EINVAL; if (arg->peer_legacy_rates.num_rates > MAX_SUPPORTED_RATES) return -EINVAL; if (arg->peer_ht_rates.num_rates > MAX_SUPPORTED_RATES) return -EINVAL; return 0; } static struct sk_buff * ath10k_wmi_op_gen_peer_assoc(struct ath10k *ar, const struct wmi_peer_assoc_complete_arg *arg) { size_t len = sizeof(struct wmi_main_peer_assoc_complete_cmd); struct sk_buff *skb; int ret; ret = ath10k_wmi_peer_assoc_check_arg(arg); if (ret) return ERR_PTR(ret); skb = ath10k_wmi_alloc_skb(ar, len); if (!skb) return ERR_PTR(-ENOMEM); ath10k_wmi_peer_assoc_fill_main(ar, skb->data, arg); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi peer assoc vdev %d addr %pM (%s)\n", arg->vdev_id, arg->addr, arg->peer_reassoc ? "reassociate" : "new"); return skb; } static struct sk_buff * ath10k_wmi_10_1_op_gen_peer_assoc(struct ath10k *ar, const struct wmi_peer_assoc_complete_arg *arg) { size_t len = sizeof(struct wmi_10_1_peer_assoc_complete_cmd); struct sk_buff *skb; int ret; ret = ath10k_wmi_peer_assoc_check_arg(arg); if (ret) return ERR_PTR(ret); skb = ath10k_wmi_alloc_skb(ar, len); if (!skb) return ERR_PTR(-ENOMEM); ath10k_wmi_peer_assoc_fill_10_1(ar, skb->data, arg); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi peer assoc vdev %d addr %pM (%s)\n", arg->vdev_id, arg->addr, arg->peer_reassoc ? "reassociate" : "new"); return skb; } static struct sk_buff * ath10k_wmi_10_2_op_gen_peer_assoc(struct ath10k *ar, const struct wmi_peer_assoc_complete_arg *arg) { size_t len = sizeof(struct wmi_10_2_peer_assoc_complete_cmd); struct sk_buff *skb; int ret; ret = ath10k_wmi_peer_assoc_check_arg(arg); if (ret) return ERR_PTR(ret); skb = ath10k_wmi_alloc_skb(ar, len); if (!skb) return ERR_PTR(-ENOMEM); ath10k_wmi_peer_assoc_fill_10_2(ar, skb->data, arg); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi peer assoc vdev %d addr %pM (%s)\n", arg->vdev_id, arg->addr, arg->peer_reassoc ? "reassociate" : "new"); return skb; } static struct sk_buff * ath10k_wmi_10_4_op_gen_peer_assoc(struct ath10k *ar, const struct wmi_peer_assoc_complete_arg *arg) { size_t len = sizeof(struct wmi_10_4_peer_assoc_complete_cmd); struct sk_buff *skb; int ret; ret = ath10k_wmi_peer_assoc_check_arg(arg); if (ret) return ERR_PTR(ret); skb = ath10k_wmi_alloc_skb(ar, len); if (!skb) return ERR_PTR(-ENOMEM); ath10k_wmi_peer_assoc_fill_10_4(ar, skb->data, arg); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi peer assoc vdev %d addr %pM (%s)\n", arg->vdev_id, arg->addr, arg->peer_reassoc ? "reassociate" : "new"); return skb; } static struct sk_buff * ath10k_wmi_10_2_op_gen_pdev_get_temperature(struct ath10k *ar) { struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, 0); if (!skb) return ERR_PTR(-ENOMEM); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi pdev get temperature\n"); return skb; } static struct sk_buff * ath10k_wmi_10_2_op_gen_pdev_bss_chan_info(struct ath10k *ar, enum wmi_bss_survey_req_type type) { struct wmi_pdev_chan_info_req_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_chan_info_req_cmd *)skb->data; cmd->type = __cpu_to_le32(type); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi pdev bss info request type %d\n", type); return skb; } /* This function assumes the beacon is already DMA mapped */ static struct sk_buff * ath10k_wmi_op_gen_beacon_dma(struct ath10k *ar, u32 vdev_id, const void *bcn, size_t bcn_len, u32 bcn_paddr, bool dtim_zero, bool deliver_cab) { struct wmi_bcn_tx_ref_cmd *cmd; struct sk_buff *skb; struct ieee80211_hdr *hdr; u16 fc; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); hdr = (struct ieee80211_hdr *)bcn; fc = le16_to_cpu(hdr->frame_control); cmd = (struct wmi_bcn_tx_ref_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); cmd->data_len = __cpu_to_le32(bcn_len); cmd->data_ptr = __cpu_to_le32(bcn_paddr); cmd->msdu_id = 0; cmd->frame_control = __cpu_to_le32(fc); cmd->flags = 0; cmd->antenna_mask = __cpu_to_le32(WMI_BCN_TX_REF_DEF_ANTENNA); if (dtim_zero) cmd->flags |= __cpu_to_le32(WMI_BCN_TX_REF_FLAG_DTIM_ZERO); if (deliver_cab) cmd->flags |= __cpu_to_le32(WMI_BCN_TX_REF_FLAG_DELIVER_CAB); return skb; } void ath10k_wmi_set_wmm_param(struct wmi_wmm_params *params, const struct wmi_wmm_params_arg *arg) { params->cwmin = __cpu_to_le32(arg->cwmin); params->cwmax = __cpu_to_le32(arg->cwmax); params->aifs = __cpu_to_le32(arg->aifs); params->txop = __cpu_to_le32(arg->txop); params->acm = __cpu_to_le32(arg->acm); params->no_ack = __cpu_to_le32(arg->no_ack); } static struct sk_buff * ath10k_wmi_op_gen_pdev_set_wmm(struct ath10k *ar, const struct wmi_wmm_params_all_arg *arg) { struct wmi_pdev_set_wmm_params *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_set_wmm_params *)skb->data; ath10k_wmi_set_wmm_param(&cmd->ac_be, &arg->ac_be); ath10k_wmi_set_wmm_param(&cmd->ac_bk, &arg->ac_bk); ath10k_wmi_set_wmm_param(&cmd->ac_vi, &arg->ac_vi); ath10k_wmi_set_wmm_param(&cmd->ac_vo, &arg->ac_vo); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi pdev set wmm params\n"); return skb; } static struct sk_buff * ath10k_wmi_op_gen_request_stats(struct ath10k *ar, u32 stats_mask) { struct wmi_request_stats_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_request_stats_cmd *)skb->data; cmd->stats_id = __cpu_to_le32(stats_mask); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi request stats 0x%08x\n", stats_mask); return skb; } static struct sk_buff * ath10k_wmi_op_gen_force_fw_hang(struct ath10k *ar, enum wmi_force_fw_hang_type type, u32 delay_ms) { struct wmi_force_fw_hang_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_force_fw_hang_cmd *)skb->data; cmd->type = __cpu_to_le32(type); cmd->delay_ms = __cpu_to_le32(delay_ms); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi force fw hang %d delay %d\n", type, delay_ms); return skb; } static struct sk_buff * ath10k_wmi_op_gen_dbglog_cfg(struct ath10k *ar, u64 module_enable, u32 log_level) { struct wmi_dbglog_cfg_cmd *cmd; struct sk_buff *skb; u32 cfg; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_dbglog_cfg_cmd *)skb->data; if (module_enable) { cfg = SM(log_level, ATH10K_DBGLOG_CFG_LOG_LVL); } else { /* set back defaults, all modules with WARN level */ cfg = SM(ATH10K_DBGLOG_LEVEL_WARN, ATH10K_DBGLOG_CFG_LOG_LVL); module_enable = ~0; } cmd->module_enable = __cpu_to_le32(module_enable); cmd->module_valid = __cpu_to_le32(~0); cmd->config_enable = __cpu_to_le32(cfg); cmd->config_valid = __cpu_to_le32(ATH10K_DBGLOG_CFG_LOG_LVL_MASK); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi dbglog cfg modules %08x %08x config %08x %08x\n", __le32_to_cpu(cmd->module_enable), __le32_to_cpu(cmd->module_valid), __le32_to_cpu(cmd->config_enable), __le32_to_cpu(cmd->config_valid)); return skb; } static struct sk_buff * ath10k_wmi_10_4_op_gen_dbglog_cfg(struct ath10k *ar, u64 module_enable, u32 log_level) { struct wmi_10_4_dbglog_cfg_cmd *cmd; struct sk_buff *skb; u32 cfg; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_10_4_dbglog_cfg_cmd *)skb->data; if (module_enable) { cfg = SM(log_level, ATH10K_DBGLOG_CFG_LOG_LVL); } else { /* set back defaults, all modules with WARN level */ cfg = SM(ATH10K_DBGLOG_LEVEL_WARN, ATH10K_DBGLOG_CFG_LOG_LVL); module_enable = ~0; } cmd->module_enable = __cpu_to_le64(module_enable); cmd->module_valid = __cpu_to_le64(~0); cmd->config_enable = __cpu_to_le32(cfg); cmd->config_valid = __cpu_to_le32(ATH10K_DBGLOG_CFG_LOG_LVL_MASK); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi dbglog cfg modules 0x%016llx 0x%016llx config %08x %08x\n", __le64_to_cpu(cmd->module_enable), __le64_to_cpu(cmd->module_valid), __le32_to_cpu(cmd->config_enable), __le32_to_cpu(cmd->config_valid)); return skb; } static struct sk_buff * ath10k_wmi_op_gen_pktlog_enable(struct ath10k *ar, u32 ev_bitmap) { struct wmi_pdev_pktlog_enable_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); ev_bitmap &= ATH10K_PKTLOG_ANY; cmd = (struct wmi_pdev_pktlog_enable_cmd *)skb->data; cmd->ev_bitmap = __cpu_to_le32(ev_bitmap); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi enable pktlog filter 0x%08x\n", ev_bitmap); return skb; } static struct sk_buff * ath10k_wmi_op_gen_pktlog_disable(struct ath10k *ar) { struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, 0); if (!skb) return ERR_PTR(-ENOMEM); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi disable pktlog\n"); return skb; } static struct sk_buff * ath10k_wmi_op_gen_pdev_set_quiet_mode(struct ath10k *ar, u32 period, u32 duration, u32 next_offset, u32 enabled) { struct wmi_pdev_set_quiet_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_set_quiet_cmd *)skb->data; cmd->period = __cpu_to_le32(period); cmd->duration = __cpu_to_le32(duration); cmd->next_start = __cpu_to_le32(next_offset); cmd->enabled = __cpu_to_le32(enabled); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi quiet param: period %u duration %u enabled %d\n", period, duration, enabled); return skb; } static struct sk_buff * ath10k_wmi_op_gen_addba_clear_resp(struct ath10k *ar, u32 vdev_id, const u8 *mac) { struct wmi_addba_clear_resp_cmd *cmd; struct sk_buff *skb; if (!mac) return ERR_PTR(-EINVAL); skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_addba_clear_resp_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ether_addr_copy(cmd->peer_macaddr.addr, mac); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi addba clear resp vdev_id 0x%X mac_addr %pM\n", vdev_id, mac); return skb; } static struct sk_buff * ath10k_wmi_op_gen_addba_send(struct ath10k *ar, u32 vdev_id, const u8 *mac, u32 tid, u32 buf_size) { struct wmi_addba_send_cmd *cmd; struct sk_buff *skb; if (!mac) return ERR_PTR(-EINVAL); skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_addba_send_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ether_addr_copy(cmd->peer_macaddr.addr, mac); cmd->tid = __cpu_to_le32(tid); cmd->buffersize = __cpu_to_le32(buf_size); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi addba send vdev_id 0x%X mac_addr %pM tid %u bufsize %u\n", vdev_id, mac, tid, buf_size); return skb; } static struct sk_buff * ath10k_wmi_op_gen_addba_set_resp(struct ath10k *ar, u32 vdev_id, const u8 *mac, u32 tid, u32 status) { struct wmi_addba_setresponse_cmd *cmd; struct sk_buff *skb; if (!mac) return ERR_PTR(-EINVAL); skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_addba_setresponse_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ether_addr_copy(cmd->peer_macaddr.addr, mac); cmd->tid = __cpu_to_le32(tid); cmd->statuscode = __cpu_to_le32(status); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi addba set resp vdev_id 0x%X mac_addr %pM tid %u status %u\n", vdev_id, mac, tid, status); return skb; } static struct sk_buff * ath10k_wmi_op_gen_delba_send(struct ath10k *ar, u32 vdev_id, const u8 *mac, u32 tid, u32 initiator, u32 reason) { struct wmi_delba_send_cmd *cmd; struct sk_buff *skb; if (!mac) return ERR_PTR(-EINVAL); skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_delba_send_cmd *)skb->data; cmd->vdev_id = __cpu_to_le32(vdev_id); ether_addr_copy(cmd->peer_macaddr.addr, mac); cmd->tid = __cpu_to_le32(tid); cmd->initiator = __cpu_to_le32(initiator); cmd->reasoncode = __cpu_to_le32(reason); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi delba send vdev_id 0x%X mac_addr %pM tid %u initiator %u reason %u\n", vdev_id, mac, tid, initiator, reason); return skb; } static struct sk_buff * ath10k_wmi_10_2_4_op_gen_pdev_get_tpc_config(struct ath10k *ar, u32 param) { struct wmi_pdev_get_tpc_config_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_get_tpc_config_cmd *)skb->data; cmd->param = __cpu_to_le32(param); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi pdev get tcp config param:%d\n", param); return skb; } size_t ath10k_wmi_fw_stats_num_peers(struct list_head *head) { struct ath10k_fw_stats_peer *i; size_t num = 0; list_for_each_entry(i, head, list) ++num; return num; } size_t ath10k_wmi_fw_stats_num_vdevs(struct list_head *head) { struct ath10k_fw_stats_vdev *i; size_t num = 0; list_for_each_entry(i, head, list) ++num; return num; } static void ath10k_wmi_fw_pdev_base_stats_fill(const struct ath10k_fw_stats_pdev *pdev, char *buf, u32 *length) { u32 len = *length; u32 buf_len = ATH10K_FW_STATS_BUF_SIZE; len += scnprintf(buf + len, buf_len - len, "\n"); len += scnprintf(buf + len, buf_len - len, "%30s\n", "ath10k PDEV stats"); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Channel noise floor", pdev->ch_noise_floor); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "Channel TX power", pdev->chan_tx_power); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "TX frame count", pdev->tx_frame_count); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "RX frame count", pdev->rx_frame_count); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "RX clear count", pdev->rx_clear_count); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "Cycle count", pdev->cycle_count); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "PHY error count", pdev->phy_err_count); *length = len; } static void ath10k_wmi_fw_pdev_extra_stats_fill(const struct ath10k_fw_stats_pdev *pdev, char *buf, u32 *length) { u32 len = *length; u32 buf_len = ATH10K_FW_STATS_BUF_SIZE; len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "RTS bad count", pdev->rts_bad); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "RTS good count", pdev->rts_good); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "FCS bad count", pdev->fcs_bad); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "No beacon count", pdev->no_beacons); len += scnprintf(buf + len, buf_len - len, "%30s %10u\n", "MIB int count", pdev->mib_int_count); len += scnprintf(buf + len, buf_len - len, "\n"); *length = len; } static void ath10k_wmi_fw_pdev_tx_stats_fill(const struct ath10k_fw_stats_pdev *pdev, char *buf, u32 *length) { u32 len = *length; u32 buf_len = ATH10K_FW_STATS_BUF_SIZE; len += scnprintf(buf + len, buf_len - len, "\n%30s\n", "ath10k PDEV TX stats"); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "HTT cookies queued", pdev->comp_queued); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "HTT cookies disp.", pdev->comp_delivered); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MSDU queued", pdev->msdu_enqued); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDU queued", pdev->mpdu_enqued); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MSDUs dropped", pdev->wmm_drop); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Local enqued", pdev->local_enqued); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Local freed", pdev->local_freed); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "HW queued", pdev->hw_queued); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "PPDUs reaped", pdev->hw_reaped); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Num underruns", pdev->underrun); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "PPDUs cleaned", pdev->tx_abort); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDUs requed", pdev->mpdus_requed); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Excessive retries", pdev->tx_ko); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "HW rate", pdev->data_rc); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Sched self tiggers", pdev->self_triggers); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Dropped due to SW retries", pdev->sw_retry_failure); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Illegal rate phy errors", pdev->illgl_rate_phy_err); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Pdev continuous xretry", pdev->pdev_cont_xretry); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "TX timeout", pdev->pdev_tx_timeout); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "PDEV resets", pdev->pdev_resets); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "PHY underrun", pdev->phy_underrun); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDU is more than txop limit", pdev->txop_ovf); *length = len; } static void ath10k_wmi_fw_pdev_rx_stats_fill(const struct ath10k_fw_stats_pdev *pdev, char *buf, u32 *length) { u32 len = *length; u32 buf_len = ATH10K_FW_STATS_BUF_SIZE; len += scnprintf(buf + len, buf_len - len, "\n%30s\n", "ath10k PDEV RX stats"); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Mid PPDU route change", pdev->mid_ppdu_route_change); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Tot. number of statuses", pdev->status_rcvd); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Extra frags on rings 0", pdev->r0_frags); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Extra frags on rings 1", pdev->r1_frags); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Extra frags on rings 2", pdev->r2_frags); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Extra frags on rings 3", pdev->r3_frags); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MSDUs delivered to HTT", pdev->htt_msdus); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDUs delivered to HTT", pdev->htt_mpdus); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MSDUs delivered to stack", pdev->loc_msdus); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDUs delivered to stack", pdev->loc_mpdus); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Oversized AMSUs", pdev->oversize_amsdu); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "PHY errors", pdev->phy_errs); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "PHY errors drops", pdev->phy_err_drop); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDU errors (FCS, MIC, ENC)", pdev->mpdu_errs); *length = len; } static void ath10k_wmi_fw_vdev_stats_fill(const struct ath10k_fw_stats_vdev *vdev, char *buf, u32 *length) { u32 len = *length; u32 buf_len = ATH10K_FW_STATS_BUF_SIZE; int i; len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "vdev id", vdev->vdev_id); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "beacon snr", vdev->beacon_snr); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "data snr", vdev->data_snr); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "num rx frames", vdev->num_rx_frames); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "num rts fail", vdev->num_rts_fail); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "num rts success", vdev->num_rts_success); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "num rx err", vdev->num_rx_err); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "num rx discard", vdev->num_rx_discard); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "num tx not acked", vdev->num_tx_not_acked); for (i = 0 ; i < ARRAY_SIZE(vdev->num_tx_frames); i++) len += scnprintf(buf + len, buf_len - len, "%25s [%02d] %u\n", "num tx frames", i, vdev->num_tx_frames[i]); for (i = 0 ; i < ARRAY_SIZE(vdev->num_tx_frames_retries); i++) len += scnprintf(buf + len, buf_len - len, "%25s [%02d] %u\n", "num tx frames retries", i, vdev->num_tx_frames_retries[i]); for (i = 0 ; i < ARRAY_SIZE(vdev->num_tx_frames_failures); i++) len += scnprintf(buf + len, buf_len - len, "%25s [%02d] %u\n", "num tx frames failures", i, vdev->num_tx_frames_failures[i]); for (i = 0 ; i < ARRAY_SIZE(vdev->tx_rate_history); i++) len += scnprintf(buf + len, buf_len - len, "%25s [%02d] 0x%08x\n", "tx rate history", i, vdev->tx_rate_history[i]); for (i = 0 ; i < ARRAY_SIZE(vdev->beacon_rssi_history); i++) len += scnprintf(buf + len, buf_len - len, "%25s [%02d] %u\n", "beacon rssi history", i, vdev->beacon_rssi_history[i]); len += scnprintf(buf + len, buf_len - len, "\n"); *length = len; } static void ath10k_wmi_fw_peer_stats_fill(const struct ath10k_fw_stats_peer *peer, char *buf, u32 *length) { u32 len = *length; u32 buf_len = ATH10K_FW_STATS_BUF_SIZE; len += scnprintf(buf + len, buf_len - len, "%30s %pM\n", "Peer MAC address", peer->peer_macaddr); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "Peer RSSI", peer->peer_rssi); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "Peer TX rate", peer->peer_tx_rate); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "Peer RX rate", peer->peer_rx_rate); len += scnprintf(buf + len, buf_len - len, "%30s %u\n", "Peer RX duration", peer->rx_duration); len += scnprintf(buf + len, buf_len - len, "\n"); *length = len; } void ath10k_wmi_main_op_fw_stats_fill(struct ath10k *ar, struct ath10k_fw_stats *fw_stats, char *buf) { u32 len = 0; u32 buf_len = ATH10K_FW_STATS_BUF_SIZE; const struct ath10k_fw_stats_pdev *pdev; const struct ath10k_fw_stats_vdev *vdev; const struct ath10k_fw_stats_peer *peer; size_t num_peers; size_t num_vdevs; spin_lock_bh(&ar->data_lock); pdev = list_first_entry_or_null(&fw_stats->pdevs, struct ath10k_fw_stats_pdev, list); if (!pdev) { ath10k_warn(ar, "failed to get pdev stats\n"); goto unlock; } num_peers = ath10k_wmi_fw_stats_num_peers(&fw_stats->peers); num_vdevs = ath10k_wmi_fw_stats_num_vdevs(&fw_stats->vdevs); ath10k_wmi_fw_pdev_base_stats_fill(pdev, buf, &len); ath10k_wmi_fw_pdev_tx_stats_fill(pdev, buf, &len); ath10k_wmi_fw_pdev_rx_stats_fill(pdev, buf, &len); len += scnprintf(buf + len, buf_len - len, "\n"); len += scnprintf(buf + len, buf_len - len, "%30s (%zu)\n", "ath10k VDEV stats", num_vdevs); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); list_for_each_entry(vdev, &fw_stats->vdevs, list) { ath10k_wmi_fw_vdev_stats_fill(vdev, buf, &len); } len += scnprintf(buf + len, buf_len - len, "\n"); len += scnprintf(buf + len, buf_len - len, "%30s (%zu)\n", "ath10k PEER stats", num_peers); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); list_for_each_entry(peer, &fw_stats->peers, list) { ath10k_wmi_fw_peer_stats_fill(peer, buf, &len); } unlock: spin_unlock_bh(&ar->data_lock); if (len >= buf_len) buf[len - 1] = 0; else buf[len] = 0; } void ath10k_wmi_10x_op_fw_stats_fill(struct ath10k *ar, struct ath10k_fw_stats *fw_stats, char *buf) { unsigned int len = 0; unsigned int buf_len = ATH10K_FW_STATS_BUF_SIZE; const struct ath10k_fw_stats_pdev *pdev; const struct ath10k_fw_stats_vdev *vdev; const struct ath10k_fw_stats_peer *peer; size_t num_peers; size_t num_vdevs; spin_lock_bh(&ar->data_lock); pdev = list_first_entry_or_null(&fw_stats->pdevs, struct ath10k_fw_stats_pdev, list); if (!pdev) { ath10k_warn(ar, "failed to get pdev stats\n"); goto unlock; } num_peers = ath10k_wmi_fw_stats_num_peers(&fw_stats->peers); num_vdevs = ath10k_wmi_fw_stats_num_vdevs(&fw_stats->vdevs); ath10k_wmi_fw_pdev_base_stats_fill(pdev, buf, &len); ath10k_wmi_fw_pdev_extra_stats_fill(pdev, buf, &len); ath10k_wmi_fw_pdev_tx_stats_fill(pdev, buf, &len); ath10k_wmi_fw_pdev_rx_stats_fill(pdev, buf, &len); len += scnprintf(buf + len, buf_len - len, "\n"); len += scnprintf(buf + len, buf_len - len, "%30s (%zu)\n", "ath10k VDEV stats", num_vdevs); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); list_for_each_entry(vdev, &fw_stats->vdevs, list) { ath10k_wmi_fw_vdev_stats_fill(vdev, buf, &len); } len += scnprintf(buf + len, buf_len - len, "\n"); len += scnprintf(buf + len, buf_len - len, "%30s (%zu)\n", "ath10k PEER stats", num_peers); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); list_for_each_entry(peer, &fw_stats->peers, list) { ath10k_wmi_fw_peer_stats_fill(peer, buf, &len); } unlock: spin_unlock_bh(&ar->data_lock); if (len >= buf_len) buf[len - 1] = 0; else buf[len] = 0; } static struct sk_buff * ath10k_wmi_op_gen_pdev_enable_adaptive_cca(struct ath10k *ar, u8 enable, u32 detect_level, u32 detect_margin) { struct wmi_pdev_set_adaptive_cca_params *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_pdev_set_adaptive_cca_params *)skb->data; cmd->enable = __cpu_to_le32(enable); cmd->cca_detect_level = __cpu_to_le32(detect_level); cmd->cca_detect_margin = __cpu_to_le32(detect_margin); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi pdev set adaptive cca params enable:%d detection level:%d detection margin:%d\n", enable, detect_level, detect_margin); return skb; } void ath10k_wmi_10_4_op_fw_stats_fill(struct ath10k *ar, struct ath10k_fw_stats *fw_stats, char *buf) { u32 len = 0; u32 buf_len = ATH10K_FW_STATS_BUF_SIZE; const struct ath10k_fw_stats_pdev *pdev; const struct ath10k_fw_stats_vdev *vdev; const struct ath10k_fw_stats_peer *peer; size_t num_peers; size_t num_vdevs; spin_lock_bh(&ar->data_lock); pdev = list_first_entry_or_null(&fw_stats->pdevs, struct ath10k_fw_stats_pdev, list); if (!pdev) { ath10k_warn(ar, "failed to get pdev stats\n"); goto unlock; } num_peers = ath10k_wmi_fw_stats_num_peers(&fw_stats->peers); num_vdevs = ath10k_wmi_fw_stats_num_vdevs(&fw_stats->vdevs); ath10k_wmi_fw_pdev_base_stats_fill(pdev, buf, &len); ath10k_wmi_fw_pdev_extra_stats_fill(pdev, buf, &len); ath10k_wmi_fw_pdev_tx_stats_fill(pdev, buf, &len); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "HW paused", pdev->hw_paused); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Seqs posted", pdev->seq_posted); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Seqs failed queueing", pdev->seq_failed_queueing); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Seqs completed", pdev->seq_completed); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Seqs restarted", pdev->seq_restarted); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MU Seqs posted", pdev->mu_seq_posted); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDUs SW flushed", pdev->mpdus_sw_flush); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDUs HW filtered", pdev->mpdus_hw_filter); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDUs truncated", pdev->mpdus_truncated); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDUs receive no ACK", pdev->mpdus_ack_failed); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "MPDUs expired", pdev->mpdus_expired); ath10k_wmi_fw_pdev_rx_stats_fill(pdev, buf, &len); len += scnprintf(buf + len, buf_len - len, "%30s %10d\n", "Num Rx Overflow errors", pdev->rx_ovfl_errs); len += scnprintf(buf + len, buf_len - len, "\n"); len += scnprintf(buf + len, buf_len - len, "%30s (%zu)\n", "ath10k VDEV stats", num_vdevs); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); list_for_each_entry(vdev, &fw_stats->vdevs, list) { ath10k_wmi_fw_vdev_stats_fill(vdev, buf, &len); } len += scnprintf(buf + len, buf_len - len, "\n"); len += scnprintf(buf + len, buf_len - len, "%30s (%zu)\n", "ath10k PEER stats", num_peers); len += scnprintf(buf + len, buf_len - len, "%30s\n\n", "================="); list_for_each_entry(peer, &fw_stats->peers, list) { ath10k_wmi_fw_peer_stats_fill(peer, buf, &len); } unlock: spin_unlock_bh(&ar->data_lock); if (len >= buf_len) buf[len - 1] = 0; else buf[len] = 0; } int ath10k_wmi_op_get_vdev_subtype(struct ath10k *ar, enum wmi_vdev_subtype subtype) { switch (subtype) { case WMI_VDEV_SUBTYPE_NONE: return WMI_VDEV_SUBTYPE_LEGACY_NONE; case WMI_VDEV_SUBTYPE_P2P_DEVICE: return WMI_VDEV_SUBTYPE_LEGACY_P2P_DEV; case WMI_VDEV_SUBTYPE_P2P_CLIENT: return WMI_VDEV_SUBTYPE_LEGACY_P2P_CLI; case WMI_VDEV_SUBTYPE_P2P_GO: return WMI_VDEV_SUBTYPE_LEGACY_P2P_GO; case WMI_VDEV_SUBTYPE_PROXY_STA: return WMI_VDEV_SUBTYPE_LEGACY_PROXY_STA; case WMI_VDEV_SUBTYPE_MESH_11S: case WMI_VDEV_SUBTYPE_MESH_NON_11S: return -ENOTSUPP; } return -ENOTSUPP; } static int ath10k_wmi_10_2_4_op_get_vdev_subtype(struct ath10k *ar, enum wmi_vdev_subtype subtype) { switch (subtype) { case WMI_VDEV_SUBTYPE_NONE: return WMI_VDEV_SUBTYPE_10_2_4_NONE; case WMI_VDEV_SUBTYPE_P2P_DEVICE: return WMI_VDEV_SUBTYPE_10_2_4_P2P_DEV; case WMI_VDEV_SUBTYPE_P2P_CLIENT: return WMI_VDEV_SUBTYPE_10_2_4_P2P_CLI; case WMI_VDEV_SUBTYPE_P2P_GO: return WMI_VDEV_SUBTYPE_10_2_4_P2P_GO; case WMI_VDEV_SUBTYPE_PROXY_STA: return WMI_VDEV_SUBTYPE_10_2_4_PROXY_STA; case WMI_VDEV_SUBTYPE_MESH_11S: return WMI_VDEV_SUBTYPE_10_2_4_MESH_11S; case WMI_VDEV_SUBTYPE_MESH_NON_11S: return -ENOTSUPP; } return -ENOTSUPP; } static int ath10k_wmi_10_4_op_get_vdev_subtype(struct ath10k *ar, enum wmi_vdev_subtype subtype) { switch (subtype) { case WMI_VDEV_SUBTYPE_NONE: return WMI_VDEV_SUBTYPE_10_4_NONE; case WMI_VDEV_SUBTYPE_P2P_DEVICE: return WMI_VDEV_SUBTYPE_10_4_P2P_DEV; case WMI_VDEV_SUBTYPE_P2P_CLIENT: return WMI_VDEV_SUBTYPE_10_4_P2P_CLI; case WMI_VDEV_SUBTYPE_P2P_GO: return WMI_VDEV_SUBTYPE_10_4_P2P_GO; case WMI_VDEV_SUBTYPE_PROXY_STA: return WMI_VDEV_SUBTYPE_10_4_PROXY_STA; case WMI_VDEV_SUBTYPE_MESH_11S: return WMI_VDEV_SUBTYPE_10_4_MESH_11S; case WMI_VDEV_SUBTYPE_MESH_NON_11S: return WMI_VDEV_SUBTYPE_10_4_MESH_NON_11S; } return -ENOTSUPP; } static struct sk_buff * ath10k_wmi_10_4_ext_resource_config(struct ath10k *ar, enum wmi_host_platform_type type, u32 fw_feature_bitmap) { struct wmi_ext_resource_config_10_4_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_ext_resource_config_10_4_cmd *)skb->data; cmd->host_platform_config = __cpu_to_le32(type); cmd->fw_feature_bitmap = __cpu_to_le32(fw_feature_bitmap); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi ext resource config host type %d firmware feature bitmap %08x\n", type, fw_feature_bitmap); return skb; } static struct sk_buff * ath10k_wmi_op_gen_echo(struct ath10k *ar, u32 value) { struct wmi_echo_cmd *cmd; struct sk_buff *skb; skb = ath10k_wmi_alloc_skb(ar, sizeof(*cmd)); if (!skb) return ERR_PTR(-ENOMEM); cmd = (struct wmi_echo_cmd *)skb->data; cmd->value = cpu_to_le32(value); ath10k_dbg(ar, ATH10K_DBG_WMI, "wmi echo value 0x%08x\n", value); return skb; } int ath10k_wmi_barrier(struct ath10k *ar) { int ret; int time_left; spin_lock_bh(&ar->data_lock); reinit_completion(&ar->wmi.barrier); spin_unlock_bh(&ar->data_lock); ret = ath10k_wmi_echo(ar, ATH10K_WMI_BARRIER_ECHO_ID); if (ret) { ath10k_warn(ar, "failed to submit wmi echo: %d\n", ret); return ret; } time_left = wait_for_completion_timeout(&ar->wmi.barrier, ATH10K_WMI_BARRIER_TIMEOUT_HZ); if (!time_left) return -ETIMEDOUT; return 0; } static const struct wmi_ops wmi_ops = { .rx = ath10k_wmi_op_rx, .map_svc = wmi_main_svc_map, .pull_scan = ath10k_wmi_op_pull_scan_ev, .pull_mgmt_rx = ath10k_wmi_op_pull_mgmt_rx_ev, .pull_ch_info = ath10k_wmi_op_pull_ch_info_ev, .pull_vdev_start = ath10k_wmi_op_pull_vdev_start_ev, .pull_peer_kick = ath10k_wmi_op_pull_peer_kick_ev, .pull_swba = ath10k_wmi_op_pull_swba_ev, .pull_phyerr_hdr = ath10k_wmi_op_pull_phyerr_ev_hdr, .pull_phyerr = ath10k_wmi_op_pull_phyerr_ev, .pull_svc_rdy = ath10k_wmi_main_op_pull_svc_rdy_ev, .pull_rdy = ath10k_wmi_op_pull_rdy_ev, .pull_fw_stats = ath10k_wmi_main_op_pull_fw_stats, .pull_roam_ev = ath10k_wmi_op_pull_roam_ev, .pull_echo_ev = ath10k_wmi_op_pull_echo_ev, .gen_pdev_suspend = ath10k_wmi_op_gen_pdev_suspend, .gen_pdev_resume = ath10k_wmi_op_gen_pdev_resume, .gen_pdev_set_rd = ath10k_wmi_op_gen_pdev_set_rd, .gen_pdev_set_param = ath10k_wmi_op_gen_pdev_set_param, .gen_init = ath10k_wmi_op_gen_init, .gen_start_scan = ath10k_wmi_op_gen_start_scan, .gen_stop_scan = ath10k_wmi_op_gen_stop_scan, .gen_vdev_create = ath10k_wmi_op_gen_vdev_create, .gen_vdev_delete = ath10k_wmi_op_gen_vdev_delete, .gen_vdev_start = ath10k_wmi_op_gen_vdev_start, .gen_vdev_stop = ath10k_wmi_op_gen_vdev_stop, .gen_vdev_up = ath10k_wmi_op_gen_vdev_up, .gen_vdev_down = ath10k_wmi_op_gen_vdev_down, .gen_vdev_set_param = ath10k_wmi_op_gen_vdev_set_param, .gen_vdev_install_key = ath10k_wmi_op_gen_vdev_install_key, .gen_vdev_spectral_conf = ath10k_wmi_op_gen_vdev_spectral_conf, .gen_vdev_spectral_enable = ath10k_wmi_op_gen_vdev_spectral_enable, /* .gen_vdev_wmm_conf not implemented */ .gen_peer_create = ath10k_wmi_op_gen_peer_create, .gen_peer_delete = ath10k_wmi_op_gen_peer_delete, .gen_peer_flush = ath10k_wmi_op_gen_peer_flush, .gen_peer_set_param = ath10k_wmi_op_gen_peer_set_param, .gen_peer_assoc = ath10k_wmi_op_gen_peer_assoc, .gen_set_psmode = ath10k_wmi_op_gen_set_psmode, .gen_set_sta_ps = ath10k_wmi_op_gen_set_sta_ps, .gen_set_ap_ps = ath10k_wmi_op_gen_set_ap_ps, .gen_scan_chan_list = ath10k_wmi_op_gen_scan_chan_list, .gen_beacon_dma = ath10k_wmi_op_gen_beacon_dma, .gen_pdev_set_wmm = ath10k_wmi_op_gen_pdev_set_wmm, .gen_request_stats = ath10k_wmi_op_gen_request_stats, .gen_force_fw_hang = ath10k_wmi_op_gen_force_fw_hang, .gen_mgmt_tx = ath10k_wmi_op_gen_mgmt_tx, .gen_dbglog_cfg = ath10k_wmi_op_gen_dbglog_cfg, .gen_pktlog_enable = ath10k_wmi_op_gen_pktlog_enable, .gen_pktlog_disable = ath10k_wmi_op_gen_pktlog_disable, .gen_pdev_set_quiet_mode = ath10k_wmi_op_gen_pdev_set_quiet_mode, /* .gen_pdev_get_temperature not implemented */ .gen_addba_clear_resp = ath10k_wmi_op_gen_addba_clear_resp, .gen_addba_send = ath10k_wmi_op_gen_addba_send, .gen_addba_set_resp = ath10k_wmi_op_gen_addba_set_resp, .gen_delba_send = ath10k_wmi_op_gen_delba_send, .fw_stats_fill = ath10k_wmi_main_op_fw_stats_fill, .get_vdev_subtype = ath10k_wmi_op_get_vdev_subtype, .gen_echo = ath10k_wmi_op_gen_echo, /* .gen_bcn_tmpl not implemented */ /* .gen_prb_tmpl not implemented */ /* .gen_p2p_go_bcn_ie not implemented */ /* .gen_adaptive_qcs not implemented */ /* .gen_pdev_enable_adaptive_cca not implemented */ }; static const struct wmi_ops wmi_10_1_ops = { .rx = ath10k_wmi_10_1_op_rx, .map_svc = wmi_10x_svc_map, .pull_svc_rdy = ath10k_wmi_10x_op_pull_svc_rdy_ev, .pull_fw_stats = ath10k_wmi_10x_op_pull_fw_stats, .gen_init = ath10k_wmi_10_1_op_gen_init, .gen_pdev_set_rd = ath10k_wmi_10x_op_gen_pdev_set_rd, .gen_start_scan = ath10k_wmi_10x_op_gen_start_scan, .gen_peer_assoc = ath10k_wmi_10_1_op_gen_peer_assoc, /* .gen_pdev_get_temperature not implemented */ /* shared with main branch */ .pull_scan = ath10k_wmi_op_pull_scan_ev, .pull_mgmt_rx = ath10k_wmi_op_pull_mgmt_rx_ev, .pull_ch_info = ath10k_wmi_op_pull_ch_info_ev, .pull_vdev_start = ath10k_wmi_op_pull_vdev_start_ev, .pull_peer_kick = ath10k_wmi_op_pull_peer_kick_ev, .pull_swba = ath10k_wmi_op_pull_swba_ev, .pull_phyerr_hdr = ath10k_wmi_op_pull_phyerr_ev_hdr, .pull_phyerr = ath10k_wmi_op_pull_phyerr_ev, .pull_rdy = ath10k_wmi_op_pull_rdy_ev, .pull_roam_ev = ath10k_wmi_op_pull_roam_ev, .pull_echo_ev = ath10k_wmi_op_pull_echo_ev, .gen_pdev_suspend = ath10k_wmi_op_gen_pdev_suspend, .gen_pdev_resume = ath10k_wmi_op_gen_pdev_resume, .gen_pdev_set_param = ath10k_wmi_op_gen_pdev_set_param, .gen_stop_scan = ath10k_wmi_op_gen_stop_scan, .gen_vdev_create = ath10k_wmi_op_gen_vdev_create, .gen_vdev_delete = ath10k_wmi_op_gen_vdev_delete, .gen_vdev_start = ath10k_wmi_op_gen_vdev_start, .gen_vdev_stop = ath10k_wmi_op_gen_vdev_stop, .gen_vdev_up = ath10k_wmi_op_gen_vdev_up, .gen_vdev_down = ath10k_wmi_op_gen_vdev_down, .gen_vdev_set_param = ath10k_wmi_op_gen_vdev_set_param, .gen_vdev_install_key = ath10k_wmi_op_gen_vdev_install_key, .gen_vdev_spectral_conf = ath10k_wmi_op_gen_vdev_spectral_conf, .gen_vdev_spectral_enable = ath10k_wmi_op_gen_vdev_spectral_enable, /* .gen_vdev_wmm_conf not implemented */ .gen_peer_create = ath10k_wmi_op_gen_peer_create, .gen_peer_delete = ath10k_wmi_op_gen_peer_delete, .gen_peer_flush = ath10k_wmi_op_gen_peer_flush, .gen_peer_set_param = ath10k_wmi_op_gen_peer_set_param, .gen_set_psmode = ath10k_wmi_op_gen_set_psmode, .gen_set_sta_ps = ath10k_wmi_op_gen_set_sta_ps, .gen_set_ap_ps = ath10k_wmi_op_gen_set_ap_ps, .gen_scan_chan_list = ath10k_wmi_op_gen_scan_chan_list, .gen_beacon_dma = ath10k_wmi_op_gen_beacon_dma, .gen_pdev_set_wmm = ath10k_wmi_op_gen_pdev_set_wmm, .gen_request_stats = ath10k_wmi_op_gen_request_stats, .gen_force_fw_hang = ath10k_wmi_op_gen_force_fw_hang, .gen_mgmt_tx = ath10k_wmi_op_gen_mgmt_tx, .gen_dbglog_cfg = ath10k_wmi_op_gen_dbglog_cfg, .gen_pktlog_enable = ath10k_wmi_op_gen_pktlog_enable, .gen_pktlog_disable = ath10k_wmi_op_gen_pktlog_disable, .gen_pdev_set_quiet_mode = ath10k_wmi_op_gen_pdev_set_quiet_mode, .gen_addba_clear_resp = ath10k_wmi_op_gen_addba_clear_resp, .gen_addba_send = ath10k_wmi_op_gen_addba_send, .gen_addba_set_resp = ath10k_wmi_op_gen_addba_set_resp, .gen_delba_send = ath10k_wmi_op_gen_delba_send, .fw_stats_fill = ath10k_wmi_10x_op_fw_stats_fill, .get_vdev_subtype = ath10k_wmi_op_get_vdev_subtype, .gen_echo = ath10k_wmi_op_gen_echo, /* .gen_bcn_tmpl not implemented */ /* .gen_prb_tmpl not implemented */ /* .gen_p2p_go_bcn_ie not implemented */ /* .gen_adaptive_qcs not implemented */ /* .gen_pdev_enable_adaptive_cca not implemented */ }; static const struct wmi_ops wmi_10_2_ops = { .rx = ath10k_wmi_10_2_op_rx, .pull_fw_stats = ath10k_wmi_10_2_op_pull_fw_stats, .gen_init = ath10k_wmi_10_2_op_gen_init, .gen_peer_assoc = ath10k_wmi_10_2_op_gen_peer_assoc, /* .gen_pdev_get_temperature not implemented */ /* shared with 10.1 */ .map_svc = wmi_10x_svc_map, .pull_svc_rdy = ath10k_wmi_10x_op_pull_svc_rdy_ev, .gen_pdev_set_rd = ath10k_wmi_10x_op_gen_pdev_set_rd, .gen_start_scan = ath10k_wmi_10x_op_gen_start_scan, .gen_echo = ath10k_wmi_op_gen_echo, .pull_scan = ath10k_wmi_op_pull_scan_ev, .pull_mgmt_rx = ath10k_wmi_op_pull_mgmt_rx_ev, .pull_ch_info = ath10k_wmi_op_pull_ch_info_ev, .pull_vdev_start = ath10k_wmi_op_pull_vdev_start_ev, .pull_peer_kick = ath10k_wmi_op_pull_peer_kick_ev, .pull_swba = ath10k_wmi_op_pull_swba_ev, .pull_phyerr_hdr = ath10k_wmi_op_pull_phyerr_ev_hdr, .pull_phyerr = ath10k_wmi_op_pull_phyerr_ev, .pull_rdy = ath10k_wmi_op_pull_rdy_ev, .pull_roam_ev = ath10k_wmi_op_pull_roam_ev, .pull_echo_ev = ath10k_wmi_op_pull_echo_ev, .gen_pdev_suspend = ath10k_wmi_op_gen_pdev_suspend, .gen_pdev_resume = ath10k_wmi_op_gen_pdev_resume, .gen_pdev_set_param = ath10k_wmi_op_gen_pdev_set_param, .gen_stop_scan = ath10k_wmi_op_gen_stop_scan, .gen_vdev_create = ath10k_wmi_op_gen_vdev_create, .gen_vdev_delete = ath10k_wmi_op_gen_vdev_delete, .gen_vdev_start = ath10k_wmi_op_gen_vdev_start, .gen_vdev_stop = ath10k_wmi_op_gen_vdev_stop, .gen_vdev_up = ath10k_wmi_op_gen_vdev_up, .gen_vdev_down = ath10k_wmi_op_gen_vdev_down, .gen_vdev_set_param = ath10k_wmi_op_gen_vdev_set_param, .gen_vdev_install_key = ath10k_wmi_op_gen_vdev_install_key, .gen_vdev_spectral_conf = ath10k_wmi_op_gen_vdev_spectral_conf, .gen_vdev_spectral_enable = ath10k_wmi_op_gen_vdev_spectral_enable, /* .gen_vdev_wmm_conf not implemented */ .gen_peer_create = ath10k_wmi_op_gen_peer_create, .gen_peer_delete = ath10k_wmi_op_gen_peer_delete, .gen_peer_flush = ath10k_wmi_op_gen_peer_flush, .gen_peer_set_param = ath10k_wmi_op_gen_peer_set_param, .gen_set_psmode = ath10k_wmi_op_gen_set_psmode, .gen_set_sta_ps = ath10k_wmi_op_gen_set_sta_ps, .gen_set_ap_ps = ath10k_wmi_op_gen_set_ap_ps, .gen_scan_chan_list = ath10k_wmi_op_gen_scan_chan_list, .gen_beacon_dma = ath10k_wmi_op_gen_beacon_dma, .gen_pdev_set_wmm = ath10k_wmi_op_gen_pdev_set_wmm, .gen_request_stats = ath10k_wmi_op_gen_request_stats, .gen_force_fw_hang = ath10k_wmi_op_gen_force_fw_hang, .gen_mgmt_tx = ath10k_wmi_op_gen_mgmt_tx, .gen_dbglog_cfg = ath10k_wmi_op_gen_dbglog_cfg, .gen_pktlog_enable = ath10k_wmi_op_gen_pktlog_enable, .gen_pktlog_disable = ath10k_wmi_op_gen_pktlog_disable, .gen_pdev_set_quiet_mode = ath10k_wmi_op_gen_pdev_set_quiet_mode, .gen_addba_clear_resp = ath10k_wmi_op_gen_addba_clear_resp, .gen_addba_send = ath10k_wmi_op_gen_addba_send, .gen_addba_set_resp = ath10k_wmi_op_gen_addba_set_resp, .gen_delba_send = ath10k_wmi_op_gen_delba_send, .fw_stats_fill = ath10k_wmi_10x_op_fw_stats_fill, .get_vdev_subtype = ath10k_wmi_op_get_vdev_subtype, /* .gen_pdev_enable_adaptive_cca not implemented */ }; static const struct wmi_ops wmi_10_2_4_ops = { .rx = ath10k_wmi_10_2_op_rx, .pull_fw_stats = ath10k_wmi_10_2_4_op_pull_fw_stats, .gen_init = ath10k_wmi_10_2_op_gen_init, .gen_peer_assoc = ath10k_wmi_10_2_op_gen_peer_assoc, .gen_pdev_get_temperature = ath10k_wmi_10_2_op_gen_pdev_get_temperature, .gen_pdev_bss_chan_info_req = ath10k_wmi_10_2_op_gen_pdev_bss_chan_info, /* shared with 10.1 */ .map_svc = wmi_10x_svc_map, .pull_svc_rdy = ath10k_wmi_10x_op_pull_svc_rdy_ev, .gen_pdev_set_rd = ath10k_wmi_10x_op_gen_pdev_set_rd, .gen_start_scan = ath10k_wmi_10x_op_gen_start_scan, .gen_echo = ath10k_wmi_op_gen_echo, .pull_scan = ath10k_wmi_op_pull_scan_ev, .pull_mgmt_rx = ath10k_wmi_op_pull_mgmt_rx_ev, .pull_ch_info = ath10k_wmi_op_pull_ch_info_ev, .pull_vdev_start = ath10k_wmi_op_pull_vdev_start_ev, .pull_peer_kick = ath10k_wmi_op_pull_peer_kick_ev, .pull_swba = ath10k_wmi_10_2_4_op_pull_swba_ev, .pull_phyerr_hdr = ath10k_wmi_op_pull_phyerr_ev_hdr, .pull_phyerr = ath10k_wmi_op_pull_phyerr_ev, .pull_rdy = ath10k_wmi_op_pull_rdy_ev, .pull_roam_ev = ath10k_wmi_op_pull_roam_ev, .pull_echo_ev = ath10k_wmi_op_pull_echo_ev, .gen_pdev_suspend = ath10k_wmi_op_gen_pdev_suspend, .gen_pdev_resume = ath10k_wmi_op_gen_pdev_resume, .gen_pdev_set_param = ath10k_wmi_op_gen_pdev_set_param, .gen_stop_scan = ath10k_wmi_op_gen_stop_scan, .gen_vdev_create = ath10k_wmi_op_gen_vdev_create, .gen_vdev_delete = ath10k_wmi_op_gen_vdev_delete, .gen_vdev_start = ath10k_wmi_op_gen_vdev_start, .gen_vdev_stop = ath10k_wmi_op_gen_vdev_stop, .gen_vdev_up = ath10k_wmi_op_gen_vdev_up, .gen_vdev_down = ath10k_wmi_op_gen_vdev_down, .gen_vdev_set_param = ath10k_wmi_op_gen_vdev_set_param, .gen_vdev_install_key = ath10k_wmi_op_gen_vdev_install_key, .gen_vdev_spectral_conf = ath10k_wmi_op_gen_vdev_spectral_conf, .gen_vdev_spectral_enable = ath10k_wmi_op_gen_vdev_spectral_enable, .gen_peer_create = ath10k_wmi_op_gen_peer_create, .gen_peer_delete = ath10k_wmi_op_gen_peer_delete, .gen_peer_flush = ath10k_wmi_op_gen_peer_flush, .gen_peer_set_param = ath10k_wmi_op_gen_peer_set_param, .gen_set_psmode = ath10k_wmi_op_gen_set_psmode, .gen_set_sta_ps = ath10k_wmi_op_gen_set_sta_ps, .gen_set_ap_ps = ath10k_wmi_op_gen_set_ap_ps, .gen_scan_chan_list = ath10k_wmi_op_gen_scan_chan_list, .gen_beacon_dma = ath10k_wmi_op_gen_beacon_dma, .gen_pdev_set_wmm = ath10k_wmi_op_gen_pdev_set_wmm, .gen_request_stats = ath10k_wmi_op_gen_request_stats, .gen_force_fw_hang = ath10k_wmi_op_gen_force_fw_hang, .gen_mgmt_tx = ath10k_wmi_op_gen_mgmt_tx, .gen_dbglog_cfg = ath10k_wmi_op_gen_dbglog_cfg, .gen_pktlog_enable = ath10k_wmi_op_gen_pktlog_enable, .gen_pktlog_disable = ath10k_wmi_op_gen_pktlog_disable, .gen_pdev_set_quiet_mode = ath10k_wmi_op_gen_pdev_set_quiet_mode, .gen_addba_clear_resp = ath10k_wmi_op_gen_addba_clear_resp, .gen_addba_send = ath10k_wmi_op_gen_addba_send, .gen_addba_set_resp = ath10k_wmi_op_gen_addba_set_resp, .gen_delba_send = ath10k_wmi_op_gen_delba_send, .gen_pdev_get_tpc_config = ath10k_wmi_10_2_4_op_gen_pdev_get_tpc_config, .fw_stats_fill = ath10k_wmi_10x_op_fw_stats_fill, .gen_pdev_enable_adaptive_cca = ath10k_wmi_op_gen_pdev_enable_adaptive_cca, .get_vdev_subtype = ath10k_wmi_10_2_4_op_get_vdev_subtype, /* .gen_bcn_tmpl not implemented */ /* .gen_prb_tmpl not implemented */ /* .gen_p2p_go_bcn_ie not implemented */ /* .gen_adaptive_qcs not implemented */ }; static const struct wmi_ops wmi_10_4_ops = { .rx = ath10k_wmi_10_4_op_rx, .map_svc = wmi_10_4_svc_map, .pull_fw_stats = ath10k_wmi_10_4_op_pull_fw_stats, .pull_scan = ath10k_wmi_op_pull_scan_ev, .pull_mgmt_rx = ath10k_wmi_10_4_op_pull_mgmt_rx_ev, .pull_ch_info = ath10k_wmi_10_4_op_pull_ch_info_ev, .pull_vdev_start = ath10k_wmi_op_pull_vdev_start_ev, .pull_peer_kick = ath10k_wmi_op_pull_peer_kick_ev, .pull_swba = ath10k_wmi_10_4_op_pull_swba_ev, .pull_phyerr_hdr = ath10k_wmi_10_4_op_pull_phyerr_ev_hdr, .pull_phyerr = ath10k_wmi_10_4_op_pull_phyerr_ev, .pull_svc_rdy = ath10k_wmi_main_op_pull_svc_rdy_ev, .pull_rdy = ath10k_wmi_op_pull_rdy_ev, .pull_roam_ev = ath10k_wmi_op_pull_roam_ev, .get_txbf_conf_scheme = ath10k_wmi_10_4_txbf_conf_scheme, .gen_pdev_suspend = ath10k_wmi_op_gen_pdev_suspend, .gen_pdev_resume = ath10k_wmi_op_gen_pdev_resume, .gen_pdev_set_rd = ath10k_wmi_10x_op_gen_pdev_set_rd, .gen_pdev_set_param = ath10k_wmi_op_gen_pdev_set_param, .gen_init = ath10k_wmi_10_4_op_gen_init, .gen_start_scan = ath10k_wmi_op_gen_start_scan, .gen_stop_scan = ath10k_wmi_op_gen_stop_scan, .gen_vdev_create = ath10k_wmi_op_gen_vdev_create, .gen_vdev_delete = ath10k_wmi_op_gen_vdev_delete, .gen_vdev_start = ath10k_wmi_op_gen_vdev_start, .gen_vdev_stop = ath10k_wmi_op_gen_vdev_stop, .gen_vdev_up = ath10k_wmi_op_gen_vdev_up, .gen_vdev_down = ath10k_wmi_op_gen_vdev_down, .gen_vdev_set_param = ath10k_wmi_op_gen_vdev_set_param, .gen_vdev_install_key = ath10k_wmi_op_gen_vdev_install_key, .gen_vdev_spectral_conf = ath10k_wmi_op_gen_vdev_spectral_conf, .gen_vdev_spectral_enable = ath10k_wmi_op_gen_vdev_spectral_enable, .gen_peer_create = ath10k_wmi_op_gen_peer_create, .gen_peer_delete = ath10k_wmi_op_gen_peer_delete, .gen_peer_flush = ath10k_wmi_op_gen_peer_flush, .gen_peer_set_param = ath10k_wmi_op_gen_peer_set_param, .gen_peer_assoc = ath10k_wmi_10_4_op_gen_peer_assoc, .gen_set_psmode = ath10k_wmi_op_gen_set_psmode, .gen_set_sta_ps = ath10k_wmi_op_gen_set_sta_ps, .gen_set_ap_ps = ath10k_wmi_op_gen_set_ap_ps, .gen_scan_chan_list = ath10k_wmi_op_gen_scan_chan_list, .gen_beacon_dma = ath10k_wmi_op_gen_beacon_dma, .gen_pdev_set_wmm = ath10k_wmi_op_gen_pdev_set_wmm, .gen_force_fw_hang = ath10k_wmi_op_gen_force_fw_hang, .gen_mgmt_tx = ath10k_wmi_op_gen_mgmt_tx, .gen_dbglog_cfg = ath10k_wmi_10_4_op_gen_dbglog_cfg, .gen_pktlog_enable = ath10k_wmi_op_gen_pktlog_enable, .gen_pktlog_disable = ath10k_wmi_op_gen_pktlog_disable, .gen_pdev_set_quiet_mode = ath10k_wmi_op_gen_pdev_set_quiet_mode, .gen_addba_clear_resp = ath10k_wmi_op_gen_addba_clear_resp, .gen_addba_send = ath10k_wmi_op_gen_addba_send, .gen_addba_set_resp = ath10k_wmi_op_gen_addba_set_resp, .gen_delba_send = ath10k_wmi_op_gen_delba_send, .fw_stats_fill = ath10k_wmi_10_4_op_fw_stats_fill, .ext_resource_config = ath10k_wmi_10_4_ext_resource_config, /* shared with 10.2 */ .pull_echo_ev = ath10k_wmi_op_pull_echo_ev, .gen_request_stats = ath10k_wmi_op_gen_request_stats, .gen_pdev_get_temperature = ath10k_wmi_10_2_op_gen_pdev_get_temperature, .get_vdev_subtype = ath10k_wmi_10_4_op_get_vdev_subtype, .gen_pdev_bss_chan_info_req = ath10k_wmi_10_2_op_gen_pdev_bss_chan_info, .gen_echo = ath10k_wmi_op_gen_echo, .gen_pdev_get_tpc_config = ath10k_wmi_10_2_4_op_gen_pdev_get_tpc_config, }; int ath10k_wmi_attach(struct ath10k *ar) { switch (ar->running_fw->fw_file.wmi_op_version) { case ATH10K_FW_WMI_OP_VERSION_10_4: ar->wmi.ops = &wmi_10_4_ops; ar->wmi.cmd = &wmi_10_4_cmd_map; ar->wmi.vdev_param = &wmi_10_4_vdev_param_map; ar->wmi.pdev_param = &wmi_10_4_pdev_param_map; ar->wmi.peer_flags = &wmi_10_2_peer_flags_map; break; case ATH10K_FW_WMI_OP_VERSION_10_2_4: ar->wmi.cmd = &wmi_10_2_4_cmd_map; ar->wmi.ops = &wmi_10_2_4_ops; ar->wmi.vdev_param = &wmi_10_2_4_vdev_param_map; ar->wmi.pdev_param = &wmi_10_2_4_pdev_param_map; ar->wmi.peer_flags = &wmi_10_2_peer_flags_map; break; case ATH10K_FW_WMI_OP_VERSION_10_2: ar->wmi.cmd = &wmi_10_2_cmd_map; ar->wmi.ops = &wmi_10_2_ops; ar->wmi.vdev_param = &wmi_10x_vdev_param_map; ar->wmi.pdev_param = &wmi_10x_pdev_param_map; ar->wmi.peer_flags = &wmi_10_2_peer_flags_map; break; case ATH10K_FW_WMI_OP_VERSION_10_1: ar->wmi.cmd = &wmi_10x_cmd_map; ar->wmi.ops = &wmi_10_1_ops; ar->wmi.vdev_param = &wmi_10x_vdev_param_map; ar->wmi.pdev_param = &wmi_10x_pdev_param_map; ar->wmi.peer_flags = &wmi_10x_peer_flags_map; break; case ATH10K_FW_WMI_OP_VERSION_MAIN: ar->wmi.cmd = &wmi_cmd_map; ar->wmi.ops = &wmi_ops; ar->wmi.vdev_param = &wmi_vdev_param_map; ar->wmi.pdev_param = &wmi_pdev_param_map; ar->wmi.peer_flags = &wmi_peer_flags_map; break; case ATH10K_FW_WMI_OP_VERSION_TLV: ath10k_wmi_tlv_attach(ar); break; case ATH10K_FW_WMI_OP_VERSION_UNSET: case ATH10K_FW_WMI_OP_VERSION_MAX: ath10k_err(ar, "unsupported WMI op version: %d\n", ar->running_fw->fw_file.wmi_op_version); return -EINVAL; } init_completion(&ar->wmi.service_ready); init_completion(&ar->wmi.unified_ready); init_completion(&ar->wmi.barrier); INIT_WORK(&ar->svc_rdy_work, ath10k_wmi_event_service_ready_work); return 0; } void ath10k_wmi_free_host_mem(struct ath10k *ar) { int i; /* free the host memory chunks requested by firmware */ for (i = 0; i < ar->wmi.num_mem_chunks; i++) { dma_unmap_single(ar->dev, ar->wmi.mem_chunks[i].paddr, ar->wmi.mem_chunks[i].len, DMA_BIDIRECTIONAL); kfree(ar->wmi.mem_chunks[i].vaddr); } ar->wmi.num_mem_chunks = 0; } void ath10k_wmi_detach(struct ath10k *ar) { cancel_work_sync(&ar->svc_rdy_work); if (ar->svc_rdy_skb) dev_kfree_skb(ar->svc_rdy_skb); }
null
null
null
null
95,515
37,807
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
202,802
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * intel-bts.h: Intel Processor Trace support * Copyright (c) 2013-2014, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * */ #ifndef INCLUDE__PERF_INTEL_BTS_H__ #define INCLUDE__PERF_INTEL_BTS_H__ #define INTEL_BTS_PMU_NAME "intel_bts" enum { INTEL_BTS_PMU_TYPE, INTEL_BTS_TIME_SHIFT, INTEL_BTS_TIME_MULT, INTEL_BTS_TIME_ZERO, INTEL_BTS_CAP_USER_TIME_ZERO, INTEL_BTS_SNAPSHOT_MODE, INTEL_BTS_AUXTRACE_PRIV_MAX, }; #define INTEL_BTS_AUXTRACE_PRIV_SIZE (INTEL_BTS_AUXTRACE_PRIV_MAX * sizeof(u64)) struct auxtrace_record; struct perf_tool; union perf_event; struct perf_session; struct auxtrace_record *intel_bts_recording_init(int *err); int intel_bts_process_auxtrace_info(union perf_event *event, struct perf_session *session); #endif
null
null
null
null
111,149
20,464
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
185,459
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/******************************************************************************* * * Intel Ethernet Controller XL710 Family Linux Virtual Function Driver * Copyright(c) 2013 - 2014 Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". * * Contact Information: * e1000-devel Mailing List <e1000-devel@lists.sourceforge.net> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * ******************************************************************************/ #include "i40e_type.h" #include "i40e_adminq.h" #include "i40e_prototype.h" #include "i40e_virtchnl.h" /** * i40e_set_mac_type - Sets MAC type * @hw: pointer to the HW structure * * This function sets the mac type of the adapter based on the * vendor ID and device ID stored in the hw structure. **/ i40e_status i40e_set_mac_type(struct i40e_hw *hw) { i40e_status status = 0; if (hw->vendor_id == PCI_VENDOR_ID_INTEL) { switch (hw->device_id) { case I40E_DEV_ID_SFP_XL710: case I40E_DEV_ID_QEMU: case I40E_DEV_ID_KX_B: case I40E_DEV_ID_KX_C: case I40E_DEV_ID_QSFP_A: case I40E_DEV_ID_QSFP_B: case I40E_DEV_ID_QSFP_C: case I40E_DEV_ID_10G_BASE_T: case I40E_DEV_ID_10G_BASE_T4: case I40E_DEV_ID_20G_KR2: case I40E_DEV_ID_20G_KR2_A: case I40E_DEV_ID_25G_B: case I40E_DEV_ID_25G_SFP28: hw->mac.type = I40E_MAC_XL710; break; case I40E_DEV_ID_SFP_X722: case I40E_DEV_ID_1G_BASE_T_X722: case I40E_DEV_ID_10G_BASE_T_X722: case I40E_DEV_ID_SFP_I_X722: hw->mac.type = I40E_MAC_X722; break; case I40E_DEV_ID_X722_VF: hw->mac.type = I40E_MAC_X722_VF; break; case I40E_DEV_ID_VF: case I40E_DEV_ID_VF_HV: hw->mac.type = I40E_MAC_VF; break; default: hw->mac.type = I40E_MAC_GENERIC; break; } } else { status = I40E_ERR_DEVICE_NOT_SUPPORTED; } hw_dbg(hw, "i40e_set_mac_type found mac: %d, returns: %d\n", hw->mac.type, status); return status; } /** * i40evf_aq_str - convert AQ err code to a string * @hw: pointer to the HW structure * @aq_err: the AQ error code to convert **/ const char *i40evf_aq_str(struct i40e_hw *hw, enum i40e_admin_queue_err aq_err) { switch (aq_err) { case I40E_AQ_RC_OK: return "OK"; case I40E_AQ_RC_EPERM: return "I40E_AQ_RC_EPERM"; case I40E_AQ_RC_ENOENT: return "I40E_AQ_RC_ENOENT"; case I40E_AQ_RC_ESRCH: return "I40E_AQ_RC_ESRCH"; case I40E_AQ_RC_EINTR: return "I40E_AQ_RC_EINTR"; case I40E_AQ_RC_EIO: return "I40E_AQ_RC_EIO"; case I40E_AQ_RC_ENXIO: return "I40E_AQ_RC_ENXIO"; case I40E_AQ_RC_E2BIG: return "I40E_AQ_RC_E2BIG"; case I40E_AQ_RC_EAGAIN: return "I40E_AQ_RC_EAGAIN"; case I40E_AQ_RC_ENOMEM: return "I40E_AQ_RC_ENOMEM"; case I40E_AQ_RC_EACCES: return "I40E_AQ_RC_EACCES"; case I40E_AQ_RC_EFAULT: return "I40E_AQ_RC_EFAULT"; case I40E_AQ_RC_EBUSY: return "I40E_AQ_RC_EBUSY"; case I40E_AQ_RC_EEXIST: return "I40E_AQ_RC_EEXIST"; case I40E_AQ_RC_EINVAL: return "I40E_AQ_RC_EINVAL"; case I40E_AQ_RC_ENOTTY: return "I40E_AQ_RC_ENOTTY"; case I40E_AQ_RC_ENOSPC: return "I40E_AQ_RC_ENOSPC"; case I40E_AQ_RC_ENOSYS: return "I40E_AQ_RC_ENOSYS"; case I40E_AQ_RC_ERANGE: return "I40E_AQ_RC_ERANGE"; case I40E_AQ_RC_EFLUSHED: return "I40E_AQ_RC_EFLUSHED"; case I40E_AQ_RC_BAD_ADDR: return "I40E_AQ_RC_BAD_ADDR"; case I40E_AQ_RC_EMODE: return "I40E_AQ_RC_EMODE"; case I40E_AQ_RC_EFBIG: return "I40E_AQ_RC_EFBIG"; } snprintf(hw->err_str, sizeof(hw->err_str), "%d", aq_err); return hw->err_str; } /** * i40evf_stat_str - convert status err code to a string * @hw: pointer to the HW structure * @stat_err: the status error code to convert **/ const char *i40evf_stat_str(struct i40e_hw *hw, i40e_status stat_err) { switch (stat_err) { case 0: return "OK"; case I40E_ERR_NVM: return "I40E_ERR_NVM"; case I40E_ERR_NVM_CHECKSUM: return "I40E_ERR_NVM_CHECKSUM"; case I40E_ERR_PHY: return "I40E_ERR_PHY"; case I40E_ERR_CONFIG: return "I40E_ERR_CONFIG"; case I40E_ERR_PARAM: return "I40E_ERR_PARAM"; case I40E_ERR_MAC_TYPE: return "I40E_ERR_MAC_TYPE"; case I40E_ERR_UNKNOWN_PHY: return "I40E_ERR_UNKNOWN_PHY"; case I40E_ERR_LINK_SETUP: return "I40E_ERR_LINK_SETUP"; case I40E_ERR_ADAPTER_STOPPED: return "I40E_ERR_ADAPTER_STOPPED"; case I40E_ERR_INVALID_MAC_ADDR: return "I40E_ERR_INVALID_MAC_ADDR"; case I40E_ERR_DEVICE_NOT_SUPPORTED: return "I40E_ERR_DEVICE_NOT_SUPPORTED"; case I40E_ERR_MASTER_REQUESTS_PENDING: return "I40E_ERR_MASTER_REQUESTS_PENDING"; case I40E_ERR_INVALID_LINK_SETTINGS: return "I40E_ERR_INVALID_LINK_SETTINGS"; case I40E_ERR_AUTONEG_NOT_COMPLETE: return "I40E_ERR_AUTONEG_NOT_COMPLETE"; case I40E_ERR_RESET_FAILED: return "I40E_ERR_RESET_FAILED"; case I40E_ERR_SWFW_SYNC: return "I40E_ERR_SWFW_SYNC"; case I40E_ERR_NO_AVAILABLE_VSI: return "I40E_ERR_NO_AVAILABLE_VSI"; case I40E_ERR_NO_MEMORY: return "I40E_ERR_NO_MEMORY"; case I40E_ERR_BAD_PTR: return "I40E_ERR_BAD_PTR"; case I40E_ERR_RING_FULL: return "I40E_ERR_RING_FULL"; case I40E_ERR_INVALID_PD_ID: return "I40E_ERR_INVALID_PD_ID"; case I40E_ERR_INVALID_QP_ID: return "I40E_ERR_INVALID_QP_ID"; case I40E_ERR_INVALID_CQ_ID: return "I40E_ERR_INVALID_CQ_ID"; case I40E_ERR_INVALID_CEQ_ID: return "I40E_ERR_INVALID_CEQ_ID"; case I40E_ERR_INVALID_AEQ_ID: return "I40E_ERR_INVALID_AEQ_ID"; case I40E_ERR_INVALID_SIZE: return "I40E_ERR_INVALID_SIZE"; case I40E_ERR_INVALID_ARP_INDEX: return "I40E_ERR_INVALID_ARP_INDEX"; case I40E_ERR_INVALID_FPM_FUNC_ID: return "I40E_ERR_INVALID_FPM_FUNC_ID"; case I40E_ERR_QP_INVALID_MSG_SIZE: return "I40E_ERR_QP_INVALID_MSG_SIZE"; case I40E_ERR_QP_TOOMANY_WRS_POSTED: return "I40E_ERR_QP_TOOMANY_WRS_POSTED"; case I40E_ERR_INVALID_FRAG_COUNT: return "I40E_ERR_INVALID_FRAG_COUNT"; case I40E_ERR_QUEUE_EMPTY: return "I40E_ERR_QUEUE_EMPTY"; case I40E_ERR_INVALID_ALIGNMENT: return "I40E_ERR_INVALID_ALIGNMENT"; case I40E_ERR_FLUSHED_QUEUE: return "I40E_ERR_FLUSHED_QUEUE"; case I40E_ERR_INVALID_PUSH_PAGE_INDEX: return "I40E_ERR_INVALID_PUSH_PAGE_INDEX"; case I40E_ERR_INVALID_IMM_DATA_SIZE: return "I40E_ERR_INVALID_IMM_DATA_SIZE"; case I40E_ERR_TIMEOUT: return "I40E_ERR_TIMEOUT"; case I40E_ERR_OPCODE_MISMATCH: return "I40E_ERR_OPCODE_MISMATCH"; case I40E_ERR_CQP_COMPL_ERROR: return "I40E_ERR_CQP_COMPL_ERROR"; case I40E_ERR_INVALID_VF_ID: return "I40E_ERR_INVALID_VF_ID"; case I40E_ERR_INVALID_HMCFN_ID: return "I40E_ERR_INVALID_HMCFN_ID"; case I40E_ERR_BACKING_PAGE_ERROR: return "I40E_ERR_BACKING_PAGE_ERROR"; case I40E_ERR_NO_PBLCHUNKS_AVAILABLE: return "I40E_ERR_NO_PBLCHUNKS_AVAILABLE"; case I40E_ERR_INVALID_PBLE_INDEX: return "I40E_ERR_INVALID_PBLE_INDEX"; case I40E_ERR_INVALID_SD_INDEX: return "I40E_ERR_INVALID_SD_INDEX"; case I40E_ERR_INVALID_PAGE_DESC_INDEX: return "I40E_ERR_INVALID_PAGE_DESC_INDEX"; case I40E_ERR_INVALID_SD_TYPE: return "I40E_ERR_INVALID_SD_TYPE"; case I40E_ERR_MEMCPY_FAILED: return "I40E_ERR_MEMCPY_FAILED"; case I40E_ERR_INVALID_HMC_OBJ_INDEX: return "I40E_ERR_INVALID_HMC_OBJ_INDEX"; case I40E_ERR_INVALID_HMC_OBJ_COUNT: return "I40E_ERR_INVALID_HMC_OBJ_COUNT"; case I40E_ERR_INVALID_SRQ_ARM_LIMIT: return "I40E_ERR_INVALID_SRQ_ARM_LIMIT"; case I40E_ERR_SRQ_ENABLED: return "I40E_ERR_SRQ_ENABLED"; case I40E_ERR_ADMIN_QUEUE_ERROR: return "I40E_ERR_ADMIN_QUEUE_ERROR"; case I40E_ERR_ADMIN_QUEUE_TIMEOUT: return "I40E_ERR_ADMIN_QUEUE_TIMEOUT"; case I40E_ERR_BUF_TOO_SHORT: return "I40E_ERR_BUF_TOO_SHORT"; case I40E_ERR_ADMIN_QUEUE_FULL: return "I40E_ERR_ADMIN_QUEUE_FULL"; case I40E_ERR_ADMIN_QUEUE_NO_WORK: return "I40E_ERR_ADMIN_QUEUE_NO_WORK"; case I40E_ERR_BAD_IWARP_CQE: return "I40E_ERR_BAD_IWARP_CQE"; case I40E_ERR_NVM_BLANK_MODE: return "I40E_ERR_NVM_BLANK_MODE"; case I40E_ERR_NOT_IMPLEMENTED: return "I40E_ERR_NOT_IMPLEMENTED"; case I40E_ERR_PE_DOORBELL_NOT_ENABLED: return "I40E_ERR_PE_DOORBELL_NOT_ENABLED"; case I40E_ERR_DIAG_TEST_FAILED: return "I40E_ERR_DIAG_TEST_FAILED"; case I40E_ERR_NOT_READY: return "I40E_ERR_NOT_READY"; case I40E_NOT_SUPPORTED: return "I40E_NOT_SUPPORTED"; case I40E_ERR_FIRMWARE_API_VERSION: return "I40E_ERR_FIRMWARE_API_VERSION"; } snprintf(hw->err_str, sizeof(hw->err_str), "%d", stat_err); return hw->err_str; } /** * i40evf_debug_aq * @hw: debug mask related to admin queue * @mask: debug mask * @desc: pointer to admin queue descriptor * @buffer: pointer to command buffer * @buf_len: max length of buffer * * Dumps debug log about adminq command with descriptor contents. **/ void i40evf_debug_aq(struct i40e_hw *hw, enum i40e_debug_mask mask, void *desc, void *buffer, u16 buf_len) { struct i40e_aq_desc *aq_desc = (struct i40e_aq_desc *)desc; u8 *buf = (u8 *)buffer; if ((!(mask & hw->debug_mask)) || (desc == NULL)) return; i40e_debug(hw, mask, "AQ CMD: opcode 0x%04X, flags 0x%04X, datalen 0x%04X, retval 0x%04X\n", le16_to_cpu(aq_desc->opcode), le16_to_cpu(aq_desc->flags), le16_to_cpu(aq_desc->datalen), le16_to_cpu(aq_desc->retval)); i40e_debug(hw, mask, "\tcookie (h,l) 0x%08X 0x%08X\n", le32_to_cpu(aq_desc->cookie_high), le32_to_cpu(aq_desc->cookie_low)); i40e_debug(hw, mask, "\tparam (0,1) 0x%08X 0x%08X\n", le32_to_cpu(aq_desc->params.internal.param0), le32_to_cpu(aq_desc->params.internal.param1)); i40e_debug(hw, mask, "\taddr (h,l) 0x%08X 0x%08X\n", le32_to_cpu(aq_desc->params.external.addr_high), le32_to_cpu(aq_desc->params.external.addr_low)); if ((buffer != NULL) && (aq_desc->datalen != 0)) { u16 len = le16_to_cpu(aq_desc->datalen); i40e_debug(hw, mask, "AQ CMD Buffer:\n"); if (buf_len < len) len = buf_len; /* write the full 16-byte chunks */ if (hw->debug_mask & mask) { char prefix[20]; snprintf(prefix, 20, "i40evf %02x:%02x.%x: \t0x", hw->bus.bus_id, hw->bus.device, hw->bus.func); print_hex_dump(KERN_INFO, prefix, DUMP_PREFIX_OFFSET, 16, 1, buf, len, false); } } } /** * i40evf_check_asq_alive * @hw: pointer to the hw struct * * Returns true if Queue is enabled else false. **/ bool i40evf_check_asq_alive(struct i40e_hw *hw) { if (hw->aq.asq.len) return !!(rd32(hw, hw->aq.asq.len) & I40E_VF_ATQLEN1_ATQENABLE_MASK); else return false; } /** * i40evf_aq_queue_shutdown * @hw: pointer to the hw struct * @unloading: is the driver unloading itself * * Tell the Firmware that we're shutting down the AdminQ and whether * or not the driver is unloading as well. **/ i40e_status i40evf_aq_queue_shutdown(struct i40e_hw *hw, bool unloading) { struct i40e_aq_desc desc; struct i40e_aqc_queue_shutdown *cmd = (struct i40e_aqc_queue_shutdown *)&desc.params.raw; i40e_status status; i40evf_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_queue_shutdown); if (unloading) cmd->driver_unloading = cpu_to_le32(I40E_AQ_DRIVER_UNLOADING); status = i40evf_asq_send_command(hw, &desc, NULL, 0, NULL); return status; } /** * i40e_aq_get_set_rss_lut * @hw: pointer to the hardware structure * @vsi_id: vsi fw index * @pf_lut: for PF table set true, for VSI table set false * @lut: pointer to the lut buffer provided by the caller * @lut_size: size of the lut buffer * @set: set true to set the table, false to get the table * * Internal function to get or set RSS look up table **/ static i40e_status i40e_aq_get_set_rss_lut(struct i40e_hw *hw, u16 vsi_id, bool pf_lut, u8 *lut, u16 lut_size, bool set) { i40e_status status; struct i40e_aq_desc desc; struct i40e_aqc_get_set_rss_lut *cmd_resp = (struct i40e_aqc_get_set_rss_lut *)&desc.params.raw; if (set) i40evf_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_set_rss_lut); else i40evf_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_get_rss_lut); /* Indirect command */ desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF); desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_RD); cmd_resp->vsi_id = cpu_to_le16((u16)((vsi_id << I40E_AQC_SET_RSS_LUT_VSI_ID_SHIFT) & I40E_AQC_SET_RSS_LUT_VSI_ID_MASK)); cmd_resp->vsi_id |= cpu_to_le16((u16)I40E_AQC_SET_RSS_LUT_VSI_VALID); if (pf_lut) cmd_resp->flags |= cpu_to_le16((u16) ((I40E_AQC_SET_RSS_LUT_TABLE_TYPE_PF << I40E_AQC_SET_RSS_LUT_TABLE_TYPE_SHIFT) & I40E_AQC_SET_RSS_LUT_TABLE_TYPE_MASK)); else cmd_resp->flags |= cpu_to_le16((u16) ((I40E_AQC_SET_RSS_LUT_TABLE_TYPE_VSI << I40E_AQC_SET_RSS_LUT_TABLE_TYPE_SHIFT) & I40E_AQC_SET_RSS_LUT_TABLE_TYPE_MASK)); status = i40evf_asq_send_command(hw, &desc, lut, lut_size, NULL); return status; } /** * i40evf_aq_get_rss_lut * @hw: pointer to the hardware structure * @vsi_id: vsi fw index * @pf_lut: for PF table set true, for VSI table set false * @lut: pointer to the lut buffer provided by the caller * @lut_size: size of the lut buffer * * get the RSS lookup table, PF or VSI type **/ i40e_status i40evf_aq_get_rss_lut(struct i40e_hw *hw, u16 vsi_id, bool pf_lut, u8 *lut, u16 lut_size) { return i40e_aq_get_set_rss_lut(hw, vsi_id, pf_lut, lut, lut_size, false); } /** * i40evf_aq_set_rss_lut * @hw: pointer to the hardware structure * @vsi_id: vsi fw index * @pf_lut: for PF table set true, for VSI table set false * @lut: pointer to the lut buffer provided by the caller * @lut_size: size of the lut buffer * * set the RSS lookup table, PF or VSI type **/ i40e_status i40evf_aq_set_rss_lut(struct i40e_hw *hw, u16 vsi_id, bool pf_lut, u8 *lut, u16 lut_size) { return i40e_aq_get_set_rss_lut(hw, vsi_id, pf_lut, lut, lut_size, true); } /** * i40e_aq_get_set_rss_key * @hw: pointer to the hw struct * @vsi_id: vsi fw index * @key: pointer to key info struct * @set: set true to set the key, false to get the key * * get the RSS key per VSI **/ static i40e_status i40e_aq_get_set_rss_key(struct i40e_hw *hw, u16 vsi_id, struct i40e_aqc_get_set_rss_key_data *key, bool set) { i40e_status status; struct i40e_aq_desc desc; struct i40e_aqc_get_set_rss_key *cmd_resp = (struct i40e_aqc_get_set_rss_key *)&desc.params.raw; u16 key_size = sizeof(struct i40e_aqc_get_set_rss_key_data); if (set) i40evf_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_set_rss_key); else i40evf_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_get_rss_key); /* Indirect command */ desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_BUF); desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_RD); cmd_resp->vsi_id = cpu_to_le16((u16)((vsi_id << I40E_AQC_SET_RSS_KEY_VSI_ID_SHIFT) & I40E_AQC_SET_RSS_KEY_VSI_ID_MASK)); cmd_resp->vsi_id |= cpu_to_le16((u16)I40E_AQC_SET_RSS_KEY_VSI_VALID); status = i40evf_asq_send_command(hw, &desc, key, key_size, NULL); return status; } /** * i40evf_aq_get_rss_key * @hw: pointer to the hw struct * @vsi_id: vsi fw index * @key: pointer to key info struct * **/ i40e_status i40evf_aq_get_rss_key(struct i40e_hw *hw, u16 vsi_id, struct i40e_aqc_get_set_rss_key_data *key) { return i40e_aq_get_set_rss_key(hw, vsi_id, key, false); } /** * i40evf_aq_set_rss_key * @hw: pointer to the hw struct * @vsi_id: vsi fw index * @key: pointer to key info struct * * set the RSS key per VSI **/ i40e_status i40evf_aq_set_rss_key(struct i40e_hw *hw, u16 vsi_id, struct i40e_aqc_get_set_rss_key_data *key) { return i40e_aq_get_set_rss_key(hw, vsi_id, key, true); } /* The i40evf_ptype_lookup table is used to convert from the 8-bit ptype in the * hardware to a bit-field that can be used by SW to more easily determine the * packet type. * * Macros are used to shorten the table lines and make this table human * readable. * * We store the PTYPE in the top byte of the bit field - this is just so that * we can check that the table doesn't have a row missing, as the index into * the table should be the PTYPE. * * Typical work flow: * * IF NOT i40evf_ptype_lookup[ptype].known * THEN * Packet is unknown * ELSE IF i40evf_ptype_lookup[ptype].outer_ip == I40E_RX_PTYPE_OUTER_IP * Use the rest of the fields to look at the tunnels, inner protocols, etc * ELSE * Use the enum i40e_rx_l2_ptype to decode the packet type * ENDIF */ /* macro to make the table lines short */ #define I40E_PTT(PTYPE, OUTER_IP, OUTER_IP_VER, OUTER_FRAG, T, TE, TEF, I, PL)\ { PTYPE, \ 1, \ I40E_RX_PTYPE_OUTER_##OUTER_IP, \ I40E_RX_PTYPE_OUTER_##OUTER_IP_VER, \ I40E_RX_PTYPE_##OUTER_FRAG, \ I40E_RX_PTYPE_TUNNEL_##T, \ I40E_RX_PTYPE_TUNNEL_END_##TE, \ I40E_RX_PTYPE_##TEF, \ I40E_RX_PTYPE_INNER_PROT_##I, \ I40E_RX_PTYPE_PAYLOAD_LAYER_##PL } #define I40E_PTT_UNUSED_ENTRY(PTYPE) \ { PTYPE, 0, 0, 0, 0, 0, 0, 0, 0, 0 } /* shorter macros makes the table fit but are terse */ #define I40E_RX_PTYPE_NOF I40E_RX_PTYPE_NOT_FRAG #define I40E_RX_PTYPE_FRG I40E_RX_PTYPE_FRAG #define I40E_RX_PTYPE_INNER_PROT_TS I40E_RX_PTYPE_INNER_PROT_TIMESYNC /* Lookup table mapping the HW PTYPE to the bit field for decoding */ struct i40e_rx_ptype_decoded i40evf_ptype_lookup[] = { /* L2 Packet types */ I40E_PTT_UNUSED_ENTRY(0), I40E_PTT(1, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY2), I40E_PTT(2, L2, NONE, NOF, NONE, NONE, NOF, TS, PAY2), I40E_PTT(3, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY2), I40E_PTT_UNUSED_ENTRY(4), I40E_PTT_UNUSED_ENTRY(5), I40E_PTT(6, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY2), I40E_PTT(7, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY2), I40E_PTT_UNUSED_ENTRY(8), I40E_PTT_UNUSED_ENTRY(9), I40E_PTT(10, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY2), I40E_PTT(11, L2, NONE, NOF, NONE, NONE, NOF, NONE, NONE), I40E_PTT(12, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(13, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(14, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(15, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(16, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(17, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(18, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(19, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(20, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(21, L2, NONE, NOF, NONE, NONE, NOF, NONE, PAY3), /* Non Tunneled IPv4 */ I40E_PTT(22, IP, IPV4, FRG, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(23, IP, IPV4, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(24, IP, IPV4, NOF, NONE, NONE, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(25), I40E_PTT(26, IP, IPV4, NOF, NONE, NONE, NOF, TCP, PAY4), I40E_PTT(27, IP, IPV4, NOF, NONE, NONE, NOF, SCTP, PAY4), I40E_PTT(28, IP, IPV4, NOF, NONE, NONE, NOF, ICMP, PAY4), /* IPv4 --> IPv4 */ I40E_PTT(29, IP, IPV4, NOF, IP_IP, IPV4, FRG, NONE, PAY3), I40E_PTT(30, IP, IPV4, NOF, IP_IP, IPV4, NOF, NONE, PAY3), I40E_PTT(31, IP, IPV4, NOF, IP_IP, IPV4, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(32), I40E_PTT(33, IP, IPV4, NOF, IP_IP, IPV4, NOF, TCP, PAY4), I40E_PTT(34, IP, IPV4, NOF, IP_IP, IPV4, NOF, SCTP, PAY4), I40E_PTT(35, IP, IPV4, NOF, IP_IP, IPV4, NOF, ICMP, PAY4), /* IPv4 --> IPv6 */ I40E_PTT(36, IP, IPV4, NOF, IP_IP, IPV6, FRG, NONE, PAY3), I40E_PTT(37, IP, IPV4, NOF, IP_IP, IPV6, NOF, NONE, PAY3), I40E_PTT(38, IP, IPV4, NOF, IP_IP, IPV6, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(39), I40E_PTT(40, IP, IPV4, NOF, IP_IP, IPV6, NOF, TCP, PAY4), I40E_PTT(41, IP, IPV4, NOF, IP_IP, IPV6, NOF, SCTP, PAY4), I40E_PTT(42, IP, IPV4, NOF, IP_IP, IPV6, NOF, ICMP, PAY4), /* IPv4 --> GRE/NAT */ I40E_PTT(43, IP, IPV4, NOF, IP_GRENAT, NONE, NOF, NONE, PAY3), /* IPv4 --> GRE/NAT --> IPv4 */ I40E_PTT(44, IP, IPV4, NOF, IP_GRENAT, IPV4, FRG, NONE, PAY3), I40E_PTT(45, IP, IPV4, NOF, IP_GRENAT, IPV4, NOF, NONE, PAY3), I40E_PTT(46, IP, IPV4, NOF, IP_GRENAT, IPV4, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(47), I40E_PTT(48, IP, IPV4, NOF, IP_GRENAT, IPV4, NOF, TCP, PAY4), I40E_PTT(49, IP, IPV4, NOF, IP_GRENAT, IPV4, NOF, SCTP, PAY4), I40E_PTT(50, IP, IPV4, NOF, IP_GRENAT, IPV4, NOF, ICMP, PAY4), /* IPv4 --> GRE/NAT --> IPv6 */ I40E_PTT(51, IP, IPV4, NOF, IP_GRENAT, IPV6, FRG, NONE, PAY3), I40E_PTT(52, IP, IPV4, NOF, IP_GRENAT, IPV6, NOF, NONE, PAY3), I40E_PTT(53, IP, IPV4, NOF, IP_GRENAT, IPV6, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(54), I40E_PTT(55, IP, IPV4, NOF, IP_GRENAT, IPV6, NOF, TCP, PAY4), I40E_PTT(56, IP, IPV4, NOF, IP_GRENAT, IPV6, NOF, SCTP, PAY4), I40E_PTT(57, IP, IPV4, NOF, IP_GRENAT, IPV6, NOF, ICMP, PAY4), /* IPv4 --> GRE/NAT --> MAC */ I40E_PTT(58, IP, IPV4, NOF, IP_GRENAT_MAC, NONE, NOF, NONE, PAY3), /* IPv4 --> GRE/NAT --> MAC --> IPv4 */ I40E_PTT(59, IP, IPV4, NOF, IP_GRENAT_MAC, IPV4, FRG, NONE, PAY3), I40E_PTT(60, IP, IPV4, NOF, IP_GRENAT_MAC, IPV4, NOF, NONE, PAY3), I40E_PTT(61, IP, IPV4, NOF, IP_GRENAT_MAC, IPV4, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(62), I40E_PTT(63, IP, IPV4, NOF, IP_GRENAT_MAC, IPV4, NOF, TCP, PAY4), I40E_PTT(64, IP, IPV4, NOF, IP_GRENAT_MAC, IPV4, NOF, SCTP, PAY4), I40E_PTT(65, IP, IPV4, NOF, IP_GRENAT_MAC, IPV4, NOF, ICMP, PAY4), /* IPv4 --> GRE/NAT -> MAC --> IPv6 */ I40E_PTT(66, IP, IPV4, NOF, IP_GRENAT_MAC, IPV6, FRG, NONE, PAY3), I40E_PTT(67, IP, IPV4, NOF, IP_GRENAT_MAC, IPV6, NOF, NONE, PAY3), I40E_PTT(68, IP, IPV4, NOF, IP_GRENAT_MAC, IPV6, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(69), I40E_PTT(70, IP, IPV4, NOF, IP_GRENAT_MAC, IPV6, NOF, TCP, PAY4), I40E_PTT(71, IP, IPV4, NOF, IP_GRENAT_MAC, IPV6, NOF, SCTP, PAY4), I40E_PTT(72, IP, IPV4, NOF, IP_GRENAT_MAC, IPV6, NOF, ICMP, PAY4), /* IPv4 --> GRE/NAT --> MAC/VLAN */ I40E_PTT(73, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, NONE, NOF, NONE, PAY3), /* IPv4 ---> GRE/NAT -> MAC/VLAN --> IPv4 */ I40E_PTT(74, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV4, FRG, NONE, PAY3), I40E_PTT(75, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, NONE, PAY3), I40E_PTT(76, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(77), I40E_PTT(78, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, TCP, PAY4), I40E_PTT(79, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, SCTP, PAY4), I40E_PTT(80, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, ICMP, PAY4), /* IPv4 -> GRE/NAT -> MAC/VLAN --> IPv6 */ I40E_PTT(81, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV6, FRG, NONE, PAY3), I40E_PTT(82, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, NONE, PAY3), I40E_PTT(83, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(84), I40E_PTT(85, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, TCP, PAY4), I40E_PTT(86, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, SCTP, PAY4), I40E_PTT(87, IP, IPV4, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, ICMP, PAY4), /* Non Tunneled IPv6 */ I40E_PTT(88, IP, IPV6, FRG, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(89, IP, IPV6, NOF, NONE, NONE, NOF, NONE, PAY3), I40E_PTT(90, IP, IPV6, NOF, NONE, NONE, NOF, UDP, PAY3), I40E_PTT_UNUSED_ENTRY(91), I40E_PTT(92, IP, IPV6, NOF, NONE, NONE, NOF, TCP, PAY4), I40E_PTT(93, IP, IPV6, NOF, NONE, NONE, NOF, SCTP, PAY4), I40E_PTT(94, IP, IPV6, NOF, NONE, NONE, NOF, ICMP, PAY4), /* IPv6 --> IPv4 */ I40E_PTT(95, IP, IPV6, NOF, IP_IP, IPV4, FRG, NONE, PAY3), I40E_PTT(96, IP, IPV6, NOF, IP_IP, IPV4, NOF, NONE, PAY3), I40E_PTT(97, IP, IPV6, NOF, IP_IP, IPV4, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(98), I40E_PTT(99, IP, IPV6, NOF, IP_IP, IPV4, NOF, TCP, PAY4), I40E_PTT(100, IP, IPV6, NOF, IP_IP, IPV4, NOF, SCTP, PAY4), I40E_PTT(101, IP, IPV6, NOF, IP_IP, IPV4, NOF, ICMP, PAY4), /* IPv6 --> IPv6 */ I40E_PTT(102, IP, IPV6, NOF, IP_IP, IPV6, FRG, NONE, PAY3), I40E_PTT(103, IP, IPV6, NOF, IP_IP, IPV6, NOF, NONE, PAY3), I40E_PTT(104, IP, IPV6, NOF, IP_IP, IPV6, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(105), I40E_PTT(106, IP, IPV6, NOF, IP_IP, IPV6, NOF, TCP, PAY4), I40E_PTT(107, IP, IPV6, NOF, IP_IP, IPV6, NOF, SCTP, PAY4), I40E_PTT(108, IP, IPV6, NOF, IP_IP, IPV6, NOF, ICMP, PAY4), /* IPv6 --> GRE/NAT */ I40E_PTT(109, IP, IPV6, NOF, IP_GRENAT, NONE, NOF, NONE, PAY3), /* IPv6 --> GRE/NAT -> IPv4 */ I40E_PTT(110, IP, IPV6, NOF, IP_GRENAT, IPV4, FRG, NONE, PAY3), I40E_PTT(111, IP, IPV6, NOF, IP_GRENAT, IPV4, NOF, NONE, PAY3), I40E_PTT(112, IP, IPV6, NOF, IP_GRENAT, IPV4, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(113), I40E_PTT(114, IP, IPV6, NOF, IP_GRENAT, IPV4, NOF, TCP, PAY4), I40E_PTT(115, IP, IPV6, NOF, IP_GRENAT, IPV4, NOF, SCTP, PAY4), I40E_PTT(116, IP, IPV6, NOF, IP_GRENAT, IPV4, NOF, ICMP, PAY4), /* IPv6 --> GRE/NAT -> IPv6 */ I40E_PTT(117, IP, IPV6, NOF, IP_GRENAT, IPV6, FRG, NONE, PAY3), I40E_PTT(118, IP, IPV6, NOF, IP_GRENAT, IPV6, NOF, NONE, PAY3), I40E_PTT(119, IP, IPV6, NOF, IP_GRENAT, IPV6, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(120), I40E_PTT(121, IP, IPV6, NOF, IP_GRENAT, IPV6, NOF, TCP, PAY4), I40E_PTT(122, IP, IPV6, NOF, IP_GRENAT, IPV6, NOF, SCTP, PAY4), I40E_PTT(123, IP, IPV6, NOF, IP_GRENAT, IPV6, NOF, ICMP, PAY4), /* IPv6 --> GRE/NAT -> MAC */ I40E_PTT(124, IP, IPV6, NOF, IP_GRENAT_MAC, NONE, NOF, NONE, PAY3), /* IPv6 --> GRE/NAT -> MAC -> IPv4 */ I40E_PTT(125, IP, IPV6, NOF, IP_GRENAT_MAC, IPV4, FRG, NONE, PAY3), I40E_PTT(126, IP, IPV6, NOF, IP_GRENAT_MAC, IPV4, NOF, NONE, PAY3), I40E_PTT(127, IP, IPV6, NOF, IP_GRENAT_MAC, IPV4, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(128), I40E_PTT(129, IP, IPV6, NOF, IP_GRENAT_MAC, IPV4, NOF, TCP, PAY4), I40E_PTT(130, IP, IPV6, NOF, IP_GRENAT_MAC, IPV4, NOF, SCTP, PAY4), I40E_PTT(131, IP, IPV6, NOF, IP_GRENAT_MAC, IPV4, NOF, ICMP, PAY4), /* IPv6 --> GRE/NAT -> MAC -> IPv6 */ I40E_PTT(132, IP, IPV6, NOF, IP_GRENAT_MAC, IPV6, FRG, NONE, PAY3), I40E_PTT(133, IP, IPV6, NOF, IP_GRENAT_MAC, IPV6, NOF, NONE, PAY3), I40E_PTT(134, IP, IPV6, NOF, IP_GRENAT_MAC, IPV6, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(135), I40E_PTT(136, IP, IPV6, NOF, IP_GRENAT_MAC, IPV6, NOF, TCP, PAY4), I40E_PTT(137, IP, IPV6, NOF, IP_GRENAT_MAC, IPV6, NOF, SCTP, PAY4), I40E_PTT(138, IP, IPV6, NOF, IP_GRENAT_MAC, IPV6, NOF, ICMP, PAY4), /* IPv6 --> GRE/NAT -> MAC/VLAN */ I40E_PTT(139, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, NONE, NOF, NONE, PAY3), /* IPv6 --> GRE/NAT -> MAC/VLAN --> IPv4 */ I40E_PTT(140, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV4, FRG, NONE, PAY3), I40E_PTT(141, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, NONE, PAY3), I40E_PTT(142, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(143), I40E_PTT(144, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, TCP, PAY4), I40E_PTT(145, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, SCTP, PAY4), I40E_PTT(146, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV4, NOF, ICMP, PAY4), /* IPv6 --> GRE/NAT -> MAC/VLAN --> IPv6 */ I40E_PTT(147, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV6, FRG, NONE, PAY3), I40E_PTT(148, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, NONE, PAY3), I40E_PTT(149, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, UDP, PAY4), I40E_PTT_UNUSED_ENTRY(150), I40E_PTT(151, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, TCP, PAY4), I40E_PTT(152, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, SCTP, PAY4), I40E_PTT(153, IP, IPV6, NOF, IP_GRENAT_MAC_VLAN, IPV6, NOF, ICMP, PAY4), /* unused entries */ I40E_PTT_UNUSED_ENTRY(154), I40E_PTT_UNUSED_ENTRY(155), I40E_PTT_UNUSED_ENTRY(156), I40E_PTT_UNUSED_ENTRY(157), I40E_PTT_UNUSED_ENTRY(158), I40E_PTT_UNUSED_ENTRY(159), I40E_PTT_UNUSED_ENTRY(160), I40E_PTT_UNUSED_ENTRY(161), I40E_PTT_UNUSED_ENTRY(162), I40E_PTT_UNUSED_ENTRY(163), I40E_PTT_UNUSED_ENTRY(164), I40E_PTT_UNUSED_ENTRY(165), I40E_PTT_UNUSED_ENTRY(166), I40E_PTT_UNUSED_ENTRY(167), I40E_PTT_UNUSED_ENTRY(168), I40E_PTT_UNUSED_ENTRY(169), I40E_PTT_UNUSED_ENTRY(170), I40E_PTT_UNUSED_ENTRY(171), I40E_PTT_UNUSED_ENTRY(172), I40E_PTT_UNUSED_ENTRY(173), I40E_PTT_UNUSED_ENTRY(174), I40E_PTT_UNUSED_ENTRY(175), I40E_PTT_UNUSED_ENTRY(176), I40E_PTT_UNUSED_ENTRY(177), I40E_PTT_UNUSED_ENTRY(178), I40E_PTT_UNUSED_ENTRY(179), I40E_PTT_UNUSED_ENTRY(180), I40E_PTT_UNUSED_ENTRY(181), I40E_PTT_UNUSED_ENTRY(182), I40E_PTT_UNUSED_ENTRY(183), I40E_PTT_UNUSED_ENTRY(184), I40E_PTT_UNUSED_ENTRY(185), I40E_PTT_UNUSED_ENTRY(186), I40E_PTT_UNUSED_ENTRY(187), I40E_PTT_UNUSED_ENTRY(188), I40E_PTT_UNUSED_ENTRY(189), I40E_PTT_UNUSED_ENTRY(190), I40E_PTT_UNUSED_ENTRY(191), I40E_PTT_UNUSED_ENTRY(192), I40E_PTT_UNUSED_ENTRY(193), I40E_PTT_UNUSED_ENTRY(194), I40E_PTT_UNUSED_ENTRY(195), I40E_PTT_UNUSED_ENTRY(196), I40E_PTT_UNUSED_ENTRY(197), I40E_PTT_UNUSED_ENTRY(198), I40E_PTT_UNUSED_ENTRY(199), I40E_PTT_UNUSED_ENTRY(200), I40E_PTT_UNUSED_ENTRY(201), I40E_PTT_UNUSED_ENTRY(202), I40E_PTT_UNUSED_ENTRY(203), I40E_PTT_UNUSED_ENTRY(204), I40E_PTT_UNUSED_ENTRY(205), I40E_PTT_UNUSED_ENTRY(206), I40E_PTT_UNUSED_ENTRY(207), I40E_PTT_UNUSED_ENTRY(208), I40E_PTT_UNUSED_ENTRY(209), I40E_PTT_UNUSED_ENTRY(210), I40E_PTT_UNUSED_ENTRY(211), I40E_PTT_UNUSED_ENTRY(212), I40E_PTT_UNUSED_ENTRY(213), I40E_PTT_UNUSED_ENTRY(214), I40E_PTT_UNUSED_ENTRY(215), I40E_PTT_UNUSED_ENTRY(216), I40E_PTT_UNUSED_ENTRY(217), I40E_PTT_UNUSED_ENTRY(218), I40E_PTT_UNUSED_ENTRY(219), I40E_PTT_UNUSED_ENTRY(220), I40E_PTT_UNUSED_ENTRY(221), I40E_PTT_UNUSED_ENTRY(222), I40E_PTT_UNUSED_ENTRY(223), I40E_PTT_UNUSED_ENTRY(224), I40E_PTT_UNUSED_ENTRY(225), I40E_PTT_UNUSED_ENTRY(226), I40E_PTT_UNUSED_ENTRY(227), I40E_PTT_UNUSED_ENTRY(228), I40E_PTT_UNUSED_ENTRY(229), I40E_PTT_UNUSED_ENTRY(230), I40E_PTT_UNUSED_ENTRY(231), I40E_PTT_UNUSED_ENTRY(232), I40E_PTT_UNUSED_ENTRY(233), I40E_PTT_UNUSED_ENTRY(234), I40E_PTT_UNUSED_ENTRY(235), I40E_PTT_UNUSED_ENTRY(236), I40E_PTT_UNUSED_ENTRY(237), I40E_PTT_UNUSED_ENTRY(238), I40E_PTT_UNUSED_ENTRY(239), I40E_PTT_UNUSED_ENTRY(240), I40E_PTT_UNUSED_ENTRY(241), I40E_PTT_UNUSED_ENTRY(242), I40E_PTT_UNUSED_ENTRY(243), I40E_PTT_UNUSED_ENTRY(244), I40E_PTT_UNUSED_ENTRY(245), I40E_PTT_UNUSED_ENTRY(246), I40E_PTT_UNUSED_ENTRY(247), I40E_PTT_UNUSED_ENTRY(248), I40E_PTT_UNUSED_ENTRY(249), I40E_PTT_UNUSED_ENTRY(250), I40E_PTT_UNUSED_ENTRY(251), I40E_PTT_UNUSED_ENTRY(252), I40E_PTT_UNUSED_ENTRY(253), I40E_PTT_UNUSED_ENTRY(254), I40E_PTT_UNUSED_ENTRY(255) }; /** * i40evf_aq_rx_ctl_read_register - use FW to read from an Rx control register * @hw: pointer to the hw struct * @reg_addr: register address * @reg_val: ptr to register value * @cmd_details: pointer to command details structure or NULL * * Use the firmware to read the Rx control register, * especially useful if the Rx unit is under heavy pressure **/ i40e_status i40evf_aq_rx_ctl_read_register(struct i40e_hw *hw, u32 reg_addr, u32 *reg_val, struct i40e_asq_cmd_details *cmd_details) { struct i40e_aq_desc desc; struct i40e_aqc_rx_ctl_reg_read_write *cmd_resp = (struct i40e_aqc_rx_ctl_reg_read_write *)&desc.params.raw; i40e_status status; if (!reg_val) return I40E_ERR_PARAM; i40evf_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_rx_ctl_reg_read); cmd_resp->address = cpu_to_le32(reg_addr); status = i40evf_asq_send_command(hw, &desc, NULL, 0, cmd_details); if (status == 0) *reg_val = le32_to_cpu(cmd_resp->value); return status; } /** * i40evf_read_rx_ctl - read from an Rx control register * @hw: pointer to the hw struct * @reg_addr: register address **/ u32 i40evf_read_rx_ctl(struct i40e_hw *hw, u32 reg_addr) { i40e_status status = 0; bool use_register; int retry = 5; u32 val = 0; use_register = (hw->aq.api_maj_ver == 1) && (hw->aq.api_min_ver < 5); if (!use_register) { do_retry: status = i40evf_aq_rx_ctl_read_register(hw, reg_addr, &val, NULL); if (hw->aq.asq_last_status == I40E_AQ_RC_EAGAIN && retry) { usleep_range(1000, 2000); retry--; goto do_retry; } } /* if the AQ access failed, try the old-fashioned way */ if (status || use_register) val = rd32(hw, reg_addr); return val; } /** * i40evf_aq_rx_ctl_write_register * @hw: pointer to the hw struct * @reg_addr: register address * @reg_val: register value * @cmd_details: pointer to command details structure or NULL * * Use the firmware to write to an Rx control register, * especially useful if the Rx unit is under heavy pressure **/ i40e_status i40evf_aq_rx_ctl_write_register(struct i40e_hw *hw, u32 reg_addr, u32 reg_val, struct i40e_asq_cmd_details *cmd_details) { struct i40e_aq_desc desc; struct i40e_aqc_rx_ctl_reg_read_write *cmd = (struct i40e_aqc_rx_ctl_reg_read_write *)&desc.params.raw; i40e_status status; i40evf_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_rx_ctl_reg_write); cmd->address = cpu_to_le32(reg_addr); cmd->value = cpu_to_le32(reg_val); status = i40evf_asq_send_command(hw, &desc, NULL, 0, cmd_details); return status; } /** * i40evf_write_rx_ctl - write to an Rx control register * @hw: pointer to the hw struct * @reg_addr: register address * @reg_val: register value **/ void i40evf_write_rx_ctl(struct i40e_hw *hw, u32 reg_addr, u32 reg_val) { i40e_status status = 0; bool use_register; int retry = 5; use_register = (hw->aq.api_maj_ver == 1) && (hw->aq.api_min_ver < 5); if (!use_register) { do_retry: status = i40evf_aq_rx_ctl_write_register(hw, reg_addr, reg_val, NULL); if (hw->aq.asq_last_status == I40E_AQ_RC_EAGAIN && retry) { usleep_range(1000, 2000); retry--; goto do_retry; } } /* if the AQ access failed, try the old-fashioned way */ if (status || use_register) wr32(hw, reg_addr, reg_val); } /** * i40e_aq_send_msg_to_pf * @hw: pointer to the hardware structure * @v_opcode: opcodes for VF-PF communication * @v_retval: return error code * @msg: pointer to the msg buffer * @msglen: msg length * @cmd_details: pointer to command details * * Send message to PF driver using admin queue. By default, this message * is sent asynchronously, i.e. i40evf_asq_send_command() does not wait for * completion before returning. **/ i40e_status i40e_aq_send_msg_to_pf(struct i40e_hw *hw, enum i40e_virtchnl_ops v_opcode, i40e_status v_retval, u8 *msg, u16 msglen, struct i40e_asq_cmd_details *cmd_details) { struct i40e_aq_desc desc; struct i40e_asq_cmd_details details; i40e_status status; i40evf_fill_default_direct_cmd_desc(&desc, i40e_aqc_opc_send_msg_to_pf); desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_SI); desc.cookie_high = cpu_to_le32(v_opcode); desc.cookie_low = cpu_to_le32(v_retval); if (msglen) { desc.flags |= cpu_to_le16((u16)(I40E_AQ_FLAG_BUF | I40E_AQ_FLAG_RD)); if (msglen > I40E_AQ_LARGE_BUF) desc.flags |= cpu_to_le16((u16)I40E_AQ_FLAG_LB); desc.datalen = cpu_to_le16(msglen); } if (!cmd_details) { memset(&details, 0, sizeof(details)); details.async = true; cmd_details = &details; } status = i40evf_asq_send_command(hw, &desc, msg, msglen, cmd_details); return status; } /** * i40e_vf_parse_hw_config * @hw: pointer to the hardware structure * @msg: pointer to the virtual channel VF resource structure * * Given a VF resource message from the PF, populate the hw struct * with appropriate information. **/ void i40e_vf_parse_hw_config(struct i40e_hw *hw, struct i40e_virtchnl_vf_resource *msg) { struct i40e_virtchnl_vsi_resource *vsi_res; int i; vsi_res = &msg->vsi_res[0]; hw->dev_caps.num_vsis = msg->num_vsis; hw->dev_caps.num_rx_qp = msg->num_queue_pairs; hw->dev_caps.num_tx_qp = msg->num_queue_pairs; hw->dev_caps.num_msix_vectors_vf = msg->max_vectors; hw->dev_caps.dcb = msg->vf_offload_flags & I40E_VIRTCHNL_VF_OFFLOAD_L2; hw->dev_caps.fcoe = (msg->vf_offload_flags & I40E_VIRTCHNL_VF_OFFLOAD_FCOE) ? 1 : 0; for (i = 0; i < msg->num_vsis; i++) { if (vsi_res->vsi_type == I40E_VSI_SRIOV) { ether_addr_copy(hw->mac.perm_addr, vsi_res->default_mac_addr); ether_addr_copy(hw->mac.addr, vsi_res->default_mac_addr); } vsi_res++; } } /** * i40e_vf_reset * @hw: pointer to the hardware structure * * Send a VF_RESET message to the PF. Does not wait for response from PF * as none will be forthcoming. Immediately after calling this function, * the admin queue should be shut down and (optionally) reinitialized. **/ i40e_status i40e_vf_reset(struct i40e_hw *hw) { return i40e_aq_send_msg_to_pf(hw, I40E_VIRTCHNL_OP_RESET_VF, 0, NULL, 0, NULL); }
null
null
null
null
93,806
41,028
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
206,023
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef _LINUX_INTERVAL_TREE_H #define _LINUX_INTERVAL_TREE_H #include <linux/rbtree.h> struct interval_tree_node { struct rb_node rb; unsigned long start; /* Start of interval */ unsigned long last; /* Last location _in_ interval */ unsigned long __subtree_last; }; extern void interval_tree_insert(struct interval_tree_node *node, struct rb_root *root); extern void interval_tree_remove(struct interval_tree_node *node, struct rb_root *root); extern struct interval_tree_node * interval_tree_iter_first(struct rb_root *root, unsigned long start, unsigned long last); extern struct interval_tree_node * interval_tree_iter_next(struct interval_tree_node *node, unsigned long start, unsigned long last); #endif /* _LINUX_INTERVAL_TREE_H */
null
null
null
null
114,370
282
null
train_val
c536b6be1a72aefd632d5530106a67c516cb9f4b
256,669
openssl
0
https://github.com/openssl/openssl
2016-09-22 23:12:38+01:00
/* * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <e_os.h> #include <openssl/err.h> #ifdef OPENSSL_FIPS # include <openssl/fips.h> # include <openssl/rand.h> #endif /* * Perform any essential OpenSSL initialization operations. Currently only * sets FIPS callbacks */ void OPENSSL_init(void) { static int done = 0; if (done) return; done = 1; #ifdef OPENSSL_FIPS FIPS_set_locking_callbacks(CRYPTO_lock, CRYPTO_add_lock); FIPS_set_error_callbacks(ERR_put_error, ERR_add_error_vdata); FIPS_set_malloc_callbacks(CRYPTO_malloc, CRYPTO_free); RAND_init_fips(); #endif }
null
null
null
null
118,114
12,319
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
177,314
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Cell Broadband Engine Performance Monitor * * (C) Copyright IBM Corporation 2001,2006 * * Author: * David Erb (djerb@us.ibm.com) * Kevin Corry (kevcorry@us.ibm.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/interrupt.h> #include <linux/types.h> #include <linux/export.h> #include <asm/io.h> #include <asm/irq_regs.h> #include <asm/machdep.h> #include <asm/pmc.h> #include <asm/reg.h> #include <asm/spu.h> #include <asm/cell-regs.h> #include "interrupt.h" /* * When writing to write-only mmio addresses, save a shadow copy. All of the * registers are 32-bit, but stored in the upper-half of a 64-bit field in * pmd_regs. */ #define WRITE_WO_MMIO(reg, x) \ do { \ u32 _x = (x); \ struct cbe_pmd_regs __iomem *pmd_regs; \ struct cbe_pmd_shadow_regs *shadow_regs; \ pmd_regs = cbe_get_cpu_pmd_regs(cpu); \ shadow_regs = cbe_get_cpu_pmd_shadow_regs(cpu); \ out_be64(&(pmd_regs->reg), (((u64)_x) << 32)); \ shadow_regs->reg = _x; \ } while (0) #define READ_SHADOW_REG(val, reg) \ do { \ struct cbe_pmd_shadow_regs *shadow_regs; \ shadow_regs = cbe_get_cpu_pmd_shadow_regs(cpu); \ (val) = shadow_regs->reg; \ } while (0) #define READ_MMIO_UPPER32(val, reg) \ do { \ struct cbe_pmd_regs __iomem *pmd_regs; \ pmd_regs = cbe_get_cpu_pmd_regs(cpu); \ (val) = (u32)(in_be64(&pmd_regs->reg) >> 32); \ } while (0) /* * Physical counter registers. * Each physical counter can act as one 32-bit counter or two 16-bit counters. */ u32 cbe_read_phys_ctr(u32 cpu, u32 phys_ctr) { u32 val_in_latch, val = 0; if (phys_ctr < NR_PHYS_CTRS) { READ_SHADOW_REG(val_in_latch, counter_value_in_latch); /* Read the latch or the actual counter, whichever is newer. */ if (val_in_latch & (1 << phys_ctr)) { READ_SHADOW_REG(val, pm_ctr[phys_ctr]); } else { READ_MMIO_UPPER32(val, pm_ctr[phys_ctr]); } } return val; } EXPORT_SYMBOL_GPL(cbe_read_phys_ctr); void cbe_write_phys_ctr(u32 cpu, u32 phys_ctr, u32 val) { struct cbe_pmd_shadow_regs *shadow_regs; u32 pm_ctrl; if (phys_ctr < NR_PHYS_CTRS) { /* Writing to a counter only writes to a hardware latch. * The new value is not propagated to the actual counter * until the performance monitor is enabled. */ WRITE_WO_MMIO(pm_ctr[phys_ctr], val); pm_ctrl = cbe_read_pm(cpu, pm_control); if (pm_ctrl & CBE_PM_ENABLE_PERF_MON) { /* The counters are already active, so we need to * rewrite the pm_control register to "re-enable" * the PMU. */ cbe_write_pm(cpu, pm_control, pm_ctrl); } else { shadow_regs = cbe_get_cpu_pmd_shadow_regs(cpu); shadow_regs->counter_value_in_latch |= (1 << phys_ctr); } } } EXPORT_SYMBOL_GPL(cbe_write_phys_ctr); /* * "Logical" counter registers. * These will read/write 16-bits or 32-bits depending on the * current size of the counter. Counters 4 - 7 are always 16-bit. */ u32 cbe_read_ctr(u32 cpu, u32 ctr) { u32 val; u32 phys_ctr = ctr & (NR_PHYS_CTRS - 1); val = cbe_read_phys_ctr(cpu, phys_ctr); if (cbe_get_ctr_size(cpu, phys_ctr) == 16) val = (ctr < NR_PHYS_CTRS) ? (val >> 16) : (val & 0xffff); return val; } EXPORT_SYMBOL_GPL(cbe_read_ctr); void cbe_write_ctr(u32 cpu, u32 ctr, u32 val) { u32 phys_ctr; u32 phys_val; phys_ctr = ctr & (NR_PHYS_CTRS - 1); if (cbe_get_ctr_size(cpu, phys_ctr) == 16) { phys_val = cbe_read_phys_ctr(cpu, phys_ctr); if (ctr < NR_PHYS_CTRS) val = (val << 16) | (phys_val & 0xffff); else val = (val & 0xffff) | (phys_val & 0xffff0000); } cbe_write_phys_ctr(cpu, phys_ctr, val); } EXPORT_SYMBOL_GPL(cbe_write_ctr); /* * Counter-control registers. * Each "logical" counter has a corresponding control register. */ u32 cbe_read_pm07_control(u32 cpu, u32 ctr) { u32 pm07_control = 0; if (ctr < NR_CTRS) READ_SHADOW_REG(pm07_control, pm07_control[ctr]); return pm07_control; } EXPORT_SYMBOL_GPL(cbe_read_pm07_control); void cbe_write_pm07_control(u32 cpu, u32 ctr, u32 val) { if (ctr < NR_CTRS) WRITE_WO_MMIO(pm07_control[ctr], val); } EXPORT_SYMBOL_GPL(cbe_write_pm07_control); /* * Other PMU control registers. Most of these are write-only. */ u32 cbe_read_pm(u32 cpu, enum pm_reg_name reg) { u32 val = 0; switch (reg) { case group_control: READ_SHADOW_REG(val, group_control); break; case debug_bus_control: READ_SHADOW_REG(val, debug_bus_control); break; case trace_address: READ_MMIO_UPPER32(val, trace_address); break; case ext_tr_timer: READ_SHADOW_REG(val, ext_tr_timer); break; case pm_status: READ_MMIO_UPPER32(val, pm_status); break; case pm_control: READ_SHADOW_REG(val, pm_control); break; case pm_interval: READ_MMIO_UPPER32(val, pm_interval); break; case pm_start_stop: READ_SHADOW_REG(val, pm_start_stop); break; } return val; } EXPORT_SYMBOL_GPL(cbe_read_pm); void cbe_write_pm(u32 cpu, enum pm_reg_name reg, u32 val) { switch (reg) { case group_control: WRITE_WO_MMIO(group_control, val); break; case debug_bus_control: WRITE_WO_MMIO(debug_bus_control, val); break; case trace_address: WRITE_WO_MMIO(trace_address, val); break; case ext_tr_timer: WRITE_WO_MMIO(ext_tr_timer, val); break; case pm_status: WRITE_WO_MMIO(pm_status, val); break; case pm_control: WRITE_WO_MMIO(pm_control, val); break; case pm_interval: WRITE_WO_MMIO(pm_interval, val); break; case pm_start_stop: WRITE_WO_MMIO(pm_start_stop, val); break; } } EXPORT_SYMBOL_GPL(cbe_write_pm); /* * Get/set the size of a physical counter to either 16 or 32 bits. */ u32 cbe_get_ctr_size(u32 cpu, u32 phys_ctr) { u32 pm_ctrl, size = 0; if (phys_ctr < NR_PHYS_CTRS) { pm_ctrl = cbe_read_pm(cpu, pm_control); size = (pm_ctrl & CBE_PM_16BIT_CTR(phys_ctr)) ? 16 : 32; } return size; } EXPORT_SYMBOL_GPL(cbe_get_ctr_size); void cbe_set_ctr_size(u32 cpu, u32 phys_ctr, u32 ctr_size) { u32 pm_ctrl; if (phys_ctr < NR_PHYS_CTRS) { pm_ctrl = cbe_read_pm(cpu, pm_control); switch (ctr_size) { case 16: pm_ctrl |= CBE_PM_16BIT_CTR(phys_ctr); break; case 32: pm_ctrl &= ~CBE_PM_16BIT_CTR(phys_ctr); break; } cbe_write_pm(cpu, pm_control, pm_ctrl); } } EXPORT_SYMBOL_GPL(cbe_set_ctr_size); /* * Enable/disable the entire performance monitoring unit. * When we enable the PMU, all pending writes to counters get committed. */ void cbe_enable_pm(u32 cpu) { struct cbe_pmd_shadow_regs *shadow_regs; u32 pm_ctrl; shadow_regs = cbe_get_cpu_pmd_shadow_regs(cpu); shadow_regs->counter_value_in_latch = 0; pm_ctrl = cbe_read_pm(cpu, pm_control) | CBE_PM_ENABLE_PERF_MON; cbe_write_pm(cpu, pm_control, pm_ctrl); } EXPORT_SYMBOL_GPL(cbe_enable_pm); void cbe_disable_pm(u32 cpu) { u32 pm_ctrl; pm_ctrl = cbe_read_pm(cpu, pm_control) & ~CBE_PM_ENABLE_PERF_MON; cbe_write_pm(cpu, pm_control, pm_ctrl); } EXPORT_SYMBOL_GPL(cbe_disable_pm); /* * Reading from the trace_buffer. * The trace buffer is two 64-bit registers. Reading from * the second half automatically increments the trace_address. */ void cbe_read_trace_buffer(u32 cpu, u64 *buf) { struct cbe_pmd_regs __iomem *pmd_regs = cbe_get_cpu_pmd_regs(cpu); *buf++ = in_be64(&pmd_regs->trace_buffer_0_63); *buf++ = in_be64(&pmd_regs->trace_buffer_64_127); } EXPORT_SYMBOL_GPL(cbe_read_trace_buffer); /* * Enabling/disabling interrupts for the entire performance monitoring unit. */ u32 cbe_get_and_clear_pm_interrupts(u32 cpu) { /* Reading pm_status clears the interrupt bits. */ return cbe_read_pm(cpu, pm_status); } EXPORT_SYMBOL_GPL(cbe_get_and_clear_pm_interrupts); void cbe_enable_pm_interrupts(u32 cpu, u32 thread, u32 mask) { /* Set which node and thread will handle the next interrupt. */ iic_set_interrupt_routing(cpu, thread, 0); /* Enable the interrupt bits in the pm_status register. */ if (mask) cbe_write_pm(cpu, pm_status, mask); } EXPORT_SYMBOL_GPL(cbe_enable_pm_interrupts); void cbe_disable_pm_interrupts(u32 cpu) { cbe_get_and_clear_pm_interrupts(cpu); cbe_write_pm(cpu, pm_status, 0); } EXPORT_SYMBOL_GPL(cbe_disable_pm_interrupts); static irqreturn_t cbe_pm_irq(int irq, void *dev_id) { perf_irq(get_irq_regs()); return IRQ_HANDLED; } static int __init cbe_init_pm_irq(void) { unsigned int irq; int rc, node; for_each_online_node(node) { irq = irq_create_mapping(NULL, IIC_IRQ_IOEX_PMI | (node << IIC_IRQ_NODE_SHIFT)); if (!irq) { printk("ERROR: Unable to allocate irq for node %d\n", node); return -EINVAL; } rc = request_irq(irq, cbe_pm_irq, 0, "cbe-pmu-0", NULL); if (rc) { printk("ERROR: Request for irq on node %d failed\n", node); return rc; } } return 0; } machine_arch_initcall(cell, cbe_init_pm_irq); void cbe_sync_irq(int node) { unsigned int irq; irq = irq_find_mapping(NULL, IIC_IRQ_IOEX_PMI | (node << IIC_IRQ_NODE_SHIFT)); if (!irq) { printk(KERN_WARNING "ERROR, unable to get existing irq %d " \ "for node %d\n", irq, node); return; } synchronize_irq(irq); } EXPORT_SYMBOL_GPL(cbe_sync_irq);
null
null
null
null
85,661
15,028
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
15,028
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_DOM_DISTILLER_CORE_DOM_DISTILLER_TEST_UTIL_H_ #define COMPONENTS_DOM_DISTILLER_CORE_DOM_DISTILLER_TEST_UTIL_H_ #include <vector> #include "components/dom_distiller/core/dom_distiller_observer.h" #include "components/leveldb_proto/testing/fake_db.h" #include "testing/gmock/include/gmock/gmock.h" namespace dom_distiller { class DomDistillerStore; namespace test { namespace util { class ObserverUpdatesMatcher : public testing::MatcherInterface< const std::vector<DomDistillerObserver::ArticleUpdate>&> { public: explicit ObserverUpdatesMatcher( const std::vector<DomDistillerObserver::ArticleUpdate>&); // MatcherInterface overrides. bool MatchAndExplain( const std::vector<DomDistillerObserver::ArticleUpdate>& actual_updates, testing::MatchResultListener* listener) const override; void DescribeTo(std::ostream* os) const override; void DescribeNegationTo(std::ostream* os) const override; private: void DescribeUpdates(std::ostream* os) const; const std::vector<DomDistillerObserver::ArticleUpdate>& expected_updates_; }; testing::Matcher<const std::vector<DomDistillerObserver::ArticleUpdate>&> HasExpectedUpdates(const std::vector<DomDistillerObserver::ArticleUpdate>&); // Creates a simple DomDistillerStore backed by |fake_db| and initialized // with |store_model|. DomDistillerStore* CreateStoreWithFakeDB( leveldb_proto::test::FakeDB<ArticleEntry>* fake_db, const leveldb_proto::test::FakeDB<ArticleEntry>::EntryMap& store_model); } // namespace util } // namespace test } // namespace dom_distiller #endif // COMPONENTS_DOM_DISTILLER_CORE_DOM_DISTILLER_TEST_UTIL_H_
null
null
null
null
11,891
43,641
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
208,636
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef __LINUX_TC_EM_META_H #define __LINUX_TC_EM_META_H #include <linux/types.h> #include <linux/pkt_cls.h> enum { TCA_EM_META_UNSPEC, TCA_EM_META_HDR, TCA_EM_META_LVALUE, TCA_EM_META_RVALUE, __TCA_EM_META_MAX }; #define TCA_EM_META_MAX (__TCA_EM_META_MAX - 1) struct tcf_meta_val { __u16 kind; __u8 shift; __u8 op; }; #define TCF_META_TYPE_MASK (0xf << 12) #define TCF_META_TYPE(kind) (((kind) & TCF_META_TYPE_MASK) >> 12) #define TCF_META_ID_MASK 0x7ff #define TCF_META_ID(kind) ((kind) & TCF_META_ID_MASK) enum { TCF_META_TYPE_VAR, TCF_META_TYPE_INT, __TCF_META_TYPE_MAX }; #define TCF_META_TYPE_MAX (__TCF_META_TYPE_MAX - 1) enum { TCF_META_ID_VALUE, TCF_META_ID_RANDOM, TCF_META_ID_LOADAVG_0, TCF_META_ID_LOADAVG_1, TCF_META_ID_LOADAVG_2, TCF_META_ID_DEV, TCF_META_ID_PRIORITY, TCF_META_ID_PROTOCOL, TCF_META_ID_PKTTYPE, TCF_META_ID_PKTLEN, TCF_META_ID_DATALEN, TCF_META_ID_MACLEN, TCF_META_ID_NFMARK, TCF_META_ID_TCINDEX, TCF_META_ID_RTCLASSID, TCF_META_ID_RTIIF, TCF_META_ID_SK_FAMILY, TCF_META_ID_SK_STATE, TCF_META_ID_SK_REUSE, TCF_META_ID_SK_BOUND_IF, TCF_META_ID_SK_REFCNT, TCF_META_ID_SK_SHUTDOWN, TCF_META_ID_SK_PROTO, TCF_META_ID_SK_TYPE, TCF_META_ID_SK_RCVBUF, TCF_META_ID_SK_RMEM_ALLOC, TCF_META_ID_SK_WMEM_ALLOC, TCF_META_ID_SK_OMEM_ALLOC, TCF_META_ID_SK_WMEM_QUEUED, TCF_META_ID_SK_RCV_QLEN, TCF_META_ID_SK_SND_QLEN, TCF_META_ID_SK_ERR_QLEN, TCF_META_ID_SK_FORWARD_ALLOCS, TCF_META_ID_SK_SNDBUF, TCF_META_ID_SK_ALLOCS, __TCF_META_ID_SK_ROUTE_CAPS, /* unimplemented but in ABI already */ TCF_META_ID_SK_HASH, TCF_META_ID_SK_LINGERTIME, TCF_META_ID_SK_ACK_BACKLOG, TCF_META_ID_SK_MAX_ACK_BACKLOG, TCF_META_ID_SK_PRIO, TCF_META_ID_SK_RCVLOWAT, TCF_META_ID_SK_RCVTIMEO, TCF_META_ID_SK_SNDTIMEO, TCF_META_ID_SK_SENDMSG_OFF, TCF_META_ID_SK_WRITE_PENDING, TCF_META_ID_VLAN_TAG, TCF_META_ID_RXHASH, __TCF_META_ID_MAX }; #define TCF_META_ID_MAX (__TCF_META_ID_MAX - 1) struct tcf_meta_hdr { struct tcf_meta_val left; struct tcf_meta_val right; }; #endif
null
null
null
null
116,983
140
null
train_val
b09a65ece69306a70044ac99ca6928eda58d7c79
270,447
tcpdump
0
https://github.com/the-tcpdump-group/tcpdump
2017-09-14 11:59:38-07:00
/* * Copyright (c) 1998-2007 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Carles Kishimoto <carles.kishimoto@gmail.com> */ /* \summary: Light Weight Access Point Protocol (LWAPP) printer */ /* specification: RFC 5412 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" /* * LWAPP transport (common) header * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |VER| RID |C|F|L| Frag ID | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Status/WLANs | Payload... | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ struct lwapp_transport_header { uint8_t version; uint8_t frag_id; uint8_t length[2]; uint16_t status; }; /* * LWAPP control header * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Message Type | Seq Num | Msg Element Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Session ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Msg Element [0..N] | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct lwapp_control_header { uint8_t msg_type; uint8_t seq_num; uint8_t len[2]; uint8_t session_id[4]; }; #define LWAPP_VERSION 0 #define LWAPP_EXTRACT_VERSION(x) (((x)&0xC0)>>6) #define LWAPP_EXTRACT_RID(x) (((x)&0x38)>>3) #define LWAPP_EXTRACT_CONTROL_BIT(x) (((x)&0x04)>>2) static const struct tok lwapp_header_bits_values[] = { { 0x01, "Last Fragment Bit"}, { 0x02, "Fragment Bit"}, { 0x04, "Control Bit"}, { 0, NULL} }; #define LWAPP_MSGTYPE_DISCOVERY_REQUEST 1 #define LWAPP_MSGTYPE_DISCOVERY_RESPONSE 2 #define LWAPP_MSGTYPE_JOIN_REQUEST 3 #define LWAPP_MSGTYPE_JOIN_RESPONSE 4 #define LWAPP_MSGTYPE_JOIN_ACK 5 #define LWAPP_MSGTYPE_JOIN_CONFIRM 6 #define LWAPP_MSGTYPE_CONFIGURE_REQUEST 10 #define LWAPP_MSGTYPE_CONFIGURE_RESPONSE 11 #define LWAPP_MSGTYPE_CONF_UPDATE_REQUEST 12 #define LWAPP_MSGTYPE_CONF_UPDATE_RESPONSE 13 #define LWAPP_MSGTYPE_WTP_EVENT_REQUEST 14 #define LWAPP_MSGTYPE_WTP_EVENT_RESPONSE 15 #define LWAPP_MSGTYPE_CHANGE_STATE_EVENT_REQUEST 16 #define LWAPP_MSGTYPE_CHANGE_STATE_EVENT_RESPONSE 17 #define LWAPP_MSGTYPE_ECHO_REQUEST 22 #define LWAPP_MSGTYPE_ECHO_RESPONSE 23 #define LWAPP_MSGTYPE_IMAGE_DATA_REQUEST 24 #define LWAPP_MSGTYPE_IMAGE_DATA_RESPONSE 25 #define LWAPP_MSGTYPE_RESET_REQUEST 26 #define LWAPP_MSGTYPE_RESET_RESPONSE 27 #define LWAPP_MSGTYPE_KEY_UPDATE_REQUEST 30 #define LWAPP_MSGTYPE_KEY_UPDATE_RESPONSE 31 #define LWAPP_MSGTYPE_PRIMARY_DISCOVERY_REQUEST 32 #define LWAPP_MSGTYPE_PRIMARY_DISCOVERY_RESPONSE 33 #define LWAPP_MSGTYPE_DATA_TRANSFER_REQUEST 34 #define LWAPP_MSGTYPE_DATA_TRANSFER_RESPONSE 35 #define LWAPP_MSGTYPE_CLEAR_CONFIG_INDICATION 36 #define LWAPP_MSGTYPE_WLAN_CONFIG_REQUEST 37 #define LWAPP_MSGTYPE_WLAN_CONFIG_RESPONSE 38 #define LWAPP_MSGTYPE_MOBILE_CONFIG_REQUEST 39 #define LWAPP_MSGTYPE_MOBILE_CONFIG_RESPONSE 40 static const struct tok lwapp_msg_type_values[] = { { LWAPP_MSGTYPE_DISCOVERY_REQUEST, "Discovery req"}, { LWAPP_MSGTYPE_DISCOVERY_RESPONSE, "Discovery resp"}, { LWAPP_MSGTYPE_JOIN_REQUEST, "Join req"}, { LWAPP_MSGTYPE_JOIN_RESPONSE, "Join resp"}, { LWAPP_MSGTYPE_JOIN_ACK, "Join ack"}, { LWAPP_MSGTYPE_JOIN_CONFIRM, "Join confirm"}, { LWAPP_MSGTYPE_CONFIGURE_REQUEST, "Configure req"}, { LWAPP_MSGTYPE_CONFIGURE_RESPONSE, "Configure resp"}, { LWAPP_MSGTYPE_CONF_UPDATE_REQUEST, "Update req"}, { LWAPP_MSGTYPE_CONF_UPDATE_RESPONSE, "Update resp"}, { LWAPP_MSGTYPE_WTP_EVENT_REQUEST, "WTP event req"}, { LWAPP_MSGTYPE_WTP_EVENT_RESPONSE, "WTP event resp"}, { LWAPP_MSGTYPE_CHANGE_STATE_EVENT_REQUEST, "Change state event req"}, { LWAPP_MSGTYPE_CHANGE_STATE_EVENT_RESPONSE, "Change state event resp"}, { LWAPP_MSGTYPE_ECHO_REQUEST, "Echo req"}, { LWAPP_MSGTYPE_ECHO_RESPONSE, "Echo resp"}, { LWAPP_MSGTYPE_IMAGE_DATA_REQUEST, "Image data req"}, { LWAPP_MSGTYPE_IMAGE_DATA_RESPONSE, "Image data resp"}, { LWAPP_MSGTYPE_RESET_REQUEST, "Channel status req"}, { LWAPP_MSGTYPE_RESET_RESPONSE, "Channel status resp"}, { LWAPP_MSGTYPE_KEY_UPDATE_REQUEST, "Key update req"}, { LWAPP_MSGTYPE_KEY_UPDATE_RESPONSE, "Key update resp"}, { LWAPP_MSGTYPE_PRIMARY_DISCOVERY_REQUEST, "Primary discovery req"}, { LWAPP_MSGTYPE_PRIMARY_DISCOVERY_RESPONSE, "Primary discovery resp"}, { LWAPP_MSGTYPE_DATA_TRANSFER_REQUEST, "Data transfer req"}, { LWAPP_MSGTYPE_DATA_TRANSFER_RESPONSE, "Data transfer resp"}, { LWAPP_MSGTYPE_CLEAR_CONFIG_INDICATION, "Clear config ind"}, { LWAPP_MSGTYPE_WLAN_CONFIG_REQUEST, "Wlan config req"}, { LWAPP_MSGTYPE_WLAN_CONFIG_RESPONSE, "Wlan config resp"}, { LWAPP_MSGTYPE_MOBILE_CONFIG_REQUEST, "Mobile config req"}, { LWAPP_MSGTYPE_MOBILE_CONFIG_RESPONSE, "Mobile config resp"}, { 0, NULL} }; /* * LWAPP message elements * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Type | Length | Value ... | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct lwapp_message_header { uint8_t type; uint8_t length[2]; }; void lwapp_control_print(netdissect_options *ndo, const u_char *pptr, u_int len, int has_ap_ident) { const struct lwapp_transport_header *lwapp_trans_header; const struct lwapp_control_header *lwapp_control_header; const u_char *tptr; int tlen; int msg_tlen; tptr=pptr; if (has_ap_ident) { /* check if enough bytes for AP identity */ ND_TCHECK2(*tptr, 6); lwapp_trans_header = (const struct lwapp_transport_header *)(pptr+6); } else { lwapp_trans_header = (const struct lwapp_transport_header *)pptr; } ND_TCHECK(*lwapp_trans_header); /* * Sanity checking of the header. */ if (LWAPP_EXTRACT_VERSION(lwapp_trans_header->version) != LWAPP_VERSION) { ND_PRINT((ndo, "LWAPP version %u packet not supported", LWAPP_EXTRACT_VERSION(lwapp_trans_header->version))); return; } /* non-verbose */ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "LWAPPv%u, %s frame, Flags [%s], length %u", LWAPP_EXTRACT_VERSION(lwapp_trans_header->version), LWAPP_EXTRACT_CONTROL_BIT(lwapp_trans_header->version) ? "Control" : "Data", bittok2str(lwapp_header_bits_values,"none",(lwapp_trans_header->version)&0x07), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ tlen=EXTRACT_16BITS(lwapp_trans_header->length); ND_PRINT((ndo, "LWAPPv%u, %s frame, Radio-id %u, Flags [%s], Frag-id %u, length %u", LWAPP_EXTRACT_VERSION(lwapp_trans_header->version), LWAPP_EXTRACT_CONTROL_BIT(lwapp_trans_header->version) ? "Control" : "Data", LWAPP_EXTRACT_RID(lwapp_trans_header->version), bittok2str(lwapp_header_bits_values,"none",(lwapp_trans_header->version)&0x07), lwapp_trans_header->frag_id, tlen)); if (has_ap_ident) { ND_PRINT((ndo, "\n\tAP identity: %s", etheraddr_string(ndo, tptr))); tptr+=sizeof(struct lwapp_transport_header)+6; } else { tptr+=sizeof(struct lwapp_transport_header); } while(tlen>0) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct lwapp_control_header)); lwapp_control_header = (const struct lwapp_control_header *)tptr; msg_tlen = EXTRACT_16BITS(lwapp_control_header->len); /* print message header */ ND_PRINT((ndo, "\n\t Msg type: %s (%u), Seqnum: %u, Msg len: %d, Session: 0x%08x", tok2str(lwapp_msg_type_values,"Unknown",lwapp_control_header->msg_type), lwapp_control_header->msg_type, lwapp_control_header->seq_num, msg_tlen, EXTRACT_32BITS(lwapp_control_header->session_id))); /* did we capture enough for fully decoding the message */ ND_TCHECK2(*tptr, msg_tlen); /* XXX - Decode sub messages for each message */ switch(lwapp_control_header->msg_type) { case LWAPP_MSGTYPE_DISCOVERY_REQUEST: case LWAPP_MSGTYPE_DISCOVERY_RESPONSE: case LWAPP_MSGTYPE_JOIN_REQUEST: case LWAPP_MSGTYPE_JOIN_RESPONSE: case LWAPP_MSGTYPE_JOIN_ACK: case LWAPP_MSGTYPE_JOIN_CONFIRM: case LWAPP_MSGTYPE_CONFIGURE_REQUEST: case LWAPP_MSGTYPE_CONFIGURE_RESPONSE: case LWAPP_MSGTYPE_CONF_UPDATE_REQUEST: case LWAPP_MSGTYPE_CONF_UPDATE_RESPONSE: case LWAPP_MSGTYPE_WTP_EVENT_REQUEST: case LWAPP_MSGTYPE_WTP_EVENT_RESPONSE: case LWAPP_MSGTYPE_CHANGE_STATE_EVENT_REQUEST: case LWAPP_MSGTYPE_CHANGE_STATE_EVENT_RESPONSE: case LWAPP_MSGTYPE_ECHO_REQUEST: case LWAPP_MSGTYPE_ECHO_RESPONSE: case LWAPP_MSGTYPE_IMAGE_DATA_REQUEST: case LWAPP_MSGTYPE_IMAGE_DATA_RESPONSE: case LWAPP_MSGTYPE_RESET_REQUEST: case LWAPP_MSGTYPE_RESET_RESPONSE: case LWAPP_MSGTYPE_KEY_UPDATE_REQUEST: case LWAPP_MSGTYPE_KEY_UPDATE_RESPONSE: case LWAPP_MSGTYPE_PRIMARY_DISCOVERY_REQUEST: case LWAPP_MSGTYPE_PRIMARY_DISCOVERY_RESPONSE: case LWAPP_MSGTYPE_DATA_TRANSFER_REQUEST: case LWAPP_MSGTYPE_DATA_TRANSFER_RESPONSE: case LWAPP_MSGTYPE_CLEAR_CONFIG_INDICATION: case LWAPP_MSGTYPE_WLAN_CONFIG_REQUEST: case LWAPP_MSGTYPE_WLAN_CONFIG_RESPONSE: case LWAPP_MSGTYPE_MOBILE_CONFIG_REQUEST: case LWAPP_MSGTYPE_MOBILE_CONFIG_RESPONSE: default: break; } tptr += sizeof(struct lwapp_control_header) + msg_tlen; tlen -= sizeof(struct lwapp_control_header) + msg_tlen; } return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); } void lwapp_data_print(netdissect_options *ndo, const u_char *pptr, u_int len) { const struct lwapp_transport_header *lwapp_trans_header; const u_char *tptr; int tlen; tptr=pptr; /* check if enough bytes for AP identity */ ND_TCHECK2(*tptr, 6); lwapp_trans_header = (const struct lwapp_transport_header *)pptr; ND_TCHECK(*lwapp_trans_header); /* * Sanity checking of the header. */ if (LWAPP_EXTRACT_VERSION(lwapp_trans_header->version) != LWAPP_VERSION) { ND_PRINT((ndo, "LWAPP version %u packet not supported", LWAPP_EXTRACT_VERSION(lwapp_trans_header->version))); return; } /* non-verbose */ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "LWAPPv%u, %s frame, Flags [%s], length %u", LWAPP_EXTRACT_VERSION(lwapp_trans_header->version), LWAPP_EXTRACT_CONTROL_BIT(lwapp_trans_header->version) ? "Control" : "Data", bittok2str(lwapp_header_bits_values,"none",(lwapp_trans_header->version)&0x07), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ tlen=EXTRACT_16BITS(lwapp_trans_header->length); ND_PRINT((ndo, "LWAPPv%u, %s frame, Radio-id %u, Flags [%s], Frag-id %u, length %u", LWAPP_EXTRACT_VERSION(lwapp_trans_header->version), LWAPP_EXTRACT_CONTROL_BIT(lwapp_trans_header->version) ? "Control" : "Data", LWAPP_EXTRACT_RID(lwapp_trans_header->version), bittok2str(lwapp_header_bits_values,"none",(lwapp_trans_header->version)&0x07), lwapp_trans_header->frag_id, tlen)); tptr+=sizeof(struct lwapp_transport_header); tlen-=sizeof(struct lwapp_transport_header); /* FIX - An IEEE 802.11 frame follows - hexdump for now */ print_unknown_data(ndo, tptr, "\n\t", tlen); return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
null
null
null
null
124,055
17,066
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
17,066
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/viz/test/test_frame_sink_manager_client.h" namespace viz { TestFrameSinkManagerClient::TestFrameSinkManagerClient( mojom::FrameSinkManager* manager) : manager_(manager) {} TestFrameSinkManagerClient::~TestFrameSinkManagerClient() = default; void TestFrameSinkManagerClient::SetFrameSinkHierarchy( const FrameSinkId& parent_frame_sink_id, const FrameSinkId& child_frame_sink_id) { frame_sink_hierarchy_[child_frame_sink_id] = parent_frame_sink_id; } void TestFrameSinkManagerClient::DisableAssignTemporaryReferences() { disabled_ = true; } void TestFrameSinkManagerClient::Reset() { disabled_ = false; frame_sink_hierarchy_.clear(); } void TestFrameSinkManagerClient::OnSurfaceCreated(const SurfaceId& surface_id) { if (disabled_) return; auto iter = frame_sink_hierarchy_.find(surface_id.frame_sink_id()); if (iter == frame_sink_hierarchy_.end()) { manager_->DropTemporaryReference(surface_id); return; } manager_->AssignTemporaryReference(surface_id, iter->second); } } // namespace viz
null
null
null
null
13,929
52,008
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
52,008
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/gpu/windows/d3d11_h264_accelerator.h" #include <windows.h> #include "base/memory/ptr_util.h" #include "base/trace_event/trace_event.h" #include "media/gpu/h264_decoder.h" #include "media/gpu/h264_dpb.h" #include "media/gpu/windows/d3d11_picture_buffer.h" #include "media/gpu/windows/return_on_failure.h" #include "third_party/angle/include/EGL/egl.h" #include "third_party/angle/include/EGL/eglext.h" #include "ui/gfx/color_space.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_image_dxgi.h" #include "ui/gl/gl_surface_egl.h" #include "ui/gl/scoped_binders.h" namespace media { class D3D11H264Picture : public H264Picture { public: D3D11H264Picture(D3D11PictureBuffer* picture) : picture(picture), level_(picture->level()) { picture->set_in_picture_use(true); } D3D11PictureBuffer* picture; size_t level_; protected: ~D3D11H264Picture() override; }; D3D11H264Picture::~D3D11H264Picture() { picture->set_in_picture_use(false); } D3D11H264Accelerator::D3D11H264Accelerator( D3D11VideoDecoderClient* client, Microsoft::WRL::ComPtr<ID3D11VideoDecoder> video_decoder, Microsoft::WRL::ComPtr<ID3D11VideoDevice> video_device, Microsoft::WRL::ComPtr<ID3D11VideoContext> video_context) : client_(client), video_decoder_(video_decoder), video_device_(video_device), video_context_(video_context) {} D3D11H264Accelerator::~D3D11H264Accelerator() {} scoped_refptr<H264Picture> D3D11H264Accelerator::CreateH264Picture() { D3D11PictureBuffer* picture = client_->GetPicture(); if (!picture) { return nullptr; } return base::MakeRefCounted<D3D11H264Picture>(picture); } bool D3D11H264Accelerator::SubmitFrameMetadata( const H264SPS* sps, const H264PPS* pps, const H264DPB& dpb, const H264Picture::Vector& ref_pic_listp0, const H264Picture::Vector& ref_pic_listb0, const H264Picture::Vector& ref_pic_listb1, const scoped_refptr<H264Picture>& pic) { scoped_refptr<D3D11H264Picture> our_pic( static_cast<D3D11H264Picture*>(pic.get())); HRESULT hr; for (;;) { hr = video_context_->DecoderBeginFrame( video_decoder_.Get(), our_pic->picture->output_view().Get(), 0, nullptr); if (hr == E_PENDING || hr == D3DERR_WASSTILLDRAWING) { // Hardware is busy. We should make the call again. // TODO(liberato): For now, just busy wait. ; } else if (!SUCCEEDED(hr)) { LOG(ERROR) << "DecoderBeginFrame failed"; return false; } else { break; } } sps_ = *sps; for (size_t i = 0; i < 16; i++) { ref_frame_list_[i].bPicEntry = 0xFF; field_order_cnt_list_[i][0] = 0; field_order_cnt_list_[i][1] = 0; frame_num_list_[i] = 0; } used_for_reference_flags_ = 0; non_existing_frame_flags_ = 0; int i = 0; // TODO(liberato): this is similar to H264Accelerator. can they share code? for (auto it = dpb.begin(); it != dpb.end(); it++) { scoped_refptr<D3D11H264Picture> our_ref_pic( static_cast<D3D11H264Picture*>(it->get())); if (!our_ref_pic->ref) { i++; continue; } ref_frame_list_[i].Index7Bits = our_ref_pic->level_; ref_frame_list_[i].AssociatedFlag = our_ref_pic->long_term; field_order_cnt_list_[i][0] = our_ref_pic->top_field_order_cnt; field_order_cnt_list_[i][1] = our_ref_pic->bottom_field_order_cnt; frame_num_list_[i] = ref_frame_list_[i].AssociatedFlag ? our_ref_pic->long_term_pic_num : our_ref_pic->frame_num; int ref = 3; used_for_reference_flags_ |= ref << (2 * i); non_existing_frame_flags_ |= (our_ref_pic->nonexisting) << i; i++; } slice_info_.clear(); return RetrieveBitstreamBuffer(); } bool D3D11H264Accelerator::RetrieveBitstreamBuffer() { DCHECK(!bitstream_buffer_bytes_); DCHECK(!bitstream_buffer_size_); current_offset_ = 0; void* buffer; UINT buffer_size; HRESULT hr = video_context_->GetDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_BITSTREAM, &buffer_size, &buffer); if (!SUCCEEDED(hr)) { LOG(ERROR) << "GetDecoderBuffer (Bitstream) failed"; return false; } bitstream_buffer_bytes_ = (uint8_t*)buffer; bitstream_buffer_size_ = buffer_size; return true; } bool D3D11H264Accelerator::SubmitSlice(const H264PPS* pps, const H264SliceHeader* slice_hdr, const H264Picture::Vector& ref_pic_list0, const H264Picture::Vector& ref_pic_list1, const scoped_refptr<H264Picture>& pic, const uint8_t* data, size_t size) { scoped_refptr<D3D11H264Picture> our_pic( static_cast<D3D11H264Picture*>(pic.get())); DXVA_PicParams_H264 pic_param = {}; #define FROM_SPS_TO_PP(a) pic_param.a = sps_.a #define FROM_SPS_TO_PP2(a, b) pic_param.a = sps_.b #define FROM_PPS_TO_PP(a) pic_param.a = pps->a #define FROM_PPS_TO_PP2(a, b) pic_param.a = pps->b #define FROM_SLICE_TO_PP(a) pic_param.a = slice_hdr->a #define FROM_SLICE_TO_PP2(a, b) pic_param.a = slice_hdr->b FROM_SPS_TO_PP2(wFrameWidthInMbsMinus1, pic_width_in_mbs_minus1); FROM_SPS_TO_PP2(wFrameHeightInMbsMinus1, pic_height_in_map_units_minus1); pic_param.CurrPic.Index7Bits = our_pic->level_; pic_param.CurrPic.AssociatedFlag = slice_hdr->bottom_field_flag; FROM_SPS_TO_PP2(num_ref_frames, max_num_ref_frames); FROM_SLICE_TO_PP(field_pic_flag); pic_param.MbaffFrameFlag = sps_.mb_adaptive_frame_field_flag && pic_param.field_pic_flag; FROM_SPS_TO_PP2(residual_colour_transform_flag, separate_colour_plane_flag); FROM_SLICE_TO_PP(sp_for_switch_flag); FROM_SPS_TO_PP(chroma_format_idc); pic_param.RefPicFlag = pic->ref; FROM_PPS_TO_PP(constrained_intra_pred_flag); FROM_PPS_TO_PP(weighted_pred_flag); FROM_PPS_TO_PP(weighted_bipred_idc); pic_param.MbsConsecutiveFlag = 1; FROM_SPS_TO_PP(frame_mbs_only_flag); FROM_PPS_TO_PP(transform_8x8_mode_flag); // TODO(liberato): sandersd@ believes that this should only be set for level // >= 3.1 . verify this and fix as needed. pic_param.MinLumaBipredSize8x8Flag = 1; pic_param.IntraPicFlag = slice_hdr->IsISlice(); FROM_SPS_TO_PP(bit_depth_luma_minus8); FROM_SPS_TO_PP(bit_depth_chroma_minus8); // The latest DXVA decoding guide says to set this to 3 if the software // decoder (this class) is following the guide. pic_param.Reserved16Bits = 3; memcpy(pic_param.RefFrameList, ref_frame_list_, sizeof pic_param.RefFrameList); if (pic_param.field_pic_flag && pic_param.CurrPic.AssociatedFlag) { pic_param.CurrFieldOrderCnt[1] = pic->bottom_field_order_cnt; pic_param.CurrFieldOrderCnt[0] = 0; } else if (pic_param.field_pic_flag && !pic_param.CurrPic.AssociatedFlag) { pic_param.CurrFieldOrderCnt[0] = pic->top_field_order_cnt; pic_param.CurrFieldOrderCnt[1] = 0; } else { pic_param.CurrFieldOrderCnt[0] = pic->top_field_order_cnt; pic_param.CurrFieldOrderCnt[1] = pic->bottom_field_order_cnt; } memcpy(pic_param.FieldOrderCntList, field_order_cnt_list_, sizeof pic_param.FieldOrderCntList); FROM_PPS_TO_PP(pic_init_qs_minus26); FROM_PPS_TO_PP(chroma_qp_index_offset); FROM_PPS_TO_PP(second_chroma_qp_index_offset); pic_param.ContinuationFlag = 1; FROM_PPS_TO_PP(pic_init_qp_minus26); FROM_PPS_TO_PP2(num_ref_idx_l0_active_minus1, num_ref_idx_l0_default_active_minus1); FROM_PPS_TO_PP2(num_ref_idx_l1_active_minus1, num_ref_idx_l1_default_active_minus1); // UNUSED: Reserved8BitsA memcpy(pic_param.FrameNumList, frame_num_list_, sizeof pic_param.FrameNumList); pic_param.UsedForReferenceFlags = used_for_reference_flags_; pic_param.NonExistingFrameFlags = non_existing_frame_flags_; pic_param.frame_num = pic->frame_num; FROM_SPS_TO_PP(log2_max_frame_num_minus4); FROM_SPS_TO_PP(pic_order_cnt_type); FROM_SPS_TO_PP(log2_max_pic_order_cnt_lsb_minus4); FROM_SPS_TO_PP(delta_pic_order_always_zero_flag); FROM_SPS_TO_PP(direct_8x8_inference_flag); FROM_PPS_TO_PP(entropy_coding_mode_flag); FROM_PPS_TO_PP2(pic_order_present_flag, bottom_field_pic_order_in_frame_present_flag); FROM_PPS_TO_PP(num_slice_groups_minus1); CHECK_EQ(0u, pic_param.num_slice_groups_minus1); // UNUSED: slice_group_map_type FROM_PPS_TO_PP(deblocking_filter_control_present_flag); FROM_PPS_TO_PP(redundant_pic_cnt_present_flag); // UNUSED: Reserved8BitsB // UNUSED: slice_group_change_rate // // // pic_param.StatusReportFeedbackNumber = 1; UINT buffer_size; void* buffer; HRESULT hr = video_context_->GetDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS, &buffer_size, &buffer); if (!SUCCEEDED(hr)) { LOG(ERROR) << "ReleaseDecoderBuffer (PictureParams) failed"; return false; } memcpy(buffer, &pic_param, sizeof(pic_param)); hr = video_context_->ReleaseDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS); if (!SUCCEEDED(hr)) { LOG(ERROR) << "ReleaseDecoderBuffer (PictureParams) failed"; return false; } DXVA_Qmatrix_H264 iq_matrix_buf = {}; if (pps->pic_scaling_matrix_present_flag) { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.bScalingLists4x4[i][j] = pps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.bScalingLists8x8[i][j] = pps->scaling_list8x8[i][j]; } } else { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.bScalingLists4x4[i][j] = sps_.scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.bScalingLists8x8[i][j] = sps_.scaling_list8x8[i][j]; } } hr = video_context_->GetDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_INVERSE_QUANTIZATION_MATRIX, &buffer_size, &buffer); if (!SUCCEEDED(hr)) { LOG(ERROR) << "GetDecoderBuffer (QuantMatrix) failed"; return false; } memcpy(buffer, &iq_matrix_buf, sizeof(iq_matrix_buf)); hr = video_context_->ReleaseDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_INVERSE_QUANTIZATION_MATRIX); if (!SUCCEEDED(hr)) { LOG(ERROR) << "ReleaseDecoderBuffer (QuantMatrix) failed"; return false; } // Ideally all slices in a frame are put in the same bitstream buffer. // However the bitstream buffer may not fit all the data, so split on the // necessary boundaries. size_t out_bitstream_size = size + 3; size_t remaining_bitstream = out_bitstream_size; size_t start_location = 0; while (remaining_bitstream > 0) { if (bitstream_buffer_size_ < remaining_bitstream && slice_info_.size() > 0) { if (!SubmitSliceData()) { LOG(ERROR) << "SubmitSliceData failed"; return false; } if (!RetrieveBitstreamBuffer()) { LOG(ERROR) << "RetrieveBitstreamBuffer failed"; return false; } } size_t bytes_to_copy = remaining_bitstream; bool contains_end = true; if (bytes_to_copy > bitstream_buffer_size_) { bytes_to_copy = bitstream_buffer_size_; contains_end = false; } size_t real_bytes_to_copy = bytes_to_copy; // TODO(jbauman): fix hack uint8_t* out_start = bitstream_buffer_bytes_; if (bytes_to_copy >= 3 && start_location == 0) { *(out_start++) = 0; *(out_start++) = 0; *(out_start++) = 1; real_bytes_to_copy -= 3; } memcpy(out_start, data + start_location, real_bytes_to_copy); DXVA_Slice_H264_Short slice_info = {}; slice_info.BSNALunitDataLocation = (UINT)current_offset_; slice_info.SliceBytesInBuffer = (UINT)bytes_to_copy; if (contains_end && start_location == 0) slice_info.wBadSliceChopping = 0; else if (!contains_end && start_location == 0) slice_info.wBadSliceChopping = 1; else if (contains_end && start_location != 0) slice_info.wBadSliceChopping = 2; else slice_info.wBadSliceChopping = 3; slice_info_.push_back(slice_info); bitstream_buffer_size_ -= bytes_to_copy; current_offset_ += bytes_to_copy; start_location += bytes_to_copy; remaining_bitstream -= bytes_to_copy; bitstream_buffer_bytes_ += bytes_to_copy; } return true; } bool D3D11H264Accelerator::SubmitSliceData() { CHECK(slice_info_.size() > 0); UINT buffer_size; void* buffer; // TODO(liberato): Should we release the other buffers on failure? HRESULT hr = video_context_->GetDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL, &buffer_size, &buffer); if (!SUCCEEDED(hr)) { LOG(ERROR) << "GetDecoderBuffer (SliceControl) failed"; return false; } CHECK_LE(sizeof(slice_info_[0]) * slice_info_.size(), buffer_size); memcpy(buffer, &slice_info_[0], sizeof(slice_info_[0]) * slice_info_.size()); hr = video_context_->ReleaseDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL); if (!SUCCEEDED(hr)) { LOG(ERROR) << "ReleaseDecoderBuffer (SliceControl) failed"; return false; } hr = video_context_->ReleaseDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_BITSTREAM); if (!SUCCEEDED(hr)) { LOG(ERROR) << "ReleaseDecoderBuffer (BitStream) failed"; return false; } D3D11_VIDEO_DECODER_BUFFER_DESC buffers[4] = {}; buffers[0].BufferType = D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS; buffers[0].DataOffset = 0; buffers[0].DataSize = sizeof(DXVA_PicParams_H264); buffers[1].BufferType = D3D11_VIDEO_DECODER_BUFFER_INVERSE_QUANTIZATION_MATRIX; buffers[1].DataOffset = 0; buffers[1].DataSize = sizeof(DXVA_Qmatrix_H264); buffers[2].BufferType = D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL; buffers[2].DataOffset = 0; buffers[2].DataSize = (UINT)(sizeof(slice_info_[0]) * slice_info_.size()); buffers[3].BufferType = D3D11_VIDEO_DECODER_BUFFER_BITSTREAM; buffers[3].DataOffset = 0; buffers[3].DataSize = (UINT)current_offset_; hr = video_context_->SubmitDecoderBuffers(video_decoder_.Get(), 4, buffers); current_offset_ = 0; slice_info_.clear(); bitstream_buffer_bytes_ = nullptr; bitstream_buffer_size_ = 0; if (!SUCCEEDED(hr)) { LOG(ERROR) << "SubmitDecoderBuffers failed"; return false; } return true; } bool D3D11H264Accelerator::SubmitDecode(const scoped_refptr<H264Picture>& pic) { if (!SubmitSliceData()) { LOG(ERROR) << "SubmitSliceData failed"; return false; } HRESULT hr = video_context_->DecoderEndFrame(video_decoder_.Get()); if (!SUCCEEDED(hr)) { LOG(ERROR) << "DecoderEndFrame failed"; return false; } return true; } void D3D11H264Accelerator::Reset() { if (!bitstream_buffer_bytes_) return; HRESULT hr = video_context_->ReleaseDecoderBuffer( video_decoder_.Get(), D3D11_VIDEO_DECODER_BUFFER_BITSTREAM); bitstream_buffer_bytes_ = nullptr; bitstream_buffer_size_ = 0; current_offset_ = 0; CHECK(SUCCEEDED(hr)); } bool D3D11H264Accelerator::OutputPicture( const scoped_refptr<H264Picture>& pic) { scoped_refptr<D3D11H264Picture> our_pic( static_cast<D3D11H264Picture*>(pic.get())); client_->OutputResult(our_pic->picture); return true; } } // namespace media
null
null
null
null
48,871
70,751
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
70,751
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sandbox/linux/seccomp-bpf/trap.h" #include <signal.h> #include "sandbox/linux/tests/unit_tests.h" #include "testing/gtest/include/gtest/gtest.h" namespace sandbox { namespace { SANDBOX_TEST_ALLOW_NOISE(Trap, SigSysAction) { // This creates a global Trap instance, and registers the signal handler // (Trap::SigSysAction). Trap::Registry(); // Send SIGSYS to self. If signal handler (SigSysAction) is not registered, // the process will be terminated with status code -SIGSYS. // Note that, SigSysAction handler would output an error message // "Unexpected SIGSYS received." so it is necessary to allow the noise. raise(SIGSYS); } } // namespace } // namespace sandbox
null
null
null
null
67,614
33,280
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
33,280
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2001 Peter Kelly (pmk@post.com) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2003, 2004, 2005, 2006, 2008, 2010, 2013 Apple Inc. All rights * reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_NAMED_NODE_MAP_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_NAMED_NODE_MAP_H_ #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" namespace blink { class Attr; class ExceptionState; class NamedNodeMap final : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); friend class Element; public: static NamedNodeMap* Create(Element* element) { return new NamedNodeMap(element); } // Public DOM interface. Attr* getNamedItem(const AtomicString&) const; Attr* removeNamedItem(const AtomicString& name, ExceptionState&); Attr* getNamedItemNS(const AtomicString& namespace_uri, const AtomicString& local_name) const; Attr* removeNamedItemNS(const AtomicString& namespace_uri, const AtomicString& local_name, ExceptionState&); Attr* setNamedItem(Attr*, ExceptionState&); Attr* setNamedItemNS(Attr*, ExceptionState&); Attr* item(unsigned index) const; size_t length() const; void NamedPropertyEnumerator(Vector<String>& names, ExceptionState&) const; bool NamedPropertyQuery(const AtomicString&, ExceptionState&) const; void Trace(blink::Visitor*); private: explicit NamedNodeMap(Element* element) : element_(element) { // Only supports NamedNodeMaps with Element associated. DCHECK(element_); } Member<Element> element_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_NAMED_NODE_MAP_H_
null
null
null
null
30,143
38,347
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
203,342
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * POWER Data Stream Control Register (DSCR) fork test * * This testcase modifies the DSCR using mtspr, forks and then * verifies that the child process has the correct changed DSCR * value using mfspr. * * When using the privilege state SPR, the instructions such as * mfspr or mtspr are priviledged and the kernel emulates them * for us. Instructions using problem state SPR can be exuecuted * directly without any emulation if the HW supports them. Else * they also get emulated by the kernel. * * Copyright 2012, Anton Blanchard, IBM Corporation. * Copyright 2015, Anshuman Khandual, IBM Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "dscr.h" int dscr_inherit(void) { unsigned long i, dscr = 0; pid_t pid; srand(getpid()); set_dscr(dscr); for (i = 0; i < COUNT; i++) { unsigned long cur_dscr, cur_dscr_usr; dscr++; if (dscr > DSCR_MAX) dscr = 0; if (i % 2 == 0) set_dscr_usr(dscr); else set_dscr(dscr); pid = fork(); if (pid == -1) { perror("fork() failed"); exit(1); } else if (pid) { int status; if (waitpid(pid, &status, 0) == -1) { perror("waitpid() failed"); exit(1); } if (!WIFEXITED(status)) { fprintf(stderr, "Child didn't exit cleanly\n"); exit(1); } if (WEXITSTATUS(status) != 0) { fprintf(stderr, "Child didn't exit cleanly\n"); return 1; } } else { cur_dscr = get_dscr(); if (cur_dscr != dscr) { fprintf(stderr, "Kernel DSCR should be %ld " "but is %ld\n", dscr, cur_dscr); exit(1); } cur_dscr_usr = get_dscr_usr(); if (cur_dscr_usr != dscr) { fprintf(stderr, "User DSCR should be %ld " "but is %ld\n", dscr, cur_dscr_usr); exit(1); } exit(0); } } return 0; } int main(int argc, char *argv[]) { return test_harness(dscr_inherit, "dscr_inherit_test"); }
null
null
null
null
111,689
6,835
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
6,835
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_QUIC_QUARTC_QUARTC_STREAM_INTERFACE_H_ #define NET_QUIC_QUARTC_QUARTC_STREAM_INTERFACE_H_ #include <stddef.h> #include <stdint.h> #include "net/quic/platform/api/quic_export.h" namespace net { // Sends and receives data with a particular QUIC stream ID, reliably and // in-order. To send/receive data out of order, use separate streams. To // send/receive unreliably, close a stream after reliability is no longer // needed. class QUIC_EXPORT_PRIVATE QuartcStreamInterface { public: virtual ~QuartcStreamInterface() {} // The QUIC stream ID. virtual uint32_t stream_id() = 0; // The amount of data buffered on this stream. virtual uint64_t bytes_buffered() = 0; // Return true if the FIN has been sent. Used by the outgoing streams to // determine if all the data has been sent virtual bool fin_sent() = 0; virtual int stream_error() = 0; struct WriteParameters { // |fin| is set to be true when there is no more data need to be send // through a particular stream. The receiving side will used it to determine // if the sender finish sending data. bool fin = false; }; // Sends data reliably and in-order. Returns the amount sent. // Does not buffer data. virtual void Write(const char* data, size_t size, const WriteParameters& param) = 0; // Marks this stream as finished writing. Asynchronously sends a FIN and // closes the write-side. The stream will no longer call OnCanWrite(). // It is not necessary to call FinishWriting() if the last call to Write() // sends a FIN. virtual void FinishWriting() = 0; // Marks this stream as finished reading. Further incoming data is discarded. // The stream will no longer call OnReceived(). // It is never necessary to call FinishReading(). The read-side closes when a // FIN is received, regardless of whether FinishReading() has been called. virtual void FinishReading() = 0; // Once Close is called, no more data can be sent, all buffered data will be // dropped and no data will be retransmitted. virtual void Close() = 0; // Implemented by the user of the QuartcStreamInterface to receive incoming // data and be notified of state changes. class Delegate { public: virtual ~Delegate() {} // Called when the stream receives the data. Called with |size| == 0 after // all stream data has been delivered. virtual void OnReceived(QuartcStreamInterface* stream, const char* data, size_t size) = 0; // Called when the stream is closed, either locally or by the remote // endpoint. Streams close when (a) fin bits are both sent and received, // (b) Close() is called, or (c) the stream is reset. // TODO(zhihuang) Creates a map from the integer error_code to WebRTC native // error code. virtual void OnClose(QuartcStreamInterface* stream) = 0; // Called when the contents of the stream's buffer changes. virtual void OnBufferChanged(QuartcStreamInterface* stream) = 0; }; // The |delegate| is not owned by QuartcStream. virtual void SetDelegate(Delegate* delegate) = 0; }; } // namespace net #endif // NET_QUIC_QUARTC_QUARTC_STREAM_INTERFACE_H_
null
null
null
null
3,698
38,697
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
203,692
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* Red Black Trees (C) 1999 Andrea Arcangeli <andrea@suse.de> (C) 2002 David Woodhouse <dwmw2@infradead.org> (C) 2012 Michel Lespinasse <walken@google.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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 tools/linux/include/linux/rbtree_augmented.h Copied from: linux/include/linux/rbtree_augmented.h */ #ifndef _TOOLS_LINUX_RBTREE_AUGMENTED_H #define _TOOLS_LINUX_RBTREE_AUGMENTED_H #include <linux/compiler.h> #include <linux/rbtree.h> /* * Please note - only struct rb_augment_callbacks and the prototypes for * rb_insert_augmented() and rb_erase_augmented() are intended to be public. * The rest are implementation details you are not expected to depend on. * * See Documentation/rbtree.txt for documentation and samples. */ struct rb_augment_callbacks { void (*propagate)(struct rb_node *node, struct rb_node *stop); void (*copy)(struct rb_node *old, struct rb_node *new); void (*rotate)(struct rb_node *old, struct rb_node *new); }; extern void __rb_insert_augmented(struct rb_node *node, struct rb_root *root, void (*augment_rotate)(struct rb_node *old, struct rb_node *new)); /* * Fixup the rbtree and update the augmented information when rebalancing. * * On insertion, the user must update the augmented information on the path * leading to the inserted node, then call rb_link_node() as usual and * rb_augment_inserted() instead of the usual rb_insert_color() call. * If rb_augment_inserted() rebalances the rbtree, it will callback into * a user provided function to update the augmented information on the * affected subtrees. */ static inline void rb_insert_augmented(struct rb_node *node, struct rb_root *root, const struct rb_augment_callbacks *augment) { __rb_insert_augmented(node, root, augment->rotate); } #define RB_DECLARE_CALLBACKS(rbstatic, rbname, rbstruct, rbfield, \ rbtype, rbaugmented, rbcompute) \ static inline void \ rbname ## _propagate(struct rb_node *rb, struct rb_node *stop) \ { \ while (rb != stop) { \ rbstruct *node = rb_entry(rb, rbstruct, rbfield); \ rbtype augmented = rbcompute(node); \ if (node->rbaugmented == augmented) \ break; \ node->rbaugmented = augmented; \ rb = rb_parent(&node->rbfield); \ } \ } \ static inline void \ rbname ## _copy(struct rb_node *rb_old, struct rb_node *rb_new) \ { \ rbstruct *old = rb_entry(rb_old, rbstruct, rbfield); \ rbstruct *new = rb_entry(rb_new, rbstruct, rbfield); \ new->rbaugmented = old->rbaugmented; \ } \ static void \ rbname ## _rotate(struct rb_node *rb_old, struct rb_node *rb_new) \ { \ rbstruct *old = rb_entry(rb_old, rbstruct, rbfield); \ rbstruct *new = rb_entry(rb_new, rbstruct, rbfield); \ new->rbaugmented = old->rbaugmented; \ old->rbaugmented = rbcompute(old); \ } \ rbstatic const struct rb_augment_callbacks rbname = { \ rbname ## _propagate, rbname ## _copy, rbname ## _rotate \ }; #define RB_RED 0 #define RB_BLACK 1 #define __rb_parent(pc) ((struct rb_node *)(pc & ~3)) #define __rb_color(pc) ((pc) & 1) #define __rb_is_black(pc) __rb_color(pc) #define __rb_is_red(pc) (!__rb_color(pc)) #define rb_color(rb) __rb_color((rb)->__rb_parent_color) #define rb_is_red(rb) __rb_is_red((rb)->__rb_parent_color) #define rb_is_black(rb) __rb_is_black((rb)->__rb_parent_color) static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p) { rb->__rb_parent_color = rb_color(rb) | (unsigned long)p; } static inline void rb_set_parent_color(struct rb_node *rb, struct rb_node *p, int color) { rb->__rb_parent_color = (unsigned long)p | color; } static inline void __rb_change_child(struct rb_node *old, struct rb_node *new, struct rb_node *parent, struct rb_root *root) { if (parent) { if (parent->rb_left == old) parent->rb_left = new; else parent->rb_right = new; } else root->rb_node = new; } extern void __rb_erase_color(struct rb_node *parent, struct rb_root *root, void (*augment_rotate)(struct rb_node *old, struct rb_node *new)); static __always_inline struct rb_node * __rb_erase_augmented(struct rb_node *node, struct rb_root *root, const struct rb_augment_callbacks *augment) { struct rb_node *child = node->rb_right, *tmp = node->rb_left; struct rb_node *parent, *rebalance; unsigned long pc; if (!tmp) { /* * Case 1: node to erase has no more than 1 child (easy!) * * Note that if there is one child it must be red due to 5) * and node must be black due to 4). We adjust colors locally * so as to bypass __rb_erase_color() later on. */ pc = node->__rb_parent_color; parent = __rb_parent(pc); __rb_change_child(node, child, parent, root); if (child) { child->__rb_parent_color = pc; rebalance = NULL; } else rebalance = __rb_is_black(pc) ? parent : NULL; tmp = parent; } else if (!child) { /* Still case 1, but this time the child is node->rb_left */ tmp->__rb_parent_color = pc = node->__rb_parent_color; parent = __rb_parent(pc); __rb_change_child(node, tmp, parent, root); rebalance = NULL; tmp = parent; } else { struct rb_node *successor = child, *child2; tmp = child->rb_left; if (!tmp) { /* * Case 2: node's successor is its right child * * (n) (s) * / \ / \ * (x) (s) -> (x) (c) * \ * (c) */ parent = successor; child2 = successor->rb_right; augment->copy(node, successor); } else { /* * Case 3: node's successor is leftmost under * node's right child subtree * * (n) (s) * / \ / \ * (x) (y) -> (x) (y) * / / * (p) (p) * / / * (s) (c) * \ * (c) */ do { parent = successor; successor = tmp; tmp = tmp->rb_left; } while (tmp); parent->rb_left = child2 = successor->rb_right; successor->rb_right = child; rb_set_parent(child, successor); augment->copy(node, successor); augment->propagate(parent, successor); } successor->rb_left = tmp = node->rb_left; rb_set_parent(tmp, successor); pc = node->__rb_parent_color; tmp = __rb_parent(pc); __rb_change_child(node, successor, tmp, root); if (child2) { successor->__rb_parent_color = pc; rb_set_parent_color(child2, parent, RB_BLACK); rebalance = NULL; } else { unsigned long pc2 = successor->__rb_parent_color; successor->__rb_parent_color = pc; rebalance = __rb_is_black(pc2) ? parent : NULL; } tmp = successor; } augment->propagate(tmp, NULL); return rebalance; } static __always_inline void rb_erase_augmented(struct rb_node *node, struct rb_root *root, const struct rb_augment_callbacks *augment) { struct rb_node *rebalance = __rb_erase_augmented(node, root, augment); if (rebalance) __rb_erase_color(rebalance, root, augment->rotate); } #endif /* _TOOLS_LINUX_RBTREE_AUGMENTED_H */
null
null
null
null
112,039
47,878
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
47,878
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/display/display.h" #include "base/command_line.h" #include "base/test/scoped_command_line.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/display/display_switches.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" namespace display { TEST(DisplayTest, WorkArea) { Display display(0, gfx::Rect(0, 0, 100, 100)); EXPECT_EQ("0,0 100x100", display.bounds().ToString()); EXPECT_EQ("0,0 100x100", display.work_area().ToString()); display.set_work_area(gfx::Rect(3, 4, 90, 80)); EXPECT_EQ("0,0 100x100", display.bounds().ToString()); EXPECT_EQ("3,4 90x80", display.work_area().ToString()); display.SetScaleAndBounds(1.0f, gfx::Rect(10, 20, 50, 50)); EXPECT_EQ("10,20 50x50", display.bounds().ToString()); EXPECT_EQ("13,24 40x30", display.work_area().ToString()); display.SetSize(gfx::Size(200, 200)); EXPECT_EQ("13,24 190x180", display.work_area().ToString()); display.UpdateWorkAreaFromInsets(gfx::Insets(3, 4, 5, 6)); EXPECT_EQ("14,23 190x192", display.work_area().ToString()); } TEST(DisplayTest, Scale) { Display display(0, gfx::Rect(0, 0, 100, 100)); display.set_work_area(gfx::Rect(10, 10, 80, 80)); EXPECT_EQ("0,0 100x100", display.bounds().ToString()); EXPECT_EQ("10,10 80x80", display.work_area().ToString()); // Scale it back to 2x display.SetScaleAndBounds(2.0f, gfx::Rect(0, 0, 140, 140)); EXPECT_EQ("0,0 70x70", display.bounds().ToString()); EXPECT_EQ("10,10 50x50", display.work_area().ToString()); // Scale it back to 1x display.SetScaleAndBounds(1.0f, gfx::Rect(0, 0, 100, 100)); EXPECT_EQ("0,0 100x100", display.bounds().ToString()); EXPECT_EQ("10,10 80x80", display.work_area().ToString()); } // https://crbug.com/517944 TEST(DisplayTest, ForcedDeviceScaleFactorByCommandLine) { base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); Display::ResetForceDeviceScaleFactorForTesting(); command_line->AppendSwitch(switches::kForceDeviceScaleFactor); EXPECT_EQ(1, Display::GetForcedDeviceScaleFactor()); Display::ResetForceDeviceScaleFactorForTesting(); } TEST(DisplayTest, ForcedDeviceScaleFactor) { Display::SetForceDeviceScaleFactor(2); EXPECT_EQ(2, Display::GetForcedDeviceScaleFactor()); Display::ResetForceDeviceScaleFactorForTesting(); } TEST(DisplayTest, DisplayHDRValues) { Display display; EXPECT_EQ(24, display.color_depth()); EXPECT_EQ(8, display.depth_per_component()); display.SetColorSpaceAndDepth(gfx::ColorSpace::CreateSCRGBLinear()); EXPECT_EQ(48, display.color_depth()); EXPECT_EQ(16, display.depth_per_component()); display.SetColorSpaceAndDepth(gfx::ColorSpace::CreateSRGB()); EXPECT_EQ(24, display.color_depth()); EXPECT_EQ(8, display.depth_per_component()); } } // namespace display
null
null
null
null
44,741
17,221
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
17,221
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/viz/common/quads/picture_draw_quad.h" #include "base/trace_event/trace_event_argument.h" #include "base/values.h" #include "cc/base/math_util.h" #include "components/viz/common/resources/platform_color.h" namespace viz { PictureDrawQuad::PictureDrawQuad() = default; PictureDrawQuad::PictureDrawQuad(const PictureDrawQuad& other) = default; PictureDrawQuad::~PictureDrawQuad() = default; void PictureDrawQuad::SetNew( const SharedQuadState* shared_quad_state, const gfx::Rect& rect, const gfx::Rect& visible_rect, bool needs_blending, const gfx::RectF& tex_coord_rect, const gfx::Size& texture_size, bool nearest_neighbor, ResourceFormat texture_format, const gfx::Rect& content_rect, float contents_scale, scoped_refptr<cc::DisplayItemList> display_item_list) { ContentDrawQuadBase::SetNew( shared_quad_state, DrawQuad::PICTURE_CONTENT, rect, visible_rect, needs_blending, tex_coord_rect, texture_size, !PlatformColor::SameComponentOrder(texture_format), false, nearest_neighbor, false); this->content_rect = content_rect; this->contents_scale = contents_scale; this->display_item_list = std::move(display_item_list); this->texture_format = texture_format; } void PictureDrawQuad::SetAll( const SharedQuadState* shared_quad_state, const gfx::Rect& rect, const gfx::Rect& visible_rect, bool needs_blending, const gfx::RectF& tex_coord_rect, const gfx::Size& texture_size, bool nearest_neighbor, ResourceFormat texture_format, const gfx::Rect& content_rect, float contents_scale, scoped_refptr<cc::DisplayItemList> display_item_list) { ContentDrawQuadBase::SetAll( shared_quad_state, DrawQuad::PICTURE_CONTENT, rect, visible_rect, needs_blending, tex_coord_rect, texture_size, !PlatformColor::SameComponentOrder(texture_format), false, nearest_neighbor, false); this->content_rect = content_rect; this->contents_scale = contents_scale; this->display_item_list = std::move(display_item_list); this->texture_format = texture_format; } const PictureDrawQuad* PictureDrawQuad::MaterialCast(const DrawQuad* quad) { DCHECK(quad->material == DrawQuad::PICTURE_CONTENT); return static_cast<const PictureDrawQuad*>(quad); } void PictureDrawQuad::ExtendValue(base::trace_event::TracedValue* value) const { ContentDrawQuadBase::ExtendValue(value); cc::MathUtil::AddToTracedValue("content_rect", content_rect, value); value->SetDouble("contents_scale", contents_scale); value->SetInteger("texture_format", texture_format); // TODO(piman): display_item_list? } } // namespace viz
null
null
null
null
14,084
35,938
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
200,933
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * drivers/pcmcia/sa1100_cerf.c * * PCMCIA implementation routines for CerfBoard * Based off the Assabet. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/device.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/gpio.h> #include <mach/hardware.h> #include <asm/mach-types.h> #include <asm/irq.h> #include <mach/cerf.h> #include "sa1100_generic.h" #define CERF_SOCKET 1 static int cerf_pcmcia_hw_init(struct soc_pcmcia_socket *skt) { int ret; ret = gpio_request_one(CERF_GPIO_CF_RESET, GPIOF_OUT_INIT_LOW, "CF_RESET"); if (ret) return ret; skt->stat[SOC_STAT_CD].gpio = CERF_GPIO_CF_CD; skt->stat[SOC_STAT_CD].name = "CF_CD"; skt->stat[SOC_STAT_BVD1].gpio = CERF_GPIO_CF_BVD1; skt->stat[SOC_STAT_BVD1].name = "CF_BVD1"; skt->stat[SOC_STAT_BVD2].gpio = CERF_GPIO_CF_BVD2; skt->stat[SOC_STAT_BVD2].name = "CF_BVD2"; skt->stat[SOC_STAT_RDY].gpio = CERF_GPIO_CF_IRQ; skt->stat[SOC_STAT_RDY].name = "CF_IRQ"; return 0; } static void cerf_pcmcia_hw_shutdown(struct soc_pcmcia_socket *skt) { gpio_free(CERF_GPIO_CF_RESET); } static int cerf_pcmcia_configure_socket(struct soc_pcmcia_socket *skt, const socket_state_t *state) { switch (state->Vcc) { case 0: case 50: case 33: break; default: printk(KERN_ERR "%s(): unrecognized Vcc %u\n", __func__, state->Vcc); return -1; } gpio_set_value(CERF_GPIO_CF_RESET, !!(state->flags & SS_RESET)); return 0; } static struct pcmcia_low_level cerf_pcmcia_ops = { .owner = THIS_MODULE, .hw_init = cerf_pcmcia_hw_init, .hw_shutdown = cerf_pcmcia_hw_shutdown, .socket_state = soc_common_cf_socket_state, .configure_socket = cerf_pcmcia_configure_socket, }; int pcmcia_cerf_init(struct device *dev) { int ret = -ENODEV; if (machine_is_cerf()) ret = sa11xx_drv_pcmcia_probe(dev, &cerf_pcmcia_ops, CERF_SOCKET, 1); return ret; }
null
null
null
null
109,280
32,114
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
197,109
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2013 Pengutronix * Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de> * * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/clocksource.h> #include <linux/clockchips.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/clk.h> #define TIMERn_CTRL 0x00 #define TIMERn_CTRL_PRESC(val) (((val) & 0xf) << 24) #define TIMERn_CTRL_PRESC_1024 TIMERn_CTRL_PRESC(10) #define TIMERn_CTRL_CLKSEL(val) (((val) & 0x3) << 16) #define TIMERn_CTRL_CLKSEL_PRESCHFPERCLK TIMERn_CTRL_CLKSEL(0) #define TIMERn_CTRL_OSMEN 0x00000010 #define TIMERn_CTRL_MODE(val) (((val) & 0x3) << 0) #define TIMERn_CTRL_MODE_UP TIMERn_CTRL_MODE(0) #define TIMERn_CTRL_MODE_DOWN TIMERn_CTRL_MODE(1) #define TIMERn_CMD 0x04 #define TIMERn_CMD_START 0x00000001 #define TIMERn_CMD_STOP 0x00000002 #define TIMERn_IEN 0x0c #define TIMERn_IF 0x10 #define TIMERn_IFS 0x14 #define TIMERn_IFC 0x18 #define TIMERn_IRQ_UF 0x00000002 #define TIMERn_TOP 0x1c #define TIMERn_CNT 0x24 struct efm32_clock_event_ddata { struct clock_event_device evtdev; void __iomem *base; unsigned periodic_top; }; static int efm32_clock_event_shutdown(struct clock_event_device *evtdev) { struct efm32_clock_event_ddata *ddata = container_of(evtdev, struct efm32_clock_event_ddata, evtdev); writel_relaxed(TIMERn_CMD_STOP, ddata->base + TIMERn_CMD); return 0; } static int efm32_clock_event_set_oneshot(struct clock_event_device *evtdev) { struct efm32_clock_event_ddata *ddata = container_of(evtdev, struct efm32_clock_event_ddata, evtdev); writel_relaxed(TIMERn_CMD_STOP, ddata->base + TIMERn_CMD); writel_relaxed(TIMERn_CTRL_PRESC_1024 | TIMERn_CTRL_CLKSEL_PRESCHFPERCLK | TIMERn_CTRL_OSMEN | TIMERn_CTRL_MODE_DOWN, ddata->base + TIMERn_CTRL); return 0; } static int efm32_clock_event_set_periodic(struct clock_event_device *evtdev) { struct efm32_clock_event_ddata *ddata = container_of(evtdev, struct efm32_clock_event_ddata, evtdev); writel_relaxed(TIMERn_CMD_STOP, ddata->base + TIMERn_CMD); writel_relaxed(ddata->periodic_top, ddata->base + TIMERn_TOP); writel_relaxed(TIMERn_CTRL_PRESC_1024 | TIMERn_CTRL_CLKSEL_PRESCHFPERCLK | TIMERn_CTRL_MODE_DOWN, ddata->base + TIMERn_CTRL); writel_relaxed(TIMERn_CMD_START, ddata->base + TIMERn_CMD); return 0; } static int efm32_clock_event_set_next_event(unsigned long evt, struct clock_event_device *evtdev) { struct efm32_clock_event_ddata *ddata = container_of(evtdev, struct efm32_clock_event_ddata, evtdev); writel_relaxed(TIMERn_CMD_STOP, ddata->base + TIMERn_CMD); writel_relaxed(evt, ddata->base + TIMERn_CNT); writel_relaxed(TIMERn_CMD_START, ddata->base + TIMERn_CMD); return 0; } static irqreturn_t efm32_clock_event_handler(int irq, void *dev_id) { struct efm32_clock_event_ddata *ddata = dev_id; writel_relaxed(TIMERn_IRQ_UF, ddata->base + TIMERn_IFC); ddata->evtdev.event_handler(&ddata->evtdev); return IRQ_HANDLED; } static struct efm32_clock_event_ddata clock_event_ddata = { .evtdev = { .name = "efm32 clockevent", .features = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_PERIODIC, .set_state_shutdown = efm32_clock_event_shutdown, .set_state_periodic = efm32_clock_event_set_periodic, .set_state_oneshot = efm32_clock_event_set_oneshot, .set_next_event = efm32_clock_event_set_next_event, .rating = 200, }, }; static struct irqaction efm32_clock_event_irq = { .name = "efm32 clockevent", .flags = IRQF_TIMER, .handler = efm32_clock_event_handler, .dev_id = &clock_event_ddata, }; static int __init efm32_clocksource_init(struct device_node *np) { struct clk *clk; void __iomem *base; unsigned long rate; int ret; clk = of_clk_get(np, 0); if (IS_ERR(clk)) { ret = PTR_ERR(clk); pr_err("failed to get clock for clocksource (%d)\n", ret); goto err_clk_get; } ret = clk_prepare_enable(clk); if (ret) { pr_err("failed to enable timer clock for clocksource (%d)\n", ret); goto err_clk_enable; } rate = clk_get_rate(clk); base = of_iomap(np, 0); if (!base) { ret = -EADDRNOTAVAIL; pr_err("failed to map registers for clocksource\n"); goto err_iomap; } writel_relaxed(TIMERn_CTRL_PRESC_1024 | TIMERn_CTRL_CLKSEL_PRESCHFPERCLK | TIMERn_CTRL_MODE_UP, base + TIMERn_CTRL); writel_relaxed(TIMERn_CMD_START, base + TIMERn_CMD); ret = clocksource_mmio_init(base + TIMERn_CNT, "efm32 timer", DIV_ROUND_CLOSEST(rate, 1024), 200, 16, clocksource_mmio_readl_up); if (ret) { pr_err("failed to init clocksource (%d)\n", ret); goto err_clocksource_init; } return 0; err_clocksource_init: iounmap(base); err_iomap: clk_disable_unprepare(clk); err_clk_enable: clk_put(clk); err_clk_get: return ret; } static int __init efm32_clockevent_init(struct device_node *np) { struct clk *clk; void __iomem *base; unsigned long rate; int irq; int ret; clk = of_clk_get(np, 0); if (IS_ERR(clk)) { ret = PTR_ERR(clk); pr_err("failed to get clock for clockevent (%d)\n", ret); goto err_clk_get; } ret = clk_prepare_enable(clk); if (ret) { pr_err("failed to enable timer clock for clockevent (%d)\n", ret); goto err_clk_enable; } rate = clk_get_rate(clk); base = of_iomap(np, 0); if (!base) { ret = -EADDRNOTAVAIL; pr_err("failed to map registers for clockevent\n"); goto err_iomap; } irq = irq_of_parse_and_map(np, 0); if (!irq) { ret = -ENOENT; pr_err("failed to get irq for clockevent\n"); goto err_get_irq; } writel_relaxed(TIMERn_IRQ_UF, base + TIMERn_IEN); clock_event_ddata.base = base; clock_event_ddata.periodic_top = DIV_ROUND_CLOSEST(rate, 1024 * HZ); clockevents_config_and_register(&clock_event_ddata.evtdev, DIV_ROUND_CLOSEST(rate, 1024), 0xf, 0xffff); ret = setup_irq(irq, &efm32_clock_event_irq); if (ret) { pr_err("Failed setup irq"); goto err_setup_irq; } return 0; err_setup_irq: err_get_irq: iounmap(base); err_iomap: clk_disable_unprepare(clk); err_clk_enable: clk_put(clk); err_clk_get: return ret; } /* * This function asserts that we have exactly one clocksource and one * clock_event_device in the end. */ static int __init efm32_timer_init(struct device_node *np) { static int has_clocksource, has_clockevent; int ret = 0; if (!has_clocksource) { ret = efm32_clocksource_init(np); if (!ret) { has_clocksource = 1; return 0; } } if (!has_clockevent) { ret = efm32_clockevent_init(np); if (!ret) { has_clockevent = 1; return 0; } } return ret; } CLOCKSOURCE_OF_DECLARE(efm32compat, "efm32,timer", efm32_timer_init); CLOCKSOURCE_OF_DECLARE(efm32, "energymicro,efm32-timer", efm32_timer_init);
null
null
null
null
105,456
53,131
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
53,131
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_ANDROID_JNI_HDR_METADATA_H_ #define MEDIA_BASE_ANDROID_JNI_HDR_METADATA_H_ #include "base/android/jni_android.h" #include "base/macros.h" namespace media { struct HDRMetadata; class VideoColorSpace; class JniHdrMetadata { public: JniHdrMetadata(const VideoColorSpace& color_space, const HDRMetadata& hdr_metadata); ~JniHdrMetadata(); base::android::ScopedJavaLocalRef<jobject> obj() { return jobject_; } // Java HdrMetadata implementation. jint Primaries(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jint ColorTransfer(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jint Range(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat PrimaryRChromaticityX(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat PrimaryRChromaticityY(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat PrimaryGChromaticityX(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat PrimaryGChromaticityY(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat PrimaryBChromaticityX(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat PrimaryBChromaticityY(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat WhitePointChromaticityX( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat WhitePointChromaticityY( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat MaxMasteringLuminance(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jfloat MinMasteringLuminance(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jint MaxContentLuminance(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); jint MaxFrameAverageLuminance( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); private: const VideoColorSpace& color_space_; const HDRMetadata& hdr_metadata_; base::android::ScopedJavaLocalRef<jobject> jobject_; DISALLOW_COPY_AND_ASSIGN(JniHdrMetadata); }; } // namespace media #endif // MEDIA_BASE_ANDROID_JNI_HDR_METADATA_H_
null
null
null
null
49,994
64,176
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
64,176
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/print_preview/extension_printer_handler.h" #include <algorithm> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/memory/ref_counted.h" #include "base/memory/ref_counted_memory.h" #include "base/strings/string_split.h" #include "base/task_scheduler/post_task.h" #include "chrome/browser/printing/pwg_raster_converter.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" #include "components/cloud_devices/common/cloud_device_description.h" #include "components/cloud_devices/common/printer_description.h" #include "device/base/device_client.h" #include "device/usb/usb_device.h" #include "device/usb/usb_service.h" #include "extensions/browser/api/device_permissions_manager.h" #include "extensions/browser/api/printer_provider/printer_provider_api.h" #include "extensions/browser/api/printer_provider/printer_provider_api_factory.h" #include "extensions/browser/api/printer_provider/printer_provider_print_job.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/api/printer_provider/usb_printer_manifest_data.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/common/permissions/usb_device_permission.h" #include "extensions/common/permissions/usb_device_permission_data.h" #include "extensions/common/value_builder.h" #include "printing/print_job_constants.h" #include "printing/pwg_raster_settings.h" using device::UsbDevice; using extensions::DevicePermissionsManager; using extensions::DictionaryBuilder; using extensions::Extension; using extensions::ExtensionRegistry; using extensions::ListBuilder; using extensions::UsbPrinterManifestData; using printing::PwgRasterConverter; namespace { const char kContentTypePdf[] = "application/pdf"; const char kContentTypePWGRaster[] = "image/pwg-raster"; const char kContentTypeAll[] = "*/*"; const char kInvalidDataPrintError[] = "INVALID_DATA"; const char kInvalidTicketPrintError[] = "INVALID_TICKET"; const char kProvisionalUsbLabel[] = "provisional-usb"; // Updates |job| with raster file path, size and last modification time. // Returns the updated print job. std::unique_ptr<extensions::PrinterProviderPrintJob> UpdateJobFileInfoOnWorkerThread( const base::FilePath& raster_path, std::unique_ptr<extensions::PrinterProviderPrintJob> job) { if (base::GetFileInfo(raster_path, &job->file_info)) job->document_path = raster_path; return job; } // Callback to PWG raster conversion. // Posts a task to update print job with info about file containing converted // PWG raster data. void UpdateJobFileInfo(std::unique_ptr<extensions::PrinterProviderPrintJob> job, ExtensionPrinterHandler::PrintJobCallback callback, bool success, const base::FilePath& pwg_file_path) { if (!success) { std::move(callback).Run(std::move(job)); return; } base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&UpdateJobFileInfoOnWorkerThread, pwg_file_path, std::move(job)), std::move(callback)); } bool HasUsbPrinterProviderPermissions(const Extension* extension) { return extension->permissions_data() && extension->permissions_data()->HasAPIPermission( extensions::APIPermission::kPrinterProvider) && extension->permissions_data()->HasAPIPermission( extensions::APIPermission::kUsb); } std::string GenerateProvisionalUsbPrinterId(const Extension* extension, const UsbDevice* device) { return base::StringPrintf("%s:%s:%s", kProvisionalUsbLabel, extension->id().c_str(), device->guid().c_str()); } bool ParseProvisionalUsbPrinterId(const std::string& printer_id, std::string* extension_id, std::string* device_guid) { std::vector<std::string> components = base::SplitString( printer_id, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (components.size() != 3) return false; if (components[0] != kProvisionalUsbLabel) return false; *extension_id = components[1]; *device_guid = components[2]; return true; } } // namespace ExtensionPrinterHandler::ExtensionPrinterHandler(Profile* profile) : profile_(profile), weak_ptr_factory_(this) {} ExtensionPrinterHandler::~ExtensionPrinterHandler() { } void ExtensionPrinterHandler::Reset() { // TODO(tbarzic): Keep track of pending request ids issued by |this| and // cancel them from here. pending_enumeration_count_ = 0; weak_ptr_factory_.InvalidateWeakPtrs(); } void ExtensionPrinterHandler::StartGetPrinters( const AddedPrintersCallback& callback, GetPrintersDoneCallback done_callback) { // Assume that there can only be one printer enumeration occuring at once. DCHECK_EQ(pending_enumeration_count_, 0); pending_enumeration_count_ = 1; done_callback_ = std::move(done_callback); bool extension_supports_usb_printers = false; ExtensionRegistry* registry = ExtensionRegistry::Get(profile_); for (const auto& extension : registry->enabled_extensions()) { if (UsbPrinterManifestData::Get(extension.get()) && HasUsbPrinterProviderPermissions(extension.get())) { extension_supports_usb_printers = true; break; } } if (extension_supports_usb_printers) { device::UsbService* service = device::DeviceClient::Get()->GetUsbService(); pending_enumeration_count_++; service->GetDevices( base::Bind(&ExtensionPrinterHandler::OnUsbDevicesEnumerated, weak_ptr_factory_.GetWeakPtr(), callback)); } extensions::PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(profile_) ->DispatchGetPrintersRequested( base::Bind(&ExtensionPrinterHandler::WrapGetPrintersCallback, weak_ptr_factory_.GetWeakPtr(), callback)); } void ExtensionPrinterHandler::StartGetCapability( const std::string& destination_id, GetCapabilityCallback callback) { extensions::PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(profile_) ->DispatchGetCapabilityRequested( destination_id, base::BindOnce(&ExtensionPrinterHandler::WrapGetCapabilityCallback, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } void ExtensionPrinterHandler::StartPrint( const std::string& destination_id, const std::string& capability, const base::string16& job_title, const std::string& ticket_json, const gfx::Size& page_size, const scoped_refptr<base::RefCountedMemory>& print_data, PrintCallback callback) { auto print_job = std::make_unique<extensions::PrinterProviderPrintJob>(); print_job->printer_id = destination_id; print_job->job_title = job_title; print_job->ticket_json = ticket_json; cloud_devices::CloudDeviceDescription printer_description; printer_description.InitFromString(capability); cloud_devices::printer::ContentTypesCapability content_types; content_types.LoadFrom(printer_description); const bool kUsePdf = content_types.Contains(kContentTypePdf) || content_types.Contains(kContentTypeAll); if (kUsePdf) { // TODO(tbarzic): Consider writing larger PDF to disk and provide the data // the same way as it's done with PWG raster. print_job->content_type = kContentTypePdf; print_job->document_bytes = print_data; DispatchPrintJob(std::move(callback), std::move(print_job)); return; } cloud_devices::CloudDeviceDescription ticket; if (!ticket.InitFromString(ticket_json)) { WrapPrintCallback(std::move(callback), base::Value(kInvalidTicketPrintError)); return; } print_job->content_type = kContentTypePWGRaster; ConvertToPWGRaster( print_data, printer_description, ticket, page_size, std::move(print_job), base::BindOnce(&ExtensionPrinterHandler::DispatchPrintJob, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } void ExtensionPrinterHandler::StartGrantPrinterAccess( const std::string& printer_id, GetPrinterInfoCallback callback) { std::string extension_id; std::string device_guid; if (!ParseProvisionalUsbPrinterId(printer_id, &extension_id, &device_guid)) { std::move(callback).Run(base::DictionaryValue()); return; } device::UsbService* service = device::DeviceClient::Get()->GetUsbService(); scoped_refptr<UsbDevice> device = service->GetDevice(device_guid); if (!device) { std::move(callback).Run(base::DictionaryValue()); return; } DevicePermissionsManager* permissions_manager = DevicePermissionsManager::Get(profile_); permissions_manager->AllowUsbDevice(extension_id, device); extensions::PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(profile_) ->DispatchGetUsbPrinterInfoRequested( extension_id, device, base::BindOnce(&ExtensionPrinterHandler::WrapGetPrinterInfoCallback, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } void ExtensionPrinterHandler::SetPwgRasterConverterForTesting( std::unique_ptr<PwgRasterConverter> pwg_raster_converter) { pwg_raster_converter_ = std::move(pwg_raster_converter); } void ExtensionPrinterHandler::ConvertToPWGRaster( const scoped_refptr<base::RefCountedMemory>& data, const cloud_devices::CloudDeviceDescription& printer_description, const cloud_devices::CloudDeviceDescription& ticket, const gfx::Size& page_size, std::unique_ptr<extensions::PrinterProviderPrintJob> job, PrintJobCallback callback) { if (!pwg_raster_converter_) { pwg_raster_converter_ = PwgRasterConverter::CreateDefault(); } pwg_raster_converter_->Start( data.get(), PwgRasterConverter::GetConversionSettings(printer_description, page_size), PwgRasterConverter::GetBitmapSettings(printer_description, ticket), base::BindOnce(&UpdateJobFileInfo, std::move(job), std::move(callback))); } void ExtensionPrinterHandler::DispatchPrintJob( PrintCallback callback, std::unique_ptr<extensions::PrinterProviderPrintJob> print_job) { if (print_job->document_path.empty() && !print_job->document_bytes) { WrapPrintCallback(std::move(callback), base::Value(kInvalidDataPrintError)); return; } extensions::PrinterProviderAPIFactory::GetInstance() ->GetForBrowserContext(profile_) ->DispatchPrintRequested( *print_job, base::BindOnce(&ExtensionPrinterHandler::WrapPrintCallback, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } void ExtensionPrinterHandler::WrapGetPrintersCallback( const AddedPrintersCallback& callback, const base::ListValue& printers, bool done) { DCHECK_GT(pending_enumeration_count_, 0); if (!printers.empty()) callback.Run(printers); if (done) pending_enumeration_count_--; if (pending_enumeration_count_ == 0) std::move(done_callback_).Run(); } void ExtensionPrinterHandler::WrapGetCapabilityCallback( GetCapabilityCallback callback, const base::DictionaryValue& capability) { auto capabilities = std::make_unique<base::DictionaryValue>(); std::unique_ptr<base::DictionaryValue> cdd = printing::ValidateCddForPrintPreview(capability); // Leave |capabilities| empty if |cdd| is empty. if (!cdd->empty()) { capabilities->SetKey(printing::kSettingCapabilities, base::Value::FromUniquePtrValue(std::move(cdd))); } std::move(callback).Run(std::move(capabilities)); } void ExtensionPrinterHandler::WrapPrintCallback(PrintCallback callback, const base::Value& status) { std::move(callback).Run(status); } void ExtensionPrinterHandler::WrapGetPrinterInfoCallback( GetPrinterInfoCallback callback, const base::DictionaryValue& printer_info) { std::move(callback).Run(printer_info); } void ExtensionPrinterHandler::OnUsbDevicesEnumerated( const AddedPrintersCallback& callback, const std::vector<scoped_refptr<UsbDevice>>& devices) { ExtensionRegistry* registry = ExtensionRegistry::Get(profile_); DevicePermissionsManager* permissions_manager = DevicePermissionsManager::Get(profile_); ListBuilder printer_list; for (const auto& extension : registry->enabled_extensions()) { const UsbPrinterManifestData* manifest_data = UsbPrinterManifestData::Get(extension.get()); if (!manifest_data || !HasUsbPrinterProviderPermissions(extension.get())) continue; const extensions::DevicePermissions* device_permissions = permissions_manager->GetForExtension(extension->id()); for (const auto& device : devices) { if (manifest_data->SupportsDevice(*device)) { std::unique_ptr<extensions::UsbDevicePermission::CheckParam> param = extensions::UsbDevicePermission::CheckParam::ForUsbDevice( extension.get(), device.get()); if (device_permissions->FindUsbDeviceEntry(device) || extension->permissions_data()->CheckAPIPermissionWithParam( extensions::APIPermission::kUsbDevice, param.get())) { // Skip devices the extension already has permission to access. continue; } printer_list.Append( DictionaryBuilder() .Set("id", GenerateProvisionalUsbPrinterId(extension.get(), device.get())) .Set("name", DevicePermissionsManager::GetPermissionMessage( device->vendor_id(), device->product_id(), device->manufacturer_string(), device->product_string(), base::string16(), false)) .Set("extensionId", extension->id()) .Set("extensionName", extension->name()) .Set("provisional", true) .Build()); } } } DCHECK_GT(pending_enumeration_count_, 0); pending_enumeration_count_--; std::unique_ptr<base::ListValue> list = printer_list.Build(); if (!list->empty()) callback.Run(*list); if (pending_enumeration_count_ == 0) std::move(done_callback_).Run(); }
null
null
null
null
61,039
40,087
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
40,087
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBMIDI_MIDI_INPUT_MAP_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBMIDI_MIDI_INPUT_MAP_H_ #include "third_party/blink/renderer/modules/webmidi/midi_input.h" #include "third_party/blink/renderer/modules/webmidi/midi_port_map.h" namespace blink { class MIDIInputMap : public MIDIPortMap<MIDIInput> { DEFINE_WRAPPERTYPEINFO(); public: explicit MIDIInputMap(const HeapVector<Member<MIDIInput>>&); }; } // namespace blink #endif
null
null
null
null
36,950
26,460
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
26,460
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "jingle/notifier/listener/notification_constants.h" namespace notifier { const char kPushNotificationsNamespace[] = "google:push"; } // namespace notifier
null
null
null
null
23,323
63,973
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
63,973
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_SIGNIN_SCREEN_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_SIGNIN_SCREEN_HANDLER_H_ #include <map> #include <memory> #include <set> #include <string> #include "ash/detachable_base/detachable_base_observer.h" #include "ash/wallpaper/wallpaper_controller_observer.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/containers/hash_tables.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/scoped_observer.h" #include "chrome/browser/chromeos/lock_screen_apps/state_observer.h" #include "chrome/browser/chromeos/login/screens/error_screen.h" #include "chrome/browser/chromeos/login/signin_specifics.h" #include "chrome/browser/chromeos/login/ui/login_display.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/ui/ash/tablet_mode_client_observer.h" #include "chrome/browser/ui/webui/chromeos/login/base_webui_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chromeos/components/proximity_auth/screenlock_bridge.h" #include "chromeos/dbus/power_manager_client.h" #include "chromeos/network/portal_detector/network_portal_detector.h" #include "components/session_manager/core/session_manager_observer.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_ui.h" #include "net/base/net_errors.h" #include "ui/base/ime/chromeos/ime_keyboard.h" #include "ui/base/ime/chromeos/input_method_manager.h" #include "ui/events/event_handler.h" class AccountId; namespace ash { namespace mojom { enum class TrayActionState; } // namespace mojom class DetachableBaseHandler; } // namespace ash namespace base { class DictionaryValue; class ListValue; } namespace lock_screen_apps { class StateController; } namespace session_manager { class SessionManager; } namespace chromeos { class CoreOobeView; class ErrorScreensHistogramHelper; class GaiaScreenHandler; class LoginFeedback; class NativeWindowDelegate; class SupervisedUserCreationScreenHandler; class User; class UserContext; // Helper class to pass initial parameters to the login screen. class LoginScreenContext { public: LoginScreenContext(); explicit LoginScreenContext(const base::ListValue* args); void set_email(const std::string& email) { email_ = email; } const std::string& email() const { return email_; } void set_oobe_ui(bool oobe_ui) { oobe_ui_ = oobe_ui; } bool oobe_ui() const { return oobe_ui_; } private: void Init(); std::string email_; bool oobe_ui_; }; // An interface for WebUILoginDisplay to call SigninScreenHandler. class LoginDisplayWebUIHandler { public: virtual void ClearAndEnablePassword() = 0; virtual void ClearUserPodPassword() = 0; virtual void OnUserRemoved(const AccountId& account_id, bool last_user_removed) = 0; virtual void OnUserImageChanged(const user_manager::User& user) = 0; virtual void OnPreferencesChanged() = 0; virtual void ResetSigninScreenHandlerDelegate() = 0; virtual void ShowError(int login_attempts, const std::string& error_text, const std::string& help_link_text, HelpAppLauncher::HelpTopic help_topic_id) = 0; virtual void ShowErrorScreen(LoginDisplay::SigninError error_id) = 0; virtual void ShowSigninUI(const std::string& email) = 0; virtual void ShowPasswordChangedDialog(bool show_password_error, const std::string& email) = 0; // Show sign-in screen for the given credentials. virtual void ShowSigninScreenForCreds(const std::string& username, const std::string& password) = 0; virtual void ShowWhitelistCheckFailedError() = 0; virtual void ShowUnrecoverableCrypthomeErrorDialog() = 0; virtual void LoadUsers(const user_manager::UserList& users, const base::ListValue& users_list) = 0; protected: virtual ~LoginDisplayWebUIHandler() {} }; // An interface for SigninScreenHandler to call WebUILoginDisplay. class SigninScreenHandlerDelegate { public: // --------------- Password change flow methods. // Cancels current password changed flow. virtual void CancelPasswordChangedFlow() = 0; // Decrypt cryptohome using user provided |old_password| // and migrate to new password. virtual void MigrateUserData(const std::string& old_password) = 0; // Ignore password change, remove existing cryptohome and // force full sync of user data. virtual void ResyncUserData() = 0; // --------------- Sign in/out methods. // Sign in using username and password specified as a part of |user_context|. // Used for both known and new users. virtual void Login(const UserContext& user_context, const SigninSpecifics& specifics) = 0; // Returns true if sign in is in progress. virtual bool IsSigninInProgress() const = 0; // Signs out if the screen is currently locked. virtual void Signout() = 0; // --------------- Shared with login display methods. // Notify the delegate when the sign-in UI is finished loading. virtual void OnSigninScreenReady() = 0; // Shows Enterprise Enrollment screen. virtual void ShowEnterpriseEnrollmentScreen() = 0; // Shows Enable Developer Features screen. virtual void ShowEnableDebuggingScreen() = 0; // Shows Demo Mode Setup screen. virtual void ShowDemoModeSetupScreen() = 0; // Shows Kiosk Enable screen. virtual void ShowKioskEnableScreen() = 0; // Shows Reset screen. virtual void ShowKioskAutolaunchScreen() = 0; // Show wrong hwid screen. virtual void ShowWrongHWIDScreen() = 0; // Show update required screen. virtual void ShowUpdateRequiredScreen() = 0; // --------------- Rest of the methods. // Cancels user adding. virtual void CancelUserAdding() = 0; // Attempts to remove given user. virtual void RemoveUser(const AccountId& account_id) = 0; // Let the delegate know about the handler it is supposed to be using. virtual void SetWebUIHandler(LoginDisplayWebUIHandler* webui_handler) = 0; // Whether login as guest is available. virtual bool IsShowGuest() const = 0; // Whether to show the user pods or only GAIA sign in. // Public sessions are always shown. virtual bool IsShowUsers() const = 0; // Whether the show user pods setting has changed. virtual bool ShowUsersHasChanged() const = 0; // Whether the create new account option in GAIA is enabled by the setting. virtual bool IsAllowNewUser() const = 0; // Whether the allow new user setting has changed. virtual bool AllowNewUserChanged() const = 0; // Whether user sign in has completed. virtual bool IsUserSigninCompleted() const = 0; // Request to (re)load user list. virtual void HandleGetUsers() = 0; // Runs an OAuth token validation check for user. virtual void CheckUserStatus(const AccountId& account_id) = 0; protected: virtual ~SigninScreenHandlerDelegate() {} }; // A class that handles the WebUI hooks in sign-in screen in OobeUI and // LoginDisplay. class SigninScreenHandler : public BaseWebUIHandler, public LoginDisplayWebUIHandler, public content::NotificationObserver, public NetworkStateInformer::NetworkStateInformerObserver, public PowerManagerClient::Observer, public input_method::ImeKeyboard::Observer, public TabletModeClientObserver, public lock_screen_apps::StateObserver, public OobeUI::Observer, public session_manager::SessionManagerObserver, public ash::WallpaperControllerObserver, public ash::DetachableBaseObserver { public: SigninScreenHandler( const scoped_refptr<NetworkStateInformer>& network_state_informer, ErrorScreen* error_screen, CoreOobeView* core_oobe_view, GaiaScreenHandler* gaia_screen_handler, JSCallsContainer* js_calls_container); ~SigninScreenHandler() override; static std::string GetUserLastInputMethod(const std::string& username); // Update current input method (namely keyboard layout) in the given IME state // to last input method used by this user. static void SetUserInputMethod( const std::string& username, input_method::InputMethodManager::State* ime_state); // Shows the sign in screen. void Show(const LoginScreenContext& context); // Sets delegate to be used by the handler. It is guaranteed that valid // delegate is set before Show() method will be called. void SetDelegate(SigninScreenHandlerDelegate* delegate); void SetNativeWindowDelegate(NativeWindowDelegate* native_window_delegate); // NetworkStateInformer::NetworkStateInformerObserver implementation: void OnNetworkReady() override; void UpdateState(NetworkError::ErrorReason reason) override; // Required Local State preferences. static void RegisterPrefs(PrefRegistrySimple* registry); // OobeUI::Observer implementation: void OnCurrentScreenChanged(OobeScreen current_screen, OobeScreen new_screen) override; void OnScreenInitialized(OobeScreen screen) override{}; // ash::WallpaperControllerObserver implementation: void OnWallpaperDataChanged() override; void OnWallpaperColorsChanged() override; void OnWallpaperBlurChanged() override; // ash::DetachableBaseObserver: void OnDetachableBasePairingStatusChanged( ash::DetachableBasePairingStatus pairing_status) override; void OnDetachableBaseRequiresUpdateChanged(bool requires_update) override; void SetFocusPODCallbackForTesting(base::Closure callback); // To avoid spurious error messages on flaky networks, the offline message is // only shown if the network is offline for a threshold number of seconds. // This method provides an ability to reduce the threshold to zero, allowing // the offline message to show instantaneously in tests. The threshold can // also be set to a high value to disable the offline message on slow // configurations like MSAN, where it otherwise triggers on every run. void SetOfflineTimeoutForTesting(base::TimeDelta offline_timeout); // Gets the keyboard remapped pref value for |pref_name| key. Returns true if // successful, otherwise returns false. bool GetKeyboardRemappedPrefValue(const std::string& pref_name, int* value); private: enum UIState { UI_STATE_UNKNOWN = 0, UI_STATE_GAIA_SIGNIN, UI_STATE_ACCOUNT_PICKER, }; friend class GaiaScreenHandler; friend class ReportDnsCacheClearedOnUIThread; friend class SupervisedUserCreationScreenHandler; void ShowImpl(); // Updates current UI of the signin screen according to |ui_state| // argument. Optionally it can pass screen initialization data via // |params| argument. void UpdateUIState(UIState ui_state, base::DictionaryValue* params); void UpdateStateInternal(NetworkError::ErrorReason reason, bool force_update); void SetupAndShowOfflineMessage(NetworkStateInformer::State state, NetworkError::ErrorReason reason); void HideOfflineMessage(NetworkStateInformer::State state, NetworkError::ErrorReason reason); void ReloadGaia(bool force_reload); // Updates the color of the scrollable container on account picker screen, // based on wallpaper color extraction results. void UpdateAccountPickerColors(); // BaseScreenHandler implementation: void DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) override; void Initialize() override; gfx::NativeWindow GetNativeWindow() override; // WebUIMessageHandler implementation: void RegisterMessages() override; // LoginDisplayWebUIHandler implementation: void ClearAndEnablePassword() override; void ClearUserPodPassword() override; void OnUserRemoved(const AccountId& account_id, bool last_user_removed) override; void OnUserImageChanged(const user_manager::User& user) override; void OnPreferencesChanged() override; void ResetSigninScreenHandlerDelegate() override; void ShowError(int login_attempts, const std::string& error_text, const std::string& help_link_text, HelpAppLauncher::HelpTopic help_topic_id) override; void ShowSigninUI(const std::string& email) override; void ShowPasswordChangedDialog(bool show_password_error, const std::string& email) override; void ShowErrorScreen(LoginDisplay::SigninError error_id) override; void ShowSigninScreenForCreds(const std::string& username, const std::string& password) override; void ShowWhitelistCheckFailedError() override; void ShowUnrecoverableCrypthomeErrorDialog() override; void LoadUsers(const user_manager::UserList& users, const base::ListValue& users_list) override; // content::NotificationObserver implementation: void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; // PowerManagerClient::Observer implementation: void SuspendDone(const base::TimeDelta& sleep_duration) override; // TabletModeClientObserver: void OnTabletModeToggled(bool enabled) override; // session_manager::SessionManagerObserver: void OnSessionStateChanged() override; // lock_screen_apps::StateObserver: void OnLockScreenNoteStateChanged(ash::mojom::TrayActionState state) override; void UpdateAddButtonStatus(); // Restore input focus to current user pod. void RefocusCurrentPod(); // Enable or disable the pin keyboard for the given account. void UpdatePinKeyboardState(const AccountId& account_id); // WebUI message handlers. void HandleGetUsers(); void HandleAuthenticateUser(const AccountId& account_id, const std::string& password, bool authenticated_by_pin); void HandleAttemptUnlock(const std::string& username); void HandleLaunchIncognito(); void HandleLaunchPublicSession(const AccountId& account_id, const std::string& locale, const std::string& input_method); void HandleOfflineLogin(const base::ListValue* args); void HandleShutdownSystem(); void HandleRebootSystem(); void HandleRemoveUser(const AccountId& account_id); void HandleToggleEnrollmentScreen(); void HandleToggleEnrollmentAd(); void HandleToggleEnableDebuggingScreen(); void HandleSetupDemoMode(); void HandleToggleKioskEnableScreen(); void HandleToggleResetScreen(); void HandleToggleKioskAutolaunchScreen(); void HandleAccountPickerReady(); void HandleWallpaperReady(); void HandleSignOutUser(); void HandleOpenInternetDetailDialog(); void HandleLoginVisible(const std::string& source); void HandleCancelPasswordChangedFlow(const AccountId& account_id); void HandleCancelUserAdding(); void HandleMigrateUserData(const std::string& password); void HandleResyncUserData(); void HandleLoginUIStateChanged(const std::string& source, bool active); void HandleUnlockOnLoginSuccess(); void HandleLoginScreenUpdate(); void HandleShowLoadingTimeoutError(); void HandleShowSupervisedUserCreationScreen(); void HandleFocusPod(const AccountId& account_id, bool is_large_pod); void HandleNoPodFocused(); void HandleHardlockPod(const std::string& user_id); void HandleLaunchKioskApp(const AccountId& app_account_id, bool diagnostic_mode); void HandleLaunchArcKioskApp(const AccountId& app_account_id); void HandleGetPublicSessionKeyboardLayouts(const AccountId& account_id, const std::string& locale); void HandleGetTabletModeState(); void HandleLogRemoveUserWarningShown(); void HandleFirstIncorrectPasswordAttempt(const AccountId& account_id); void HandleMaxIncorrectPasswordAttempts(const AccountId& account_id); void HandleSendFeedback(); void HandleSendFeedbackAndResyncUserData(); void HandleRequestNewNoteAction(const std::string& request_type); void HandleNewNoteLaunchAnimationDone(); void HandleCloseLockScreenApp(); // Sends the list of |keyboard_layouts| available for the |locale| that is // currently selected for the public session identified by |user_id|. void SendPublicSessionKeyboardLayouts( const AccountId& account_id, const std::string& locale, std::unique_ptr<base::ListValue> keyboard_layouts); // Returns true iff // (i) log in is restricted to some user list, // (ii) all users in the restricted list are present. bool AllWhitelistedUsersPresent(); // Cancels password changed flow - switches back to login screen. // Called as a callback after cookies are cleared. void CancelPasswordChangedFlowInternal(); // Returns true if current visible screen is the Gaia sign-in page. bool IsGaiaVisible() const; // Returns true if current visible screen is the error screen over // Gaia sign-in page. bool IsGaiaHiddenByError() const; // Returns true if current screen is the error screen over signin // screen. bool IsSigninScreenHiddenByError() const; // Returns true if guest signin is allowed. bool IsGuestSigninAllowed() const; bool ShouldLoadGaia() const; net::Error FrameError() const; // input_method::ImeKeyboard::Observer implementation: void OnCapsLockChanged(bool enabled) override; void OnLayoutChanging(const std::string& layout_name) override {} // Callback invoked after the feedback is finished. void OnFeedbackFinished(); // Callback invoked after the feedback sent from the unrecoverable cryptohome // page is finished. void OnUnrecoverableCryptohomeFeedbackFinished(); // Called when the cros property controlling allowed input methods changes. void OnAllowedInputMethodsChanged(); // After proxy auth information has been supplied, this function re-enables // responding to network state notifications. void ReenableNetworkStateUpdatesAfterProxyAuth(); // Determines whether a warning about the detachable base getting changed // should be shown to the user. The warning is shown a detachable base is // present, and the user whose pod is currently focused has used a different // base last time. It updates the detachable base warning visibility as // required. void UpdateDetachableBaseChangedError(); // Sends a request to the UI to show a detachable base change warning for the // currently focused user pod. The warning warns the user that the currently // attached base is different than the one they last used, and that it might // not be trusted. void ShowDetachableBaseChangedError(); // If a detachable base change warning was requested to be shown, sends a // request to UI to hide the warning. void HideDetachableBaseChangedError(); // Current UI state of the signin screen. UIState ui_state_ = UI_STATE_UNKNOWN; // A delegate that glues this handler with backend LoginDisplay. SigninScreenHandlerDelegate* delegate_ = nullptr; // A delegate used to get gfx::NativeWindow. NativeWindowDelegate* native_window_delegate_ = nullptr; // Whether screen should be shown right after initialization. bool show_on_init_ = false; // Keeps whether screen should be shown for OOBE. bool oobe_ui_ = false; // Is account picker being shown for the first time. bool is_account_picker_showing_first_time_ = false; // Network state informer used to keep signin screen up. scoped_refptr<NetworkStateInformer> network_state_informer_; // Set to true once |LOGIN_WEBUI_VISIBLE| notification is observed. bool webui_visible_ = false; bool preferences_changed_delayed_ = false; ErrorScreen* error_screen_ = nullptr; CoreOobeView* core_oobe_view_ = nullptr; NetworkStateInformer::State last_network_state_ = NetworkStateInformer::UNKNOWN; base::CancelableClosure update_state_closure_; base::CancelableClosure connecting_closure_; content::NotificationRegistrar registrar_; std::unique_ptr<CrosSettings::ObserverSubscription> allowed_input_methods_subscription_; // Whether we're currently ignoring network state updates because a proxy auth // UI pending (or we're waiting for a grace period after the proxy auth UI is // finished for the network to switch into the ONLINE state). bool network_state_ignored_until_proxy_auth_ = false; // Used for pending GAIA reloads. NetworkError::ErrorReason gaia_reload_reason_ = NetworkError::ERROR_REASON_NONE; bool caps_lock_enabled_ = false; // If network has accidentally changed to the one that requires proxy // authentication, we will automatically reload gaia page that will bring // "Proxy authentication" dialog to the user. To prevent flakiness, we will do // it at most 3 times. int proxy_auth_dialog_reload_times_; // True if we need to reload gaia page to bring back "Proxy authentication" // dialog. bool proxy_auth_dialog_need_reload_ = false; // Non-owning ptr. // TODO(antrim@): remove this dependency. GaiaScreenHandler* gaia_screen_handler_ = nullptr; // Input Method Engine state used at signin screen. scoped_refptr<input_method::InputMethodManager::State> ime_state_; // This callback captures "focusPod finished" event for tests. base::Closure test_focus_pod_callback_; // True if SigninScreenHandler has already been added to OobeUI observers. bool oobe_ui_observer_added_ = false; bool is_offline_timeout_for_test_set_ = false; base::TimeDelta offline_timeout_for_test_; std::unique_ptr<ErrorScreensHistogramHelper> histogram_helper_; std::unique_ptr<LoginFeedback> login_feedback_; std::unique_ptr<AccountId> focused_pod_account_id_; // If set, the account for which detachable base change warning was shown in // the login UI. base::Optional<AccountId> account_with_detachable_base_error_; ScopedObserver<session_manager::SessionManager, session_manager::SessionManagerObserver> session_manager_observer_; ScopedObserver<lock_screen_apps::StateController, lock_screen_apps::StateObserver> lock_screen_apps_observer_; ScopedObserver<ash::DetachableBaseHandler, ash::DetachableBaseObserver> detachable_base_observer_; base::WeakPtrFactory<SigninScreenHandler> weak_factory_; DISALLOW_COPY_AND_ASSIGN(SigninScreenHandler); }; } // namespace chromeos #endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_LOGIN_SIGNIN_SCREEN_HANDLER_H_
null
null
null
null
60,836
18,835
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
183,830
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * QLogic iSCSI HBA Driver * Copyright (c) 2003-2013 QLogic Corporation * * See LICENSE.qla4xxx for copyright and licensing details. */ #define QLA4XXX_DRIVER_VERSION "5.04.00-k6"
null
null
null
null
92,177
12,955
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
12,955
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/url_pattern_index/fuzzy_pattern_matching.h" #include <vector> #include "testing/gtest/include/gtest/gtest.h" namespace url_pattern_index { TEST(SubresourceFilterFuzzyPatternMatchingTest, StartsWithFuzzy) { const struct { const char* text; const char* subpattern; bool expected_starts_with; } kTestCases[] = { {"abc", "", true}, {"abc", "a", true}, {"abc", "ab", true}, {"abc", "abc", true}, {"abc", "abcd", false}, {"abc", "abc^^", false}, {"abc", "abcd^", false}, {"abc", "ab^", false}, {"abc", "bc", false}, {"abc", "bc^", false}, {"abc", "^abc", false}, }; // TODO(pkalinnikov): Make end-of-string match '^' again. for (const auto& test_case : kTestCases) { SCOPED_TRACE(testing::Message() << "Test: " << test_case.text << "; Subpattern: " << test_case.subpattern); const bool starts_with = StartsWithFuzzy(test_case.text, test_case.subpattern); EXPECT_EQ(test_case.expected_starts_with, starts_with); } } TEST(SubresourceFilterFuzzyPatternMatchingTest, EndsWithFuzzy) { const struct { const char* text; const char* subpattern; bool expected_ends_with; } kTestCases[] = { {"abc", "", true}, {"abc", "c", true}, {"abc", "bc", true}, {"abc", "abc", true}, {"abc", "0abc", false}, {"abc", "abc^^", false}, {"abc", "abcd^", false}, {"abc", "ab^", false}, {"abc", "ab", false}, {"abc", "^abc", false}, }; // TODO(pkalinnikov): Make end-of-string match '^' again. for (const auto& test_case : kTestCases) { SCOPED_TRACE(testing::Message() << "Test: " << test_case.text << "; Subpattern: " << test_case.subpattern); const bool ends_with = EndsWithFuzzy(test_case.text, test_case.subpattern); EXPECT_EQ(test_case.expected_ends_with, ends_with); } } TEST(SubresourceFilterFuzzyPatternMatchingTest, FindFuzzy) { const struct { base::StringPiece text; base::StringPiece subpattern; std::vector<size_t> expected_occurrences; } kTestCases[] = { {"abcd", "", {0, 1, 2, 3, 4}}, {"abcd", "de", std::vector<size_t>()}, {"abcd", "ab", {0}}, {"abcd", "bc", {1}}, {"abcd", "cd", {2}}, {"a/bc/a/b", "", {0, 1, 2, 3, 4, 5, 6, 7, 8}}, {"a/bc/a/b", "de", std::vector<size_t>()}, {"a/bc/a/b", "a/", {0, 5}}, {"a/bc/a/c", "a/c", {5}}, {"a/bc/a/c", "a^c", {5}}, {"a/bc/a/c", "a?c", std::vector<size_t>()}, {"ab^cd", "ab/cd", std::vector<size_t>()}, {"ab^cd", "b/c", std::vector<size_t>()}, {"ab^cd", "ab^cd", {0}}, {"ab^cd", "b^c", {1}}, {"ab^b/b", "b/b", {3}}, {"a/a/a/a", "a/a", {0, 2, 4}}, {"a/a/a/a", "^a^a^a", {1}}, {"a/a/a/a", "^a^a?a", std::vector<size_t>()}, {"a/a/a/a", "?a?a?a", std::vector<size_t>()}, }; for (const auto& test_case : kTestCases) { SCOPED_TRACE(testing::Message() << "Test: " << test_case.text << "; Subpattern: " << test_case.subpattern); std::vector<size_t> occurrences; for (size_t position = 0; position <= test_case.text.size(); ++position) { position = FindFuzzy(test_case.text, test_case.subpattern, position); if (position == base::StringPiece::npos) break; occurrences.push_back(position); } EXPECT_EQ(test_case.expected_occurrences, occurrences); } } } // namespace url_pattern_index
null
null
null
null
9,818
10,320
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
10,320
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef HEADLESS_LIB_HEADLESS_CRASH_REPORTER_CLIENT_H_ #define HEADLESS_LIB_HEADLESS_CRASH_REPORTER_CLIENT_H_ #include "base/files/file_path.h" #include "base/macros.h" #include "base/strings/string16.h" #include "build/build_config.h" #include "components/crash/content/app/crash_reporter_client.h" namespace headless { class HeadlessCrashReporterClient : public crash_reporter::CrashReporterClient { public: HeadlessCrashReporterClient(); ~HeadlessCrashReporterClient() override; void set_crash_dumps_dir(const base::FilePath& dir) { crash_dumps_dir_ = dir; } const base::FilePath& crash_dumps_dir() const { return crash_dumps_dir_; } #if defined(OS_POSIX) && !defined(OS_MACOSX) // Returns a textual description of the product type and version to include // in the crash report. void GetProductNameAndVersion(const char** product_name, const char** version) override; base::FilePath GetReporterLogFilename() override; #endif // defined(OS_POSIX) && !defined(OS_MACOSX) #if defined(OS_WIN) bool GetCrashDumpLocation(base::string16* crash_dir) override; #else bool GetCrashDumpLocation(base::FilePath* crash_dir) override; #endif bool EnableBreakpadForProcess(const std::string& process_type) override; private: base::FilePath crash_dumps_dir_; DISALLOW_COPY_AND_ASSIGN(HeadlessCrashReporterClient); }; } // namespace headless #endif // HEADLESS_LIB_HEADLESS_CRASH_REPORTER_CLIENT_H_
null
null
null
null
7,183
32,617
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
32,617
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/input/context_menu_allowed_scope.h" namespace blink { static unsigned g_context_menu_allowed_count = 0; ContextMenuAllowedScope::ContextMenuAllowedScope() { g_context_menu_allowed_count++; } ContextMenuAllowedScope::~ContextMenuAllowedScope() { DCHECK_GT(g_context_menu_allowed_count, 0U); g_context_menu_allowed_count--; } bool ContextMenuAllowedScope::IsContextMenuAllowed() { return g_context_menu_allowed_count; } } // namespace blink
null
null
null
null
29,480
63,851
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
63,851
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_BLUETOOTH_DIALOG_LOCALIZED_STRINGS_PROVIDER_H_ #define CHROME_BROWSER_UI_WEBUI_CHROMEOS_BLUETOOTH_DIALOG_LOCALIZED_STRINGS_PROVIDER_H_ namespace content { class WebUIDataSource; } namespace chromeos { namespace bluetooth_dialog { // Adds the strings needed for network elements to |html_source|. String ids // correspond to ids in ui/webui/resources/cr_elements/chromeos/network/. void AddLocalizedStrings(content::WebUIDataSource* html_source); } // namespace bluetooth_dialog } // namespace chromeos #endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_BLUETOOTH_DIALOG_LOCALIZED_STRINGS_PROVIDER_H_
null
null
null
null
60,714
26,377
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
26,377
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "printing/backend/cups_helper.h" #include <cups/ppd.h> #include <stddef.h> #include <string> #include <vector> #include "base/base_paths.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/values.h" #include "printing/backend/print_backend.h" #include "printing/backend/print_backend_consts.h" #include "printing/units.h" #include "url/gurl.h" using base::EqualsCaseInsensitiveASCII; namespace printing { // This section contains helper code for PPD parsing for semantic capabilities. namespace { const char kColorDevice[] = "ColorDevice"; const char kColorModel[] = "ColorModel"; const char kColorMode[] = "ColorMode"; const char kProcessColorModel[] = "ProcessColorModel"; const char kPrintoutMode[] = "PrintoutMode"; const char kDraftGray[] = "Draft.Gray"; const char kHighGray[] = "High.Gray"; constexpr char kDuplex[] = "Duplex"; constexpr char kDuplexNone[] = "None"; constexpr char kDuplexTumble[] = "DuplexTumble"; constexpr char kPageSize[] = "PageSize"; // Brother printer specific options. constexpr char kBrotherDuplex[] = "BRDuplex"; constexpr char kBrotherMonoColor[] = "BRMonoColor"; constexpr char kBrotherPrintQuality[] = "BRPrintQuality"; // Samsung printer specific options. constexpr char kSamsungColorTrue[] = "True"; constexpr char kSamsungColorFalse[] = "False"; const double kMicronsPerPoint = 10.0f * kHundrethsMMPerInch / kPointsPerInch; void ParseLpOptions(const base::FilePath& filepath, base::StringPiece printer_name, int* num_options, cups_option_t** options) { std::string content; if (!base::ReadFileToString(filepath, &content)) return; const char kDest[] = "dest"; const char kDefault[] = "default"; const size_t kDestLen = sizeof(kDest) - 1; const size_t kDefaultLen = sizeof(kDefault) - 1; for (base::StringPiece line : base::SplitStringPiece(content, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { if (base::StartsWith(line, base::StringPiece(kDefault, kDefaultLen), base::CompareCase::INSENSITIVE_ASCII) && isspace(line[kDefaultLen])) { line = line.substr(kDefaultLen); } else if (base::StartsWith(line, base::StringPiece(kDest, kDestLen), base::CompareCase::INSENSITIVE_ASCII) && isspace(line[kDestLen])) { line = line.substr(kDestLen); } else { continue; } line = base::TrimWhitespaceASCII(line, base::TRIM_ALL); if (line.empty()) continue; size_t space_found = line.find(' '); if (space_found == base::StringPiece::npos) continue; base::StringPiece name = line.substr(0, space_found); if (name.empty()) continue; if (!EqualsCaseInsensitiveASCII(printer_name, name)) continue; // This is not the required printer. line = line.substr(space_found + 1); // Remove extra spaces. line = base::TrimWhitespaceASCII(line, base::TRIM_ALL); if (line.empty()) continue; // Parse the selected printer custom options. Need to pass a // null-terminated string. *num_options = cupsParseOptions(line.as_string().c_str(), 0, options); } } void MarkLpOptions(base::StringPiece printer_name, ppd_file_t** ppd) { cups_option_t* options = nullptr; int num_options = 0; const char kSystemLpOptionPath[] = "/etc/cups/lpoptions"; const char kUserLpOptionPath[] = ".cups/lpoptions"; std::vector<base::FilePath> file_locations; file_locations.push_back(base::FilePath(kSystemLpOptionPath)); base::FilePath homedir; PathService::Get(base::DIR_HOME, &homedir); file_locations.push_back(base::FilePath(homedir.Append(kUserLpOptionPath))); for (const base::FilePath& location : file_locations) { num_options = 0; options = nullptr; ParseLpOptions(location, printer_name, &num_options, &options); if (num_options > 0 && options) { cupsMarkOptions(*ppd, num_options, options); cupsFreeOptions(num_options, options); } } } void GetDuplexSettings(ppd_file_t* ppd, bool* duplex_capable, DuplexMode* duplex_default) { ppd_choice_t* duplex_choice = ppdFindMarkedChoice(ppd, kDuplex); if (!duplex_choice) { ppd_option_t* option = ppdFindOption(ppd, kDuplex); if (!option) option = ppdFindOption(ppd, kBrotherDuplex); if (!option) return; duplex_choice = ppdFindChoice(option, option->defchoice); } if (!duplex_choice) return; *duplex_capable = true; const char* choice = duplex_choice->choice; if (EqualsCaseInsensitiveASCII(choice, kDuplexNone)) { *duplex_default = SIMPLEX; } else if (EqualsCaseInsensitiveASCII(choice, kDuplexTumble)) { *duplex_default = SHORT_EDGE; } else { *duplex_default = LONG_EDGE; } } bool GetBasicColorModelSettings(ppd_file_t* ppd, ColorModel* color_model_for_black, ColorModel* color_model_for_color, bool* color_is_default) { ppd_option_t* color_model = ppdFindOption(ppd, kColorModel); if (!color_model) return false; if (ppdFindChoice(color_model, kBlack)) *color_model_for_black = BLACK; else if (ppdFindChoice(color_model, kGray)) *color_model_for_black = GRAY; else if (ppdFindChoice(color_model, kGrayscale)) *color_model_for_black = GRAYSCALE; if (ppdFindChoice(color_model, kColor)) *color_model_for_color = COLOR; else if (ppdFindChoice(color_model, kCMYK)) *color_model_for_color = CMYK; else if (ppdFindChoice(color_model, kRGB)) *color_model_for_color = RGB; else if (ppdFindChoice(color_model, kRGBA)) *color_model_for_color = RGBA; else if (ppdFindChoice(color_model, kRGB16)) *color_model_for_color = RGB16; else if (ppdFindChoice(color_model, kCMY)) *color_model_for_color = CMY; else if (ppdFindChoice(color_model, kKCMY)) *color_model_for_color = KCMY; else if (ppdFindChoice(color_model, kCMY_K)) *color_model_for_color = CMY_K; ppd_choice_t* marked_choice = ppdFindMarkedChoice(ppd, kColorModel); if (!marked_choice) marked_choice = ppdFindChoice(color_model, color_model->defchoice); if (marked_choice) { *color_is_default = !EqualsCaseInsensitiveASCII(marked_choice->choice, kBlack) && !EqualsCaseInsensitiveASCII(marked_choice->choice, kGray) && !EqualsCaseInsensitiveASCII(marked_choice->choice, kGrayscale); } return true; } bool GetPrintOutModeColorSettings(ppd_file_t* ppd, ColorModel* color_model_for_black, ColorModel* color_model_for_color, bool* color_is_default) { ppd_option_t* printout_mode = ppdFindOption(ppd, kPrintoutMode); if (!printout_mode) return false; *color_model_for_color = PRINTOUTMODE_NORMAL; *color_model_for_black = PRINTOUTMODE_NORMAL; // Check to see if NORMAL_GRAY value is supported by PrintoutMode. // If NORMAL_GRAY is not supported, NORMAL value is used to // represent grayscale. If NORMAL_GRAY is supported, NORMAL is used to // represent color. if (ppdFindChoice(printout_mode, kNormalGray)) *color_model_for_black = PRINTOUTMODE_NORMAL_GRAY; // Get the default marked choice to identify the default color setting // value. ppd_choice_t* printout_mode_choice = ppdFindMarkedChoice(ppd, kPrintoutMode); if (!printout_mode_choice) { printout_mode_choice = ppdFindChoice(printout_mode, printout_mode->defchoice); } if (printout_mode_choice) { if (EqualsCaseInsensitiveASCII(printout_mode_choice->choice, kNormalGray) || EqualsCaseInsensitiveASCII(printout_mode_choice->choice, kHighGray) || EqualsCaseInsensitiveASCII(printout_mode_choice->choice, kDraftGray)) { *color_model_for_black = PRINTOUTMODE_NORMAL_GRAY; *color_is_default = false; } } return true; } bool GetColorModeSettings(ppd_file_t* ppd, ColorModel* color_model_for_black, ColorModel* color_model_for_color, bool* color_is_default) { // Samsung printers use "ColorMode" attribute in their PPDs. ppd_option_t* color_mode_option = ppdFindOption(ppd, kColorMode); if (!color_mode_option) return false; if (ppdFindChoice(color_mode_option, kColor) || ppdFindChoice(color_mode_option, kSamsungColorTrue)) { *color_model_for_color = COLORMODE_COLOR; } if (ppdFindChoice(color_mode_option, kMonochrome) || ppdFindChoice(color_mode_option, kSamsungColorFalse)) { *color_model_for_black = COLORMODE_MONOCHROME; } ppd_choice_t* mode_choice = ppdFindMarkedChoice(ppd, kColorMode); if (!mode_choice) { mode_choice = ppdFindChoice(color_mode_option, color_mode_option->defchoice); } if (mode_choice) { *color_is_default = EqualsCaseInsensitiveASCII(mode_choice->choice, kColor) || EqualsCaseInsensitiveASCII(mode_choice->choice, kSamsungColorTrue); } return true; } bool GetBrotherColorSettings(ppd_file_t* ppd, ColorModel* color_model_for_black, ColorModel* color_model_for_color, bool* color_is_default) { // Some Brother printers use "BRMonoColor" attribute in their PPDs. // Some Brother printers use "BRPrintQuality" attribute in their PPDs. ppd_option_t* color_mode_option = ppdFindOption(ppd, kBrotherMonoColor); if (!color_mode_option) color_mode_option = ppdFindOption(ppd, kBrotherPrintQuality); if (!color_mode_option) return false; if (ppdFindChoice(color_mode_option, kFullColor)) *color_model_for_color = BROTHER_CUPS_COLOR; else if (ppdFindChoice(color_mode_option, kColor)) *color_model_for_color = BROTHER_BRSCRIPT3_COLOR; if (ppdFindChoice(color_mode_option, kMono)) *color_model_for_black = BROTHER_CUPS_MONO; else if (ppdFindChoice(color_mode_option, kBlack)) *color_model_for_black = BROTHER_BRSCRIPT3_BLACK; ppd_choice_t* marked_choice = ppdFindMarkedChoice(ppd, kColorMode); if (!marked_choice) { marked_choice = ppdFindChoice(color_mode_option, color_mode_option->defchoice); } if (marked_choice) { *color_is_default = !EqualsCaseInsensitiveASCII(marked_choice->choice, kBlack) && !EqualsCaseInsensitiveASCII(marked_choice->choice, kMono); } return true; } bool GetHPColorSettings(ppd_file_t* ppd, ColorModel* color_model_for_black, ColorModel* color_model_for_color, bool* color_is_default) { // HP printers use "Color/Color Model" attribute in their PPDs. ppd_option_t* color_mode_option = ppdFindOption(ppd, kColor); if (!color_mode_option) return false; if (ppdFindChoice(color_mode_option, kColor)) *color_model_for_color = HP_COLOR_COLOR; if (ppdFindChoice(color_mode_option, kBlack)) *color_model_for_black = HP_COLOR_BLACK; ppd_choice_t* mode_choice = ppdFindMarkedChoice(ppd, kColorMode); if (!mode_choice) { mode_choice = ppdFindChoice(color_mode_option, color_mode_option->defchoice); } if (mode_choice) { *color_is_default = EqualsCaseInsensitiveASCII(mode_choice->choice, kColor); } return true; } bool GetProcessColorModelSettings(ppd_file_t* ppd, ColorModel* color_model_for_black, ColorModel* color_model_for_color, bool* color_is_default) { // Canon printers use "ProcessColorModel" attribute in their PPDs. ppd_option_t* color_mode_option = ppdFindOption(ppd, kProcessColorModel); if (!color_mode_option) return false; if (ppdFindChoice(color_mode_option, kRGB)) *color_model_for_color = PROCESSCOLORMODEL_RGB; else if (ppdFindChoice(color_mode_option, kCMYK)) *color_model_for_color = PROCESSCOLORMODEL_CMYK; if (ppdFindChoice(color_mode_option, kGreyscale)) *color_model_for_black = PROCESSCOLORMODEL_GREYSCALE; ppd_choice_t* mode_choice = ppdFindMarkedChoice(ppd, kProcessColorModel); if (!mode_choice) { mode_choice = ppdFindChoice(color_mode_option, color_mode_option->defchoice); } if (mode_choice) { *color_is_default = !EqualsCaseInsensitiveASCII(mode_choice->choice, kGreyscale); } return true; } bool GetColorModelSettings(ppd_file_t* ppd, ColorModel* cm_black, ColorModel* cm_color, bool* is_color) { bool is_color_device = false; ppd_attr_t* attr = ppdFindAttr(ppd, kColorDevice, nullptr); if (attr && attr->value) is_color_device = ppd->color_device; *is_color = is_color_device; return (is_color_device && GetBasicColorModelSettings(ppd, cm_black, cm_color, is_color)) || GetPrintOutModeColorSettings(ppd, cm_black, cm_color, is_color) || GetColorModeSettings(ppd, cm_black, cm_color, is_color) || GetHPColorSettings(ppd, cm_black, cm_color, is_color) || GetBrotherColorSettings(ppd, cm_black, cm_color, is_color) || GetProcessColorModelSettings(ppd, cm_black, cm_color, is_color); } // Default port for IPP print servers. const int kDefaultIPPServerPort = 631; } // namespace // Helper wrapper around http_t structure, with connection and cleanup // functionality. HttpConnectionCUPS::HttpConnectionCUPS(const GURL& print_server_url, http_encryption_t encryption) : http_(nullptr) { // If we have an empty url, use default print server. if (print_server_url.is_empty()) return; int port = print_server_url.IntPort(); if (port == url::PORT_UNSPECIFIED) port = kDefaultIPPServerPort; http_ = httpConnectEncrypt(print_server_url.host().c_str(), port, encryption); if (!http_) { LOG(ERROR) << "CP_CUPS: Failed connecting to print server: " << print_server_url; } } HttpConnectionCUPS::~HttpConnectionCUPS() { if (http_) httpClose(http_); } void HttpConnectionCUPS::SetBlocking(bool blocking) { httpBlocking(http_, blocking ? 1 : 0); } http_t* HttpConnectionCUPS::http() { return http_; } bool ParsePpdCapabilities(base::StringPiece printer_name, base::StringPiece printer_capabilities, PrinterSemanticCapsAndDefaults* printer_info) { base::FilePath ppd_file_path; if (!base::CreateTemporaryFile(&ppd_file_path)) return false; int data_size = printer_capabilities.length(); if (data_size != base::WriteFile( ppd_file_path, printer_capabilities.data(), data_size)) { base::DeleteFile(ppd_file_path, false); return false; } ppd_file_t* ppd = ppdOpenFile(ppd_file_path.value().c_str()); if (!ppd) { int line = 0; ppd_status_t ppd_status = ppdLastError(&line); LOG(ERROR) << "Failed to open PDD file: error " << ppd_status << " at line " << line << ", " << ppdErrorString(ppd_status); return false; } ppdMarkDefaults(ppd); MarkLpOptions(printer_name, &ppd); PrinterSemanticCapsAndDefaults caps; caps.collate_capable = true; caps.collate_default = true; caps.copies_capable = true; GetDuplexSettings(ppd, &caps.duplex_capable, &caps.duplex_default); bool is_color = false; ColorModel cm_color = UNKNOWN_COLOR_MODEL, cm_black = UNKNOWN_COLOR_MODEL; if (!GetColorModelSettings(ppd, &cm_black, &cm_color, &is_color)) { VLOG(1) << "Unknown printer color model"; } caps.color_changeable = ((cm_color != UNKNOWN_COLOR_MODEL) && (cm_black != UNKNOWN_COLOR_MODEL) && (cm_color != cm_black)); caps.color_default = is_color; caps.color_model = cm_color; caps.bw_model = cm_black; if (ppd->num_sizes > 0 && ppd->sizes) { VLOG(1) << "Paper list size - " << ppd->num_sizes; ppd_option_t* paper_option = ppdFindOption(ppd, kPageSize); for (int i = 0; i < ppd->num_sizes; ++i) { gfx::Size paper_size_microns( static_cast<int>(ppd->sizes[i].width * kMicronsPerPoint + 0.5), static_cast<int>(ppd->sizes[i].length * kMicronsPerPoint + 0.5)); if (paper_size_microns.width() > 0 && paper_size_microns.height() > 0) { PrinterSemanticCapsAndDefaults::Paper paper; paper.size_um = paper_size_microns; paper.vendor_id = ppd->sizes[i].name; if (paper_option) { ppd_choice_t* paper_choice = ppdFindChoice(paper_option, ppd->sizes[i].name); // Human readable paper name should be UTF-8 encoded, but some PPDs // do not follow this standard. if (paper_choice && base::IsStringUTF8(paper_choice->text)) { paper.display_name = paper_choice->text; } } caps.papers.push_back(paper); if (i == 0 || ppd->sizes[i].marked) { caps.default_paper = paper; } } } } ppdClose(ppd); base::DeleteFile(ppd_file_path, false); *printer_info = caps; return true; } } // namespace printing
null
null
null
null
23,240
50,096
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
50,096
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_BASE_COCOA_UNDERLAY_OPENGL_HOSTING_WINDOW_H_ #define UI_BASE_COCOA_UNDERLAY_OPENGL_HOSTING_WINDOW_H_ #import <Cocoa/Cocoa.h> #include "ui/base/ui_base_export.h" // Common base class for windows that host a OpenGL surface that renders under // the window. Previously contained methods related to hole punching, now just // contains common asserts. UI_BASE_EXPORT @interface UnderlayOpenGLHostingWindow : NSWindow @end #endif // UI_BASE_COCOA_UNDERLAY_OPENGL_HOSTING_WINDOW_H_
null
null
null
null
46,959
40,391
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
205,386
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * tifm.h - TI FlashMedia driver * * Copyright (C) 2006 Alex Dubov <oakad@yahoo.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #ifndef _TIFM_H #define _TIFM_H #include <linux/spinlock.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/pci.h> #include <linux/workqueue.h> /* Host registers (relative to pci base address): */ enum { FM_SET_INTERRUPT_ENABLE = 0x008, FM_CLEAR_INTERRUPT_ENABLE = 0x00c, FM_INTERRUPT_STATUS = 0x014 }; /* Socket registers (relative to socket base address): */ enum { SOCK_CONTROL = 0x004, SOCK_PRESENT_STATE = 0x008, SOCK_DMA_ADDRESS = 0x00c, SOCK_DMA_CONTROL = 0x010, SOCK_DMA_FIFO_INT_ENABLE_SET = 0x014, SOCK_DMA_FIFO_INT_ENABLE_CLEAR = 0x018, SOCK_DMA_FIFO_STATUS = 0x020, SOCK_FIFO_CONTROL = 0x024, SOCK_FIFO_PAGE_SIZE = 0x028, SOCK_MMCSD_COMMAND = 0x104, SOCK_MMCSD_ARG_LOW = 0x108, SOCK_MMCSD_ARG_HIGH = 0x10c, SOCK_MMCSD_CONFIG = 0x110, SOCK_MMCSD_STATUS = 0x114, SOCK_MMCSD_INT_ENABLE = 0x118, SOCK_MMCSD_COMMAND_TO = 0x11c, SOCK_MMCSD_DATA_TO = 0x120, SOCK_MMCSD_DATA = 0x124, SOCK_MMCSD_BLOCK_LEN = 0x128, SOCK_MMCSD_NUM_BLOCKS = 0x12c, SOCK_MMCSD_BUFFER_CONFIG = 0x130, SOCK_MMCSD_SPI_CONFIG = 0x134, SOCK_MMCSD_SDIO_MODE_CONFIG = 0x138, SOCK_MMCSD_RESPONSE = 0x144, SOCK_MMCSD_SDIO_SR = 0x164, SOCK_MMCSD_SYSTEM_CONTROL = 0x168, SOCK_MMCSD_SYSTEM_STATUS = 0x16c, SOCK_MS_COMMAND = 0x184, SOCK_MS_DATA = 0x188, SOCK_MS_STATUS = 0x18c, SOCK_MS_SYSTEM = 0x190, SOCK_FIFO_ACCESS = 0x200 }; #define TIFM_CTRL_LED 0x00000040 #define TIFM_CTRL_FAST_CLK 0x00000100 #define TIFM_CTRL_POWER_MASK 0x00000007 #define TIFM_SOCK_STATE_OCCUPIED 0x00000008 #define TIFM_SOCK_STATE_POWERED 0x00000080 #define TIFM_FIFO_ENABLE 0x00000001 #define TIFM_FIFO_READY 0x00000001 #define TIFM_FIFO_MORE 0x00000008 #define TIFM_FIFO_INT_SETALL 0x0000ffff #define TIFM_FIFO_INTMASK 0x00000005 #define TIFM_DMA_RESET 0x00000002 #define TIFM_DMA_TX 0x00008000 #define TIFM_DMA_EN 0x00000001 #define TIFM_DMA_TSIZE 0x0000007f #define TIFM_TYPE_XD 1 #define TIFM_TYPE_MS 2 #define TIFM_TYPE_SD 3 struct tifm_device_id { unsigned char type; }; struct tifm_driver; struct tifm_dev { char __iomem *addr; spinlock_t lock; unsigned char type; unsigned int socket_id; void (*card_event)(struct tifm_dev *sock); void (*data_event)(struct tifm_dev *sock); struct device dev; }; struct tifm_driver { struct tifm_device_id *id_table; int (*probe)(struct tifm_dev *dev); void (*remove)(struct tifm_dev *dev); int (*suspend)(struct tifm_dev *dev, pm_message_t state); int (*resume)(struct tifm_dev *dev); struct device_driver driver; }; struct tifm_adapter { char __iomem *addr; spinlock_t lock; unsigned int irq_status; unsigned int socket_change_set; unsigned int id; unsigned int num_sockets; struct completion *finish_me; struct work_struct media_switcher; struct device dev; void (*eject)(struct tifm_adapter *fm, struct tifm_dev *sock); int (*has_ms_pif)(struct tifm_adapter *fm, struct tifm_dev *sock); struct tifm_dev *sockets[0]; }; struct tifm_adapter *tifm_alloc_adapter(unsigned int num_sockets, struct device *dev); int tifm_add_adapter(struct tifm_adapter *fm); void tifm_remove_adapter(struct tifm_adapter *fm); void tifm_free_adapter(struct tifm_adapter *fm); void tifm_free_device(struct device *dev); struct tifm_dev *tifm_alloc_device(struct tifm_adapter *fm, unsigned int id, unsigned char type); int tifm_register_driver(struct tifm_driver *drv); void tifm_unregister_driver(struct tifm_driver *drv); void tifm_eject(struct tifm_dev *sock); int tifm_has_ms_pif(struct tifm_dev *sock); int tifm_map_sg(struct tifm_dev *sock, struct scatterlist *sg, int nents, int direction); void tifm_unmap_sg(struct tifm_dev *sock, struct scatterlist *sg, int nents, int direction); void tifm_queue_work(struct work_struct *work); static inline void *tifm_get_drvdata(struct tifm_dev *dev) { return dev_get_drvdata(&dev->dev); } static inline void tifm_set_drvdata(struct tifm_dev *dev, void *data) { dev_set_drvdata(&dev->dev, data); } #endif
null
null
null
null
113,733
36,478
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
36,478
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_CRYPTO_RESULT_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_CRYPTO_RESULT_H_ #include "third_party/blink/public/platform/web_crypto.h" #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/wtf/thread_safe_ref_counted.h" namespace blink { // Result cancellation status interface to allow non-Blink webcrypto threads // to query for status. class CryptoResultCancel : public ThreadSafeRefCounted<CryptoResultCancel> { public: virtual ~CryptoResultCancel() = default; virtual bool Cancelled() const = 0; }; // Receives notification of completion of the crypto operation. class PLATFORM_EXPORT CryptoResult : public GarbageCollectedFinalized<CryptoResult> { public: virtual ~CryptoResult() = default; virtual void CompleteWithError(WebCryptoErrorType, const WebString&) = 0; virtual void CompleteWithBuffer(const void* bytes, unsigned bytes_size) = 0; virtual void CompleteWithJson(const char* utf8_data, unsigned length) = 0; virtual void CompleteWithBoolean(bool) = 0; virtual void CompleteWithKey(const WebCryptoKey&) = 0; virtual void CompleteWithKeyPair(const WebCryptoKey& public_key, const WebCryptoKey& private_key) = 0; virtual void Trace(blink::Visitor* visitor) {} }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_CRYPTO_RESULT_H_
null
null
null
null
33,341
58,351
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
58,351
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/data_use_measurement/chrome_data_use_ascriber.h" #include <string> #include <utility> #include <vector> #include "base/feature_list.h" #include "build/build_config.h" #include "chrome/browser/data_use_measurement/chrome_data_use_recorder.h" #include "chrome/browser/data_use_measurement/page_load_capping/chrome_page_load_capping_features.h" #include "components/data_use_measurement/content/content_url_request_classifier.h" #include "components/data_use_measurement/core/data_use_recorder.h" #include "components/data_use_measurement/core/data_use_user_data.h" #include "components/data_use_measurement/core/url_request_classifier.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/resource_request_info.h" #include "ipc/ipc_message.h" #include "net/url_request/url_request.h" namespace data_use_measurement { const base::Feature kDisableAscriberIfDataSaverDisabled{ "DisableAscriberIfDataSaverDisabled", base::FEATURE_DISABLED_BY_DEFAULT}; // static const void* const ChromeDataUseAscriber::DataUseRecorderEntryAsUserData:: kDataUseAscriberUserDataKey = &ChromeDataUseAscriber::DataUseRecorderEntryAsUserData:: kDataUseAscriberUserDataKey; ChromeDataUseAscriber::DataUseRecorderEntryAsUserData:: DataUseRecorderEntryAsUserData(DataUseRecorderEntry entry) : entry_(entry) {} ChromeDataUseAscriber::DataUseRecorderEntryAsUserData:: ~DataUseRecorderEntryAsUserData() {} ChromeDataUseAscriber::MainRenderFrameEntry::MainRenderFrameEntry( ChromeDataUseAscriber::DataUseRecorderEntry data_use_recorder) : data_use_recorder(data_use_recorder), is_visible(false) {} ChromeDataUseAscriber::MainRenderFrameEntry::~MainRenderFrameEntry() {} ChromeDataUseAscriber::ChromeDataUseAscriber() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); } ChromeDataUseAscriber::~ChromeDataUseAscriber() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(main_render_frame_entry_map_.empty()); DCHECK(subframe_to_mainframe_map_.empty()); if (page_capping_observer_) { // Remove the |page_capping_observer_| before the ObserverList is deleted. RemoveObserver(page_capping_observer_.get()); } // DCHECK(pending_navigation_data_use_map_.empty()); // DCHECK(data_use_recorders_.empty()); } ChromeDataUseRecorder* ChromeDataUseAscriber::GetOrCreateDataUseRecorder( net::URLRequest* request) { DataUseRecorderEntry entry = GetOrCreateDataUseRecorderEntry(request); return entry == data_use_recorders_.end() ? nullptr : &(*entry); } ChromeDataUseRecorder* ChromeDataUseAscriber::GetDataUseRecorder( const net::URLRequest& request) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // If a DataUseRecorder has already been set as user data, then return that. auto* user_data = static_cast<DataUseRecorderEntryAsUserData*>(request.GetUserData( DataUseRecorderEntryAsUserData::kDataUseAscriberUserDataKey)); return user_data ? &(*user_data->recorder_entry()) : nullptr; } ChromeDataUseAscriber::DataUseRecorderEntry ChromeDataUseAscriber::GetDataUseRecorderEntry(const net::URLRequest* request) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // If a DataUseRecorder has already been set as user data, then return that. auto* user_data = static_cast<DataUseRecorderEntryAsUserData*>(request->GetUserData( DataUseRecorderEntryAsUserData::kDataUseAscriberUserDataKey)); return user_data ? user_data->recorder_entry() : data_use_recorders_.end(); } ChromeDataUseAscriber::DataUseRecorderEntry ChromeDataUseAscriber::GetOrCreateDataUseRecorderEntry( net::URLRequest* request) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // If a DataUseRecorder has already been created, then return that. auto recorder = GetDataUseRecorderEntry(request); if (recorder != data_use_recorders_.end()) return recorder; // If request is associated with a ChromeService, create a new // DataUseRecorder for it. There is no reason to aggregate URLRequests // from ChromeServices into the same DataUseRecorder instance. DataUseUserData* service = static_cast<DataUseUserData*>( request->GetUserData(DataUseUserData::kUserDataKey)); if (service) { DataUseRecorderEntry entry = CreateNewDataUseRecorder(request, DataUse::TrafficType::SERVICES); entry->data_use().set_description( DataUseUserData::GetServiceNameAsString(service->service_name())); return entry; } if (!request->url().SchemeIsHTTPOrHTTPS()) return data_use_recorders_.end(); const content::ResourceRequestInfo* request_info = content::ResourceRequestInfo::ForRequest(request); if (!request_info || request_info->GetGlobalRequestID() == content::GlobalRequestID()) { // Create a new DataUseRecorder for all non-content initiated requests. DataUseRecorderEntry entry = CreateNewDataUseRecorder(request, DataUse::TrafficType::UNKNOWN); DataUse& data_use = entry->data_use(); data_use.set_url(request->url()); return entry; } if (request_info->GetResourceType() == content::RESOURCE_TYPE_MAIN_FRAME) { DataUseRecorderEntry new_entry = CreateNewDataUseRecorder(request, DataUse::TrafficType::USER_TRAFFIC); new_entry->set_main_frame_request_id(request_info->GetGlobalRequestID()); pending_navigation_data_use_map_.insert( std::make_pair(request_info->GetGlobalRequestID(), new_entry)); return new_entry; } int render_process_id = -1; int render_frame_id = -1; bool has_valid_frame = content::ResourceRequestInfo::GetRenderFrameForRequest( request, &render_process_id, &render_frame_id); if (has_valid_frame && render_frame_id != SpecialRoutingIDs::MSG_ROUTING_NONE) { // Browser tests may not set up DataUseWebContentsObservers in which case // this class never sees navigation and frame events so DataUseRecorders // will never be destroyed. To avoid this, we ignore requests whose // render frames don't have a record. However, this can also be caused by // URLRequests racing the frame create events. // TODO(kundaji): Add UMA. RenderFrameHostID frame_key(render_process_id, render_frame_id); const auto main_frame_key_iter = subframe_to_mainframe_map_.find(frame_key); if (main_frame_key_iter == subframe_to_mainframe_map_.end()) { return data_use_recorders_.end(); } const auto main_frame_it = main_render_frame_entry_map_.find(main_frame_key_iter->second); if (main_frame_it == main_render_frame_entry_map_.end() || main_frame_it->second.data_use_recorder == data_use_recorders_.end()) { return data_use_recorders_.end(); } AscribeRecorderWithRequest(request, main_frame_it->second.data_use_recorder); return main_frame_it->second.data_use_recorder; } // Create a new DataUseRecorder for all other requests. DataUseRecorderEntry entry = CreateNewDataUseRecorder( request, content::ResourceRequestInfo::OriginatedFromServiceWorker(request) ? DataUse::TrafficType::SERVICE_WORKER : DataUse::TrafficType::UNKNOWN); DataUse& data_use = entry->data_use(); data_use.set_url(request->url()); return entry; } void ChromeDataUseAscriber::OnBeforeUrlRequest(net::URLRequest* request) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(request); if (IsDisabled()) return; requests_.insert(request); DataUseAscriber::OnBeforeUrlRequest(request); } void ChromeDataUseAscriber::OnUrlRequestCompleted(net::URLRequest* request, bool started) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(request); if (IsDisabled()) return; if (requests_.find(request) == requests_.end()) return; const DataUseRecorderEntry entry = GetDataUseRecorderEntry(request); if (entry == data_use_recorders_.end()) { requests_.erase(request); return; } for (auto& observer : observers_) observer.OnPageResourceLoad(*request, &entry->data_use()); OnUrlRequestCompletedOrDestroyed(request); } void ChromeDataUseAscriber::OnUrlRequestDestroyed(net::URLRequest* request) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(request); if (IsDisabled()) return; if (requests_.find(request) == requests_.end()) return; OnUrlRequestCompletedOrDestroyed(request); } void ChromeDataUseAscriber::OnUrlRequestCompletedOrDestroyed( net::URLRequest* request) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(request); if (IsDisabled()) return; DCHECK(request); const DataUseRecorderEntry entry = GetDataUseRecorderEntry(request); if (entry == data_use_recorders_.end()) { requests_.erase(request); return; } { const content::ResourceRequestInfo* request_info = content::ResourceRequestInfo::ForRequest(request); if (request_info && request_info->GetResourceType() == content::RESOURCE_TYPE_MAIN_FRAME && !request->status().is_success()) { // If mainframe request was not successful, then NavigationHandle in // DidFinishMainFrameNavigation will not have GlobalRequestID. So we erase // the DataUseRecorderEntry here. pending_navigation_data_use_map_.erase(entry->main_frame_request_id()); } } const auto main_frame_it = main_render_frame_entry_map_.find(entry->main_frame_id()); // Check whether the frame is tracked in the main render frame map, and if it // is, check if |entry| is currently tracked by that frame. bool frame_is_tracked = main_frame_it != main_render_frame_entry_map_.end() && main_frame_it->second.data_use_recorder != data_use_recorders_.end() && main_frame_it->second.data_use_recorder == entry; // For non-main frame requests, the page load can only be tracked in the frame // map. bool page_load_is_tracked = frame_is_tracked; const content::ResourceRequestInfo* request_info = content::ResourceRequestInfo::ForRequest(request); // If the frame is not tracked, but this is a main frame request, it might be // the case that the navigation has not commit yet. if (!frame_is_tracked && request_info && request_info->GetResourceType() == content::RESOURCE_TYPE_MAIN_FRAME) { page_load_is_tracked = pending_navigation_data_use_map_.find(entry->main_frame_request_id()) != pending_navigation_data_use_map_.end(); } entry->OnUrlRequestDestroyed(request); request->RemoveUserData( DataUseRecorderEntryAsUserData::kDataUseAscriberUserDataKey); // If all requests are done for |entry| and no more requests can be attributed // to it, it is safe to delete. if (entry->IsDataUseComplete() && !page_load_is_tracked) { NotifyPageLoadConcluded(entry); data_use_recorders_.erase(entry); } requests_.erase(request); } void ChromeDataUseAscriber::RenderFrameCreated(int render_process_id, int render_frame_id, int main_render_process_id, int main_render_frame_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (IsDisabled()) return; const auto render_frame = RenderFrameHostID(render_process_id, render_frame_id); if (main_render_process_id != -1 && main_render_frame_id != -1) { // Create an entry in |subframe_to_mainframe_map_| for this frame mapped to // it's parent frame. subframe_to_mainframe_map_.insert(std::make_pair( render_frame, RenderFrameHostID(main_render_process_id, main_render_frame_id))); } else { subframe_to_mainframe_map_.insert( std::make_pair(render_frame, render_frame)); DCHECK(main_render_frame_entry_map_.find(render_frame) == main_render_frame_entry_map_.end()); DataUseRecorderEntry entry = CreateNewDataUseRecorder(nullptr, DataUse::TrafficType::USER_TRAFFIC); entry->set_main_frame_id(render_frame); main_render_frame_entry_map_.emplace(std::piecewise_construct, std::forward_as_tuple(render_frame), std::forward_as_tuple(entry)); } } void ChromeDataUseAscriber::RenderFrameDeleted(int render_process_id, int render_frame_id, int main_render_process_id, int main_render_frame_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (IsDisabled()) return; RenderFrameHostID key(render_process_id, render_frame_id); if (main_render_process_id == -1 && main_render_frame_id == -1) { auto main_frame_it = main_render_frame_entry_map_.find(key); if (main_render_frame_entry_map_.end() != main_frame_it) { DataUseRecorderEntry entry = main_frame_it->second.data_use_recorder; // Stop tracking requests for the old frame. std::vector<net::URLRequest*> pending_url_requests; entry->GetPendingURLRequests(&pending_url_requests); for (net::URLRequest* request : pending_url_requests) { OnUrlRequestCompletedOrDestroyed(request); } ValidateAndCleanUp(entry); DCHECK(entry->IsDataUseComplete()); NotifyPageLoadConcluded(entry); data_use_recorders_.erase(entry); main_render_frame_entry_map_.erase(main_frame_it); } } subframe_to_mainframe_map_.erase(key); } void ChromeDataUseAscriber::ValidateAndCleanUp(DataUseRecorderEntry entry) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); for (auto it = requests_.begin(); it != requests_.end();) { const net::URLRequest* request = *it; DCHECK(request); const DataUseRecorderEntry request_entry = GetDataUseRecorderEntry(request); if (request_entry == data_use_recorders_.end()) { requests_.erase(it++); continue; } // All requests that point to |entry| should have been deleted. DCHECK(entry != request_entry); if (entry == request_entry) { requests_.erase(it++); } else { ++it; } } } void ChromeDataUseAscriber::ReadyToCommitMainFrameNavigation( content::GlobalRequestID global_request_id, int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (IsDisabled()) return; main_render_frame_entry_map_ .find(RenderFrameHostID(render_process_id, render_frame_id)) ->second.pending_navigation_global_request_id = global_request_id; } void ChromeDataUseAscriber::DidFinishMainFrameNavigation( int render_process_id, int render_frame_id, const GURL& gurl, bool is_same_document_navigation, uint32_t page_transition, base::TimeTicks time) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (IsDisabled()) return; RenderFrameHostID main_frame(render_process_id, render_frame_id); auto main_frame_it = main_render_frame_entry_map_.find(main_frame); if (main_frame_it == main_render_frame_entry_map_.end()) return; // Find the global request id of the pending navigation. auto global_request_id = main_frame_it->second.pending_navigation_global_request_id; main_frame_it->second.pending_navigation_global_request_id = content::GlobalRequestID(); // TODO(rajendrant): Analyze why global request ID was not found in // pending navigation map, in tests. if (global_request_id == content::GlobalRequestID()) return; // Find the pending navigation entry. auto navigation_iter = pending_navigation_data_use_map_.find(global_request_id); // We might not find a navigation entry since the pending navigation may not // have caused any HTTP or HTTPS URLRequests to be made. if (navigation_iter == pending_navigation_data_use_map_.end()) { // No pending navigation entry to worry about. However, the old frame entry // must be removed from frame map, and possibly marked complete and deleted. if (main_frame_it != main_render_frame_entry_map_.end()) { const DataUseRecorderEntry old_frame_entry = main_frame_it->second.data_use_recorder; DataUse::TrafficType old_traffic_type = old_frame_entry->data_use().traffic_type(); old_frame_entry->set_page_transition(page_transition); main_frame_it->second.data_use_recorder = data_use_recorders_.end(); NotifyPageLoadCommit(old_frame_entry); if (old_frame_entry->IsDataUseComplete()) { NotifyPageLoadConcluded(old_frame_entry); data_use_recorders_.erase(old_frame_entry); } // Add a new recorder to the render frame map to replace the deleted one. main_frame_it->second.data_use_recorder = data_use_recorders_.emplace( data_use_recorders_.end(), old_traffic_type); main_frame_it->second.data_use_recorder->set_main_frame_id(main_frame); } return; } const DataUseRecorderEntry entry = navigation_iter->second; pending_navigation_data_use_map_.erase(navigation_iter); entry->set_main_frame_id(main_frame); // If the frame has already been deleted then mark this navigation as having // concluded its data use. if (main_frame_it == main_render_frame_entry_map_.end()) { entry->set_page_transition(page_transition); NotifyPageLoadCommit(entry); if (entry->IsDataUseComplete()) { NotifyPageLoadConcluded(entry); data_use_recorders_.erase(entry); } return; } DataUseRecorderEntry old_frame_entry = main_frame_it->second.data_use_recorder; old_frame_entry->set_page_transition(page_transition); if (old_frame_entry == entry) return; if (is_same_document_navigation) { std::vector<net::URLRequest*> pending_url_requests; entry->GetPendingURLRequests(&pending_url_requests); for (net::URLRequest* request : pending_url_requests) { entry->MovePendingURLRequestTo(&(*old_frame_entry), request); request->RemoveUserData( DataUseRecorderEntryAsUserData::kDataUseAscriberUserDataKey); AscribeRecorderWithRequest(request, old_frame_entry); } entry->RemoveAllPendingURLRequests(); DCHECK(entry->IsDataUseComplete()); data_use_recorders_.erase(entry); NotifyPageLoadCommit(old_frame_entry); } else { DataUse& data_use = entry->data_use(); DCHECK(!data_use.url().is_valid() || data_use.url() == gurl) << "is valid: " << data_use.url().is_valid() << "; data_use.url(): " << data_use.url().spec() << "; gurl: " << gurl.spec(); if (!data_use.url().is_valid()) { data_use.set_url(gurl); } // |time| is when navigation commit finished in UI thread. Before this // navigation finish is processed in IO thread, there could be some // subresource requests started and get asribed to |old_frame_entry|. Move // these requests that started after |time| but ascribed to the previous // page load to page load |entry|. std::vector<net::URLRequest*> pending_url_requests; old_frame_entry->GetPendingURLRequests(&pending_url_requests); for (net::URLRequest* request : pending_url_requests) { DCHECK( !old_frame_entry->GetPendingURLRequestStartTime(request).is_null()); if (old_frame_entry->GetPendingURLRequestStartTime(request) > time) { old_frame_entry->MovePendingURLRequestTo(&*entry, request); request->RemoveUserData( DataUseRecorderEntryAsUserData::kDataUseAscriberUserDataKey); AscribeRecorderWithRequest(request, entry); } } // Stop tracking requests for the old frame. pending_url_requests.clear(); old_frame_entry->GetPendingURLRequests(&pending_url_requests); for (net::URLRequest* request : pending_url_requests) { OnUrlRequestCompletedOrDestroyed(request); } DCHECK(old_frame_entry->IsDataUseComplete()); ValidateAndCleanUp(old_frame_entry); NotifyPageLoadConcluded(old_frame_entry); data_use_recorders_.erase(old_frame_entry); entry->set_is_visible(main_frame_it->second.is_visible); main_frame_it->second.data_use_recorder = entry; NotifyPageLoadCommit(entry); } } void ChromeDataUseAscriber::DidFinishLoad(int render_process_id, int render_frame_id, const GURL& validated_url) { // Only continue for validated HTTP* URLs (e.g., not internal error pages). if (!validated_url.SchemeIsHTTPOrHTTPS()) return; RenderFrameHostID main_frame(render_process_id, render_frame_id); auto main_frame_it = main_render_frame_entry_map_.find(main_frame); if (main_frame_it == main_render_frame_entry_map_.end()) return; // Check that the DataUse entry has a committed URL. DataUseRecorderEntry entry = main_frame_it->second.data_use_recorder; DataUse& data_use = entry->data_use(); if (data_use.url().is_valid()) { NotifyDidFinishLoad(entry); } } void ChromeDataUseAscriber::NotifyPageLoadCommit(DataUseRecorderEntry entry) { for (auto& observer : observers_) observer.OnPageLoadCommit(&entry->data_use()); } void ChromeDataUseAscriber::NotifyDidFinishLoad(DataUseRecorderEntry entry) { for (auto& observer : observers_) observer.OnPageDidFinishLoad(&entry->data_use()); } void ChromeDataUseAscriber::NotifyPageLoadConcluded( DataUseRecorderEntry entry) { for (auto& observer : observers_) observer.OnPageLoadConcluded(&entry->data_use()); } std::unique_ptr<URLRequestClassifier> ChromeDataUseAscriber::CreateURLRequestClassifier() const { return std::make_unique<ContentURLRequestClassifier>(); } ChromeDataUseAscriber::DataUseRecorderEntry ChromeDataUseAscriber::CreateNewDataUseRecorder( net::URLRequest* request, DataUse::TrafficType traffic_type) { DataUseRecorderEntry entry = data_use_recorders_.emplace(data_use_recorders_.end(), traffic_type); if (request) AscribeRecorderWithRequest(request, entry); return entry; } void ChromeDataUseAscriber::AscribeRecorderWithRequest( net::URLRequest* request, DataUseRecorderEntry entry) { entry->AddPendingURLRequest(request); request->SetUserData( DataUseRecorderEntryAsUserData::kDataUseAscriberUserDataKey, std::make_unique<DataUseRecorderEntryAsUserData>(entry)); } void ChromeDataUseAscriber::WasShownOrHidden(int main_render_process_id, int main_render_frame_id, bool visible) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (IsDisabled()) return; auto main_frame_it = main_render_frame_entry_map_.find( RenderFrameHostID(main_render_process_id, main_render_frame_id)); if (main_frame_it != main_render_frame_entry_map_.end()) { main_frame_it->second.is_visible = visible; if (main_frame_it->second.data_use_recorder != data_use_recorders_.end()) main_frame_it->second.data_use_recorder->set_is_visible(visible); } } void ChromeDataUseAscriber::RenderFrameHostChanged(int old_render_process_id, int old_render_frame_id, int new_render_process_id, int new_render_frame_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (IsDisabled()) return; auto old_frame_iter = main_render_frame_entry_map_.find( RenderFrameHostID(old_render_process_id, old_render_frame_id)); if (old_frame_iter != main_render_frame_entry_map_.end()) { WasShownOrHidden(new_render_process_id, new_render_frame_id, true); if (old_frame_iter->second.pending_navigation_global_request_id != content::GlobalRequestID()) { // Transfer the pending navigation global request ID from old to new main // frame. main_render_frame_entry_map_ .find(RenderFrameHostID(new_render_process_id, new_render_frame_id)) ->second.pending_navigation_global_request_id = old_frame_iter->second.pending_navigation_global_request_id; old_frame_iter->second.pending_navigation_global_request_id = content::GlobalRequestID(); } } } bool ChromeDataUseAscriber::IsDisabled() const { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); // TODO(rajendrant): https://crbug.com/753559. Fix platform specific race // conditions and re-enable. return base::FeatureList::IsEnabled(kDisableAscriberIfDataSaverDisabled) && disable_ascriber_; } void ChromeDataUseAscriber::DisableAscriber() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); disable_ascriber_ = true; } } // namespace data_use_measurement
null
null
null
null
55,214
13,879
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
13,879
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_OFFLINE_PAGES_CORE_OFFLINE_PAGE_MODEL_EVENT_LOGGER_H_ #define COMPONENTS_OFFLINE_PAGES_CORE_OFFLINE_PAGE_MODEL_EVENT_LOGGER_H_ #include "components/offline_pages/core/offline_event_logger.h" namespace offline_pages { class OfflinePageModelEventLogger : public OfflineEventLogger { public: // Records that a page has been saved for |name_space| with |url| // and |offline_id|. void RecordPageSaved(const std::string& name_space, const std::string& url, int64_t offline_id); // Records that a page with |offline_id| has been deleted. void RecordPageDeleted(int64_t offline_id); // Records that a page with |offline_id| has been expired. void RecordPageExpired(int64_t offline_id); // Records that the offline store has been cleared. void RecordStoreCleared(); // Records that there was an error when clearing the offline store. void RecordStoreClearError(); // Records that there was an error when reloading the offline store. void RecordStoreReloadError(); }; } // namespace offline_pages #endif // COMPONENTS_OFFLINE_PAGES_CORE_OFFLINE_PAGE_MODEL_EVENT_LOGGER_H_
null
null
null
null
10,742
7,686
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
172,681
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Architecture specific sysfs attributes in /sys/kernel * * Copyright (C) 2007, Intel Corp. * Huang Ying <ying.huang@intel.com> * Copyright (C) 2013, 2013 Red Hat, Inc. * Dave Young <dyoung@redhat.com> * * This file is released under the GPLv2 */ #include <linux/kobject.h> #include <linux/string.h> #include <linux/sysfs.h> #include <linux/init.h> #include <linux/stat.h> #include <linux/slab.h> #include <linux/mm.h> #include <asm/io.h> #include <asm/setup.h> static ssize_t version_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "0x%04x\n", boot_params.hdr.version); } static struct kobj_attribute boot_params_version_attr = __ATTR_RO(version); static ssize_t boot_params_data_read(struct file *fp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { memcpy(buf, (void *)&boot_params + off, count); return count; } static struct bin_attribute boot_params_data_attr = { .attr = { .name = "data", .mode = S_IRUGO, }, .read = boot_params_data_read, .size = sizeof(boot_params), }; static struct attribute *boot_params_version_attrs[] = { &boot_params_version_attr.attr, NULL, }; static struct bin_attribute *boot_params_data_attrs[] = { &boot_params_data_attr, NULL, }; static struct attribute_group boot_params_attr_group = { .attrs = boot_params_version_attrs, .bin_attrs = boot_params_data_attrs, }; static int kobj_to_setup_data_nr(struct kobject *kobj, int *nr) { const char *name; name = kobject_name(kobj); return kstrtoint(name, 10, nr); } static int get_setup_data_paddr(int nr, u64 *paddr) { int i = 0; struct setup_data *data; u64 pa_data = boot_params.hdr.setup_data; while (pa_data) { if (nr == i) { *paddr = pa_data; return 0; } data = ioremap_cache(pa_data, sizeof(*data)); if (!data) return -ENOMEM; pa_data = data->next; iounmap(data); i++; } return -EINVAL; } static int __init get_setup_data_size(int nr, size_t *size) { int i = 0; struct setup_data *data; u64 pa_data = boot_params.hdr.setup_data; while (pa_data) { data = ioremap_cache(pa_data, sizeof(*data)); if (!data) return -ENOMEM; if (nr == i) { *size = data->len; iounmap(data); return 0; } pa_data = data->next; iounmap(data); i++; } return -EINVAL; } static ssize_t type_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { int nr, ret; u64 paddr; struct setup_data *data; ret = kobj_to_setup_data_nr(kobj, &nr); if (ret) return ret; ret = get_setup_data_paddr(nr, &paddr); if (ret) return ret; data = ioremap_cache(paddr, sizeof(*data)); if (!data) return -ENOMEM; ret = sprintf(buf, "0x%x\n", data->type); iounmap(data); return ret; } static ssize_t setup_data_data_read(struct file *fp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { int nr, ret = 0; u64 paddr; struct setup_data *data; void *p; ret = kobj_to_setup_data_nr(kobj, &nr); if (ret) return ret; ret = get_setup_data_paddr(nr, &paddr); if (ret) return ret; data = ioremap_cache(paddr, sizeof(*data)); if (!data) return -ENOMEM; if (off > data->len) { ret = -EINVAL; goto out; } if (count > data->len - off) count = data->len - off; if (!count) goto out; ret = count; p = ioremap_cache(paddr + sizeof(*data), data->len); if (!p) { ret = -ENOMEM; goto out; } memcpy(buf, p + off, count); iounmap(p); out: iounmap(data); return ret; } static struct kobj_attribute type_attr = __ATTR_RO(type); static struct bin_attribute data_attr __ro_after_init = { .attr = { .name = "data", .mode = S_IRUGO, }, .read = setup_data_data_read, }; static struct attribute *setup_data_type_attrs[] = { &type_attr.attr, NULL, }; static struct bin_attribute *setup_data_data_attrs[] = { &data_attr, NULL, }; static struct attribute_group setup_data_attr_group = { .attrs = setup_data_type_attrs, .bin_attrs = setup_data_data_attrs, }; static int __init create_setup_data_node(struct kobject *parent, struct kobject **kobjp, int nr) { int ret = 0; size_t size; struct kobject *kobj; char name[16]; /* should be enough for setup_data nodes numbers */ snprintf(name, 16, "%d", nr); kobj = kobject_create_and_add(name, parent); if (!kobj) return -ENOMEM; ret = get_setup_data_size(nr, &size); if (ret) goto out_kobj; data_attr.size = size; ret = sysfs_create_group(kobj, &setup_data_attr_group); if (ret) goto out_kobj; *kobjp = kobj; return 0; out_kobj: kobject_put(kobj); return ret; } static void __init cleanup_setup_data_node(struct kobject *kobj) { sysfs_remove_group(kobj, &setup_data_attr_group); kobject_put(kobj); } static int __init get_setup_data_total_num(u64 pa_data, int *nr) { int ret = 0; struct setup_data *data; *nr = 0; while (pa_data) { *nr += 1; data = ioremap_cache(pa_data, sizeof(*data)); if (!data) { ret = -ENOMEM; goto out; } pa_data = data->next; iounmap(data); } out: return ret; } static int __init create_setup_data_nodes(struct kobject *parent) { struct kobject *setup_data_kobj, **kobjp; u64 pa_data; int i, j, nr, ret = 0; pa_data = boot_params.hdr.setup_data; if (!pa_data) return 0; setup_data_kobj = kobject_create_and_add("setup_data", parent); if (!setup_data_kobj) { ret = -ENOMEM; goto out; } ret = get_setup_data_total_num(pa_data, &nr); if (ret) goto out_setup_data_kobj; kobjp = kmalloc(sizeof(*kobjp) * nr, GFP_KERNEL); if (!kobjp) { ret = -ENOMEM; goto out_setup_data_kobj; } for (i = 0; i < nr; i++) { ret = create_setup_data_node(setup_data_kobj, kobjp + i, i); if (ret) goto out_clean_nodes; } kfree(kobjp); return 0; out_clean_nodes: for (j = i - 1; j > 0; j--) cleanup_setup_data_node(*(kobjp + j)); kfree(kobjp); out_setup_data_kobj: kobject_put(setup_data_kobj); out: return ret; } static int __init boot_params_ksysfs_init(void) { int ret; struct kobject *boot_params_kobj; boot_params_kobj = kobject_create_and_add("boot_params", kernel_kobj); if (!boot_params_kobj) { ret = -ENOMEM; goto out; } ret = sysfs_create_group(boot_params_kobj, &boot_params_attr_group); if (ret) goto out_boot_params_kobj; ret = create_setup_data_nodes(boot_params_kobj); if (ret) goto out_create_group; return 0; out_create_group: sysfs_remove_group(boot_params_kobj, &boot_params_attr_group); out_boot_params_kobj: kobject_put(boot_params_kobj); out: return ret; } arch_initcall(boot_params_ksysfs_init);
null
null
null
null
81,028
28,067
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
28,067
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_LITE_H__ #define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_LITE_H__ #include <map> #include <string> #include <google/protobuf/compiler/java/java_field.h> namespace google { namespace protobuf { namespace compiler { namespace java { class Context; // context.h class ClassNameResolver; // name_resolver.h } } } namespace protobuf { namespace compiler { namespace java { class ImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: explicit ImmutableEnumFieldLiteGenerator( const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, Context* context); ~ImmutableEnumFieldLiteGenerator(); // implements ImmutableFieldLiteGenerator ------------------------------------ int GetNumBitsForMessage() const; int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; void GenerateVisitCode(io::Printer* printer) const; void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; void GenerateParsingCode(io::Printer* printer) const; void GenerateParsingDoneCode(io::Printer* printer) const; void GenerateSerializationCode(io::Printer* printer) const; void GenerateSerializedSizeCode(io::Printer* printer) const; void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; string GetBoxedType() const; protected: const FieldDescriptor* descriptor_; std::map<string, string> variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; ClassNameResolver* name_resolver_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableEnumFieldLiteGenerator); }; class ImmutableEnumOneofFieldLiteGenerator : public ImmutableEnumFieldLiteGenerator { public: ImmutableEnumOneofFieldLiteGenerator( const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, Context* context); ~ImmutableEnumOneofFieldLiteGenerator(); void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateVisitCode(io::Printer* printer) const; void GenerateParsingCode(io::Printer* printer) const; void GenerateSerializationCode(io::Printer* printer) const; void GenerateSerializedSizeCode(io::Printer* printer) const; void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableEnumOneofFieldLiteGenerator); }; class RepeatedImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator { public: explicit RepeatedImmutableEnumFieldLiteGenerator( const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, Context* context); ~RepeatedImmutableEnumFieldLiteGenerator(); // implements ImmutableFieldLiteGenerator ------------------------------------ int GetNumBitsForMessage() const; int GetNumBitsForBuilder() const; void GenerateInterfaceMembers(io::Printer* printer) const; void GenerateMembers(io::Printer* printer) const; void GenerateBuilderMembers(io::Printer* printer) const; void GenerateInitializationCode(io::Printer* printer) const; void GenerateVisitCode(io::Printer* printer) const; void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; void GenerateParsingCode(io::Printer* printer) const; void GenerateParsingCodeFromPacked(io::Printer* printer) const; void GenerateParsingDoneCode(io::Printer* printer) const; void GenerateSerializationCode(io::Printer* printer) const; void GenerateSerializedSizeCode(io::Printer* printer) const; void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCode(io::Printer* printer) const; string GetBoxedType() const; private: const FieldDescriptor* descriptor_; std::map<string, string> variables_; const int messageBitIndex_; const int builderBitIndex_; Context* context_; ClassNameResolver* name_resolver_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableEnumFieldLiteGenerator); }; } // namespace java } // namespace compiler } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_LITE_H__
null
null
null
null
24,930
15,493
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
180,488
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* IEEE754 floating point arithmetic * double precision: common utilities */ /* * MIPS floating point support * Copyright (C) 1994-2000 Algorithmics Ltd. * * This program is free software; you can distribute it and/or modify it * under the terms of the GNU General Public License (Version 2) as * published by the Free Software Foundation. * * This program is distributed in the hope 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 St, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "ieee754dp.h" union ieee754dp ieee754dp_neg(union ieee754dp x) { union ieee754dp y; if (ieee754_csr.abs2008) { y = x; DPSIGN(y) = !DPSIGN(x); } else { unsigned int oldrm; oldrm = ieee754_csr.rm; ieee754_csr.rm = FPU_CSR_RD; y = ieee754dp_sub(ieee754dp_zero(0), x); ieee754_csr.rm = oldrm; } return y; } union ieee754dp ieee754dp_abs(union ieee754dp x) { union ieee754dp y; if (ieee754_csr.abs2008) { y = x; DPSIGN(y) = 0; } else { unsigned int oldrm; oldrm = ieee754_csr.rm; ieee754_csr.rm = FPU_CSR_RD; if (DPSIGN(x)) y = ieee754dp_sub(ieee754dp_zero(0), x); else y = ieee754dp_add(ieee754dp_zero(0), x); ieee754_csr.rm = oldrm; } return y; }
null
null
null
null
88,835
14,298
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
179,293
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Etrax general port I/O device * * Copyright (c) 1999-2007 Axis Communications AB * * Authors: Bjorn Wesen (initial version) * Ola Knutsson (LED handling) * Johan Adolfsson (read/set directions, write, port G) */ #include <linux/module.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/ioport.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/string.h> #include <linux/poll.h> #include <linux/init.h> #include <linux/interrupt.h> #include <asm/etraxgpio.h> #include <arch/svinto.h> #include <asm/io.h> #include <asm/irq.h> #include <arch/io_interface_mux.h> #define GPIO_MAJOR 120 /* experimental MAJOR number */ #define D(x) #if 0 static int dp_cnt; #define DP(x) do { dp_cnt++; if (dp_cnt % 1000 == 0) x; }while(0) #else #define DP(x) #endif static char gpio_name[] = "etrax gpio"; #if 0 static wait_queue_head_t *gpio_wq; #endif static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg); static ssize_t gpio_write(struct file *file, const char __user *buf, size_t count, loff_t *off); static int gpio_open(struct inode *inode, struct file *filp); static int gpio_release(struct inode *inode, struct file *filp); static unsigned int gpio_poll(struct file *filp, struct poll_table_struct *wait); /* private data per open() of this driver */ struct gpio_private { struct gpio_private *next; /* These fields are for PA and PB only */ volatile unsigned char *port, *shadow; volatile unsigned char *dir, *dir_shadow; unsigned char changeable_dir; unsigned char changeable_bits; unsigned char clk_mask; unsigned char data_mask; unsigned char write_msb; unsigned char pad1, pad2, pad3; /* These fields are generic */ unsigned long highalarm, lowalarm; wait_queue_head_t alarm_wq; int minor; }; /* linked list of alarms to check for */ static struct gpio_private *alarmlist; static int gpio_some_alarms; /* Set if someone uses alarm */ static unsigned long gpio_pa_irq_enabled_mask; static DEFINE_SPINLOCK(gpio_lock); /* Protect directions etc */ /* Port A and B use 8 bit access, but Port G is 32 bit */ #define NUM_PORTS (GPIO_MINOR_B+1) static volatile unsigned char *ports[NUM_PORTS] = { R_PORT_PA_DATA, R_PORT_PB_DATA, }; static volatile unsigned char *shads[NUM_PORTS] = { &port_pa_data_shadow, &port_pb_data_shadow }; /* What direction bits that are user changeable 1=changeable*/ #ifndef CONFIG_ETRAX_PA_CHANGEABLE_DIR #define CONFIG_ETRAX_PA_CHANGEABLE_DIR 0x00 #endif #ifndef CONFIG_ETRAX_PB_CHANGEABLE_DIR #define CONFIG_ETRAX_PB_CHANGEABLE_DIR 0x00 #endif #ifndef CONFIG_ETRAX_PA_CHANGEABLE_BITS #define CONFIG_ETRAX_PA_CHANGEABLE_BITS 0xFF #endif #ifndef CONFIG_ETRAX_PB_CHANGEABLE_BITS #define CONFIG_ETRAX_PB_CHANGEABLE_BITS 0xFF #endif static unsigned char changeable_dir[NUM_PORTS] = { CONFIG_ETRAX_PA_CHANGEABLE_DIR, CONFIG_ETRAX_PB_CHANGEABLE_DIR }; static unsigned char changeable_bits[NUM_PORTS] = { CONFIG_ETRAX_PA_CHANGEABLE_BITS, CONFIG_ETRAX_PB_CHANGEABLE_BITS }; static volatile unsigned char *dir[NUM_PORTS] = { R_PORT_PA_DIR, R_PORT_PB_DIR }; static volatile unsigned char *dir_shadow[NUM_PORTS] = { &port_pa_dir_shadow, &port_pb_dir_shadow }; /* All bits in port g that can change dir. */ static const unsigned long int changeable_dir_g_mask = 0x01FFFF01; /* Port G is 32 bit, handle it special, some bits are both inputs and outputs at the same time, only some of the bits can change direction and some of them in groups of 8 bit. */ static unsigned long changeable_dir_g; static unsigned long dir_g_in_bits; static unsigned long dir_g_out_bits; static unsigned long dir_g_shadow; /* 1=output */ #define USE_PORTS(priv) ((priv)->minor <= GPIO_MINOR_B) static unsigned int gpio_poll(struct file *file, poll_table *wait) { unsigned int mask = 0; struct gpio_private *priv = file->private_data; unsigned long data; unsigned long flags; spin_lock_irqsave(&gpio_lock, flags); poll_wait(file, &priv->alarm_wq, wait); if (priv->minor == GPIO_MINOR_A) { unsigned long tmp; data = *R_PORT_PA_DATA; /* PA has support for high level interrupt - * lets activate for those low and with highalarm set */ tmp = ~data & priv->highalarm & 0xFF; tmp = (tmp << R_IRQ_MASK1_SET__pa0__BITNR); gpio_pa_irq_enabled_mask |= tmp; *R_IRQ_MASK1_SET = tmp; } else if (priv->minor == GPIO_MINOR_B) data = *R_PORT_PB_DATA; else if (priv->minor == GPIO_MINOR_G) data = *R_PORT_G_DATA; else { mask = 0; goto out; } if ((data & priv->highalarm) || (~data & priv->lowalarm)) { mask = POLLIN|POLLRDNORM; } out: spin_unlock_irqrestore(&gpio_lock, flags); DP(printk("gpio_poll ready: mask 0x%08X\n", mask)); return mask; } int etrax_gpio_wake_up_check(void) { struct gpio_private *priv; unsigned long data = 0; int ret = 0; unsigned long flags; spin_lock_irqsave(&gpio_lock, flags); priv = alarmlist; while (priv) { if (USE_PORTS(priv)) data = *priv->port; else if (priv->minor == GPIO_MINOR_G) data = *R_PORT_G_DATA; if ((data & priv->highalarm) || (~data & priv->lowalarm)) { DP(printk("etrax_gpio_wake_up_check %i\n",priv->minor)); wake_up_interruptible(&priv->alarm_wq); ret = 1; } priv = priv->next; } spin_unlock_irqrestore(&gpio_lock, flags); return ret; } static irqreturn_t gpio_poll_timer_interrupt(int irq, void *dev_id) { if (gpio_some_alarms) { etrax_gpio_wake_up_check(); return IRQ_HANDLED; } return IRQ_NONE; } static irqreturn_t gpio_interrupt(int irq, void *dev_id) { unsigned long tmp; unsigned long flags; spin_lock_irqsave(&gpio_lock, flags); /* Find what PA interrupts are active */ tmp = (*R_IRQ_READ1); /* Find those that we have enabled */ tmp &= gpio_pa_irq_enabled_mask; /* Clear them.. */ *R_IRQ_MASK1_CLR = tmp; gpio_pa_irq_enabled_mask &= ~tmp; spin_unlock_irqrestore(&gpio_lock, flags); if (gpio_some_alarms) return IRQ_RETVAL(etrax_gpio_wake_up_check()); return IRQ_NONE; } static void gpio_write_bit(struct gpio_private *priv, unsigned char data, int bit) { *priv->port = *priv->shadow &= ~(priv->clk_mask); if (data & 1 << bit) *priv->port = *priv->shadow |= priv->data_mask; else *priv->port = *priv->shadow &= ~(priv->data_mask); /* For FPGA: min 5.0ns (DCC) before CCLK high */ *priv->port = *priv->shadow |= priv->clk_mask; } static void gpio_write_byte(struct gpio_private *priv, unsigned char data) { int i; if (priv->write_msb) for (i = 7; i >= 0; i--) gpio_write_bit(priv, data, i); else for (i = 0; i <= 7; i++) gpio_write_bit(priv, data, i); } static ssize_t gpio_write(struct file *file, const char __user *buf, size_t count, loff_t *off) { struct gpio_private *priv = file->private_data; unsigned long flags; ssize_t retval = count; if (priv->minor != GPIO_MINOR_A && priv->minor != GPIO_MINOR_B) return -EFAULT; if (!access_ok(VERIFY_READ, buf, count)) return -EFAULT; spin_lock_irqsave(&gpio_lock, flags); /* It must have been configured using the IO_CFG_WRITE_MODE */ /* Perhaps a better error code? */ if (priv->clk_mask == 0 || priv->data_mask == 0) { retval = -EPERM; goto out; } D(printk(KERN_DEBUG "gpio_write: %02X to data 0x%02X " "clk 0x%02X msb: %i\n", count, priv->data_mask, priv->clk_mask, priv->write_msb)); while (count--) gpio_write_byte(priv, *buf++); out: spin_unlock_irqrestore(&gpio_lock, flags); return retval; } static int gpio_open(struct inode *inode, struct file *filp) { struct gpio_private *priv; int p = iminor(inode); unsigned long flags; if (p > GPIO_MINOR_LAST) return -EINVAL; priv = kzalloc(sizeof(struct gpio_private), GFP_KERNEL); if (!priv) return -ENOMEM; priv->minor = p; /* initialize the io/alarm struct */ if (USE_PORTS(priv)) { /* A and B */ priv->port = ports[p]; priv->shadow = shads[p]; priv->dir = dir[p]; priv->dir_shadow = dir_shadow[p]; priv->changeable_dir = changeable_dir[p]; priv->changeable_bits = changeable_bits[p]; } else { priv->port = NULL; priv->shadow = NULL; priv->dir = NULL; priv->dir_shadow = NULL; priv->changeable_dir = 0; priv->changeable_bits = 0; } priv->highalarm = 0; priv->lowalarm = 0; priv->clk_mask = 0; priv->data_mask = 0; init_waitqueue_head(&priv->alarm_wq); filp->private_data = priv; /* link it into our alarmlist */ spin_lock_irqsave(&gpio_lock, flags); priv->next = alarmlist; alarmlist = priv; spin_unlock_irqrestore(&gpio_lock, flags); return 0; } static int gpio_release(struct inode *inode, struct file *filp) { struct gpio_private *p; struct gpio_private *todel; unsigned long flags; spin_lock_irqsave(&gpio_lock, flags); p = alarmlist; todel = filp->private_data; /* unlink from alarmlist and free the private structure */ if (p == todel) { alarmlist = todel->next; } else { while (p->next != todel) p = p->next; p->next = todel->next; } kfree(todel); /* Check if there are still any alarms set */ p = alarmlist; while (p) { if (p->highalarm | p->lowalarm) { gpio_some_alarms = 1; goto out; } p = p->next; } gpio_some_alarms = 0; out: spin_unlock_irqrestore(&gpio_lock, flags); return 0; } /* Main device API. ioctl's to read/set/clear bits, as well as to * set alarms to wait for using a subsequent select(). */ unsigned long inline setget_input(struct gpio_private *priv, unsigned long arg) { /* Set direction 0=unchanged 1=input, * return mask with 1=input */ if (USE_PORTS(priv)) { *priv->dir = *priv->dir_shadow &= ~((unsigned char)arg & priv->changeable_dir); return ~(*priv->dir_shadow) & 0xFF; /* Only 8 bits */ } if (priv->minor != GPIO_MINOR_G) return 0; /* We must fiddle with R_GEN_CONFIG to change dir */ if (((arg & dir_g_in_bits) != arg) && (arg & changeable_dir_g)) { arg &= changeable_dir_g; /* Clear bits in genconfig to set to input */ if (arg & (1<<0)) { genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, g0dir); dir_g_in_bits |= (1<<0); dir_g_out_bits &= ~(1<<0); } if ((arg & 0x0000FF00) == 0x0000FF00) { genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, g8_15dir); dir_g_in_bits |= 0x0000FF00; dir_g_out_bits &= ~0x0000FF00; } if ((arg & 0x00FF0000) == 0x00FF0000) { genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, g16_23dir); dir_g_in_bits |= 0x00FF0000; dir_g_out_bits &= ~0x00FF0000; } if (arg & (1<<24)) { genconfig_shadow &= ~IO_MASK(R_GEN_CONFIG, g24dir); dir_g_in_bits |= (1<<24); dir_g_out_bits &= ~(1<<24); } D(printk(KERN_DEBUG "gpio: SETINPUT on port G set " "genconfig to 0x%08lX " "in_bits: 0x%08lX " "out_bits: 0x%08lX\n", (unsigned long)genconfig_shadow, dir_g_in_bits, dir_g_out_bits)); *R_GEN_CONFIG = genconfig_shadow; /* Must be a >120 ns delay before writing this again */ } return dir_g_in_bits; } /* setget_input */ unsigned long inline setget_output(struct gpio_private *priv, unsigned long arg) { if (USE_PORTS(priv)) { *priv->dir = *priv->dir_shadow |= ((unsigned char)arg & priv->changeable_dir); return *priv->dir_shadow; } if (priv->minor != GPIO_MINOR_G) return 0; /* We must fiddle with R_GEN_CONFIG to change dir */ if (((arg & dir_g_out_bits) != arg) && (arg & changeable_dir_g)) { /* Set bits in genconfig to set to output */ if (arg & (1<<0)) { genconfig_shadow |= IO_MASK(R_GEN_CONFIG, g0dir); dir_g_out_bits |= (1<<0); dir_g_in_bits &= ~(1<<0); } if ((arg & 0x0000FF00) == 0x0000FF00) { genconfig_shadow |= IO_MASK(R_GEN_CONFIG, g8_15dir); dir_g_out_bits |= 0x0000FF00; dir_g_in_bits &= ~0x0000FF00; } if ((arg & 0x00FF0000) == 0x00FF0000) { genconfig_shadow |= IO_MASK(R_GEN_CONFIG, g16_23dir); dir_g_out_bits |= 0x00FF0000; dir_g_in_bits &= ~0x00FF0000; } if (arg & (1<<24)) { genconfig_shadow |= IO_MASK(R_GEN_CONFIG, g24dir); dir_g_out_bits |= (1<<24); dir_g_in_bits &= ~(1<<24); } D(printk(KERN_INFO "gpio: SETOUTPUT on port G set " "genconfig to 0x%08lX " "in_bits: 0x%08lX " "out_bits: 0x%08lX\n", (unsigned long)genconfig_shadow, dir_g_in_bits, dir_g_out_bits)); *R_GEN_CONFIG = genconfig_shadow; /* Must be a >120 ns delay before writing this again */ } return dir_g_out_bits & 0x7FFFFFFF; } /* setget_output */ static int gpio_leds_ioctl(unsigned int cmd, unsigned long arg); static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { unsigned long flags; unsigned long val; int ret = 0; struct gpio_private *priv = file->private_data; if (_IOC_TYPE(cmd) != ETRAXGPIO_IOCTYPE) return -EINVAL; switch (_IOC_NR(cmd)) { case IO_READBITS: /* Use IO_READ_INBITS and IO_READ_OUTBITS instead */ // read the port spin_lock_irqsave(&gpio_lock, flags); if (USE_PORTS(priv)) { ret = *priv->port; } else if (priv->minor == GPIO_MINOR_G) { ret = (*R_PORT_G_DATA) & 0x7FFFFFFF; } spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_SETBITS: // set changeable bits with a 1 in arg spin_lock_irqsave(&gpio_lock, flags); if (USE_PORTS(priv)) { *priv->port = *priv->shadow |= ((unsigned char)arg & priv->changeable_bits); } else if (priv->minor == GPIO_MINOR_G) { *R_PORT_G_DATA = port_g_data_shadow |= (arg & dir_g_out_bits); } spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_CLRBITS: // clear changeable bits with a 1 in arg spin_lock_irqsave(&gpio_lock, flags); if (USE_PORTS(priv)) { *priv->port = *priv->shadow &= ~((unsigned char)arg & priv->changeable_bits); } else if (priv->minor == GPIO_MINOR_G) { *R_PORT_G_DATA = port_g_data_shadow &= ~((unsigned long)arg & dir_g_out_bits); } spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_HIGHALARM: // set alarm when bits with 1 in arg go high spin_lock_irqsave(&gpio_lock, flags); priv->highalarm |= arg; gpio_some_alarms = 1; spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_LOWALARM: // set alarm when bits with 1 in arg go low spin_lock_irqsave(&gpio_lock, flags); priv->lowalarm |= arg; gpio_some_alarms = 1; spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_CLRALARM: /* clear alarm for bits with 1 in arg */ spin_lock_irqsave(&gpio_lock, flags); priv->highalarm &= ~arg; priv->lowalarm &= ~arg; { /* Must update gpio_some_alarms */ struct gpio_private *p = alarmlist; int some_alarms; p = alarmlist; some_alarms = 0; while (p) { if (p->highalarm | p->lowalarm) { some_alarms = 1; break; } p = p->next; } gpio_some_alarms = some_alarms; } spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_READDIR: /* Use IO_SETGET_INPUT/OUTPUT instead! */ /* Read direction 0=input 1=output */ spin_lock_irqsave(&gpio_lock, flags); if (USE_PORTS(priv)) { ret = *priv->dir_shadow; } else if (priv->minor == GPIO_MINOR_G) { /* Note: Some bits are both in and out, * Those that are dual is set here as well. */ ret = (dir_g_shadow | dir_g_out_bits) & 0x7FFFFFFF; } spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_SETINPUT: /* Use IO_SETGET_INPUT instead! */ /* Set direction 0=unchanged 1=input, * return mask with 1=input */ spin_lock_irqsave(&gpio_lock, flags); ret = setget_input(priv, arg) & 0x7FFFFFFF; spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_SETOUTPUT: /* Use IO_SETGET_OUTPUT instead! */ /* Set direction 0=unchanged 1=output, * return mask with 1=output */ spin_lock_irqsave(&gpio_lock, flags); ret = setget_output(priv, arg) & 0x7FFFFFFF; spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_SHUTDOWN: spin_lock_irqsave(&gpio_lock, flags); SOFT_SHUTDOWN(); spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_GET_PWR_BT: spin_lock_irqsave(&gpio_lock, flags); #if defined (CONFIG_ETRAX_SOFT_SHUTDOWN) ret = (*R_PORT_G_DATA & ( 1 << CONFIG_ETRAX_POWERBUTTON_BIT)); #else ret = 0; #endif spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_CFG_WRITE_MODE: spin_lock_irqsave(&gpio_lock, flags); priv->clk_mask = arg & 0xFF; priv->data_mask = (arg >> 8) & 0xFF; priv->write_msb = (arg >> 16) & 0x01; /* Check if we're allowed to change the bits and * the direction is correct */ if (!((priv->clk_mask & priv->changeable_bits) && (priv->data_mask & priv->changeable_bits) && (priv->clk_mask & *priv->dir_shadow) && (priv->data_mask & *priv->dir_shadow))) { priv->clk_mask = 0; priv->data_mask = 0; ret = -EPERM; } spin_unlock_irqrestore(&gpio_lock, flags); break; case IO_READ_INBITS: /* *arg is result of reading the input pins */ spin_lock_irqsave(&gpio_lock, flags); if (USE_PORTS(priv)) { val = *priv->port; } else if (priv->minor == GPIO_MINOR_G) { val = *R_PORT_G_DATA; } spin_unlock_irqrestore(&gpio_lock, flags); if (copy_to_user((void __user *)arg, &val, sizeof(val))) ret = -EFAULT; break; case IO_READ_OUTBITS: /* *arg is result of reading the output shadow */ spin_lock_irqsave(&gpio_lock, flags); if (USE_PORTS(priv)) { val = *priv->shadow; } else if (priv->minor == GPIO_MINOR_G) { val = port_g_data_shadow; } spin_unlock_irqrestore(&gpio_lock, flags); if (copy_to_user((void __user *)arg, &val, sizeof(val))) ret = -EFAULT; break; case IO_SETGET_INPUT: /* bits set in *arg is set to input, * *arg updated with current input pins. */ if (copy_from_user(&val, (void __user *)arg, sizeof(val))) { ret = -EFAULT; break; } spin_lock_irqsave(&gpio_lock, flags); val = setget_input(priv, val); spin_unlock_irqrestore(&gpio_lock, flags); if (copy_to_user((void __user *)arg, &val, sizeof(val))) ret = -EFAULT; break; case IO_SETGET_OUTPUT: /* bits set in *arg is set to output, * *arg updated with current output pins. */ if (copy_from_user(&val, (void __user *)arg, sizeof(val))) { ret = -EFAULT; break; } spin_lock_irqsave(&gpio_lock, flags); val = setget_output(priv, val); spin_unlock_irqrestore(&gpio_lock, flags); if (copy_to_user((void __user *)arg, &val, sizeof(val))) ret = -EFAULT; break; default: spin_lock_irqsave(&gpio_lock, flags); if (priv->minor == GPIO_MINOR_LEDS) ret = gpio_leds_ioctl(cmd, arg); else ret = -EINVAL; spin_unlock_irqrestore(&gpio_lock, flags); } /* switch */ return ret; } static int gpio_leds_ioctl(unsigned int cmd, unsigned long arg) { unsigned char green; unsigned char red; switch (_IOC_NR(cmd)) { case IO_LEDACTIVE_SET: green = ((unsigned char)arg) & 1; red = (((unsigned char)arg) >> 1) & 1; CRIS_LED_ACTIVE_SET_G(green); CRIS_LED_ACTIVE_SET_R(red); break; case IO_LED_SETBIT: CRIS_LED_BIT_SET(arg); break; case IO_LED_CLRBIT: CRIS_LED_BIT_CLR(arg); break; default: return -EINVAL; } /* switch */ return 0; } static const struct file_operations gpio_fops = { .owner = THIS_MODULE, .poll = gpio_poll, .unlocked_ioctl = gpio_ioctl, .write = gpio_write, .open = gpio_open, .release = gpio_release, .llseek = noop_llseek, }; static void ioif_watcher(const unsigned int gpio_in_available, const unsigned int gpio_out_available, const unsigned char pa_available, const unsigned char pb_available) { unsigned long int flags; D(printk(KERN_DEBUG "gpio.c: ioif_watcher called\n")); D(printk(KERN_DEBUG "gpio.c: G in: 0x%08x G out: 0x%08x " "PA: 0x%02x PB: 0x%02x\n", gpio_in_available, gpio_out_available, pa_available, pb_available)); spin_lock_irqsave(&gpio_lock, flags); dir_g_in_bits = gpio_in_available; dir_g_out_bits = gpio_out_available; /* Initialise the dir_g_shadow etc. depending on genconfig */ /* 0=input 1=output */ if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g0dir, out)) dir_g_shadow |= (1 << 0); if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g8_15dir, out)) dir_g_shadow |= 0x0000FF00; if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g16_23dir, out)) dir_g_shadow |= 0x00FF0000; if (genconfig_shadow & IO_STATE(R_GEN_CONFIG, g24dir, out)) dir_g_shadow |= (1 << 24); changeable_dir_g = changeable_dir_g_mask; changeable_dir_g &= dir_g_out_bits; changeable_dir_g &= dir_g_in_bits; /* Correct the bits that can change direction */ dir_g_out_bits &= ~changeable_dir_g; dir_g_out_bits |= dir_g_shadow; dir_g_in_bits &= ~changeable_dir_g; dir_g_in_bits |= (~dir_g_shadow & changeable_dir_g); spin_unlock_irqrestore(&gpio_lock, flags); printk(KERN_INFO "GPIO port G: in_bits: 0x%08lX out_bits: 0x%08lX " "val: %08lX\n", dir_g_in_bits, dir_g_out_bits, (unsigned long)*R_PORT_G_DATA); printk(KERN_INFO "GPIO port G: dir: %08lX changeable: %08lX\n", dir_g_shadow, changeable_dir_g); } /* main driver initialization routine, called from mem.c */ static int __init gpio_init(void) { int res; #if defined (CONFIG_ETRAX_CSP0_LEDS) int i; #endif res = register_chrdev(GPIO_MAJOR, gpio_name, &gpio_fops); if (res < 0) { printk(KERN_ERR "gpio: couldn't get a major number.\n"); return res; } /* Clear all leds */ #if defined (CONFIG_ETRAX_CSP0_LEDS) || defined (CONFIG_ETRAX_PA_LEDS) || defined (CONFIG_ETRAX_PB_LEDS) CRIS_LED_NETWORK_SET(0); CRIS_LED_ACTIVE_SET(0); CRIS_LED_DISK_READ(0); CRIS_LED_DISK_WRITE(0); #if defined (CONFIG_ETRAX_CSP0_LEDS) for (i = 0; i < 32; i++) CRIS_LED_BIT_SET(i); #endif #endif /* The I/O interface allocation watcher will be called when * registering it. */ if (cris_io_interface_register_watcher(ioif_watcher)){ printk(KERN_WARNING "gpio_init: Failed to install IO " "if allocator watcher\n"); } printk(KERN_INFO "ETRAX 100LX GPIO driver v2.5, (c) 2001-2008 " "Axis Communications AB\n"); /* We call etrax_gpio_wake_up_check() from timer interrupt and * from default_idle() in kernel/process.c * The check in default_idle() reduces latency from ~15 ms to ~6 ms * in some tests. */ res = request_irq(TIMER0_IRQ_NBR, gpio_poll_timer_interrupt, IRQF_SHARED, "gpio poll", gpio_name); if (res) { printk(KERN_CRIT "err: timer0 irq for gpio\n"); return res; } res = request_irq(PA_IRQ_NBR, gpio_interrupt, IRQF_SHARED, "gpio PA", gpio_name); if (res) printk(KERN_CRIT "err: PA irq for gpio\n"); return res; } /* this makes sure that gpio_init is called during kernel boot */ module_init(gpio_init);
null
null
null
null
87,640
36,611
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
36,611
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_string.h" #include "third_party/blink/renderer/platform/bindings/v8_binding.h" namespace blink { void TraceWrapperV8String::Concat(v8::Isolate* isolate, const String& string) { DCHECK(isolate); v8::HandleScope handle_scope(isolate); v8::Local<v8::String> target_string = (string_.IsEmpty()) ? V8String(isolate, string) : v8::String::Concat(string_.NewLocal(isolate), V8String(isolate, string)); string_.Set(isolate, target_string); } String TraceWrapperV8String::Flatten(v8::Isolate* isolate) const { if (IsEmpty()) return String(); DCHECK(isolate); v8::HandleScope handle_scope(isolate); return V8StringToWebCoreString<String>(string_.NewLocal(isolate), kExternalize); } } // namespace blink
null
null
null
null
33,474
15,761
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
15,761
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SYNC_SYNCABLE_METAHANDLE_SET_H_ #define COMPONENTS_SYNC_SYNCABLE_METAHANDLE_SET_H_ #include <stdint.h> #include <set> namespace syncer { namespace syncable { using MetahandleSet = std::set<int64_t>; } // namespace syncable } // namespace syncer #endif // COMPONENTS_SYNC_SYNCABLE_METAHANDLE_SET_H_
null
null
null
null
12,624
38,154
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
38,154
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper_transform_cache.h" #include "third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h" namespace blink { // All transform caches invalidate themselves by tracking a local cache // generation, and invalidating their cache if their cache generation disagrees // with s_global_generation. unsigned GeometryMapperTransformCache::s_global_generation; void GeometryMapperTransformCache::ClearCache() { s_global_generation++; } // Computes flatten(m) ^ -1, return true if the inversion succeeded. static bool InverseProjection(const TransformationMatrix& m, TransformationMatrix& out) { out = m; out.FlattenTo2d(); if (!out.IsInvertible()) return false; out = out.Inverse(); return true; } void GeometryMapperTransformCache::Update( const TransformPaintPropertyNode& node) { DCHECK_NE(cache_generation_, s_global_generation); cache_generation_ = s_global_generation; if (!node.Parent()) { to_screen_.MakeIdentity(); to_screen_is_invertible_ = true; projection_from_screen_.MakeIdentity(); projection_from_screen_is_valid_ = true; plane_root_ = &node; to_plane_root_.MakeIdentity(); from_plane_root_.MakeIdentity(); return; } const GeometryMapperTransformCache& parent = node.Parent()->GetTransformCache(); TransformationMatrix local = node.Matrix(); local.ApplyTransformOrigin(node.Origin()); to_screen_ = parent.to_screen_; if (node.FlattensInheritedTransform()) to_screen_.FlattenTo2d(); to_screen_.Multiply(local); to_screen_is_invertible_ = to_screen_.IsInvertible(); projection_from_screen_is_valid_ = InverseProjection(to_screen_, projection_from_screen_); if (!local.IsFlat() || !local.IsInvertible()) { plane_root_ = &node; to_plane_root_.MakeIdentity(); from_plane_root_.MakeIdentity(); } else { // (local.IsFlat() && local.IsInvertible()) plane_root_ = parent.plane_root_; to_plane_root_ = parent.to_plane_root_; to_plane_root_.Multiply(local); from_plane_root_ = local.Inverse(); from_plane_root_.Multiply(parent.from_plane_root_); } } } // namespace blink
null
null
null
null
35,017
24,157
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
24,157
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/download/save_types.h" #include "base/files/file_path.h" namespace content { SaveFileCreateInfo::SaveFileCreateInfo(const base::FilePath& path, const GURL& url, SaveItemId save_item_id, SavePackageId save_package_id, int render_process_id, int render_frame_routing_id, SaveFileSource save_source) : path(path), url(url), save_item_id(save_item_id), save_package_id(save_package_id), render_process_id(render_process_id), render_frame_routing_id(render_frame_routing_id), save_source(save_source) {} SaveFileCreateInfo::SaveFileCreateInfo(const GURL& url, const GURL& final_url, SaveItemId save_item_id, SavePackageId save_package_id, int render_process_id, int render_frame_routing_id, const std::string& content_disposition) : url(url), final_url(final_url), save_item_id(save_item_id), save_package_id(save_package_id), render_process_id(render_process_id), render_frame_routing_id(render_frame_routing_id), content_disposition(content_disposition), save_source(SaveFileCreateInfo::SAVE_FILE_FROM_NET) {} SaveFileCreateInfo::SaveFileCreateInfo(const SaveFileCreateInfo& other) = default; SaveFileCreateInfo::~SaveFileCreateInfo() {} } // namespace content
null
null
null
null
21,020
40,611
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
40,611
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2017 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CRASHPAD_UTIL_POSIX_SIGNALS_H_ #define CRASHPAD_UTIL_POSIX_SIGNALS_H_ #include <signal.h> #include "base/macros.h" namespace crashpad { //! \brief Utilities for handling POSIX signals. class Signals { public: //! \brief A signal number used by Crashpad to simulate signals. static constexpr int kSimulatedSigno = -1; //! \brief The type used for `struct sigaction::sa_sigaction`. using Handler = void (*)(int, siginfo_t*, void*); //! \brief A group of `struct sigaction` structures corresponding to a set //! of signals’ previous actions, addressable by signal number. //! //! This type is used to store previous signal actions when new actions are //! installed in batch by InstallCrashHandlers() or //! InstallTerminateHandlers(). //! //! This object is not initialized by any constructor. Its expected initial //! state is to have its contents filled with zeroes. Because signal handlers //! are stateless (there is no “context” parameter), any state must be //! accessed via objects of static storage duration, and it is expected that //! objects of this class will only ever exist with static storage duration, //! which in the absence of a constructor will be zero-initialized as //! expected. In the event that an object of this class must exist with a //! different storage duration, such as automatic or dynamic storage duration, //! it must be explicitly initialized. For example: `OldActions old_actions = //! {};`. class OldActions { public: // DISALLOW_COPY_AND_ASSIGN removes the default constructor, so explicitly // opt for it. This should not result in any static initialization code even // when an object of this class is given static storage duration. OldActions() = default; //! \brief Returns a `struct sigaction` structure corresponding to the //! given signal. //! //! \note This method is safe to call from a signal handler. struct sigaction* ActionForSignal(int sig); private: // As a small storage optimization, don’t waste any space on a slot for // signal 0, because there is no signal 0. struct sigaction actions_[NSIG - 1]; DISALLOW_COPY_AND_ASSIGN(OldActions); }; //! \brief Installs a new signal handler. //! //! \param[in] sig The signal number to handle. //! \param[in] handler A signal-handling function to execute, used as the //! `struct sigaction::sa_sigaction` field when calling `sigaction()`. //! \param[in] flags Flags to pass to `sigaction()` in the `struct //! sigaction::sa_flags` field. `SA_SIGINFO` will be specified implicitly. //! \param[out] old_action The previous action for the signal, replaced by the //! new action. May be `nullptr` if not needed. //! //! \return `true` on success. `false` on failure with a message logged. //! //! \warning This function may not be called from a signal handler because of //! its use of logging. See RestoreHandlerAndReraiseSignalOnReturn() //! instead. static bool InstallHandler(int sig, Handler handler, int flags, struct sigaction* old_action); //! \brief Installs `SIG_DFL` for the signal \a sig. //! //! \param[in] sig The signal to set the default action for. //! //! \return `true` on success, `false` on failure with errno set. No message //! is logged. static bool InstallDefaultHandler(int sig); //! \brief Installs a new signal handler for all signals associated with //! crashes. //! //! Signals associated with crashes are those whose default dispositions //! involve creating a core dump. The precise set of signals involved varies //! between operating systems. //! //! A single signal may either be associated with a crash or with termination //! (see InstallTerminateHandlers()), and perhaps neither, but never both. //! //! \param[in] handler A signal-handling function to execute, used as the //! `struct sigaction::sa_sigaction` field when calling `sigaction()`. //! \param[in] flags Flags to pass to `sigaction()` in the `struct //! sigaction::sa_flags` field. `SA_SIGINFO` will be specified implicitly. //! \param[out] old_actions The previous actions for the signals, replaced by //! the new action. May be `nullptr` if not needed. The same \a //! old_actions object may be used for calls to both this function and //! InstallTerminateHandlers(). //! //! \return `true` on success. `false` on failure with a message logged. //! //! \warning This function may not be called from a signal handler because of //! its use of logging. See RestoreHandlerAndReraiseSignalOnReturn() //! instead. static bool InstallCrashHandlers(Handler handler, int flags, OldActions* old_actions); //! \brief Installs a new signal handler for all signals associated with //! termination. //! //! Signals associated with termination are those whose default dispositions //! involve terminating the process without creating a core dump. The precise //! set of signals involved varies between operating systems. //! //! A single signal may either be associated with termination or with a //! crash (see InstalCrashHandlers()), and perhaps neither, but never both. //! //! \param[in] handler A signal-handling function to execute, used as the //! `struct sigaction::sa_sigaction` field when calling `sigaction()`. //! \param[in] flags Flags to pass to `sigaction()` in the `struct //! sigaction::sa_flags` field. `SA_SIGINFO` will be specified implicitly. //! \param[out] old_actions The previous actions for the signals, replaced by //! the new action. May be `nullptr` if not needed. The same \a //! old_actions object may be used for calls to both this function and //! InstallCrashHandlers(). //! //! \return `true` on success. `false` on failure with a message logged. //! //! \warning This function may not be called from a signal handler because of //! its use of logging. See RestoreHandlerAndReraiseSignalOnReturn() //! instead. static bool InstallTerminateHandlers(Handler handler, int flags, OldActions* old_actions); //! \brief Determines whether a signal will be re-raised autonomously upon //! return from a signal handler. //! //! Certain signals, when generated synchronously in response to a hardware //! fault, are unrecoverable. Upon return from the signal handler, the same //! action that triggered the signal to be raised initially will be retried, //! and unless the signal handler took action to mitigate this error, the same //! signal will be re-raised. As an example, a CPU will not be able to read //! unmapped memory (causing `SIGSEGV`), thus the signal will be re-raised //! upon return from the signal handler unless the signal handler established //! a memory mapping where required. //! //! It is important to distinguish between these synchronous signals generated //! in response to a hardware fault and signals generated asynchronously or in //! software. As an example, `SIGSEGV` will not re-raise autonomously if sent //! by `kill()`. //! //! This function distinguishes between signals that can re-raise //! autonomously, and for those that can, between instances of the signal that //! were generated synchronously in response to a hardware fault and instances //! that were generated by other means. //! //! \param[in] siginfo A pointer to a `siginfo_t` object received by a signal //! handler. //! //! \return `true` if the signal being handled will re-raise itself //! autonomously upon return from a signal handler. `false` if it will //! not. When this function returns `false`, a signal can still be //! re-raised upon return from a signal handler by calling `raise()` from //! within the signal handler. //! //! \note This function is safe to call from a signal handler. static bool WillSignalReraiseAutonomously(const siginfo_t* siginfo); //! \brief Restores a previous signal action and arranges to re-raise a signal //! on return from a signal handler. //! //! \param[in] siginfo A pointer to a `siginfo_t` object received by a signal //! handler. //! \param[in] old_action The previous action for the signal, which will be //! re-established as the signal’s action. May be `nullptr`, which directs //! the default action for the signal to be used. //! //! If this function fails, it will immediately call `_exit()` and set an exit //! status of `191`. //! //! \note This function may only be called from a signal handler. static void RestoreHandlerAndReraiseSignalOnReturn( const siginfo_t* siginfo, const struct sigaction* old_action); //! \brief Determines whether a signal is associated with a crash. //! //! Signals associated with crashes are those whose default dispositions //! involve creating a core dump. The precise set of signals involved varies //! between operating systems. //! //! \param[in] sig The signal to test. //! //! \return `true` if \a sig is associated with a crash. `false` otherwise. //! //! \note This function is safe to call from a signal handler. static bool IsCrashSignal(int sig); //! \brief Determines whether a signal is associated with termination. //! //! Signals associated with termination are those whose default dispositions //! involve terminating the process without creating a core dump. The precise //! set of signals involved varies between operating systems. //! //! \param[in] sig The signal to test. //! //! \return `true` if \a sig is associated with termination. `false` //! otherwise. //! //! \note This function is safe to call from a signal handler. static bool IsTerminateSignal(int sig); private: DISALLOW_IMPLICIT_CONSTRUCTORS(Signals); }; } // namespace crashpad #endif // CRASHPAD_UTIL_POSIX_SIGNALS_H_
null
null
null
null
37,474
33,192
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
33,192
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_PSEUDO_ELEMENT_DATA_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_PSEUDO_ELEMENT_DATA_H_ #include "base/macros.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { class PseudoElementData final : public GarbageCollected<PseudoElementData> { public: static PseudoElementData* Create(); void SetPseudoElement(PseudoId, PseudoElement*); PseudoElement* GetPseudoElement(PseudoId) const; bool HasPseudoElements() const; void ClearPseudoElements(); void Trace(blink::Visitor* visitor) { visitor->Trace(generated_before_); visitor->Trace(generated_after_); visitor->Trace(generated_first_letter_); visitor->Trace(backdrop_); } private: PseudoElementData() = default; Member<PseudoElement> generated_before_; Member<PseudoElement> generated_after_; Member<PseudoElement> generated_first_letter_; Member<PseudoElement> backdrop_; DISALLOW_COPY_AND_ASSIGN(PseudoElementData); }; inline PseudoElementData* PseudoElementData::Create() { return new PseudoElementData(); } inline bool PseudoElementData::HasPseudoElements() const { return generated_before_ || generated_after_ || backdrop_ || generated_first_letter_; } inline void PseudoElementData::ClearPseudoElements() { SetPseudoElement(kPseudoIdBefore, nullptr); SetPseudoElement(kPseudoIdAfter, nullptr); SetPseudoElement(kPseudoIdBackdrop, nullptr); SetPseudoElement(kPseudoIdFirstLetter, nullptr); } inline void PseudoElementData::SetPseudoElement(PseudoId pseudo_id, PseudoElement* element) { switch (pseudo_id) { case kPseudoIdBefore: if (generated_before_) generated_before_->Dispose(); generated_before_ = element; break; case kPseudoIdAfter: if (generated_after_) generated_after_->Dispose(); generated_after_ = element; break; case kPseudoIdBackdrop: if (backdrop_) backdrop_->Dispose(); backdrop_ = element; break; case kPseudoIdFirstLetter: if (generated_first_letter_) generated_first_letter_->Dispose(); generated_first_letter_ = element; break; default: NOTREACHED(); } } inline PseudoElement* PseudoElementData::GetPseudoElement( PseudoId pseudo_id) const { switch (pseudo_id) { case kPseudoIdBefore: return generated_before_; case kPseudoIdAfter: return generated_after_; case kPseudoIdBackdrop: return backdrop_; case kPseudoIdFirstLetter: return generated_first_letter_; default: return nullptr; } } } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_PSEUDO_ELEMENT_DATA_H_
null
null
null
null
30,055
15,159
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
15,159
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/signin/core/browser/signin_status_metrics_provider_base.h" #include "base/metrics/histogram_macros.h" SigninStatusMetricsProviderBase::SigninStatusMetricsProviderBase() : signin_status_(UNKNOWN_SIGNIN_STATUS) {} SigninStatusMetricsProviderBase::~SigninStatusMetricsProviderBase() {} void SigninStatusMetricsProviderBase::RecordSigninStatusHistogram( SigninStatus signin_status) { UMA_HISTOGRAM_ENUMERATION("UMA.ProfileSignInStatus", signin_status, SIGNIN_STATUS_MAX); } void SigninStatusMetricsProviderBase::UpdateSigninStatus( SigninStatus new_status) { // The recorded sign-in status value can't be changed once it's recorded as // error until the next UMA upload. if (signin_status_ == ERROR_GETTING_SIGNIN_STATUS) return; signin_status_ = new_status; } void SigninStatusMetricsProviderBase::ResetSigninStatus() { signin_status_ = UNKNOWN_SIGNIN_STATUS; }
null
null
null
null
12,022
17,800
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
17,800
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <stdint.h> #include "base/logging.h" #include "base/memory/ptr_util.h" #include "components/webcrypto/algorithm_implementation.h" #include "components/webcrypto/algorithms/ec.h" #include "components/webcrypto/algorithms/util.h" #include "components/webcrypto/blink_key_handle.h" #include "components/webcrypto/crypto_data.h" #include "components/webcrypto/generate_key_result.h" #include "components/webcrypto/status.h" #include "crypto/openssl_util.h" #include "crypto/secure_util.h" #include "third_party/blink/public/platform/web_crypto_algorithm_params.h" #include "third_party/blink/public/platform/web_crypto_key.h" #include "third_party/blink/public/platform/web_crypto_key_algorithm.h" #include "third_party/boringssl/src/include/openssl/bn.h" #include "third_party/boringssl/src/include/openssl/digest.h" #include "third_party/boringssl/src/include/openssl/ec.h" #include "third_party/boringssl/src/include/openssl/ec_key.h" #include "third_party/boringssl/src/include/openssl/ecdsa.h" #include "third_party/boringssl/src/include/openssl/evp.h" #include "third_party/boringssl/src/include/openssl/mem.h" namespace webcrypto { namespace { // Extracts the OpenSSL key and digest from a WebCrypto key + algorithm. The // returned pkey pointer will remain valid as long as |key| is alive. Status GetPKeyAndDigest(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, EVP_PKEY** pkey, const EVP_MD** digest) { *pkey = GetEVP_PKEY(key); *digest = GetDigest(algorithm.EcdsaParams()->GetHash()); if (!*digest) return Status::ErrorUnsupported(); return Status::Success(); } // Gets the EC key's order size in bytes. Status GetEcGroupOrderSize(EVP_PKEY* pkey, size_t* order_size_bytes) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); EC_KEY* ec = EVP_PKEY_get0_EC_KEY(pkey); if (!ec) return Status::ErrorUnexpected(); const EC_GROUP* group = EC_KEY_get0_group(ec); bssl::UniquePtr<BIGNUM> order(BN_new()); if (!EC_GROUP_get_order(group, order.get(), nullptr)) return Status::OperationError(); *order_size_bytes = BN_num_bytes(order.get()); return Status::Success(); } // Formats a DER-encoded signature (ECDSA-Sig-Value as specified in RFC 3279) to // the signature format expected by WebCrypto (raw concatenated "r" and "s"). // // TODO(eroman): Where is the specification for WebCrypto's signature format? Status ConvertDerSignatureToWebCryptoSignature( EVP_PKEY* key, std::vector<uint8_t>* signature) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); bssl::UniquePtr<ECDSA_SIG> ecdsa_sig( ECDSA_SIG_from_bytes(signature->data(), signature->size())); if (!ecdsa_sig.get()) return Status::ErrorUnexpected(); // Determine the maximum length of r and s. size_t order_size_bytes; Status status = GetEcGroupOrderSize(key, &order_size_bytes); if (status.IsError()) return status; signature->resize(order_size_bytes * 2); if (!BN_bn2bin_padded(signature->data(), order_size_bytes, ecdsa_sig.get()->r)) { return Status::ErrorUnexpected(); } if (!BN_bn2bin_padded(&(*signature)[order_size_bytes], order_size_bytes, ecdsa_sig.get()->s)) { return Status::ErrorUnexpected(); } return Status::Success(); } // Formats a WebCrypto ECDSA signature to a DER-encoded signature // (ECDSA-Sig-Value as specified in RFC 3279). // // TODO(eroman): What is the specification for WebCrypto's signature format? // // If the signature length is incorrect (not 2 * order_size), then // Status::Success() is returned and |*incorrect_length| is set to true; // // Otherwise on success, der_signature is filled with a ASN.1 encoded // ECDSA-Sig-Value. Status ConvertWebCryptoSignatureToDerSignature( EVP_PKEY* key, const CryptoData& signature, std::vector<uint8_t>* der_signature, bool* incorrect_length) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); // Determine the length of r and s. size_t order_size_bytes; Status status = GetEcGroupOrderSize(key, &order_size_bytes); if (status.IsError()) return status; // If the size of the signature is incorrect, verification must fail. Success // is returned here rather than an error, so that the caller can fail // verification with a boolean, rather than reject the promise with an // exception. if (signature.byte_length() != 2 * order_size_bytes) { *incorrect_length = true; return Status::Success(); } *incorrect_length = false; // Construct an ECDSA_SIG from |signature|. bssl::UniquePtr<ECDSA_SIG> ecdsa_sig(ECDSA_SIG_new()); if (!ecdsa_sig) return Status::OperationError(); if (!BN_bin2bn(signature.bytes(), order_size_bytes, ecdsa_sig->r) || !BN_bin2bn(signature.bytes() + order_size_bytes, order_size_bytes, ecdsa_sig->s)) { return Status::ErrorUnexpected(); } // Encode the signature. uint8_t* der; size_t der_len; if (!ECDSA_SIG_to_bytes(&der, &der_len, ecdsa_sig.get())) return Status::OperationError(); der_signature->assign(der, der + der_len); OPENSSL_free(der); return Status::Success(); } class EcdsaImplementation : public EcAlgorithm { public: EcdsaImplementation() : EcAlgorithm(blink::kWebCryptoKeyUsageVerify, blink::kWebCryptoKeyUsageSign) {} const char* GetJwkAlgorithm( const blink::WebCryptoNamedCurve curve) const override { switch (curve) { case blink::kWebCryptoNamedCurveP256: return "ES256"; case blink::kWebCryptoNamedCurveP384: return "ES384"; case blink::kWebCryptoNamedCurveP521: // This is not a typo! ES512 means P-521 with SHA-512. return "ES512"; default: return nullptr; } } Status Sign(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, const CryptoData& data, std::vector<uint8_t>* buffer) const override { if (key.GetType() != blink::kWebCryptoKeyTypePrivate) return Status::ErrorUnexpectedKeyType(); crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); EVP_PKEY* private_key = nullptr; const EVP_MD* digest = nullptr; Status status = GetPKeyAndDigest(algorithm, key, &private_key, &digest); if (status.IsError()) return status; // NOTE: A call to EVP_DigestSignFinal() with a NULL second parameter // returns a maximum allocation size, while the call without a NULL returns // the real one, which may be smaller. bssl::ScopedEVP_MD_CTX ctx; size_t sig_len = 0; if (!EVP_DigestSignInit(ctx.get(), nullptr, digest, nullptr, private_key) || !EVP_DigestSignUpdate(ctx.get(), data.bytes(), data.byte_length()) || !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) { return Status::OperationError(); } buffer->resize(sig_len); if (!EVP_DigestSignFinal(ctx.get(), buffer->data(), &sig_len)) return Status::OperationError(); buffer->resize(sig_len); // ECDSA signing in BoringSSL outputs a DER-encoded (r,s). WebCrypto however // expects a padded bitstring that is r concatenated to s. Convert to the // expected format. return ConvertDerSignatureToWebCryptoSignature(private_key, buffer); } Status Verify(const blink::WebCryptoAlgorithm& algorithm, const blink::WebCryptoKey& key, const CryptoData& signature, const CryptoData& data, bool* signature_match) const override { if (key.GetType() != blink::kWebCryptoKeyTypePublic) return Status::ErrorUnexpectedKeyType(); crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); EVP_PKEY* public_key = nullptr; const EVP_MD* digest = nullptr; Status status = GetPKeyAndDigest(algorithm, key, &public_key, &digest); if (status.IsError()) return status; std::vector<uint8_t> der_signature; bool incorrect_length_signature = false; status = ConvertWebCryptoSignatureToDerSignature( public_key, signature, &der_signature, &incorrect_length_signature); if (status.IsError()) return status; if (incorrect_length_signature) { *signature_match = false; return Status::Success(); } bssl::ScopedEVP_MD_CTX ctx; if (!EVP_DigestVerifyInit(ctx.get(), nullptr, digest, nullptr, public_key) || !EVP_DigestVerifyUpdate(ctx.get(), data.bytes(), data.byte_length())) { return Status::OperationError(); } *signature_match = 1 == EVP_DigestVerifyFinal(ctx.get(), der_signature.data(), der_signature.size()); return Status::Success(); } }; } // namespace std::unique_ptr<AlgorithmImplementation> CreateEcdsaImplementation() { return base::WrapUnique(new EcdsaImplementation); } } // namespace webcrypto
null
null
null
null
14,663
3,136
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
156,193
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * MPEG-1/2 demuxer * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #include "avio_internal.h" #include "internal.h" #include "mpeg.h" #if CONFIG_VOBSUB_DEMUXER # include "subtitles.h" # include "libavutil/bprint.h" # include "libavutil/opt.h" #endif #include "libavutil/avassert.h" /*********************************************/ /* demux code */ #define MAX_SYNC_SIZE 100000 static int check_pes(const uint8_t *p, const uint8_t *end) { int pes1; int pes2 = (p[3] & 0xC0) == 0x80 && (p[4] & 0xC0) != 0x40 && ((p[4] & 0xC0) == 0x00 || (p[4] & 0xC0) >> 2 == (p[6] & 0xF0)); for (p += 3; p < end && *p == 0xFF; p++) ; if ((*p & 0xC0) == 0x40) p += 2; if ((*p & 0xF0) == 0x20) pes1 = p[0] & p[2] & p[4] & 1; else if ((*p & 0xF0) == 0x30) pes1 = p[0] & p[2] & p[4] & p[5] & p[7] & p[9] & 1; else pes1 = *p == 0x0F; return pes1 || pes2; } static int check_pack_header(const uint8_t *buf) { return (buf[1] & 0xC0) == 0x40 || (buf[1] & 0xF0) == 0x20; } static int mpegps_probe(AVProbeData *p) { uint32_t code = -1; int i; int sys = 0, pspack = 0, priv1 = 0, vid = 0; int audio = 0, invalid = 0, score = 0; int endpes = 0; for (i = 0; i < p->buf_size; i++) { code = (code << 8) + p->buf[i]; if ((code & 0xffffff00) == 0x100) { int len = p->buf[i + 1] << 8 | p->buf[i + 2]; int pes = endpes <= i && check_pes(p->buf + i, p->buf + p->buf_size); int pack = check_pack_header(p->buf + i); if (code == SYSTEM_HEADER_START_CODE) sys++; else if (code == PACK_START_CODE && pack) pspack++; else if ((code & 0xf0) == VIDEO_ID && pes) { endpes = i + len; vid++; } // skip pes payload to avoid start code emulation for private // and audio streams else if ((code & 0xe0) == AUDIO_ID && pes) {audio++; i+=len;} else if (code == PRIVATE_STREAM_1 && pes) {priv1++; i+=len;} else if (code == 0x1fd && pes) vid++; //VC1 else if ((code & 0xf0) == VIDEO_ID && !pes) invalid++; else if ((code & 0xe0) == AUDIO_ID && !pes) invalid++; else if (code == PRIVATE_STREAM_1 && !pes) invalid++; } } if (vid + audio > invalid + 1) /* invalid VDR files nd short PES streams */ score = AVPROBE_SCORE_EXTENSION / 2; // av_log(NULL, AV_LOG_ERROR, "vid:%d aud:%d sys:%d pspack:%d invalid:%d size:%d \n", // vid, audio, sys, pspack, invalid, p->buf_size); if (sys > invalid && sys * 9 <= pspack * 10) return (audio > 12 || vid > 3 || pspack > 2) ? AVPROBE_SCORE_EXTENSION + 2 : AVPROBE_SCORE_EXTENSION / 2 + 1; // 1 more than mp3 if (pspack > invalid && (priv1 + vid + audio) * 10 >= pspack * 9) return pspack > 2 ? AVPROBE_SCORE_EXTENSION + 2 : AVPROBE_SCORE_EXTENSION / 2; // 1 more than .mpg if ((!!vid ^ !!audio) && (audio > 4 || vid > 1) && !sys && !pspack && p->buf_size > 2048 && vid + audio > invalid) /* PES stream */ return (audio > 12 || vid > 6 + 2 * invalid) ? AVPROBE_SCORE_EXTENSION + 2 : AVPROBE_SCORE_EXTENSION / 2; // 02-Penguin.flac has sys:0 priv1:0 pspack:0 vid:0 audio:1 // mp3_misidentified_2.mp3 has sys:0 priv1:0 pspack:0 vid:0 audio:6 // Have\ Yourself\ a\ Merry\ Little\ Christmas.mp3 0 0 0 5 0 1 len:21618 return score; } typedef struct MpegDemuxContext { AVClass *class; int32_t header_state; unsigned char psm_es_type[256]; int sofdec; int dvd; int imkh_cctv; int raw_ac3; #if CONFIG_VOBSUB_DEMUXER AVFormatContext *sub_ctx; FFDemuxSubtitlesQueue q[32]; char *sub_name; #endif } MpegDemuxContext; static int mpegps_read_header(AVFormatContext *s) { MpegDemuxContext *m = s->priv_data; char buffer[7] = { 0 }; int64_t last_pos = avio_tell(s->pb); m->header_state = 0xff; s->ctx_flags |= AVFMTCTX_NOHEADER; avio_get_str(s->pb, 6, buffer, sizeof(buffer)); if (!memcmp("IMKH", buffer, 4)) { m->imkh_cctv = 1; } else if (!memcmp("Sofdec", buffer, 6)) { m->sofdec = 1; } else avio_seek(s->pb, last_pos, SEEK_SET); /* no need to do more */ return 0; } static int64_t get_pts(AVIOContext *pb, int c) { uint8_t buf[5]; buf[0] = c < 0 ? avio_r8(pb) : c; avio_read(pb, buf + 1, 4); return ff_parse_pes_pts(buf); } static int find_next_start_code(AVIOContext *pb, int *size_ptr, int32_t *header_state) { unsigned int state, v; int val, n; state = *header_state; n = *size_ptr; while (n > 0) { if (avio_feof(pb)) break; v = avio_r8(pb); n--; if (state == 0x000001) { state = ((state << 8) | v) & 0xffffff; val = state; goto found; } state = ((state << 8) | v) & 0xffffff; } val = -1; found: *header_state = state; *size_ptr = n; return val; } /** * Extract stream types from a program stream map * According to ISO/IEC 13818-1 ('MPEG-2 Systems') table 2-35 * * @return number of bytes occupied by PSM in the bitstream */ static long mpegps_psm_parse(MpegDemuxContext *m, AVIOContext *pb) { int psm_length, ps_info_length, es_map_length; psm_length = avio_rb16(pb); avio_r8(pb); avio_r8(pb); ps_info_length = avio_rb16(pb); /* skip program_stream_info */ avio_skip(pb, ps_info_length); /*es_map_length = */avio_rb16(pb); /* Ignore es_map_length, trust psm_length */ es_map_length = psm_length - ps_info_length - 10; /* at least one es available? */ while (es_map_length >= 4) { unsigned char type = avio_r8(pb); unsigned char es_id = avio_r8(pb); uint16_t es_info_length = avio_rb16(pb); /* remember mapping from stream id to stream type */ m->psm_es_type[es_id] = type; /* skip program_stream_info */ avio_skip(pb, es_info_length); es_map_length -= 4 + es_info_length; } avio_rb32(pb); /* crc32 */ return 2 + psm_length; } /* read the next PES header. Return its position in ppos * (if not NULL), and its start code, pts and dts. */ static int mpegps_read_pes_header(AVFormatContext *s, int64_t *ppos, int *pstart_code, int64_t *ppts, int64_t *pdts) { MpegDemuxContext *m = s->priv_data; int len, size, startcode, c, flags, header_len; int pes_ext, ext2_len, id_ext, skip; int64_t pts, dts; int64_t last_sync = avio_tell(s->pb); error_redo: avio_seek(s->pb, last_sync, SEEK_SET); redo: /* next start code (should be immediately after) */ m->header_state = 0xff; size = MAX_SYNC_SIZE; startcode = find_next_start_code(s->pb, &size, &m->header_state); last_sync = avio_tell(s->pb); if (startcode < 0) { if (avio_feof(s->pb)) return AVERROR_EOF; // FIXME we should remember header_state return FFERROR_REDO; } if (startcode == PACK_START_CODE) goto redo; if (startcode == SYSTEM_HEADER_START_CODE) goto redo; if (startcode == PADDING_STREAM) { avio_skip(s->pb, avio_rb16(s->pb)); goto redo; } if (startcode == PRIVATE_STREAM_2) { if (!m->sofdec) { /* Need to detect whether this from a DVD or a 'Sofdec' stream */ int len = avio_rb16(s->pb); int bytesread = 0; uint8_t *ps2buf = av_malloc(len); if (ps2buf) { bytesread = avio_read(s->pb, ps2buf, len); if (bytesread != len) { avio_skip(s->pb, len - bytesread); } else { uint8_t *p = 0; if (len >= 6) p = memchr(ps2buf, 'S', len - 5); if (p) m->sofdec = !memcmp(p+1, "ofdec", 5); m->sofdec -= !m->sofdec; if (m->sofdec < 0) { if (len == 980 && ps2buf[0] == 0) { /* PCI structure? */ uint32_t startpts = AV_RB32(ps2buf + 0x0d); uint32_t endpts = AV_RB32(ps2buf + 0x11); uint8_t hours = ((ps2buf[0x19] >> 4) * 10) + (ps2buf[0x19] & 0x0f); uint8_t mins = ((ps2buf[0x1a] >> 4) * 10) + (ps2buf[0x1a] & 0x0f); uint8_t secs = ((ps2buf[0x1b] >> 4) * 10) + (ps2buf[0x1b] & 0x0f); m->dvd = (hours <= 23 && mins <= 59 && secs <= 59 && (ps2buf[0x19] & 0x0f) < 10 && (ps2buf[0x1a] & 0x0f) < 10 && (ps2buf[0x1b] & 0x0f) < 10 && endpts >= startpts); } else if (len == 1018 && ps2buf[0] == 1) { /* DSI structure? */ uint8_t hours = ((ps2buf[0x1d] >> 4) * 10) + (ps2buf[0x1d] & 0x0f); uint8_t mins = ((ps2buf[0x1e] >> 4) * 10) + (ps2buf[0x1e] & 0x0f); uint8_t secs = ((ps2buf[0x1f] >> 4) * 10) + (ps2buf[0x1f] & 0x0f); m->dvd = (hours <= 23 && mins <= 59 && secs <= 59 && (ps2buf[0x1d] & 0x0f) < 10 && (ps2buf[0x1e] & 0x0f) < 10 && (ps2buf[0x1f] & 0x0f) < 10); } } } av_free(ps2buf); /* If this isn't a DVD packet or no memory * could be allocated, just ignore it. * If we did, move back to the start of the * packet (plus 'length' field) */ if (!m->dvd || avio_skip(s->pb, -(len + 2)) < 0) { /* Skip back failed. * This packet will be lost but that can't be helped * if we can't skip back */ goto redo; } } else { /* No memory */ avio_skip(s->pb, len); goto redo; } } else if (!m->dvd) { int len = avio_rb16(s->pb); avio_skip(s->pb, len); goto redo; } } if (startcode == PROGRAM_STREAM_MAP) { mpegps_psm_parse(m, s->pb); goto redo; } /* find matching stream */ if (!((startcode >= 0x1c0 && startcode <= 0x1df) || (startcode >= 0x1e0 && startcode <= 0x1ef) || (startcode == 0x1bd) || (startcode == PRIVATE_STREAM_2) || (startcode == 0x1fd))) goto redo; if (ppos) { *ppos = avio_tell(s->pb) - 4; } len = avio_rb16(s->pb); pts = dts = AV_NOPTS_VALUE; if (startcode != PRIVATE_STREAM_2) { /* stuffing */ for (;;) { if (len < 1) goto error_redo; c = avio_r8(s->pb); len--; /* XXX: for MPEG-1, should test only bit 7 */ if (c != 0xff) break; } if ((c & 0xc0) == 0x40) { /* buffer scale & size */ avio_r8(s->pb); c = avio_r8(s->pb); len -= 2; } if ((c & 0xe0) == 0x20) { dts = pts = get_pts(s->pb, c); len -= 4; if (c & 0x10) { dts = get_pts(s->pb, -1); len -= 5; } } else if ((c & 0xc0) == 0x80) { /* mpeg 2 PES */ flags = avio_r8(s->pb); header_len = avio_r8(s->pb); len -= 2; if (header_len > len) goto error_redo; len -= header_len; if (flags & 0x80) { dts = pts = get_pts(s->pb, -1); header_len -= 5; if (flags & 0x40) { dts = get_pts(s->pb, -1); header_len -= 5; } } if (flags & 0x3f && header_len == 0) { flags &= 0xC0; av_log(s, AV_LOG_WARNING, "Further flags set but no bytes left\n"); } if (flags & 0x01) { /* PES extension */ pes_ext = avio_r8(s->pb); header_len--; /* Skip PES private data, program packet sequence counter * and P-STD buffer */ skip = (pes_ext >> 4) & 0xb; skip += skip & 0x9; if (pes_ext & 0x40 || skip > header_len) { av_log(s, AV_LOG_WARNING, "pes_ext %X is invalid\n", pes_ext); pes_ext = skip = 0; } avio_skip(s->pb, skip); header_len -= skip; if (pes_ext & 0x01) { /* PES extension 2 */ ext2_len = avio_r8(s->pb); header_len--; if ((ext2_len & 0x7f) > 0) { id_ext = avio_r8(s->pb); if ((id_ext & 0x80) == 0) startcode = ((startcode & 0xff) << 8) | id_ext; header_len--; } } } if (header_len < 0) goto error_redo; avio_skip(s->pb, header_len); } else if (c != 0xf) goto redo; } if (startcode == PRIVATE_STREAM_1) { int ret = ffio_ensure_seekback(s->pb, 2); if (ret < 0) return ret; startcode = avio_r8(s->pb); m->raw_ac3 = 0; if (startcode == 0x0b) { if (avio_r8(s->pb) == 0x77) { startcode = 0x80; m->raw_ac3 = 1; avio_skip(s->pb, -2); } else { avio_skip(s->pb, -1); } } else { len--; } } if (len < 0) goto error_redo; if (dts != AV_NOPTS_VALUE && ppos) { int i; for (i = 0; i < s->nb_streams; i++) { if (startcode == s->streams[i]->id && (s->pb->seekable & AVIO_SEEKABLE_NORMAL) /* index useless on streams anyway */) { ff_reduce_index(s, i); av_add_index_entry(s->streams[i], *ppos, dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */); } } } *pstart_code = startcode; *ppts = pts; *pdts = dts; return len; } static int mpegps_read_packet(AVFormatContext *s, AVPacket *pkt) { MpegDemuxContext *m = s->priv_data; AVStream *st; int len, startcode, i, es_type, ret; int lpcm_header_len = -1; //Init to suppress warning int request_probe= 0; enum AVCodecID codec_id = AV_CODEC_ID_NONE; enum AVMediaType type; int64_t pts, dts, dummy_pos; // dummy_pos is needed for the index building to work redo: len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts); if (len < 0) return len; if (startcode >= 0x80 && startcode <= 0xcf) { if (len < 4) goto skip; if (!m->raw_ac3) { /* audio: skip header */ avio_r8(s->pb); lpcm_header_len = avio_rb16(s->pb); len -= 3; if (startcode >= 0xb0 && startcode <= 0xbf) { /* MLP/TrueHD audio has a 4-byte header */ avio_r8(s->pb); len--; } } } /* now find stream */ for (i = 0; i < s->nb_streams; i++) { st = s->streams[i]; if (st->id == startcode) goto found; } es_type = m->psm_es_type[startcode & 0xff]; if (es_type == STREAM_TYPE_VIDEO_MPEG1) { codec_id = AV_CODEC_ID_MPEG2VIDEO; type = AVMEDIA_TYPE_VIDEO; } else if (es_type == STREAM_TYPE_VIDEO_MPEG2) { codec_id = AV_CODEC_ID_MPEG2VIDEO; type = AVMEDIA_TYPE_VIDEO; } else if (es_type == STREAM_TYPE_AUDIO_MPEG1 || es_type == STREAM_TYPE_AUDIO_MPEG2) { codec_id = AV_CODEC_ID_MP3; type = AVMEDIA_TYPE_AUDIO; } else if (es_type == STREAM_TYPE_AUDIO_AAC) { codec_id = AV_CODEC_ID_AAC; type = AVMEDIA_TYPE_AUDIO; } else if (es_type == STREAM_TYPE_VIDEO_MPEG4) { codec_id = AV_CODEC_ID_MPEG4; type = AVMEDIA_TYPE_VIDEO; } else if (es_type == STREAM_TYPE_VIDEO_H264) { codec_id = AV_CODEC_ID_H264; type = AVMEDIA_TYPE_VIDEO; } else if (es_type == STREAM_TYPE_AUDIO_AC3) { codec_id = AV_CODEC_ID_AC3; type = AVMEDIA_TYPE_AUDIO; } else if (m->imkh_cctv && es_type == 0x91) { codec_id = AV_CODEC_ID_PCM_MULAW; type = AVMEDIA_TYPE_AUDIO; } else if (startcode >= 0x1e0 && startcode <= 0x1ef) { static const unsigned char avs_seqh[4] = { 0, 0, 1, 0xb0 }; unsigned char buf[8]; avio_read(s->pb, buf, 8); avio_seek(s->pb, -8, SEEK_CUR); if (!memcmp(buf, avs_seqh, 4) && (buf[6] != 0 || buf[7] != 1)) codec_id = AV_CODEC_ID_CAVS; else request_probe= 1; type = AVMEDIA_TYPE_VIDEO; } else if (startcode == PRIVATE_STREAM_2) { type = AVMEDIA_TYPE_DATA; codec_id = AV_CODEC_ID_DVD_NAV; } else if (startcode >= 0x1c0 && startcode <= 0x1df) { type = AVMEDIA_TYPE_AUDIO; if (m->sofdec > 0) { codec_id = AV_CODEC_ID_ADPCM_ADX; // Auto-detect AC-3 request_probe = 50; } else if (m->imkh_cctv && startcode == 0x1c0 && len > 80) { codec_id = AV_CODEC_ID_PCM_ALAW; request_probe = 50; } else { codec_id = AV_CODEC_ID_MP2; if (m->imkh_cctv) request_probe = 25; } } else if (startcode >= 0x80 && startcode <= 0x87) { type = AVMEDIA_TYPE_AUDIO; codec_id = AV_CODEC_ID_AC3; } else if ((startcode >= 0x88 && startcode <= 0x8f) || (startcode >= 0x98 && startcode <= 0x9f)) { /* 0x90 - 0x97 is reserved for SDDS in DVD specs */ type = AVMEDIA_TYPE_AUDIO; codec_id = AV_CODEC_ID_DTS; } else if (startcode >= 0xa0 && startcode <= 0xaf) { type = AVMEDIA_TYPE_AUDIO; if (lpcm_header_len >= 6 && startcode == 0xa1) { codec_id = AV_CODEC_ID_MLP; } else { codec_id = AV_CODEC_ID_PCM_DVD; } } else if (startcode >= 0xb0 && startcode <= 0xbf) { type = AVMEDIA_TYPE_AUDIO; codec_id = AV_CODEC_ID_TRUEHD; } else if (startcode >= 0xc0 && startcode <= 0xcf) { /* Used for both AC-3 and E-AC-3 in EVOB files */ type = AVMEDIA_TYPE_AUDIO; codec_id = AV_CODEC_ID_AC3; } else if (startcode >= 0x20 && startcode <= 0x3f) { type = AVMEDIA_TYPE_SUBTITLE; codec_id = AV_CODEC_ID_DVD_SUBTITLE; } else if (startcode >= 0xfd55 && startcode <= 0xfd5f) { type = AVMEDIA_TYPE_VIDEO; codec_id = AV_CODEC_ID_VC1; } else { skip: /* skip packet */ avio_skip(s->pb, len); goto redo; } /* no stream found: add a new stream */ st = avformat_new_stream(s, NULL); if (!st) goto skip; st->id = startcode; st->codecpar->codec_type = type; st->codecpar->codec_id = codec_id; if ( st->codecpar->codec_id == AV_CODEC_ID_PCM_MULAW || st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW) { st->codecpar->channels = 1; st->codecpar->channel_layout = AV_CH_LAYOUT_MONO; st->codecpar->sample_rate = 8000; } st->request_probe = request_probe; st->need_parsing = AVSTREAM_PARSE_FULL; found: if (st->discard >= AVDISCARD_ALL) goto skip; if (startcode >= 0xa0 && startcode <= 0xaf) { if (st->codecpar->codec_id == AV_CODEC_ID_MLP) { if (len < 6) goto skip; avio_skip(s->pb, 6); len -=6; } } ret = av_get_packet(s->pb, pkt, len); pkt->pts = pts; pkt->dts = dts; pkt->pos = dummy_pos; pkt->stream_index = st->index; if (s->debug & FF_FDEBUG_TS) av_log(s, AV_LOG_TRACE, "%d: pts=%0.3f dts=%0.3f size=%d\n", pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0, pkt->size); return (ret < 0) ? ret : 0; } static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit) { int len, startcode; int64_t pos, pts, dts; pos = *ppos; if (avio_seek(s->pb, pos, SEEK_SET) < 0) return AV_NOPTS_VALUE; for (;;) { len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts); if (len < 0) { if (s->debug & FF_FDEBUG_TS) av_log(s, AV_LOG_TRACE, "none (ret=%d)\n", len); return AV_NOPTS_VALUE; } if (startcode == s->streams[stream_index]->id && dts != AV_NOPTS_VALUE) { break; } avio_skip(s->pb, len); } if (s->debug & FF_FDEBUG_TS) av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" dts=0x%"PRIx64" %0.3f\n", pos, dts, dts / 90000.0); *ppos = pos; return dts; } AVInputFormat ff_mpegps_demuxer = { .name = "mpeg", .long_name = NULL_IF_CONFIG_SMALL("MPEG-PS (MPEG-2 Program Stream)"), .priv_data_size = sizeof(MpegDemuxContext), .read_probe = mpegps_probe, .read_header = mpegps_read_header, .read_packet = mpegps_read_packet, .read_timestamp = mpegps_read_dts, .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT, }; #if CONFIG_VOBSUB_DEMUXER #define REF_STRING "# VobSub index file," #define MAX_LINE_SIZE 2048 static int vobsub_probe(AVProbeData *p) { if (!strncmp(p->buf, REF_STRING, sizeof(REF_STRING) - 1)) return AVPROBE_SCORE_MAX; return 0; } static int vobsub_read_header(AVFormatContext *s) { int i, ret = 0, header_parsed = 0, langidx = 0; MpegDemuxContext *vobsub = s->priv_data; size_t fname_len; char *header_str; AVBPrint header; int64_t delay = 0; AVStream *st = NULL; int stream_id = -1; char id[64] = {0}; char alt[MAX_LINE_SIZE] = {0}; AVInputFormat *iformat; if (!vobsub->sub_name) { char *ext; vobsub->sub_name = av_strdup(s->url); if (!vobsub->sub_name) { ret = AVERROR(ENOMEM); goto end; } fname_len = strlen(vobsub->sub_name); ext = vobsub->sub_name - 3 + fname_len; if (fname_len < 4 || *(ext - 1) != '.') { av_log(s, AV_LOG_ERROR, "The input index filename is too short " "to guess the associated .SUB file\n"); ret = AVERROR_INVALIDDATA; goto end; } memcpy(ext, !strncmp(ext, "IDX", 3) ? "SUB" : "sub", 3); av_log(s, AV_LOG_VERBOSE, "IDX/SUB: %s -> %s\n", s->url, vobsub->sub_name); } if (!(iformat = av_find_input_format("mpeg"))) { ret = AVERROR_DEMUXER_NOT_FOUND; goto end; } vobsub->sub_ctx = avformat_alloc_context(); if (!vobsub->sub_ctx) { ret = AVERROR(ENOMEM); goto end; } if ((ret = ff_copy_whiteblacklists(vobsub->sub_ctx, s)) < 0) goto end; ret = avformat_open_input(&vobsub->sub_ctx, vobsub->sub_name, iformat, NULL); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Unable to open %s as MPEG subtitles\n", vobsub->sub_name); goto end; } av_bprint_init(&header, 0, AV_BPRINT_SIZE_UNLIMITED); while (!avio_feof(s->pb)) { char line[MAX_LINE_SIZE]; int len = ff_get_line(s->pb, line, sizeof(line)); if (!len) break; line[strcspn(line, "\r\n")] = 0; if (!strncmp(line, "id:", 3)) { if (sscanf(line, "id: %63[^,], index: %u", id, &stream_id) != 2) { av_log(s, AV_LOG_WARNING, "Unable to parse index line '%s', " "assuming 'id: und, index: 0'\n", line); strcpy(id, "und"); stream_id = 0; } if (stream_id >= FF_ARRAY_ELEMS(vobsub->q)) { av_log(s, AV_LOG_ERROR, "Maximum number of subtitles streams reached\n"); ret = AVERROR(EINVAL); goto end; } header_parsed = 1; alt[0] = '\0'; /* We do not create the stream immediately to avoid adding empty * streams. See the following timestamp entry. */ av_log(s, AV_LOG_DEBUG, "IDX stream[%d] id=%s\n", stream_id, id); } else if (!strncmp(line, "timestamp:", 10)) { AVPacket *sub; int hh, mm, ss, ms; int64_t pos, timestamp; const char *p = line + 10; if (stream_id == -1) { av_log(s, AV_LOG_ERROR, "Timestamp declared before any stream\n"); ret = AVERROR_INVALIDDATA; goto end; } if (!st || st->id != stream_id) { st = avformat_new_stream(s, NULL); if (!st) { ret = AVERROR(ENOMEM); goto end; } st->id = stream_id; st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; st->codecpar->codec_id = AV_CODEC_ID_DVD_SUBTITLE; avpriv_set_pts_info(st, 64, 1, 1000); av_dict_set(&st->metadata, "language", id, 0); if (alt[0]) av_dict_set(&st->metadata, "title", alt, 0); } if (sscanf(p, "%02d:%02d:%02d:%03d, filepos: %"SCNx64, &hh, &mm, &ss, &ms, &pos) != 5) { av_log(s, AV_LOG_ERROR, "Unable to parse timestamp line '%s', " "abort parsing\n", line); ret = AVERROR_INVALIDDATA; goto end; } timestamp = (hh*3600LL + mm*60LL + ss) * 1000LL + ms + delay; timestamp = av_rescale_q(timestamp, av_make_q(1, 1000), st->time_base); sub = ff_subtitles_queue_insert(&vobsub->q[s->nb_streams - 1], "", 0, 0); if (!sub) { ret = AVERROR(ENOMEM); goto end; } sub->pos = pos; sub->pts = timestamp; sub->stream_index = s->nb_streams - 1; } else if (!strncmp(line, "alt:", 4)) { const char *p = line + 4; while (*p == ' ') p++; av_log(s, AV_LOG_DEBUG, "IDX stream[%d] name=%s\n", stream_id, p); av_strlcpy(alt, p, sizeof(alt)); header_parsed = 1; } else if (!strncmp(line, "delay:", 6)) { int sign = 1, hh = 0, mm = 0, ss = 0, ms = 0; const char *p = line + 6; while (*p == ' ') p++; if (*p == '-' || *p == '+') { sign = *p == '-' ? -1 : 1; p++; } sscanf(p, "%d:%d:%d:%d", &hh, &mm, &ss, &ms); delay = ((hh*3600LL + mm*60LL + ss) * 1000LL + ms) * sign; } else if (!strncmp(line, "langidx:", 8)) { const char *p = line + 8; if (sscanf(p, "%d", &langidx) != 1) av_log(s, AV_LOG_ERROR, "Invalid langidx specified\n"); } else if (!header_parsed) { if (line[0] && line[0] != '#') av_bprintf(&header, "%s\n", line); } } if (langidx < s->nb_streams) s->streams[langidx]->disposition |= AV_DISPOSITION_DEFAULT; for (i = 0; i < s->nb_streams; i++) { vobsub->q[i].sort = SUB_SORT_POS_TS; vobsub->q[i].keep_duplicates = 1; ff_subtitles_queue_finalize(s, &vobsub->q[i]); } if (!av_bprint_is_complete(&header)) { av_bprint_finalize(&header, NULL); ret = AVERROR(ENOMEM); goto end; } av_bprint_finalize(&header, &header_str); for (i = 0; i < s->nb_streams; i++) { AVStream *sub_st = s->streams[i]; sub_st->codecpar->extradata = av_strdup(header_str); sub_st->codecpar->extradata_size = header.len; } av_free(header_str); end: return ret; } static int vobsub_read_packet(AVFormatContext *s, AVPacket *pkt) { MpegDemuxContext *vobsub = s->priv_data; FFDemuxSubtitlesQueue *q; AVIOContext *pb = vobsub->sub_ctx->pb; int ret, psize, total_read = 0, i; AVPacket idx_pkt = { 0 }; int64_t min_ts = INT64_MAX; int sid = 0; for (i = 0; i < s->nb_streams; i++) { FFDemuxSubtitlesQueue *tmpq = &vobsub->q[i]; int64_t ts; av_assert0(tmpq->nb_subs); ts = tmpq->subs[tmpq->current_sub_idx].pts; if (ts < min_ts) { min_ts = ts; sid = i; } } q = &vobsub->q[sid]; ret = ff_subtitles_queue_read_packet(q, &idx_pkt); if (ret < 0) return ret; /* compute maximum packet size using the next packet position. This is * useful when the len in the header is non-sense */ if (q->current_sub_idx < q->nb_subs) { psize = q->subs[q->current_sub_idx].pos - idx_pkt.pos; } else { int64_t fsize = avio_size(pb); psize = fsize < 0 ? 0xffff : fsize - idx_pkt.pos; } avio_seek(pb, idx_pkt.pos, SEEK_SET); av_init_packet(pkt); pkt->size = 0; pkt->data = NULL; do { int n, to_read, startcode; int64_t pts, dts; int64_t old_pos = avio_tell(pb), new_pos; int pkt_size; ret = mpegps_read_pes_header(vobsub->sub_ctx, NULL, &startcode, &pts, &dts); if (ret < 0) { if (pkt->size) // raise packet even if incomplete break; goto fail; } to_read = ret & 0xffff; new_pos = avio_tell(pb); pkt_size = ret + (new_pos - old_pos); /* this prevents reads above the current packet */ if (total_read + pkt_size > psize) break; total_read += pkt_size; /* the current chunk doesn't match the stream index (unlikely) */ if ((startcode & 0x1f) != s->streams[idx_pkt.stream_index]->id) break; ret = av_grow_packet(pkt, to_read); if (ret < 0) goto fail; n = avio_read(pb, pkt->data + (pkt->size - to_read), to_read); if (n < to_read) pkt->size -= to_read - n; } while (total_read < psize); pkt->pts = pkt->dts = idx_pkt.pts; pkt->pos = idx_pkt.pos; pkt->stream_index = idx_pkt.stream_index; av_packet_unref(&idx_pkt); return 0; fail: av_packet_unref(pkt); av_packet_unref(&idx_pkt); return ret; } static int vobsub_read_seek(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags) { MpegDemuxContext *vobsub = s->priv_data; /* Rescale requested timestamps based on the first stream (timebase is the * same for all subtitles stream within a .idx/.sub). Rescaling is done just * like in avformat_seek_file(). */ if (stream_index == -1 && s->nb_streams != 1) { int i, ret = 0; AVRational time_base = s->streams[0]->time_base; ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base); min_ts = av_rescale_rnd(min_ts, time_base.den, time_base.num * (int64_t)AV_TIME_BASE, AV_ROUND_UP | AV_ROUND_PASS_MINMAX); max_ts = av_rescale_rnd(max_ts, time_base.den, time_base.num * (int64_t)AV_TIME_BASE, AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX); for (i = 0; i < s->nb_streams; i++) { int r = ff_subtitles_queue_seek(&vobsub->q[i], s, stream_index, min_ts, ts, max_ts, flags); if (r < 0) ret = r; } return ret; } if (stream_index == -1) // only 1 stream stream_index = 0; return ff_subtitles_queue_seek(&vobsub->q[stream_index], s, stream_index, min_ts, ts, max_ts, flags); } static int vobsub_read_close(AVFormatContext *s) { int i; MpegDemuxContext *vobsub = s->priv_data; for (i = 0; i < s->nb_streams; i++) ff_subtitles_queue_clean(&vobsub->q[i]); if (vobsub->sub_ctx) avformat_close_input(&vobsub->sub_ctx); return 0; } static const AVOption options[] = { { "sub_name", "URI for .sub file", offsetof(MpegDemuxContext, sub_name), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_DECODING_PARAM }, { NULL } }; static const AVClass vobsub_demuxer_class = { .class_name = "vobsub", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVInputFormat ff_vobsub_demuxer = { .name = "vobsub", .long_name = NULL_IF_CONFIG_SMALL("VobSub subtitle format"), .priv_data_size = sizeof(MpegDemuxContext), .read_probe = vobsub_probe, .read_header = vobsub_read_header, .read_packet = vobsub_read_packet, .read_seek2 = vobsub_read_seek, .read_close = vobsub_read_close, .flags = AVFMT_SHOW_IDS, .extensions = "idx", .priv_class = &vobsub_demuxer_class, }; #endif
null
null
null
null
72,248
28,332
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
193,327
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * FB driver for the SSD1305 OLED Controller * * based on SSD1306 driver by Noralf Tronnes * * 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. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/gpio.h> #include <linux/delay.h> #include "fbtft.h" #define DRVNAME "fb_ssd1305" #define WIDTH 128 #define HEIGHT 64 /* * write_reg() caveat: * * This doesn't work because D/C has to be LOW for both values: * write_reg(par, val1, val2); * * Do it like this: * write_reg(par, val1); * write_reg(par, val2); */ /* Init sequence taken from the Adafruit SSD1306 Arduino library */ static int init_display(struct fbtft_par *par) { par->fbtftops.reset(par); if (par->gamma.curves[0] == 0) { mutex_lock(&par->gamma.lock); if (par->info->var.yres == 64) par->gamma.curves[0] = 0xCF; else par->gamma.curves[0] = 0x8F; mutex_unlock(&par->gamma.lock); } /* Set Display OFF */ write_reg(par, 0xAE); /* Set Display Clock Divide Ratio/ Oscillator Frequency */ write_reg(par, 0xD5); write_reg(par, 0x80); /* Set Multiplex Ratio */ write_reg(par, 0xA8); if (par->info->var.yres == 64) write_reg(par, 0x3F); else write_reg(par, 0x1F); /* Set Display Offset */ write_reg(par, 0xD3); write_reg(par, 0x0); /* Set Display Start Line */ write_reg(par, 0x40 | 0x0); /* Charge Pump Setting */ write_reg(par, 0x8D); /* A[2] = 1b, Enable charge pump during display on */ write_reg(par, 0x14); /* Set Memory Addressing Mode */ write_reg(par, 0x20); /* Vertical addressing mode */ write_reg(par, 0x01); /* * Set Segment Re-map * column address 127 is mapped to SEG0 */ write_reg(par, 0xA0 | ((par->info->var.rotate == 180) ? 0x0 : 0x1)); /* * Set COM Output Scan Direction * remapped mode. Scan from COM[N-1] to COM0 */ write_reg(par, ((par->info->var.rotate == 180) ? 0xC8 : 0xC0)); /* Set COM Pins Hardware Configuration */ write_reg(par, 0xDA); if (par->info->var.yres == 64) { /* A[4]=1b, Alternative COM pin configuration */ write_reg(par, 0x12); } else { /* A[4]=0b, Sequential COM pin configuration */ write_reg(par, 0x02); } /* Set Pre-charge Period */ write_reg(par, 0xD9); write_reg(par, 0xF1); /* * Entire Display ON * Resume to RAM content display. Output follows RAM content */ write_reg(par, 0xA4); /* * Set Normal Display * 0 in RAM: OFF in display panel * 1 in RAM: ON in display panel */ write_reg(par, 0xA6); /* Set Display ON */ write_reg(par, 0xAF); return 0; } static void set_addr_win(struct fbtft_par *par, int xs, int ys, int xe, int ye) { /* Set Lower Column Start Address for Page Addressing Mode */ write_reg(par, 0x00 | ((par->info->var.rotate == 180) ? 0x0 : 0x4)); /* Set Higher Column Start Address for Page Addressing Mode */ write_reg(par, 0x10 | 0x0); /* Set Display Start Line */ write_reg(par, 0x40 | 0x0); } static int blank(struct fbtft_par *par, bool on) { if (on) write_reg(par, 0xAE); else write_reg(par, 0xAF); return 0; } /* Gamma is used to control Contrast */ static int set_gamma(struct fbtft_par *par, u32 *curves) { curves[0] &= 0xFF; /* Set Contrast Control for BANK0 */ write_reg(par, 0x81); write_reg(par, curves[0]); return 0; } static int write_vmem(struct fbtft_par *par, size_t offset, size_t len) { u16 *vmem16 = (u16 *)par->info->screen_buffer; u8 *buf = par->txbuf.buf; int x, y, i; int ret; for (x = 0; x < par->info->var.xres; x++) { for (y = 0; y < par->info->var.yres / 8; y++) { *buf = 0x00; for (i = 0; i < 8; i++) *buf |= (vmem16[(y * 8 + i) * par->info->var.xres + x] ? 1 : 0) << i; buf++; } } /* Write data */ gpio_set_value(par->gpio.dc, 1); ret = par->fbtftops.write(par, par->txbuf.buf, par->info->var.xres * par->info->var.yres / 8); if (ret < 0) dev_err(par->info->device, "write failed and returned: %d\n", ret); return ret; } static struct fbtft_display display = { .regwidth = 8, .width = WIDTH, .height = HEIGHT, .txbuflen = WIDTH * HEIGHT / 8, .gamma_num = 1, .gamma_len = 1, .gamma = "00", .fbtftops = { .write_vmem = write_vmem, .init_display = init_display, .set_addr_win = set_addr_win, .blank = blank, .set_gamma = set_gamma, }, }; FBTFT_REGISTER_DRIVER(DRVNAME, "solomon,ssd1305", &display); MODULE_ALIAS("spi:" DRVNAME); MODULE_ALIAS("platform:" DRVNAME); MODULE_ALIAS("spi:ssd1305"); MODULE_ALIAS("platform:ssd1305"); MODULE_DESCRIPTION("SSD1305 OLED Driver"); MODULE_AUTHOR("Alexey Mednyy"); MODULE_LICENSE("GPL");
null
null
null
null
101,674
58,613
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
58,613
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_EXTENSIONS_EXTENSION_ERROR_UI_H_ #define CHROME_BROWSER_EXTENSIONS_EXTENSION_ERROR_UI_H_ #include <vector> #include "base/macros.h" #include "base/strings/string16.h" namespace content { class BrowserContext; } namespace extensions { class ExtensionSet; // This class encapsulates the UI we want to show users when certain events // occur related to installed extensions. class ExtensionErrorUI { public: class Delegate { public: // Get the BrowserContext associated with this UI. virtual content::BrowserContext* GetContext() = 0; // Get the set of external extensions to warn the user about. virtual const ExtensionSet& GetExternalExtensions() = 0; // Get the set of blacklisted extensions to warn the user about. virtual const ExtensionSet& GetBlacklistedExtensions() = 0; // Handle the user clicking to get more details on the extension alert. virtual void OnAlertDetails() = 0; // Handle the user clicking "accept" on the extension alert. virtual void OnAlertAccept() = 0; // Handle the alert closing. virtual void OnAlertClosed() = 0; }; static ExtensionErrorUI* Create(Delegate* delegate); virtual ~ExtensionErrorUI(); // Shows the installation error in a bubble view. Should return true if a // bubble is shown, false if one could not be shown. virtual bool ShowErrorInBubbleView() = 0; // Shows the extension page. Called as a result of the user clicking more // info and should be only called from the context of a callback // (BubbleViewDidClose or BubbleViewAccept/CancelButtonPressed). // It should use the same browser as where the bubble was shown. virtual void ShowExtensions() = 0; // Closes the error UI. This will end up calling BubbleViewDidClose, possibly // synchronously. virtual void Close() = 0; protected: explicit ExtensionErrorUI(Delegate* delegate); // Model methods for the bubble view. base::string16 GetBubbleViewTitle(); std::vector<base::string16> GetBubbleViewMessages(); base::string16 GetBubbleViewAcceptButtonLabel(); base::string16 GetBubbleViewCancelButtonLabel(); // Sub-classes should call this methods based on the actions taken by the user // in the error bubble. void BubbleViewDidClose(); // destroys |this| void BubbleViewAcceptButtonPressed(); void BubbleViewCancelButtonPressed(); private: base::string16 GenerateMessage(); Delegate* delegate_; base::string16 message_; // Displayed in the body of the alert. DISALLOW_COPY_AND_ASSIGN(ExtensionErrorUI); }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_EXTENSION_ERROR_UI_H_
null
null
null
null
55,476
28,004
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
192,999
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc. * 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 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. * * File: desc.h * * Purpose:The header file of descriptor * * Revision History: * * Author: Tevin Chen * * Date: May 21, 1996 * */ #ifndef __DESC_H__ #define __DESC_H__ #include <linux/types.h> #include <linux/mm.h> #include "linux/ieee80211.h" #define B_OWNED_BY_CHIP 1 #define B_OWNED_BY_HOST 0 /* Bits in the RSR register */ #define RSR_ADDRBROAD 0x80 #define RSR_ADDRMULTI 0x40 #define RSR_ADDRUNI 0x00 #define RSR_IVLDTYP 0x20 #define RSR_IVLDLEN 0x10 /* invalid len (> 2312 byte) */ #define RSR_BSSIDOK 0x08 #define RSR_CRCOK 0x04 #define RSR_BCNSSIDOK 0x02 #define RSR_ADDROK 0x01 /* Bits in the new RSR register */ #define NEWRSR_DECRYPTOK 0x10 #define NEWRSR_CFPIND 0x08 #define NEWRSR_HWUTSF 0x04 #define NEWRSR_BCNHITAID 0x02 #define NEWRSR_BCNHITAID0 0x01 /* Bits in the TSR0 register */ #define TSR0_PWRSTS1_2 0xC0 #define TSR0_PWRSTS7 0x20 #define TSR0_NCR 0x1F /* Bits in the TSR1 register */ #define TSR1_TERR 0x80 #define TSR1_PWRSTS4_6 0x70 #define TSR1_RETRYTMO 0x08 #define TSR1_TMO 0x04 #define TSR1_PWRSTS3 0x02 #define ACK_DATA 0x01 /* Bits in the TCR register */ #define EDMSDU 0x04 /* end of sdu */ #define TCR_EDP 0x02 /* end of packet */ #define TCR_STP 0x01 /* start of packet */ /* max transmit or receive buffer size */ #define CB_MAX_BUF_SIZE 2900U /* NOTE: must be multiple of 4 */ #define CB_MAX_TX_BUF_SIZE CB_MAX_BUF_SIZE #define CB_MAX_RX_BUF_SIZE_NORMAL CB_MAX_BUF_SIZE #define CB_BEACON_BUF_SIZE 512U #define CB_MAX_RX_DESC 128 #define CB_MIN_RX_DESC 16 #define CB_MAX_TX_DESC 64 #define CB_MIN_TX_DESC 16 #define CB_MAX_RECEIVED_PACKETS 16 /* * limit our receive routine to indicating * this many at a time for 2 reasons: * 1. driver flow control to protocol layer * 2. limit the time used in ISR routine */ #define CB_EXTRA_RD_NUM 32 #define CB_RD_NUM 32 #define CB_TD_NUM 32 /* * max number of physical segments in a single NDIS packet. Above this * threshold, the packet is copied into a single physically contiguous buffer */ #define CB_MAX_SEGMENT 4 #define CB_MIN_MAP_REG_NUM 4 #define CB_MAX_MAP_REG_NUM CB_MAX_TX_DESC #define CB_PROTOCOL_RESERVED_SECTION 16 /* * if retrys excess 15 times , tx will abort, and if tx fifo underflow, * tx will fail, we should try to resend it */ #define CB_MAX_TX_ABORT_RETRY 3 /* WMAC definition FIFO Control */ #define FIFOCTL_AUTO_FB_1 0x1000 #define FIFOCTL_AUTO_FB_0 0x0800 #define FIFOCTL_GRPACK 0x0400 #define FIFOCTL_11GA 0x0300 #define FIFOCTL_11GB 0x0200 #define FIFOCTL_11B 0x0100 #define FIFOCTL_11A 0x0000 #define FIFOCTL_RTS 0x0080 #define FIFOCTL_ISDMA0 0x0040 #define FIFOCTL_GENINT 0x0020 #define FIFOCTL_TMOEN 0x0010 #define FIFOCTL_LRETRY 0x0008 #define FIFOCTL_CRCDIS 0x0004 #define FIFOCTL_NEEDACK 0x0002 #define FIFOCTL_LHEAD 0x0001 /* WMAC definition Frag Control */ #define FRAGCTL_AES 0x0300 #define FRAGCTL_TKIP 0x0200 #define FRAGCTL_LEGACY 0x0100 #define FRAGCTL_NONENCRYPT 0x0000 #define FRAGCTL_ENDFRAG 0x0003 #define FRAGCTL_MIDFRAG 0x0002 #define FRAGCTL_STAFRAG 0x0001 #define FRAGCTL_NONFRAG 0x0000 #define TYPE_TXDMA0 0 #define TYPE_AC0DMA 1 #define TYPE_ATIMDMA 2 #define TYPE_SYNCDMA 3 #define TYPE_MAXTD 2 #define TYPE_BEACONDMA 4 #define TYPE_RXDMA0 0 #define TYPE_RXDMA1 1 #define TYPE_MAXRD 2 /* TD_INFO flags control bit */ #define TD_FLAGS_NETIF_SKB 0x01 /* check if need release skb */ /* check if called from private skb (hostap) */ #define TD_FLAGS_PRIV_SKB 0x02 #define TD_FLAGS_PS_RETRY 0x04 /* check if PS STA frame re-transmit */ /* * ref_sk_buff is used for mapping the skb structure between pre-built * driver-obj & running kernel. Since different kernel version (2.4x) may * change skb structure, i.e. pre-built driver-obj may link to older skb that * leads error. */ struct vnt_rd_info { struct sk_buff *skb; dma_addr_t skb_dma; }; struct vnt_rdes0 { volatile __le16 res_count; #ifdef __BIG_ENDIAN union { volatile u16 f15_reserved; struct { volatile u8 f8_reserved1; volatile u8 owner:1; volatile u8 f7_reserved:7; } __packed; } __packed; #else u16 f15_reserved:15; u16 owner:1; #endif } __packed; struct vnt_rdes1 { __le16 req_count; u16 reserved; } __packed; /* Rx descriptor*/ struct vnt_rx_desc { volatile struct vnt_rdes0 rd0; volatile struct vnt_rdes1 rd1; volatile __le32 buff_addr; volatile __le32 next_desc; struct vnt_rx_desc *next __aligned(8); struct vnt_rd_info *rd_info __aligned(8); } __packed; struct vnt_tdes0 { volatile u8 tsr0; volatile u8 tsr1; #ifdef __BIG_ENDIAN union { volatile u16 f15_txtime; struct { volatile u8 f8_reserved; volatile u8 owner:1; volatile u8 f7_reserved:7; } __packed; } __packed; #else volatile u16 f15_txtime:15; volatile u16 owner:1; #endif } __packed; struct vnt_tdes1 { volatile __le16 req_count; volatile u8 tcr; volatile u8 reserved; } __packed; struct vnt_td_info { void *mic_hdr; struct sk_buff *skb; unsigned char *buf; dma_addr_t buf_dma; u16 req_count; u8 flags; }; /* transmit descriptor */ struct vnt_tx_desc { volatile struct vnt_tdes0 td0; volatile struct vnt_tdes1 td1; volatile __le32 buff_addr; volatile __le32 next_desc; struct vnt_tx_desc *next __aligned(8); struct vnt_td_info *td_info __aligned(8); } __packed; /* Length, Service, and Signal fields of Phy for Tx */ struct vnt_phy_field { u8 signal; u8 service; __le16 len; } __packed; union vnt_phy_field_swap { struct vnt_phy_field field_read; u16 swap[2]; u32 field_write; }; #endif /* __DESC_H__ */
null
null
null
null
101,346
5,289
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
170,284
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* card-ad1816a.c - driver for ADI SoundPort AD1816A based soundcards. Copyright (C) 2000 by Massimo Piccioni <dafastidio@libero.it> 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 <linux/init.h> #include <linux/time.h> #include <linux/wait.h> #include <linux/pnp.h> #include <linux/module.h> #include <sound/core.h> #include <sound/initval.h> #include <sound/ad1816a.h> #include <sound/mpu401.h> #include <sound/opl3.h> #define PFX "ad1816a: " MODULE_AUTHOR("Massimo Piccioni <dafastidio@libero.it>"); MODULE_DESCRIPTION("AD1816A, AD1815"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{Highscreen,Sound-Boostar 16 3D}," "{Analog Devices,AD1815}," "{Analog Devices,AD1816A}," "{TerraTec,Base 64}," "{TerraTec,AudioSystem EWS64S}," "{Aztech/Newcom SC-16 3D}," "{Shark Predator ISA}}"); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 1-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */ static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */ static long mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */ static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */ static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* Pnp setup */ static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* Pnp setup */ static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* PnP setup */ static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* PnP setup */ static int clockfreq[SNDRV_CARDS]; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for ad1816a based soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for ad1816a based soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable ad1816a based soundcard."); module_param_array(clockfreq, int, NULL, 0444); MODULE_PARM_DESC(clockfreq, "Clock frequency for ad1816a driver (default = 0)."); static struct pnp_card_device_id snd_ad1816a_pnpids[] = { /* Analog Devices AD1815 */ { .id = "ADS7150", .devs = { { .id = "ADS7150" }, { .id = "ADS7151" } } }, /* Analog Device AD1816? */ { .id = "ADS7180", .devs = { { .id = "ADS7180" }, { .id = "ADS7181" } } }, /* Analog Devices AD1816A - added by Kenneth Platz <kxp@atl.hp.com> */ { .id = "ADS7181", .devs = { { .id = "ADS7180" }, { .id = "ADS7181" } } }, /* Analog Devices AD1816A - Aztech/Newcom SC-16 3D */ { .id = "AZT1022", .devs = { { .id = "AZT1018" }, { .id = "AZT2002" } } }, /* Highscreen Sound-Boostar 16 3D - added by Stefan Behnel */ { .id = "LWC1061", .devs = { { .id = "ADS7180" }, { .id = "ADS7181" } } }, /* Highscreen Sound-Boostar 16 3D */ { .id = "MDK1605", .devs = { { .id = "ADS7180" }, { .id = "ADS7181" } } }, /* Shark Predator ISA - added by Ken Arromdee */ { .id = "SMM7180", .devs = { { .id = "ADS7180" }, { .id = "ADS7181" } } }, /* Analog Devices AD1816A - Terratec AudioSystem EWS64 S */ { .id = "TER1112", .devs = { { .id = "ADS7180" }, { .id = "ADS7181" } } }, /* Analog Devices AD1816A - Terratec AudioSystem EWS64 S */ { .id = "TER1112", .devs = { { .id = "TER1100" }, { .id = "TER1101" } } }, /* Analog Devices AD1816A - Terratec Base 64 */ { .id = "TER1411", .devs = { { .id = "ADS7180" }, { .id = "ADS7181" } } }, /* end */ { .id = "" } }; MODULE_DEVICE_TABLE(pnp_card, snd_ad1816a_pnpids); #define DRIVER_NAME "snd-card-ad1816a" static int snd_card_ad1816a_pnp(int dev, struct pnp_card_link *card, const struct pnp_card_device_id *id) { struct pnp_dev *pdev; int err; pdev = pnp_request_card_device(card, id->devs[0].id, NULL); if (pdev == NULL) return -EBUSY; err = pnp_activate_dev(pdev); if (err < 0) { printk(KERN_ERR PFX "AUDIO PnP configure failure\n"); return -EBUSY; } port[dev] = pnp_port_start(pdev, 2); fm_port[dev] = pnp_port_start(pdev, 1); dma1[dev] = pnp_dma(pdev, 0); dma2[dev] = pnp_dma(pdev, 1); irq[dev] = pnp_irq(pdev, 0); pdev = pnp_request_card_device(card, id->devs[1].id, NULL); if (pdev == NULL) { mpu_port[dev] = -1; snd_printk(KERN_WARNING PFX "MPU401 device busy, skipping.\n"); return 0; } err = pnp_activate_dev(pdev); if (err < 0) { printk(KERN_ERR PFX "MPU401 PnP configure failure\n"); mpu_port[dev] = -1; } else { mpu_port[dev] = pnp_port_start(pdev, 0); mpu_irq[dev] = pnp_irq(pdev, 0); } return 0; } static int snd_card_ad1816a_probe(int dev, struct pnp_card_link *pcard, const struct pnp_card_device_id *pid) { int error; struct snd_card *card; struct snd_ad1816a *chip; struct snd_opl3 *opl3; error = snd_card_new(&pcard->card->dev, index[dev], id[dev], THIS_MODULE, sizeof(struct snd_ad1816a), &card); if (error < 0) return error; chip = card->private_data; if ((error = snd_card_ad1816a_pnp(dev, pcard, pid))) { snd_card_free(card); return error; } if ((error = snd_ad1816a_create(card, port[dev], irq[dev], dma1[dev], dma2[dev], chip)) < 0) { snd_card_free(card); return error; } if (clockfreq[dev] >= 5000 && clockfreq[dev] <= 100000) chip->clock_freq = clockfreq[dev]; strcpy(card->driver, "AD1816A"); strcpy(card->shortname, "ADI SoundPort AD1816A"); sprintf(card->longname, "%s, SS at 0x%lx, irq %d, dma %d&%d", card->shortname, chip->port, irq[dev], dma1[dev], dma2[dev]); if ((error = snd_ad1816a_pcm(chip, 0)) < 0) { snd_card_free(card); return error; } if ((error = snd_ad1816a_mixer(chip)) < 0) { snd_card_free(card); return error; } error = snd_ad1816a_timer(chip, 0); if (error < 0) { snd_card_free(card); return error; } if (mpu_port[dev] > 0) { if (snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, mpu_port[dev], 0, mpu_irq[dev], NULL) < 0) printk(KERN_ERR PFX "no MPU-401 device at 0x%lx.\n", mpu_port[dev]); } if (fm_port[dev] > 0) { if (snd_opl3_create(card, fm_port[dev], fm_port[dev] + 2, OPL3_HW_AUTO, 0, &opl3) < 0) { printk(KERN_ERR PFX "no OPL device at 0x%lx-0x%lx.\n", fm_port[dev], fm_port[dev] + 2); } else { error = snd_opl3_hwdep_new(opl3, 0, 1, NULL); if (error < 0) { snd_card_free(card); return error; } } } if ((error = snd_card_register(card)) < 0) { snd_card_free(card); return error; } pnp_set_card_drvdata(pcard, card); return 0; } static unsigned int ad1816a_devices; static int snd_ad1816a_pnp_detect(struct pnp_card_link *card, const struct pnp_card_device_id *id) { static int dev; int res; for ( ; dev < SNDRV_CARDS; dev++) { if (!enable[dev]) continue; res = snd_card_ad1816a_probe(dev, card, id); if (res < 0) return res; dev++; ad1816a_devices++; return 0; } return -ENODEV; } static void snd_ad1816a_pnp_remove(struct pnp_card_link *pcard) { snd_card_free(pnp_get_card_drvdata(pcard)); pnp_set_card_drvdata(pcard, NULL); } #ifdef CONFIG_PM static int snd_ad1816a_pnp_suspend(struct pnp_card_link *pcard, pm_message_t state) { struct snd_card *card = pnp_get_card_drvdata(pcard); snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); snd_ad1816a_suspend(card->private_data); return 0; } static int snd_ad1816a_pnp_resume(struct pnp_card_link *pcard) { struct snd_card *card = pnp_get_card_drvdata(pcard); snd_ad1816a_resume(card->private_data); snd_power_change_state(card, SNDRV_CTL_POWER_D0); return 0; } #endif static struct pnp_card_driver ad1816a_pnpc_driver = { .flags = PNP_DRIVER_RES_DISABLE, .name = "ad1816a", .id_table = snd_ad1816a_pnpids, .probe = snd_ad1816a_pnp_detect, .remove = snd_ad1816a_pnp_remove, #ifdef CONFIG_PM .suspend = snd_ad1816a_pnp_suspend, .resume = snd_ad1816a_pnp_resume, #endif }; static int __init alsa_card_ad1816a_init(void) { int err; err = pnp_register_card_driver(&ad1816a_pnpc_driver); if (err) return err; if (!ad1816a_devices) { pnp_unregister_card_driver(&ad1816a_pnpc_driver); #ifdef MODULE printk(KERN_ERR "no AD1816A based soundcards found.\n"); #endif /* MODULE */ return -ENODEV; } return 0; } static void __exit alsa_card_ad1816a_exit(void) { pnp_unregister_card_driver(&ad1816a_pnpc_driver); } module_init(alsa_card_ad1816a_init) module_exit(alsa_card_ad1816a_exit)
null
null
null
null
78,631
295
null
train_val
a6802e21d824e786d1e2a8440cf749a6e1a8d95f
160,423
ImageMagick
0
https://github.com/ImageMagick/ImageMagick
2017-07-18 18:28:29-04:00
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO PPPP EEEEE RRRR TTTTT Y Y % % P P R R O O P P E R R T Y Y % % PPPP RRRR O O PPPP EEE RRRR T Y % % P R R O O P E R R T Y % % P R R OOO P EEEEE R R T Y % % % % % % MagickCore Property Methods % % % % Software Design % % Cristy % % March 2000 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/compare.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/fx-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/layer.h" #include "MagickCore/locale-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/montage.h" #include "MagickCore/option.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/signature.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/token.h" #include "MagickCore/token-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS2_LCMS2_H) #include <lcms2/lcms2.h> #elif defined(MAGICKCORE_HAVE_LCMS2_H) #include "lcms2.h" #elif defined(MAGICKCORE_HAVE_LCMS_LCMS_H) #include <lcms/lcms.h> #else #include "lcms.h" #endif #endif /* Define declarations. */ #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) #define cmsUInt32Number DWORD #endif #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProperties() clones all the image properties to another image. % % The format of the CloneImageProperties method is: % % MagickBooleanType CloneImageProperties(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProperties(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); if (clone_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", clone_image->filename); (void) CopyMagickString(image->filename,clone_image->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,clone_image->magick_filename, MagickPathExtent); image->compression=clone_image->compression; image->quality=clone_image->quality; image->depth=clone_image->depth; image->matte_color=clone_image->matte_color; image->background_color=clone_image->background_color; image->border_color=clone_image->border_color; image->transparent_color=clone_image->transparent_color; image->gamma=clone_image->gamma; image->chromaticity=clone_image->chromaticity; image->rendering_intent=clone_image->rendering_intent; image->black_point_compensation=clone_image->black_point_compensation; image->units=clone_image->units; image->montage=(char *) NULL; image->directory=(char *) NULL; (void) CloneString(&image->geometry,clone_image->geometry); image->offset=clone_image->offset; image->resolution.x=clone_image->resolution.x; image->resolution.y=clone_image->resolution.y; image->page=clone_image->page; image->tile_offset=clone_image->tile_offset; image->extract_info=clone_image->extract_info; image->filter=clone_image->filter; image->fuzz=clone_image->fuzz; image->intensity=clone_image->intensity; image->interlace=clone_image->interlace; image->interpolate=clone_image->interpolate; image->endian=clone_image->endian; image->gravity=clone_image->gravity; image->compose=clone_image->compose; image->orientation=clone_image->orientation; image->scene=clone_image->scene; image->dispose=clone_image->dispose; image->delay=clone_image->delay; image->ticks_per_second=clone_image->ticks_per_second; image->iterations=clone_image->iterations; image->total_colors=clone_image->total_colors; image->taint=clone_image->taint; image->progress_monitor=clone_image->progress_monitor; image->client_data=clone_image->client_data; image->start_loop=clone_image->start_loop; image->error=clone_image->error; image->signature=clone_image->signature; if (clone_image->properties != (void *) NULL) { if (image->properties != (void *) NULL) DestroyImageProperties(image); image->properties=CloneSplayTree((SplayTreeInfo *) clone_image->properties,(void *(*)(void *)) ConstantString, (void *(*)(void *)) ConstantString); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e f i n e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineImageProperty() associates an assignment string of the form % "key=value" with an artifact or options. It is equivelent to % SetImageProperty(). % % The format of the DefineImageProperty method is: % % MagickBooleanType DefineImageProperty(Image *image,const char *property, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DefineImageProperty(Image *image, const char *property,ExceptionInfo *exception) { char key[MagickPathExtent], value[MagickPathExtent]; register char *p; assert(image != (Image *) NULL); assert(property != (const char *) NULL); (void) CopyMagickString(key,property,MagickPathExtent-1); for (p=key; *p != '\0'; p++) if (*p == '=') break; *value='\0'; if (*p == '=') (void) CopyMagickString(value,p+1,MagickPathExtent); *p='\0'; return(SetImageProperty(image,key,value,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProperty() deletes an image property. % % The format of the DeleteImageProperty method is: % % MagickBooleanType DeleteImageProperty(Image *image,const char *property) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % */ MagickExport MagickBooleanType DeleteImageProperty(Image *image, const char *property) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->properties == (void *) NULL) return(MagickFalse); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->properties,property)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProperties() destroys all properties and associated memory % attached to the given image. % % The format of the DestroyDefines method is: % % void DestroyImageProperties(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProperties(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->properties != (void *) NULL) image->properties=(void *) DestroySplayTree((SplayTreeInfo *) image->properties); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatImageProperty() permits formatted property/value pairs to be saved as % an image property. % % The format of the FormatImageProperty method is: % % MagickBooleanType FormatImageProperty(Image *image,const char *property, % const char *format,...) % % A description of each parameter follows. % % o image: The image. % % o property: The attribute property. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport MagickBooleanType FormatImageProperty(Image *image, const char *property,const char *format,...) { char value[MagickPathExtent]; ExceptionInfo *exception; MagickBooleanType status; ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(value,MagickPathExtent,format,operands); (void) n; va_end(operands); exception=AcquireExceptionInfo(); status=SetImageProperty(image,property,value,exception); exception=DestroyExceptionInfo(exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProperty() gets a value associated with an image property. % % This includes, profile prefixes, such as "exif:", "iptc:" and "8bim:" % It does not handle non-prifile prefixes, such as "fx:", "option:", or % "artifact:". % % The returned string is stored as a properity of the same name for faster % lookup later. It should NOT be freed by the caller. % % The format of the GetImageProperty method is: % % const char *GetImageProperty(const Image *image,const char *key, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o key: the key. % % o exception: return any errors or warnings in this structure. % */ static char *TracePSClippath(const unsigned char *,size_t), *TraceSVGClippath(const unsigned char *,size_t,const size_t, const size_t); static MagickBooleanType GetIPTCProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, *message; const StringInfo *profile; long count, dataset, record; register ssize_t i; size_t length; profile=GetImageProfile(image,"iptc"); if (profile == (StringInfo *) NULL) profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return(MagickFalse); count=sscanf(key,"IPTC:%ld:%ld",&dataset,&record); if (count != 2) return(MagickFalse); attribute=(char *) NULL; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=(ssize_t) length) { length=1; if ((ssize_t) GetStringInfoDatum(profile)[i] != 0x1c) continue; length=(size_t) (GetStringInfoDatum(profile)[i+3] << 8); length|=GetStringInfoDatum(profile)[i+4]; if (((long) GetStringInfoDatum(profile)[i+1] == dataset) && ((long) GetStringInfoDatum(profile)[i+2] == record)) { message=(char *) NULL; if (~length >= 1) message=(char *) AcquireQuantumMemory(length+1UL,sizeof(*message)); if (message != (char *) NULL) { (void) CopyMagickString(message,(char *) GetStringInfoDatum( profile)+i+5,length+1); (void) ConcatenateString(&attribute,message); (void) ConcatenateString(&attribute,";"); message=DestroyString(message); } } i+=5; } if ((attribute == (char *) NULL) || (*attribute == ';')) { if (attribute != (char *) NULL) attribute=DestroyString(attribute); return(MagickFalse); } attribute[strlen(attribute)-1]='\0'; (void) SetImageProperty((Image *) image,key,(const char *) attribute, exception); attribute=DestroyString(attribute); return(MagickTrue); } static inline int ReadPropertyByte(const unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed int ReadPropertyMSBLong(const unsigned char **p, size_t *length) { union { unsigned int unsigned_value; signed int signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[4]; unsigned int value; if (*length < 4) return(-1); for (i=0; i < 4; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline signed short ReadPropertyMSBShort(const unsigned char **p, size_t *length) { union { unsigned short unsigned_value; signed short signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[2]; unsigned short value; if (*length < 2) return((unsigned short) ~0); for (i=0; i < 2; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, format[MagickPathExtent], name[MagickPathExtent], *resource; const StringInfo *profile; const unsigned char *info; long start, stop; MagickBooleanType status; register ssize_t i; size_t length; ssize_t count, id, sub_number; /* There are no newlines in path names, so it's safe as terminator. */ profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return(MagickFalse); count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop, name,format); if ((count != 2) && (count != 3) && (count != 4)) return(MagickFalse); if (count < 4) (void) CopyMagickString(format,"SVG",MagickPathExtent); if (count < 3) *name='\0'; sub_number=1; if (*name == '#') sub_number=(ssize_t) StringToLong(&name[1]); sub_number=MagickMax(sub_number,1L); resource=(char *) NULL; status=MagickFalse; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while ((length > 0) && (status == MagickFalse)) { if (ReadPropertyByte(&info,&length) != (unsigned char) '8') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadPropertyMSBShort(&info,&length); if (id < (ssize_t) start) continue; if (id > (ssize_t) stop) continue; if (resource != (char *) NULL) resource=DestroyString(resource); count=(ssize_t) ReadPropertyByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { resource=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) resource=(char *) AcquireQuantumMemory((size_t) count+ MagickPathExtent,sizeof(*resource)); if (resource != (char *) NULL) { for (i=0; i < (ssize_t) count; i++) resource[i]=(char) ReadPropertyByte(&info,&length); resource[count]='\0'; } } if ((count & 0x01) == 0) (void) ReadPropertyByte(&info,&length); count=(ssize_t) ReadPropertyMSBLong(&info,&length); if ((count < 0) || ((size_t) count > length)) { length=0; continue; } if ((*name != '\0') && (*name != '#')) if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) { /* No name match, scroll forward and try next. */ info+=count; length-=MagickMin(count,(ssize_t) length); continue; } if ((*name == '#') && (sub_number != 1)) { /* No numbered match, scroll forward and try next. */ sub_number--; info+=count; length-=MagickMin(count,(ssize_t) length); continue; } /* We have the resource of interest. */ attribute=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, sizeof(*attribute)); if (attribute != (char *) NULL) { (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); attribute[count]='\0'; info+=count; length-=MagickMin(count,(ssize_t) length); if ((id <= 1999) || (id >= 2999)) (void) SetImageProperty((Image *) image,key,(const char *) attribute, exception); else { char *path; if (LocaleCompare(format,"svg") == 0) path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, image->columns,image->rows); else path=TracePSClippath((unsigned char *) attribute,(size_t) count); (void) SetImageProperty((Image *) image,key,(const char *) path, exception); path=DestroyString(path); } attribute=DestroyString(attribute); status=MagickTrue; } } if (resource != (char *) NULL) resource=DestroyString(resource); return(status); } static inline signed int ReadPropertySignedLong(const EndianType endian, const unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian, const unsigned char *buffer) { unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; return(value & 0xffffffff); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; return(value & 0xffffffff); } static inline signed short ReadPropertySignedShort(const EndianType endian, const unsigned char *buffer) { union { unsigned short unsigned_value; signed short signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian, const unsigned char *buffer) { unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; return(value & 0xffff); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; return(value & 0xffff); } static MagickBooleanType GetEXIFProperty(const Image *image, const char *property,ExceptionInfo *exception) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define EXIF_FMT_BYTE 1 #define EXIF_FMT_STRING 2 #define EXIF_FMT_USHORT 3 #define EXIF_FMT_ULONG 4 #define EXIF_FMT_URATIONAL 5 #define EXIF_FMT_SBYTE 6 #define EXIF_FMT_UNDEFINED 7 #define EXIF_FMT_SSHORT 8 #define EXIF_FMT_SLONG 9 #define EXIF_FMT_SRATIONAL 10 #define EXIF_FMT_SINGLE 11 #define EXIF_FMT_DOUBLE 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_GPS_OFFSET 0x8825 #define TAG_INTEROP_OFFSET 0xa005 #define EXIFMultipleValues(size,format,arg) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",arg); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } #define EXIFMultipleFractions(size,format,arg1,arg2) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",(arg1),(arg2)); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } typedef struct _DirectoryInfo { const unsigned char *directory; size_t entry; ssize_t offset; } DirectoryInfo; typedef struct _TagInfo { size_t tag; const char *description; } TagInfo; static TagInfo EXIFTag[] = { { 0x001, "exif:InteroperabilityIndex" }, { 0x002, "exif:InteroperabilityVersion" }, { 0x100, "exif:ImageWidth" }, { 0x101, "exif:ImageLength" }, { 0x102, "exif:BitsPerSample" }, { 0x103, "exif:Compression" }, { 0x106, "exif:PhotometricInterpretation" }, { 0x10a, "exif:FillOrder" }, { 0x10d, "exif:DocumentName" }, { 0x10e, "exif:ImageDescription" }, { 0x10f, "exif:Make" }, { 0x110, "exif:Model" }, { 0x111, "exif:StripOffsets" }, { 0x112, "exif:Orientation" }, { 0x115, "exif:SamplesPerPixel" }, { 0x116, "exif:RowsPerStrip" }, { 0x117, "exif:StripByteCounts" }, { 0x11a, "exif:XResolution" }, { 0x11b, "exif:YResolution" }, { 0x11c, "exif:PlanarConfiguration" }, { 0x11d, "exif:PageName" }, { 0x11e, "exif:XPosition" }, { 0x11f, "exif:YPosition" }, { 0x118, "exif:MinSampleValue" }, { 0x119, "exif:MaxSampleValue" }, { 0x120, "exif:FreeOffsets" }, { 0x121, "exif:FreeByteCounts" }, { 0x122, "exif:GrayResponseUnit" }, { 0x123, "exif:GrayResponseCurve" }, { 0x124, "exif:T4Options" }, { 0x125, "exif:T6Options" }, { 0x128, "exif:ResolutionUnit" }, { 0x12d, "exif:TransferFunction" }, { 0x131, "exif:Software" }, { 0x132, "exif:DateTime" }, { 0x13b, "exif:Artist" }, { 0x13e, "exif:WhitePoint" }, { 0x13f, "exif:PrimaryChromaticities" }, { 0x140, "exif:ColorMap" }, { 0x141, "exif:HalfToneHints" }, { 0x142, "exif:TileWidth" }, { 0x143, "exif:TileLength" }, { 0x144, "exif:TileOffsets" }, { 0x145, "exif:TileByteCounts" }, { 0x14a, "exif:SubIFD" }, { 0x14c, "exif:InkSet" }, { 0x14d, "exif:InkNames" }, { 0x14e, "exif:NumberOfInks" }, { 0x150, "exif:DotRange" }, { 0x151, "exif:TargetPrinter" }, { 0x152, "exif:ExtraSample" }, { 0x153, "exif:SampleFormat" }, { 0x154, "exif:SMinSampleValue" }, { 0x155, "exif:SMaxSampleValue" }, { 0x156, "exif:TransferRange" }, { 0x157, "exif:ClipPath" }, { 0x158, "exif:XClipPathUnits" }, { 0x159, "exif:YClipPathUnits" }, { 0x15a, "exif:Indexed" }, { 0x15b, "exif:JPEGTables" }, { 0x15f, "exif:OPIProxy" }, { 0x200, "exif:JPEGProc" }, { 0x201, "exif:JPEGInterchangeFormat" }, { 0x202, "exif:JPEGInterchangeFormatLength" }, { 0x203, "exif:JPEGRestartInterval" }, { 0x205, "exif:JPEGLosslessPredictors" }, { 0x206, "exif:JPEGPointTransforms" }, { 0x207, "exif:JPEGQTables" }, { 0x208, "exif:JPEGDCTables" }, { 0x209, "exif:JPEGACTables" }, { 0x211, "exif:YCbCrCoefficients" }, { 0x212, "exif:YCbCrSubSampling" }, { 0x213, "exif:YCbCrPositioning" }, { 0x214, "exif:ReferenceBlackWhite" }, { 0x2bc, "exif:ExtensibleMetadataPlatform" }, { 0x301, "exif:Gamma" }, { 0x302, "exif:ICCProfileDescriptor" }, { 0x303, "exif:SRGBRenderingIntent" }, { 0x320, "exif:ImageTitle" }, { 0x5001, "exif:ResolutionXUnit" }, { 0x5002, "exif:ResolutionYUnit" }, { 0x5003, "exif:ResolutionXLengthUnit" }, { 0x5004, "exif:ResolutionYLengthUnit" }, { 0x5005, "exif:PrintFlags" }, { 0x5006, "exif:PrintFlagsVersion" }, { 0x5007, "exif:PrintFlagsCrop" }, { 0x5008, "exif:PrintFlagsBleedWidth" }, { 0x5009, "exif:PrintFlagsBleedWidthScale" }, { 0x500A, "exif:HalftoneLPI" }, { 0x500B, "exif:HalftoneLPIUnit" }, { 0x500C, "exif:HalftoneDegree" }, { 0x500D, "exif:HalftoneShape" }, { 0x500E, "exif:HalftoneMisc" }, { 0x500F, "exif:HalftoneScreen" }, { 0x5010, "exif:JPEGQuality" }, { 0x5011, "exif:GridSize" }, { 0x5012, "exif:ThumbnailFormat" }, { 0x5013, "exif:ThumbnailWidth" }, { 0x5014, "exif:ThumbnailHeight" }, { 0x5015, "exif:ThumbnailColorDepth" }, { 0x5016, "exif:ThumbnailPlanes" }, { 0x5017, "exif:ThumbnailRawBytes" }, { 0x5018, "exif:ThumbnailSize" }, { 0x5019, "exif:ThumbnailCompressedSize" }, { 0x501a, "exif:ColorTransferFunction" }, { 0x501b, "exif:ThumbnailData" }, { 0x5020, "exif:ThumbnailImageWidth" }, { 0x5021, "exif:ThumbnailImageHeight" }, { 0x5022, "exif:ThumbnailBitsPerSample" }, { 0x5023, "exif:ThumbnailCompression" }, { 0x5024, "exif:ThumbnailPhotometricInterp" }, { 0x5025, "exif:ThumbnailImageDescription" }, { 0x5026, "exif:ThumbnailEquipMake" }, { 0x5027, "exif:ThumbnailEquipModel" }, { 0x5028, "exif:ThumbnailStripOffsets" }, { 0x5029, "exif:ThumbnailOrientation" }, { 0x502a, "exif:ThumbnailSamplesPerPixel" }, { 0x502b, "exif:ThumbnailRowsPerStrip" }, { 0x502c, "exif:ThumbnailStripBytesCount" }, { 0x502d, "exif:ThumbnailResolutionX" }, { 0x502e, "exif:ThumbnailResolutionY" }, { 0x502f, "exif:ThumbnailPlanarConfig" }, { 0x5030, "exif:ThumbnailResolutionUnit" }, { 0x5031, "exif:ThumbnailTransferFunction" }, { 0x5032, "exif:ThumbnailSoftwareUsed" }, { 0x5033, "exif:ThumbnailDateTime" }, { 0x5034, "exif:ThumbnailArtist" }, { 0x5035, "exif:ThumbnailWhitePoint" }, { 0x5036, "exif:ThumbnailPrimaryChromaticities" }, { 0x5037, "exif:ThumbnailYCbCrCoefficients" }, { 0x5038, "exif:ThumbnailYCbCrSubsampling" }, { 0x5039, "exif:ThumbnailYCbCrPositioning" }, { 0x503A, "exif:ThumbnailRefBlackWhite" }, { 0x503B, "exif:ThumbnailCopyRight" }, { 0x5090, "exif:LuminanceTable" }, { 0x5091, "exif:ChrominanceTable" }, { 0x5100, "exif:FrameDelay" }, { 0x5101, "exif:LoopCount" }, { 0x5110, "exif:PixelUnit" }, { 0x5111, "exif:PixelPerUnitX" }, { 0x5112, "exif:PixelPerUnitY" }, { 0x5113, "exif:PaletteHistogram" }, { 0x1000, "exif:RelatedImageFileFormat" }, { 0x1001, "exif:RelatedImageLength" }, { 0x1002, "exif:RelatedImageWidth" }, { 0x800d, "exif:ImageID" }, { 0x80e3, "exif:Matteing" }, { 0x80e4, "exif:DataType" }, { 0x80e5, "exif:ImageDepth" }, { 0x80e6, "exif:TileDepth" }, { 0x828d, "exif:CFARepeatPatternDim" }, { 0x828e, "exif:CFAPattern2" }, { 0x828f, "exif:BatteryLevel" }, { 0x8298, "exif:Copyright" }, { 0x829a, "exif:ExposureTime" }, { 0x829d, "exif:FNumber" }, { 0x83bb, "exif:IPTC/NAA" }, { 0x84e3, "exif:IT8RasterPadding" }, { 0x84e5, "exif:IT8ColorTable" }, { 0x8649, "exif:ImageResourceInformation" }, { 0x8769, "exif:ExifOffset" }, { 0x8773, "exif:InterColorProfile" }, { 0x8822, "exif:ExposureProgram" }, { 0x8824, "exif:SpectralSensitivity" }, { 0x8825, "exif:GPSInfo" }, { 0x8827, "exif:ISOSpeedRatings" }, { 0x8828, "exif:OECF" }, { 0x8829, "exif:Interlace" }, { 0x882a, "exif:TimeZoneOffset" }, { 0x882b, "exif:SelfTimerMode" }, { 0x9000, "exif:ExifVersion" }, { 0x9003, "exif:DateTimeOriginal" }, { 0x9004, "exif:DateTimeDigitized" }, { 0x9101, "exif:ComponentsConfiguration" }, { 0x9102, "exif:CompressedBitsPerPixel" }, { 0x9201, "exif:ShutterSpeedValue" }, { 0x9202, "exif:ApertureValue" }, { 0x9203, "exif:BrightnessValue" }, { 0x9204, "exif:ExposureBiasValue" }, { 0x9205, "exif:MaxApertureValue" }, { 0x9206, "exif:SubjectDistance" }, { 0x9207, "exif:MeteringMode" }, { 0x9208, "exif:LightSource" }, { 0x9209, "exif:Flash" }, { 0x920a, "exif:FocalLength" }, { 0x920b, "exif:FlashEnergy" }, { 0x920c, "exif:SpatialFrequencyResponse" }, { 0x920d, "exif:Noise" }, { 0x9211, "exif:ImageNumber" }, { 0x9212, "exif:SecurityClassification" }, { 0x9213, "exif:ImageHistory" }, { 0x9214, "exif:SubjectArea" }, { 0x9215, "exif:ExposureIndex" }, { 0x9216, "exif:TIFF-EPStandardID" }, { 0x927c, "exif:MakerNote" }, { 0x9C9b, "exif:WinXP-Title" }, { 0x9C9c, "exif:WinXP-Comments" }, { 0x9C9d, "exif:WinXP-Author" }, { 0x9C9e, "exif:WinXP-Keywords" }, { 0x9C9f, "exif:WinXP-Subject" }, { 0x9286, "exif:UserComment" }, { 0x9290, "exif:SubSecTime" }, { 0x9291, "exif:SubSecTimeOriginal" }, { 0x9292, "exif:SubSecTimeDigitized" }, { 0xa000, "exif:FlashPixVersion" }, { 0xa001, "exif:ColorSpace" }, { 0xa002, "exif:ExifImageWidth" }, { 0xa003, "exif:ExifImageLength" }, { 0xa004, "exif:RelatedSoundFile" }, { 0xa005, "exif:InteroperabilityOffset" }, { 0xa20b, "exif:FlashEnergy" }, { 0xa20c, "exif:SpatialFrequencyResponse" }, { 0xa20d, "exif:Noise" }, { 0xa20e, "exif:FocalPlaneXResolution" }, { 0xa20f, "exif:FocalPlaneYResolution" }, { 0xa210, "exif:FocalPlaneResolutionUnit" }, { 0xa214, "exif:SubjectLocation" }, { 0xa215, "exif:ExposureIndex" }, { 0xa216, "exif:TIFF/EPStandardID" }, { 0xa217, "exif:SensingMethod" }, { 0xa300, "exif:FileSource" }, { 0xa301, "exif:SceneType" }, { 0xa302, "exif:CFAPattern" }, { 0xa401, "exif:CustomRendered" }, { 0xa402, "exif:ExposureMode" }, { 0xa403, "exif:WhiteBalance" }, { 0xa404, "exif:DigitalZoomRatio" }, { 0xa405, "exif:FocalLengthIn35mmFilm" }, { 0xa406, "exif:SceneCaptureType" }, { 0xa407, "exif:GainControl" }, { 0xa408, "exif:Contrast" }, { 0xa409, "exif:Saturation" }, { 0xa40a, "exif:Sharpness" }, { 0xa40b, "exif:DeviceSettingDescription" }, { 0xa40c, "exif:SubjectDistanceRange" }, { 0xa420, "exif:ImageUniqueID" }, { 0xc4a5, "exif:PrintImageMatching" }, { 0xa500, "exif:Gamma" }, { 0xc640, "exif:CR2Slice" }, { 0x10000, "exif:GPSVersionID" }, { 0x10001, "exif:GPSLatitudeRef" }, { 0x10002, "exif:GPSLatitude" }, { 0x10003, "exif:GPSLongitudeRef" }, { 0x10004, "exif:GPSLongitude" }, { 0x10005, "exif:GPSAltitudeRef" }, { 0x10006, "exif:GPSAltitude" }, { 0x10007, "exif:GPSTimeStamp" }, { 0x10008, "exif:GPSSatellites" }, { 0x10009, "exif:GPSStatus" }, { 0x1000a, "exif:GPSMeasureMode" }, { 0x1000b, "exif:GPSDop" }, { 0x1000c, "exif:GPSSpeedRef" }, { 0x1000d, "exif:GPSSpeed" }, { 0x1000e, "exif:GPSTrackRef" }, { 0x1000f, "exif:GPSTrack" }, { 0x10010, "exif:GPSImgDirectionRef" }, { 0x10011, "exif:GPSImgDirection" }, { 0x10012, "exif:GPSMapDatum" }, { 0x10013, "exif:GPSDestLatitudeRef" }, { 0x10014, "exif:GPSDestLatitude" }, { 0x10015, "exif:GPSDestLongitudeRef" }, { 0x10016, "exif:GPSDestLongitude" }, { 0x10017, "exif:GPSDestBearingRef" }, { 0x10018, "exif:GPSDestBearing" }, { 0x10019, "exif:GPSDestDistanceRef" }, { 0x1001a, "exif:GPSDestDistance" }, { 0x1001b, "exif:GPSProcessingMethod" }, { 0x1001c, "exif:GPSAreaInformation" }, { 0x1001d, "exif:GPSDateStamp" }, { 0x1001e, "exif:GPSDifferential" }, { 0x00000, (const char *) NULL } }; const StringInfo *profile; const unsigned char *directory, *exif; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; MagickBooleanType status; register ssize_t i; size_t entry, length, number_entries, tag, tag_value; SplayTreeInfo *exif_resources; ssize_t all, id, level, offset, tag_offset; static int tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; /* If EXIF data exists, then try to parse the request for a tag. */ profile=GetImageProfile(image,"exif"); if (profile == (const StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); while (isspace((int) ((unsigned char) *property)) != 0) property++; if (strlen(property) <= 5) return(MagickFalse); all=0; tag=(~0UL); switch (*(property+5)) { case '*': { /* Caller has asked for all the tags in the EXIF data. */ tag=0; all=1; /* return the data in description=value format */ break; } case '!': { tag=0; all=2; /* return the data in tagid=value format */ break; } case '#': case '@': { int c; size_t n; /* Check for a hex based tag specification first. */ tag=(*(property+5) == '@') ? 1UL : 0UL; property+=6; n=strlen(property); if (n != 4) return(MagickFalse); /* Parse tag specification as a hex number. */ n/=4; do { for (i=(ssize_t) n-1L; i >= 0; i--) { c=(*property++); tag<<=4; if ((c >= '0') && (c <= '9')) tag|=(c-'0'); else if ((c >= 'A') && (c <= 'F')) tag|=(c-('A'-10)); else if ((c >= 'a') && (c <= 'f')) tag|=(c-('a'-10)); else return(MagickFalse); } } while (*property != '\0'); break; } default: { /* Try to match the text with a tag name instead. */ for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (LocaleCompare(EXIFTag[i].description,property) == 0) { tag=(size_t) EXIFTag[i].tag; break; } } break; } } if (tag == (~0UL)) return(MagickFalse); length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); while (length != 0) { if (ReadPropertyByte(&exif,&length) != 0x45) continue; if (ReadPropertyByte(&exif,&length) != 0x78) continue; if (ReadPropertyByte(&exif,&length) != 0x69) continue; if (ReadPropertyByte(&exif,&length) != 0x66) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif); endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadPropertySignedLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); /* Set the pointer to the first IFD and follow it were it leads. */ status=MagickFalse; directory=exif+offset; level=0; entry=0; tag_offset=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { /* If there is anything on the stack then pop it off. */ if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; tag_offset=directory_stack[level].offset; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory); for ( ; entry < number_entries; entry++) { register unsigned char *p, *q; size_t format; ssize_t number_bytes, components; q=(unsigned char *) (directory+(12*entry)+2); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset; format=(size_t) ReadPropertyUnsignedShort(endian,q+2); if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes))) break; components=(ssize_t) ReadPropertySignedLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*tag_bytes[format]; if (number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { ssize_t offset; /* The directory entry contains an offset. */ offset=(ssize_t) ReadPropertySignedLong(endian,q+8); if ((offset < 0) || (size_t) offset >= length) continue; if ((ssize_t) (offset+number_bytes) < offset) continue; /* prevent overflow */ if ((size_t) (offset+number_bytes) > length) continue; p=(unsigned char *) (exif+offset); } if ((all != 0) || (tag == (size_t) tag_value)) { char buffer[MagickPathExtent], *value; value=(char *) NULL; *buffer='\0'; switch (format) { case EXIF_FMT_BYTE: case EXIF_FMT_UNDEFINED: { EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1)); break; } case EXIF_FMT_SBYTE: { EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1)); break; } case EXIF_FMT_SSHORT: { EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1)); break; } case EXIF_FMT_USHORT: { EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1)); break; } case EXIF_FMT_ULONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertyUnsignedLong(endian,p1)); break; } case EXIF_FMT_SLONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertySignedLong(endian,p1)); break; } case EXIF_FMT_URATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertyUnsignedLong(endian,p1),(double) ReadPropertyUnsignedLong(endian,p1+4)); break; } case EXIF_FMT_SRATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertySignedLong(endian,p1),(double) ReadPropertySignedLong(endian,p1+4)); break; } case EXIF_FMT_SINGLE: { EXIFMultipleValues(4,"%f",(double) *(float *) p1); break; } case EXIF_FMT_DOUBLE: { EXIFMultipleValues(8,"%f",*(double *) p1); break; } default: case EXIF_FMT_STRING: { value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { register ssize_t i; for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if ((isprint((int) p[i]) != 0) || (p[i] == '\0')) value[i]=(char) p[i]; } value[i]='\0'; } break; } } if (value != (char *) NULL) { char *key; register const char *p; key=AcquireString(property); switch (all) { case 1: { const char *description; register ssize_t i; description="unknown"; for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (EXIFTag[i].tag == tag_value) { description=EXIFTag[i].description; break; } } (void) FormatLocaleString(key,MagickPathExtent,"%s", description); if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); break; } case 2: { if (tag_value < 0x10000) (void) FormatLocaleString(key,MagickPathExtent,"#%04lx", (unsigned long) tag_value); else if (tag_value < 0x20000) (void) FormatLocaleString(key,MagickPathExtent,"@%04lx", (unsigned long) (tag_value & 0xffff)); else (void) FormatLocaleString(key,MagickPathExtent,"unknown"); break; } default: { if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); } } p=(const char *) NULL; if (image->properties != (void *) NULL) p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,key); if (p == (const char *) NULL) (void) SetImageProperty((Image *) image,key,value,exception); value=DestroyString(value); key=DestroyString(key); status=MagickTrue; } } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET)) { ssize_t offset; offset=(ssize_t) ReadPropertySignedLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { ssize_t tag_offset1; tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 : 0); directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; directory_stack[level].offset=tag_offset; level++; directory_stack[level].directory=exif+offset; directory_stack[level].offset=tag_offset1; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; directory_stack[level].offset=tag_offset1; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(status); } static MagickBooleanType GetICCProperty(const Image *image,const char *property, ExceptionInfo *exception) { const StringInfo *profile; magick_unreferenced(property); profile=GetImageProfile(image,"icc"); if (profile == (StringInfo *) NULL) profile=GetImageProfile(image,"icm"); if (profile == (StringInfo *) NULL) return(MagickFalse); if (GetStringInfoLength(profile) < 128) return(MagickFalse); /* minimum ICC profile length */ #if defined(MAGICKCORE_LCMS_DELEGATE) { cmsHPROFILE icc_profile; icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile), (cmsUInt32Number) GetStringInfoLength(profile)); if (icc_profile != (cmsHPROFILE *) NULL) { #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) const char *name; name=cmsTakeProductName(icc_profile); if (name != (const char *) NULL) (void) SetImageProperty((Image *) image,"icc:name",name,exception); #else char info[MagickPathExtent]; (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription,"en","US", info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:description",info, exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoManufacturer,"en","US", info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:manufacturer",info, exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoModel,"en","US",info, MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:model",info,exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoCopyright,"en","US", info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:copyright",info,exception); #endif (void) cmsCloseProfile(icc_profile); } } #endif return(MagickTrue); } static MagickBooleanType SkipXMPValue(const char *value) { if (value == (const char*) NULL) return(MagickTrue); while (*value != '\0') { if (isspace((int) ((unsigned char) *value)) == 0) return(MagickFalse); value++; } return(MagickTrue); } static MagickBooleanType GetXMPProperty(const Image *image,const char *property) { char *xmp_profile; const char *content; const StringInfo *profile; ExceptionInfo *exception; MagickBooleanType status; register const char *p; XMLTreeInfo *child, *description, *node, *rdf, *xmp; profile=GetImageProfile(image,"xmp"); if (profile == (StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); xmp_profile=StringInfoToString(profile); if (xmp_profile == (char *) NULL) return(MagickFalse); for (p=xmp_profile; *p != '\0'; p++) if ((*p == '<') && (*(p+1) == 'x')) break; exception=AcquireExceptionInfo(); xmp=NewXMLTree((char *) p,exception); xmp_profile=DestroyString(xmp_profile); exception=DestroyExceptionInfo(exception); if (xmp == (XMLTreeInfo *) NULL) return(MagickFalse); status=MagickFalse; rdf=GetXMLTreeChild(xmp,"rdf:RDF"); if (rdf != (XMLTreeInfo *) NULL) { if (image->properties == (void *) NULL) ((Image *) image)->properties=NewSplayTree(CompareSplayTreeString, RelinquishMagickMemory,RelinquishMagickMemory); description=GetXMLTreeChild(rdf,"rdf:Description"); while (description != (XMLTreeInfo *) NULL) { char *xmp_namespace; node=GetXMLTreeChild(description,(const char *) NULL); while (node != (XMLTreeInfo *) NULL) { child=GetXMLTreeChild(node,(const char *) NULL); content=GetXMLTreeContent(node); if ((child == (XMLTreeInfo *) NULL) && (SkipXMPValue(content) == MagickFalse)) { xmp_namespace=ConstantString(GetXMLTreeTag(node)); (void) SubstituteString(&xmp_namespace,"exif:","xmp:"); (void) AddValueToSplayTree((SplayTreeInfo *) image->properties, xmp_namespace,ConstantString(content)); } while (child != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(child); if (SkipXMPValue(content) == MagickFalse) { xmp_namespace=ConstantString(GetXMLTreeTag(node)); (void) SubstituteString(&xmp_namespace,"exif:","xmp:"); (void) AddValueToSplayTree((SplayTreeInfo *) image->properties, xmp_namespace,ConstantString(content)); } child=GetXMLTreeSibling(child); } node=GetXMLTreeSibling(node); } description=GetNextXMLTreeTag(description); } } xmp=DestroyXMLTree(xmp); return(status); } static char *TracePSClippath(const unsigned char *blob,size_t length) { char *path, *message; MagickBooleanType in_subpath; PointInfo first[3], last[3], point[3]; register ssize_t i, x; ssize_t knot_count, selector, y; path=AcquireString((char *) NULL); if (path == (char *) NULL) return((char *) NULL); message=AcquireString((char *) NULL); (void) FormatLocaleString(message,MagickPathExtent,"/ClipImage\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent,"{\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /c {curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /l {lineto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /m {moveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /v {currentpoint 6 2 roll curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /y {2 copy curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /z {closepath} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," newpath\n"); (void) ConcatenateString(&path,message); /* The clipping path format is defined in "Adobe Photoshop File Formats Specification" version 6.0 downloadable from adobe.com. */ (void) ResetMagickMemory(point,0,sizeof(point)); (void) ResetMagickMemory(first,0,sizeof(first)); (void) ResetMagickMemory(last,0,sizeof(last)); knot_count=0; in_subpath=MagickFalse; while (length > 0) { selector=(ssize_t) ReadPropertyMSBShort(&blob,&length); switch (selector) { case 0: case 3: { if (knot_count != 0) { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Expected subpath length record. */ knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length); blob+=22; length-=MagickMin(22,(ssize_t) length); break; } case 1: case 2: case 4: case 5: { if (knot_count == 0) { /* Unexpected subpath knot */ blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Add sub-path knot */ for (i=0; i < 3; i++) { size_t xx, yy; yy=(size_t) ReadPropertyMSBLong(&blob,&length); xx=(size_t) ReadPropertyMSBLong(&blob,&length); x=(ssize_t) xx; if (xx > 2147483647) x=(ssize_t) xx-4294967295U-1; y=(ssize_t) yy; if (yy > 2147483647) y=(ssize_t) yy-4294967295U-1; point[i].x=(double) x/4096/4096; point[i].y=1.0-(double) y/4096/4096; } if (in_subpath == MagickFalse) { (void) FormatLocaleString(message,MagickPathExtent," %g %g m\n", point[1].x,point[1].y); for (i=0; i < 3; i++) { first[i]=point[i]; last[i]=point[i]; } } else { /* Handle special cases when Bezier curves are used to describe corners and straight lines. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g l\n",point[1].x,point[1].y); else if ((last[1].x == last[2].x) && (last[1].y == last[2].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g v\n",point[0].x,point[0].y, point[1].x,point[1].y); else if ((point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g y\n",last[2].x,last[2].y, point[1].x,point[1].y); else (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g %g %g c\n",last[2].x, last[2].y,point[0].x,point[0].y,point[1].x,point[1].y); for (i=0; i < 3; i++) last[i]=point[i]; } (void) ConcatenateString(&path,message); in_subpath=MagickTrue; knot_count--; /* Close the subpath if there are no more knots. */ if (knot_count == 0) { /* Same special handling as above except we compare to the first point in the path and close the path. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g l z\n",first[1].x,first[1].y); else if ((last[1].x == last[2].x) && (last[1].y == last[2].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g v z\n",first[0].x,first[0].y, first[1].x,first[1].y); else if ((first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g y z\n",last[2].x,last[2].y, first[1].x,first[1].y); else (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g %g %g c z\n",last[2].x, last[2].y,first[0].x,first[0].y,first[1].x,first[1].y); (void) ConcatenateString(&path,message); in_subpath=MagickFalse; } break; } case 6: case 7: case 8: default: { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } } } /* Returns an empty PS path if the path has no knots. */ (void) FormatLocaleString(message,MagickPathExtent," eoclip\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent,"} bind def"); (void) ConcatenateString(&path,message); message=DestroyString(message); return(path); } static char *TraceSVGClippath(const unsigned char *blob,size_t length, const size_t columns,const size_t rows) { char *path, *message; MagickBooleanType in_subpath; PointInfo first[3], last[3], point[3]; register ssize_t i; ssize_t knot_count, selector, x, y; path=AcquireString((char *) NULL); if (path == (char *) NULL) return((char *) NULL); message=AcquireString((char *) NULL); (void) FormatLocaleString(message,MagickPathExtent,( "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" "<svg xmlns=\"http://www.w3.org/2000/svg\"" " width=\"%.20g\" height=\"%.20g\">\n" "<g>\n" "<path fill-rule=\"evenodd\" style=\"fill:#000000;stroke:#000000;" "stroke-width:0;stroke-antialiasing:false\" d=\"\n"),(double) columns, (double) rows); (void) ConcatenateString(&path,message); (void) ResetMagickMemory(point,0,sizeof(point)); (void) ResetMagickMemory(first,0,sizeof(first)); (void) ResetMagickMemory(last,0,sizeof(last)); knot_count=0; in_subpath=MagickFalse; while (length != 0) { selector=(ssize_t) ReadPropertyMSBShort(&blob,&length); switch (selector) { case 0: case 3: { if (knot_count != 0) { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Expected subpath length record. */ knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length); blob+=22; length-=MagickMin(22,(ssize_t) length); break; } case 1: case 2: case 4: case 5: { if (knot_count == 0) { /* Unexpected subpath knot. */ blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Add sub-path knot */ for (i=0; i < 3; i++) { unsigned int xx, yy; yy=(unsigned int) ReadPropertyMSBLong(&blob,&length); xx=(unsigned int) ReadPropertyMSBLong(&blob,&length); x=(ssize_t) xx; if (xx > 2147483647) x=(ssize_t) xx-4294967295U-1; y=(ssize_t) yy; if (yy > 2147483647) y=(ssize_t) yy-4294967295U-1; point[i].x=(double) x*columns/4096/4096; point[i].y=(double) y*rows/4096/4096; } if (in_subpath == MagickFalse) { (void) FormatLocaleString(message,MagickPathExtent,"M %g %g\n", point[1].x,point[1].y); for (i=0; i < 3; i++) { first[i]=point[i]; last[i]=point[i]; } } else { /* Handle special cases when Bezier curves are used to describe corners and straight lines. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, "L %g %g\n",point[1].x,point[1].y); else (void) FormatLocaleString(message,MagickPathExtent, "C %g %g %g %g %g %g\n",last[2].x, last[2].y,point[0].x,point[0].y,point[1].x,point[1].y); for (i=0; i < 3; i++) last[i]=point[i]; } (void) ConcatenateString(&path,message); in_subpath=MagickTrue; knot_count--; /* Close the subpath if there are no more knots. */ if (knot_count == 0) { /* Same special handling as above except we compare to the first point in the path and close the path. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, "L %g %g Z\n",first[1].x,first[1].y); else (void) FormatLocaleString(message,MagickPathExtent, "C %g %g %g %g %g %g Z\n",last[2].x, last[2].y,first[0].x,first[0].y,first[1].x,first[1].y); (void) ConcatenateString(&path,message); in_subpath=MagickFalse; } break; } case 6: case 7: case 8: default: { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } } } /* Return an empty SVG image if the path does not have knots. */ (void) ConcatenateString(&path,"\"/>\n</g>\n</svg>\n"); message=DestroyString(message); return(path); } MagickExport const char *GetImageProperty(const Image *image, const char *property,ExceptionInfo *exception) { register const char *p; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); p=(const char *) NULL; if (image->properties != (void *) NULL) { if (property == (const char *) NULL) { ResetSplayTreeIterator((SplayTreeInfo *) image->properties); p=(const char *) GetNextValueInSplayTree((SplayTreeInfo *) image->properties); return(p); } p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,property); if (p != (const char *) NULL) return(p); } if ((property == (const char *) NULL) || (strchr(property,':') == (char *) NULL)) return(p); switch (*property) { case '8': { if (LocaleNCompare("8bim:",property,5) == 0) { (void) Get8BIMProperty(image,property,exception); break; } break; } case 'E': case 'e': { if (LocaleNCompare("exif:",property,5) == 0) { (void) GetEXIFProperty(image,property,exception); break; } break; } case 'I': case 'i': { if ((LocaleNCompare("icc:",property,4) == 0) || (LocaleNCompare("icm:",property,4) == 0)) { (void) GetICCProperty(image,property,exception); break; } if (LocaleNCompare("iptc:",property,5) == 0) { (void) GetIPTCProperty(image,property,exception); break; } break; } case 'X': case 'x': { if (LocaleNCompare("xmp:",property,4) == 0) { (void) GetXMPProperty(image,property); break; } break; } default: break; } if (image->properties != (void *) NULL) { p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,property); return(p); } return((const char *) NULL); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t M a g i c k P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickProperty() gets attributes or calculated values that is associated % with a fixed known property name, or single letter property. It may be % called if no image is defined (IMv7), in which case only global image_info % values are available: % % \n newline % \r carriage return % < less-than character. % > greater-than character. % & ampersand character. % %% a percent sign % %b file size of image read in % %c comment meta-data property % %d directory component of path % %e filename extension or suffix % %f filename (including suffix) % %g layer canvas page geometry (equivalent to "%Wx%H%X%Y") % %h current image height in pixels % %i image filename (note: becomes output filename for "info:") % %k CALCULATED: number of unique colors % %l label meta-data property % %m image file format (file magic) % %n number of images in current image sequence % %o output filename (used for delegates) % %p index of image in current image list % %q quantum depth (compile-time constant) % %r image class and colorspace % %s scene number (from input unless re-assigned) % %t filename without directory or extension (suffix) % %u unique temporary filename (used for delegates) % %w current width in pixels % %x x resolution (density) % %y y resolution (density) % %z image depth (as read in unless modified, image save depth) % %A image transparency channel enabled (true/false) % %C image compression type % %D image GIF dispose method % %G original image size (%wx%h; before any resizes) % %H page (canvas) height % %M Magick filename (original file exactly as given, including read mods) % %O page (canvas) offset ( = %X%Y ) % %P page (canvas) size ( = %Wx%H ) % %Q image compression quality ( 0 = default ) % %S ?? scenes ?? % %T image time delay (in centi-seconds) % %U image resolution units % %W page (canvas) width % %X page (canvas) x offset (including sign) % %Y page (canvas) y offset (including sign) % %Z unique filename (used for delegates) % %@ CALCULATED: trim bounding box (without actually trimming) % %# CALCULATED: 'signature' hash of image values % % This routine only handles specifically known properties. It does not % handle special prefixed properties, profiles, or expressions. Nor does % it return any free-form property strings. % % The returned string is stored in a structure somewhere, and should not be % directly freed. If the string was generated (common) the string will be % stored as as either as artifact or option 'get-property'. These may be % deleted (cleaned up) when no longer required, but neither artifact or % option is guranteed to exist. % % The format of the GetMagickProperty method is: % % const char *GetMagickProperty(ImageInfo *image_info,Image *image, % const char *property,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info (optional) % % o image: the image (optional) % % o key: the key. % % o exception: return any errors or warnings in this structure. % */ static const char *GetMagickPropertyLetter(ImageInfo *image_info, Image *image,const char letter,ExceptionInfo *exception) { #define WarnNoImageReturn(format,arg) \ if (image == (Image *) NULL ) { \ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \ "NoImageForProperty",format,arg); \ return((const char *) NULL); \ } #define WarnNoImageInfoReturn(format,arg) \ if (image_info == (ImageInfo *) NULL ) { \ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \ "NoImageInfoForProperty",format,arg); \ return((const char *) NULL); \ } char value[MagickPathExtent]; /* formatted string to store as an artifact */ const char *string; /* return a string already stored somewher */ if ((image != (Image *) NULL) && (image->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images"); *value='\0'; /* formatted string */ string=(char *) NULL; /* constant string reference */ /* Get properities that are directly defined by images. */ switch (letter) { case 'b': /* image size read in - in bytes */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatMagickSize(image->extent,MagickFalse,"B",MagickPathExtent, value); if (image->extent == 0) (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B", MagickPathExtent,value); break; } case 'c': /* image comment property - empty string by default */ { WarnNoImageReturn("\"%%%c\"",letter); string=GetImageProperty(image,"comment",exception); if ( string == (const char *) NULL ) string=""; break; } case 'd': /* Directory component of filename */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,HeadPath,value); if (*value == '\0') string=""; break; } case 'e': /* Filename extension (suffix) of image file */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,ExtensionPath,value); if (*value == '\0') string=""; break; } case 'f': /* Filename without directory component */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,TailPath,value); if (*value == '\0') string=""; break; } case 'g': /* Image geometry, canvas and offset %Wx%H+%X+%Y */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); break; } case 'h': /* Image height (current) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->rows != 0 ? image->rows : image->magick_rows)); break; } case 'i': /* Filename last used for an image (read or write) */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->filename; break; } case 'k': /* Number of unique colors */ { /* FUTURE: ensure this does not generate the formatted comment! */ WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetNumberColors(image,(FILE *) NULL,exception)); break; } case 'l': /* Image label property - empty string by default */ { WarnNoImageReturn("\"%%%c\"",letter); string=GetImageProperty(image,"label",exception); if (string == (const char *) NULL) string=""; break; } case 'm': /* Image format (file magick) */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->magick; break; } case 'n': /* Number of images in the list. */ { if ( image != (Image *) NULL ) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageListLength(image)); else string="0"; /* no images or scenes */ break; } case 'o': /* Output Filename - for delegate use only */ WarnNoImageInfoReturn("\"%%%c\"",letter); string=image_info->filename; break; case 'p': /* Image index in current image list */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageIndexInList(image)); break; } case 'q': /* Quantum depth of image in memory */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) MAGICKCORE_QUANTUM_DEPTH); break; } case 'r': /* Image storage class, colorspace, and alpha enabled. */ { ColorspaceType colorspace; WarnNoImageReturn("\"%%%c\"",letter); colorspace=image->colorspace; if (SetImageGray(image,exception) != MagickFalse) colorspace=GRAYColorspace; /* FUTURE: this is IMv6 not IMv7 */ (void) FormatLocaleString(value,MagickPathExtent,"%s %s %s", CommandOptionToMnemonic(MagickClassOptions,(ssize_t) image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions, (ssize_t) colorspace),image->alpha_trait != UndefinedPixelTrait ? "Alpha" : ""); break; } case 's': /* Image scene number */ { #if 0 /* this seems non-sensical -- simplifing */ if (image_info->number_scenes != 0) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene); else if (image != (Image *) NULL) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); else string="0"; #else WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); #endif break; } case 't': /* Base filename without directory or extention */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,BasePath,value); if (*value == '\0') string=""; break; } case 'u': /* Unique filename */ { WarnNoImageInfoReturn("\"%%%c\"",letter); string=image_info->unique; break; } case 'w': /* Image width (current) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->columns != 0 ? image->columns : image->magick_columns)); break; } case 'x': /* Image horizontal resolution (with units) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", fabs(image->resolution.x) > MagickEpsilon ? image->resolution.x : 72.0); break; } case 'y': /* Image vertical resolution (with units) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", fabs(image->resolution.y) > MagickEpsilon ? image->resolution.y : 72.0); break; } case 'z': /* Image depth as read in */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->depth); break; } case 'A': /* Image alpha channel */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickPixelTraitOptions,(ssize_t) image->alpha_trait); break; } case 'C': /* Image compression method. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickCompressOptions,(ssize_t) image->compression); break; } case 'D': /* Image dispose method. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickDisposeOptions,(ssize_t) image->dispose); break; } case 'G': /* Image size as geometry = "%wx%h" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g",(double) image->magick_columns,(double) image->magick_rows); break; } case 'H': /* layer canvas height */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->page.height); break; } case 'M': /* Magick filename - filename given incl. coder & read mods */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->magick_filename; break; } case 'O': /* layer canvas offset with sign = "+%X+%Y" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+ld%+ld",(long) image->page.x,(long) image->page.y); break; } case 'P': /* layer canvas page size = "%Wx%H" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g",(double) image->page.width,(double) image->page.height); break; } case 'Q': /* image compression quality */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->quality == 0 ? 92 : image->quality)); break; } case 'S': /* Number of scenes in image list. */ { WarnNoImageInfoReturn("\"%%%c\"",letter); #if 0 /* What is this number? -- it makes no sense - simplifing */ if (image_info->number_scenes == 0) string="2147483647"; else if ( image != (Image *) NULL ) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene+image_info->number_scenes); else string="0"; #else (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image_info->number_scenes == 0 ? 2147483647 : image_info->number_scenes)); #endif break; } case 'T': /* image time delay for animations */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->delay); break; } case 'U': /* Image resolution units. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t) image->units); break; } case 'W': /* layer canvas width */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->page.width); break; } case 'X': /* layer canvas X offset */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double) image->page.x); break; } case 'Y': /* layer canvas Y offset */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double) image->page.y); break; } case '%': /* percent escaped */ { string="%"; break; } case '@': /* Trim bounding box, without actually Trimming! */ { RectangleInfo page; WarnNoImageReturn("\"%%%c\"",letter); page=GetImageBoundingBox(image,exception); (void) FormatLocaleString(value,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) page.width,(double) page.height, (double) page.x,(double)page.y); break; } case '#': { /* Image signature. */ WarnNoImageReturn("\"%%%c\"",letter); (void) SignatureImage(image,exception); string=GetImageProperty(image,"signature",exception); break; } } if (string != (char *) NULL) return(string); if (*value != '\0') { /* Create a cloned copy of result. */ if (image != (Image *) NULL) { (void) SetImageArtifact(image,"get-property",value); return(GetImageArtifact(image,"get-property")); } else { (void) SetImageOption(image_info,"get-property",value); return(GetImageOption(image_info,"get-property")); } } return((char *) NULL); } MagickExport const char *GetMagickProperty(ImageInfo *image_info, Image *image,const char *property,ExceptionInfo *exception) { char value[MagickPathExtent]; const char *string; assert(property[0] != '\0'); assert(image != (Image *) NULL || image_info != (ImageInfo *) NULL ); if (property[1] == '\0') /* single letter property request */ return(GetMagickPropertyLetter(image_info,image,*property,exception)); if ((image != (Image *) NULL) && (image->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images"); *value='\0'; /* formated string */ string=(char *) NULL; /* constant string reference */ switch (*property) { case 'b': { if (LocaleCompare("basename",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,BasePath,value); if (*value == '\0') string=""; break; } if (LocaleCompare("bit-depth",property) == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageDepth(image,exception)); break; } break; } case 'c': { if (LocaleCompare("channels",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); /* FUTURE: return actual image channels */ (void) FormatLocaleString(value,MagickPathExtent,"%s", CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) image->colorspace)); LocaleLower(value); if( image->alpha_trait != UndefinedPixelTrait ) (void) ConcatenateMagickString(value,"a",MagickPathExtent); break; } if (LocaleCompare("colorspace",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); /* FUTURE: return actual colorspace - no 'gray' stuff */ string=CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) image->colorspace); break; } if (LocaleCompare("compose",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickComposeOptions,(ssize_t) image->compose); break; } if (LocaleCompare("copyright",property) == 0) { (void) CopyMagickString(value,GetMagickCopyright(),MagickPathExtent); break; } break; } case 'd': { if (LocaleCompare("depth",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->depth); break; } if (LocaleCompare("directory",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,HeadPath,value); if (*value == '\0') string=""; break; } break; } case 'e': { if (LocaleCompare("entropy",property) == 0) { double entropy; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageEntropy(image,&entropy,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),entropy); break; } if (LocaleCompare("extension",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,ExtensionPath,value); if (*value == '\0') string=""; break; } break; } case 'g': { if (LocaleCompare("gamma",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),image->gamma); break; } break; } case 'h': { if (LocaleCompare("height",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", image->magick_rows != 0 ? (double) image->magick_rows : 256.0); break; } break; } case 'i': { if (LocaleCompare("input",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=image->filename; break; } break; } case 'k': { if (LocaleCompare("kurtosis",property) == 0) { double kurtosis, skewness; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),kurtosis); break; } break; } case 'm': { if (LocaleCompare("magick",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=image->magick; break; } if ((LocaleCompare("maxima",property) == 0) || (LocaleCompare("max",property) == 0)) { double maximum, minimum; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageRange(image,&minimum,&maximum,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),maximum); break; } if (LocaleCompare("mean",property) == 0) { double mean, standard_deviation; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageMean(image,&mean,&standard_deviation,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),mean); break; } if ((LocaleCompare("minima",property) == 0) || (LocaleCompare("min",property) == 0)) { double maximum, minimum; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageRange(image,&minimum,&maximum,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),minimum); break; } break; } case 'o': { if (LocaleCompare("opaque",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) IsImageOpaque(image,exception)); break; } if (LocaleCompare("orientation",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickOrientationOptions,(ssize_t) image->orientation); break; } if (LocaleCompare("output",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); (void) CopyMagickString(value,image_info->filename,MagickPathExtent); break; } break; } case 'p': { #if defined(MAGICKCORE_LCMS_DELEGATE) if (LocaleCompare("profile:icc",property) == 0 || LocaleCompare("profile:icm",property) == 0) { #if !defined(LCMS_VERSION) || (LCMS_VERSION < 2000) #define cmsUInt32Number DWORD #endif const StringInfo *profile; cmsHPROFILE icc_profile; profile=GetImageProfile(image,property+8); if (profile == (StringInfo *) NULL) break; icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile), (cmsUInt32Number) GetStringInfoLength(profile)); if (icc_profile != (cmsHPROFILE *) NULL) { #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) string=cmsTakeProductName(icc_profile); #else (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription, "en","US",value,MagickPathExtent); #endif (void) cmsCloseProfile(icc_profile); } } #endif if (LocaleCompare("profiles",property) == 0) { const char *name; ResetImageProfileIterator(image); name=GetNextImageProfile(image); if (name != (char *) NULL) { (void) CopyMagickString(value,name,MagickPathExtent); name=GetNextImageProfile(image); while (name != (char *) NULL) { ConcatenateMagickString(value,",",MagickPathExtent); ConcatenateMagickString(value,name,MagickPathExtent); name=GetNextImageProfile(image); } } break; } break; } case 'r': { if (LocaleCompare("resolution.x",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.x); break; } if (LocaleCompare("resolution.y",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.y); break; } break; } case 's': { if (LocaleCompare("scene",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); if (image_info->number_scenes != 0) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene); else { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); } break; } if (LocaleCompare("scenes",property) == 0) { /* FUTURE: equivelent to %n? */ WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageListLength(image)); break; } if (LocaleCompare("size",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B", MagickPathExtent,value); break; } if (LocaleCompare("skewness",property) == 0) { double kurtosis, skewness; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),skewness); break; } if (LocaleCompare("standard-deviation",property) == 0) { double mean, standard_deviation; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageMean(image,&mean,&standard_deviation,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),standard_deviation); break; } break; } case 't': { if (LocaleCompare("type",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickTypeOptions,(ssize_t) IdentifyImageType(image,exception)); break; } break; } case 'u': { if (LocaleCompare("unique",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); string=image_info->unique; break; } if (LocaleCompare("units",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t) image->units); break; } break; } case 'v': { if (LocaleCompare("version",property) == 0) { string=GetMagickVersion((size_t *) NULL); break; } break; } case 'w': { if (LocaleCompare("width",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->magick_columns != 0 ? image->magick_columns : 256)); break; } break; } } if (string != (char *) NULL) return(string); if (*value != '\0') { /* Create a cloned copy of result, that will get cleaned up, eventually. */ if (image != (Image *) NULL) { (void) SetImageArtifact(image,"get-property",value); return(GetImageArtifact(image,"get-property")); } else { (void) SetImageOption(image_info,"get-property",value); return(GetImageOption(image_info,"get-property")); } } return((char *) NULL); } #undef WarnNoImageReturn /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProperty() gets the next free-form string property name. % % The format of the GetNextImageProperty method is: % % char *GetNextImageProperty(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetNextImageProperty(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return((const char *) NULL); return((const char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->properties)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageProperties() replaces any embedded formatting characters with % the appropriate image property and returns the interpreted text. % % This searches for and replaces % \n \r \% replaced by newline, return, and percent resp. % &lt; &gt; &amp; replaced by '<', '>', '&' resp. % %% replaced by percent % % %x %[x] where 'x' is a single letter properity, case sensitive). % %[type:name] where 'type' a is special and known prefix. % %[name] where 'name' is a specifically known attribute, calculated % value, or a per-image property string name, or a per-image % 'artifact' (as generated from a global option). % It may contain ':' as long as the prefix is not special. % % Single letter % substitutions will only happen if the character before the % percent is NOT a number. But braced substitutions will always be performed. % This prevents the typical usage of percent in a interpreted geometry % argument from being substituted when the percent is a geometry flag. % % If 'glob-expresions' ('*' or '?' characters) is used for 'name' it may be % used as a search pattern to print multiple lines of "name=value\n" pairs of % the associacted set of properties. % % The returned string must be freed using DestoryString() by the caller. % % The format of the InterpretImageProperties method is: % % char *InterpretImageProperties(ImageInfo *image_info, % Image *image,const char *embed_text,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. (required) % % o image: the image. (optional) % % o embed_text: the address of a character string containing the embedded % formatting characters. % % o exception: return any errors or warnings in this structure. % */ MagickExport char *InterpretImageProperties(ImageInfo *image_info,Image *image, const char *embed_text,ExceptionInfo *exception) { #define ExtendInterpretText(string_length) \ DisableMSCWarning(4127) \ { \ size_t length=(string_length); \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ } \ RestoreMSCWarning #define AppendKeyValue2Text(key,value)\ DisableMSCWarning(4127) \ { \ size_t length=strlen(key)+strlen(value)+2; \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ q+=FormatLocaleString(q,extent,"%s=%s\n",(key),(value)); \ } \ RestoreMSCWarning #define AppendString2Text(string) \ DisableMSCWarning(4127) \ { \ size_t length=strlen((string)); \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ (void) CopyMagickString(q,(string),extent); \ q+=length; \ } \ RestoreMSCWarning char *interpret_text; MagickBooleanType number; register char *q; /* current position in interpret_text */ register const char *p; /* position in embed_text string being expanded */ size_t extent; /* allocated length of interpret_text */ assert(image == NULL || image->signature == MagickCoreSignature); assert(image_info == NULL || image_info->signature == MagickCoreSignature); if ((image != (Image *) NULL) && (image->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-image"); if (embed_text == (const char *) NULL) return(ConstantString("")); p=embed_text; while ((isspace((int) ((unsigned char) *p)) != 0) && (*p != '\0')) p++; if (*p == '\0') return(ConstantString("")); if ((*p == '@') && (IsPathAccessible(p+1) != MagickFalse)) { /* Handle a '@' replace string from file. */ if (IsRightsAuthorized(PathPolicyDomain,ReadPolicyRights,p) == MagickFalse) { errno=EPERM; (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, "NotAuthorized","`%s'",p); return(ConstantString("")); } interpret_text=FileToString(p+1,~0UL,exception); if (interpret_text != (char *) NULL) return(interpret_text); } /* Translate any embedded format characters. */ interpret_text=AcquireString(embed_text); /* new string with extra space */ extent=MagickPathExtent; /* allocated space in string */ number=MagickFalse; /* is last char a number? */ for (q=interpret_text; *p!='\0'; number=isdigit(*p) ? MagickTrue : MagickFalse,p++) { /* Look for the various escapes, (and handle other specials) */ *q='\0'; ExtendInterpretText(MagickPathExtent); switch (*p) { case '\\': { switch (*(p+1)) { case '\0': continue; case 'r': /* convert to RETURN */ { *q++='\r'; p++; continue; } case 'n': /* convert to NEWLINE */ { *q++='\n'; p++; continue; } case '\n': /* EOL removal UNIX,MacOSX */ { p++; continue; } case '\r': /* EOL removal DOS,Windows */ { p++; if (*p == '\n') /* return-newline EOL */ p++; continue; } default: { p++; *q++=(*p); } } continue; } case '&': { if (LocaleNCompare("&lt;",p,4) == 0) { *q++='<'; p+=3; } else if (LocaleNCompare("&gt;",p,4) == 0) { *q++='>'; p+=3; } else if (LocaleNCompare("&amp;",p,5) == 0) { *q++='&'; p+=4; } else *q++=(*p); continue; } case '%': break; /* continue to next set of handlers */ default: { *q++=(*p); /* any thing else is 'as normal' */ continue; } } p++; /* advance beyond the percent */ /* Doubled Percent - or percent at end of string. */ if ((*p == '\0') || (*p == '\'') || (*p == '"')) p--; if (*p == '%') { *q++='%'; continue; } /* Single letter escapes %c. */ if (*p != '[') { const char *string; if (number != MagickFalse) { /* But only if not preceeded by a number! */ *q++='%'; /* do NOT substitute the percent */ p--; /* back up one */ continue; } string=GetMagickPropertyLetter(image_info,image,*p, exception); if (string != (char *) NULL) { AppendString2Text(string); if (image != (Image *) NULL) (void) DeleteImageArtifact(image,"get-property"); if (image_info != (ImageInfo *) NULL) (void) DeleteImageOption(image_info,"get-property"); continue; } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%%c\"",*p); continue; } { char pattern[2*MagickPathExtent]; const char *key, *string; register ssize_t len; ssize_t depth; /* Braced Percent Escape %[...]. */ p++; /* advance p to just inside the opening brace */ depth=1; if (*p == ']') { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%[]\""); break; } for (len=0; len<(MagickPathExtent-1L) && (*p != '\0');) { if ((*p == '\\') && (*(p+1) != '\0')) { /* Skip escaped braces within braced pattern. */ pattern[len++]=(*p++); pattern[len++]=(*p++); continue; } if (*p == '[') depth++; if (*p == ']') depth--; if (depth <= 0) break; pattern[len++]=(*p++); } pattern[len]='\0'; if (depth != 0) { /* Check for unmatched final ']' for "%[...]". */ if (len >= 64) { pattern[61] = '.'; /* truncate string for error message */ pattern[62] = '.'; pattern[63] = '.'; pattern[64] = '\0'; } (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnbalancedBraces","\"%%[%s\"",pattern); interpret_text=DestroyString(interpret_text); return((char *) NULL); } /* Special Lookup Prefixes %[prefix:...]. */ if (LocaleNCompare("fx:",pattern,3) == 0) { double value; FxInfo *fx_info; MagickBooleanType status; /* FX - value calculator. */ if (image == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } fx_info=AcquireFxInfo(image,pattern+3,exception); status=FxEvaluateChannelExpression(fx_info,IntensityPixelChannel,0,0, &value,exception); fx_info=DestroyFxInfo(fx_info); if (status != MagickFalse) { char result[MagickPathExtent]; (void) FormatLocaleString(result,MagickPathExtent,"%.*g", GetMagickPrecision(),(double) value); AppendString2Text(result); } continue; } if (LocaleNCompare("hex:",pattern,4) == 0) { double value; FxInfo *fx_info; MagickStatusType status; PixelInfo pixel; /* Pixel - color value calculator. */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } GetPixelInfo(image,&pixel); fx_info=AcquireFxInfo(image,pattern+6,exception); status=FxEvaluateChannelExpression(fx_info,RedPixelChannel,0,0, &value,exception); pixel.red=(double) QuantumRange*value; status&=FxEvaluateChannelExpression(fx_info,GreenPixelChannel,0,0, &value,exception); pixel.green=(double) QuantumRange*value; status&=FxEvaluateChannelExpression(fx_info,BluePixelChannel,0,0, &value,exception); pixel.blue=(double) QuantumRange*value; if (image->colorspace == CMYKColorspace) { status&=FxEvaluateChannelExpression(fx_info,BlackPixelChannel,0,0, &value,exception); pixel.black=(double) QuantumRange*value; } status&=FxEvaluateChannelExpression(fx_info,AlphaPixelChannel,0,0, &value,exception); pixel.alpha=(double) QuantumRange*value; fx_info=DestroyFxInfo(fx_info); if (status != MagickFalse) { char hex[MagickPathExtent], name[MagickPathExtent]; (void) QueryColorname(image,&pixel,SVGCompliance,name,exception); GetColorTuple(&pixel,MagickTrue,hex); AppendString2Text(hex+1); } continue; } if (LocaleNCompare("pixel:",pattern,6) == 0) { double value; FxInfo *fx_info; MagickStatusType status; PixelInfo pixel; /* Pixel - color value calculator. */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } GetPixelInfo(image,&pixel); fx_info=AcquireFxInfo(image,pattern+6,exception); status=FxEvaluateChannelExpression(fx_info,RedPixelChannel,0,0, &value,exception); pixel.red=(double) QuantumRange*value; status&=FxEvaluateChannelExpression(fx_info,GreenPixelChannel,0,0, &value,exception); pixel.green=(double) QuantumRange*value; status&=FxEvaluateChannelExpression(fx_info,BluePixelChannel,0,0, &value,exception); pixel.blue=(double) QuantumRange*value; if (image->colorspace == CMYKColorspace) { status&=FxEvaluateChannelExpression(fx_info,BlackPixelChannel,0,0, &value,exception); pixel.black=(double) QuantumRange*value; } status&=FxEvaluateChannelExpression(fx_info,AlphaPixelChannel,0,0, &value,exception); pixel.alpha=(double) QuantumRange*value; fx_info=DestroyFxInfo(fx_info); if (status != MagickFalse) { char name[MagickPathExtent]; (void) QueryColorname(image,&pixel,SVGCompliance,name,exception); AppendString2Text(name); } continue; } if (LocaleNCompare("option:",pattern,7) == 0) { /* Option - direct global option lookup (with globbing). */ if (image_info == (ImageInfo *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+7) != MagickFalse) { ResetImageOptionIterator(image_info); while ((key=GetNextImageOption(image_info)) != (const char *) NULL) if (GlobExpression(key,pattern+7,MagickTrue) != MagickFalse) { string=GetImageOption(image_info,key); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? key found but no string value! */ } continue; } string=GetImageOption(image_info,pattern+7); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (LocaleNCompare("artifact:",pattern,9) == 0) { /* Artifact - direct image artifact lookup (with glob). */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+9) != MagickFalse) { ResetImageArtifactIterator(image); while ((key=GetNextImageArtifact(image)) != (const char *) NULL) if (GlobExpression(key,pattern+9,MagickTrue) != MagickFalse) { string=GetImageArtifact(image,key); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? key found but no string value! */ } continue; } string=GetImageArtifact(image,pattern+9); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (LocaleNCompare("property:",pattern,9) == 0) { /* Property - direct image property lookup (with glob). */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+9) != MagickFalse) { ResetImagePropertyIterator(image); while ((key=GetNextImageProperty(image)) != (const char *) NULL) if (GlobExpression(key,pattern,MagickTrue) != MagickFalse) { string=GetImageProperty(image,key,exception); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? */ } continue; } string=GetImageProperty(image,pattern+9,exception); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (image != (Image *) NULL) { /* Properties without special prefix. This handles attributes, properties, and profiles such as %[exif:...]. Note the profile properties may also include a glob expansion pattern. */ string=GetImageProperty(image,pattern,exception); if (string != (const char *) NULL) { AppendString2Text(string); if (image != (Image *) NULL) (void)DeleteImageArtifact(image,"get-property"); if (image_info != (ImageInfo *) NULL) (void)DeleteImageOption(image_info,"get-property"); continue; } } if (IsGlob(pattern) != MagickFalse) { /* Handle property 'glob' patterns such as: %[*] %[user:array_??] %[filename:e*]> */ if (image == (Image *) NULL) continue; /* else no image to retrieve proprty - no list */ ResetImagePropertyIterator(image); while ((key=GetNextImageProperty(image)) != (const char *) NULL) if (GlobExpression(key,pattern,MagickTrue) != MagickFalse) { string=GetImageProperty(image,key,exception); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? */ } continue; } /* Look for a known property or image attribute such as %[basename] %[denisty] %[delay]. Also handles a braced single letter: %[b] %[G] %[g]. */ string=GetMagickProperty(image_info,image,pattern,exception); if (string != (const char *) NULL) { AppendString2Text(string); continue; } /* Look for a per-image artifact. This includes option lookup (FUTURE: interpreted according to image). */ if (image != (Image *) NULL) { string=GetImageArtifact(image,pattern); if (string != (char *) NULL) { AppendString2Text(string); continue; } } else if (image_info != (ImageInfo *) NULL) { /* No image, so direct 'option' lookup (no delayed percent escapes). */ string=GetImageOption(image_info,pattern); if (string != (char *) NULL) { AppendString2Text(string); continue; } } PropertyLookupFailure: /* Failed to find any match anywhere! */ if (len >= 64) { pattern[61] = '.'; /* truncate string for error message */ pattern[62] = '.'; pattern[63] = '.'; pattern[64] = '\0'; } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%[%s]\"",pattern); } } *q='\0'; return(interpret_text); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProperty() removes a property from the image and returns its % value. % % In this case the ConstantString() value returned should be freed by the % caller when finished. % % The format of the RemoveImageProperty method is: % % char *RemoveImageProperty(Image *image,const char *property) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % */ MagickExport char *RemoveImageProperty(Image *image,const char *property) { char *value; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->properties == (void *) NULL) return((char *) NULL); value=(char *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->properties, property); return(value); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P r o p e r t y I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePropertyIterator() resets the image properties iterator. Use it % in conjunction with GetNextImageProperty() to iterate over all the values % associated with an image property. % % The format of the ResetImagePropertyIterator method is: % % ResetImagePropertyIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImagePropertyIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->properties == (void *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->properties); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProperty() saves the given string value either to specific known % attribute or to a freeform property string. % % Attempting to set a property that is normally calculated will produce % an exception. % % The format of the SetImageProperty method is: % % MagickBooleanType SetImageProperty(Image *image,const char *property, % const char *value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % % o values: the image property values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageProperty(Image *image, const char *property,const char *value,ExceptionInfo *exception) { MagickBooleanType status; MagickStatusType flags; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->properties == (void *) NULL) image->properties=NewSplayTree(CompareSplayTreeString, RelinquishMagickMemory,RelinquishMagickMemory); /* create splay-tree */ if (value == (const char *) NULL) return(DeleteImageProperty(image,property)); /* delete if NULL */ status=MagickTrue; if (strlen(property) <= 1) { /* Do not 'set' single letter properties - read only shorthand. */ (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } /* FUTURE: binary chars or quotes in key should produce a error */ /* Set attributes with known names or special prefixes return result is found, or break to set a free form properity */ switch (*property) { #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case '8': { if (LocaleNCompare("8bim:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; } #endif case 'B': case 'b': { if (LocaleCompare("background",property) == 0) { (void) QueryColorCompliance(value,AllCompliance, &image->background_color,exception); /* check for FUTURE: value exception?? */ /* also add user input to splay tree */ } break; /* not an attribute, add as a property */ } case 'C': case 'c': { if (LocaleCompare("channels",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } if (LocaleCompare("colorspace",property) == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, value); if (colorspace < 0) return(MagickFalse); /* FUTURE: value exception?? */ return(SetImageColorspace(image,(ColorspaceType) colorspace,exception)); } if (LocaleCompare("compose",property) == 0) { ssize_t compose; compose=ParseCommandOption(MagickComposeOptions,MagickFalse,value); if (compose < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->compose=(CompositeOperator) compose; return(MagickTrue); } if (LocaleCompare("compress",property) == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions,MagickFalse, value); if (compression < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->compression=(CompressionType) compression; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'D': case 'd': { if (LocaleCompare("delay",property) == 0) { GeometryInfo geometry_info; flags=ParseGeometry(value,&geometry_info); if ((flags & GreaterValue) != 0) { if (image->delay > (size_t) floor(geometry_info.rho+0.5)) image->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (image->delay < (size_t) floor(geometry_info.rho+0.5)) image->delay=(ssize_t) floor(geometry_info.sigma+0.5); } else image->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); return(MagickTrue); } if (LocaleCompare("delay_units",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } if (LocaleCompare("density",property) == 0) { GeometryInfo geometry_info; flags=ParseGeometry(value,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; return(MagickTrue); } if (LocaleCompare("depth",property) == 0) { image->depth=StringToUnsignedLong(value); return(MagickTrue); } if (LocaleCompare("dispose",property) == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,value); if (dispose < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->dispose=(DisposeType) dispose; return(MagickTrue); } break; /* not an attribute, add as a property */ } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case 'E': case 'e': { if (LocaleNCompare("exif:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'F': case 'f': { if (LocaleNCompare("fx:",property,3) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #endif case 'G': case 'g': { if (LocaleCompare("gamma",property) == 0) { image->gamma=StringToDouble(value,(char **) NULL); return(MagickTrue); } if (LocaleCompare("gravity",property) == 0) { ssize_t gravity; gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value); if (gravity < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->gravity=(GravityType) gravity; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'H': case 'h': { if (LocaleCompare("height",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'I': case 'i': { if (LocaleCompare("intensity",property) == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickIntentOptions,MagickFalse,value); if (intensity < 0) return(MagickFalse); image->intensity=(PixelIntensityMethod) intensity; return(MagickTrue); } if (LocaleCompare("intent",property) == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, value); if (rendering_intent < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->rendering_intent=(RenderingIntent) rendering_intent; return(MagickTrue); } if (LocaleCompare("interpolate",property) == 0) { ssize_t interpolate; interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, value); if (interpolate < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->interpolate=(PixelInterpolateMethod) interpolate; return(MagickTrue); } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ if (LocaleNCompare("iptc:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } #endif break; /* not an attribute, add as a property */ } case 'K': case 'k': if (LocaleCompare("kurtosis",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'L': case 'l': { if (LocaleCompare("loop",property) == 0) { image->iterations=StringToUnsignedLong(value); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'M': case 'm': if ((LocaleCompare("magick",property) == 0) || (LocaleCompare("max",property) == 0) || (LocaleCompare("mean",property) == 0) || (LocaleCompare("min",property) == 0) || (LocaleCompare("min",property) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'O': case 'o': if (LocaleCompare("opaque",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'P': case 'p': { if (LocaleCompare("page",property) == 0) { char *geometry; geometry=GetPageGeometry(value); flags=ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); return(MagickTrue); } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ if (LocaleNCompare("pixel:",property,6) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } #endif if (LocaleCompare("profile",property) == 0) { ImageInfo *image_info; StringInfo *profile; image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,value,MagickPathExtent); (void) SetImageInfo(image_info,1,exception); profile=FileToStringInfo(image_info->filename,~0UL,exception); if (profile != (StringInfo *) NULL) status=SetImageProfile(image,image_info->magick,profile,exception); image_info=DestroyImageInfo(image_info); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'R': case 'r': { if (LocaleCompare("rendering-intent",property) == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, value); if (rendering_intent < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->rendering_intent=(RenderingIntent) rendering_intent; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'S': case 's': if ((LocaleCompare("size",property) == 0) || (LocaleCompare("skewness",property) == 0) || (LocaleCompare("scenes",property) == 0) || (LocaleCompare("standard-deviation",property) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'T': case 't': { if (LocaleCompare("tile-offset",property) == 0) { char *geometry; geometry=GetPageGeometry(value); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'U': case 'u': { if (LocaleCompare("units",property) == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse,value); if (units < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->units=(ResolutionType) units; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'V': case 'v': { if (LocaleCompare("version",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'W': case 'w': { if (LocaleCompare("width",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case 'X': case 'x': { if (LocaleNCompare("xmp:",property,4) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #endif } /* Default: not an attribute, add as a property */ status=AddValueToSplayTree((SplayTreeInfo *) image->properties, ConstantString(property),ConstantString(value)); /* FUTURE: error if status is bad? */ return(status); }
null
null
null
null
72,716
30,108
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
30,108
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* -LICENSE-START- ** Copyright (c) 2016 Blackmagic Design ** ** Permission is hereby granted, free of charge, to any person or organization ** obtaining a copy of the software and accompanying documentation covered by ** this license (the "Software") to use, reproduce, display, distribute, ** execute, and transmit the Software, and to prepare derivative works of the ** Software, and to permit third-parties to whom the Software is furnished to ** do so, all subject to the following: ** ** The copyright notices in the Software and this entire statement, including ** the above license grant, this restriction and the following disclaimer, ** must be included in all copies of the Software, in whole or in part, and ** all derivative works of the Software, unless such copies or derivative ** works are solely in the form of machine-executable object code generated by ** a source language processor. ** ** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** DEALINGS IN THE SOFTWARE. ** -LICENSE-END- */ #ifndef BMD_DECKLINKAPICONFIGURATION_H #define BMD_DECKLINKAPICONFIGURATION_H #ifndef BMD_CONST #if defined(_MSC_VER) #define BMD_CONST __declspec(selectany) static const #else #define BMD_CONST static const #endif #endif // Type Declarations // Interface ID Declarations BMD_CONST REFIID IID_IDeckLinkConfiguration = /* CB71734A-FE37-4E8D-8E13-802133A1C3F2 */ {0xCB,0x71,0x73,0x4A,0xFE,0x37,0x4E,0x8D,0x8E,0x13,0x80,0x21,0x33,0xA1,0xC3,0xF2}; BMD_CONST REFIID IID_IDeckLinkEncoderConfiguration = /* 138050E5-C60A-4552-BF3F-0F358049327E */ {0x13,0x80,0x50,0xE5,0xC6,0x0A,0x45,0x52,0xBF,0x3F,0x0F,0x35,0x80,0x49,0x32,0x7E}; /* Enum BMDDeckLinkConfigurationID - DeckLink Configuration ID */ typedef uint32_t BMDDeckLinkConfigurationID; enum _BMDDeckLinkConfigurationID { /* Serial port Flags */ bmdDeckLinkConfigSwapSerialRxTx = 'ssrt', /* Video Input/Output Flags */ bmdDeckLinkConfigUse1080pNotPsF = 'fpro', /* Video Input/Output Integers */ bmdDeckLinkConfigHDMI3DPackingFormat = '3dpf', bmdDeckLinkConfigBypass = 'byps', bmdDeckLinkConfigClockTimingAdjustment = 'ctad', bmdDeckLinkConfigDuplexMode = 'dupx', /* Audio Input/Output Flags */ bmdDeckLinkConfigAnalogAudioConsumerLevels = 'aacl', /* Video output flags */ bmdDeckLinkConfigFieldFlickerRemoval = 'fdfr', bmdDeckLinkConfigHD1080p24ToHD1080i5994Conversion = 'to59', bmdDeckLinkConfig444SDIVideoOutput = '444o', bmdDeckLinkConfigBlackVideoOutputDuringCapture = 'bvoc', bmdDeckLinkConfigLowLatencyVideoOutput = 'llvo', bmdDeckLinkConfigDownConversionOnAllAnalogOutput = 'caao', bmdDeckLinkConfigSMPTELevelAOutput = 'smta', /* Video Output Integers */ bmdDeckLinkConfigVideoOutputConnection = 'vocn', bmdDeckLinkConfigVideoOutputConversionMode = 'vocm', bmdDeckLinkConfigAnalogVideoOutputFlags = 'avof', bmdDeckLinkConfigReferenceInputTimingOffset = 'glot', bmdDeckLinkConfigVideoOutputIdleOperation = 'voio', bmdDeckLinkConfigDefaultVideoOutputMode = 'dvom', bmdDeckLinkConfigDefaultVideoOutputModeFlags = 'dvof', bmdDeckLinkConfigSDIOutputLinkConfiguration = 'solc', /* Video Output Floats */ bmdDeckLinkConfigVideoOutputComponentLumaGain = 'oclg', bmdDeckLinkConfigVideoOutputComponentChromaBlueGain = 'occb', bmdDeckLinkConfigVideoOutputComponentChromaRedGain = 'occr', bmdDeckLinkConfigVideoOutputCompositeLumaGain = 'oilg', bmdDeckLinkConfigVideoOutputCompositeChromaGain = 'oicg', bmdDeckLinkConfigVideoOutputSVideoLumaGain = 'oslg', bmdDeckLinkConfigVideoOutputSVideoChromaGain = 'oscg', /* Video Input Flags */ bmdDeckLinkConfigVideoInputScanning = 'visc', // Applicable to H264 Pro Recorder only bmdDeckLinkConfigUseDedicatedLTCInput = 'dltc', // Use timecode from LTC input instead of SDI stream bmdDeckLinkConfigSDIInput3DPayloadOverride = '3dds', /* Video Input Integers */ bmdDeckLinkConfigVideoInputConnection = 'vicn', bmdDeckLinkConfigAnalogVideoInputFlags = 'avif', bmdDeckLinkConfigVideoInputConversionMode = 'vicm', bmdDeckLinkConfig32PulldownSequenceInitialTimecodeFrame = 'pdif', bmdDeckLinkConfigVANCSourceLine1Mapping = 'vsl1', bmdDeckLinkConfigVANCSourceLine2Mapping = 'vsl2', bmdDeckLinkConfigVANCSourceLine3Mapping = 'vsl3', bmdDeckLinkConfigCapturePassThroughMode = 'cptm', /* Video Input Floats */ bmdDeckLinkConfigVideoInputComponentLumaGain = 'iclg', bmdDeckLinkConfigVideoInputComponentChromaBlueGain = 'iccb', bmdDeckLinkConfigVideoInputComponentChromaRedGain = 'iccr', bmdDeckLinkConfigVideoInputCompositeLumaGain = 'iilg', bmdDeckLinkConfigVideoInputCompositeChromaGain = 'iicg', bmdDeckLinkConfigVideoInputSVideoLumaGain = 'islg', bmdDeckLinkConfigVideoInputSVideoChromaGain = 'iscg', /* Audio Input Flags */ bmdDeckLinkConfigMicrophonePhantomPower = 'mphp', /* Audio Input Integers */ bmdDeckLinkConfigAudioInputConnection = 'aicn', /* Audio Input Floats */ bmdDeckLinkConfigAnalogAudioInputScaleChannel1 = 'ais1', bmdDeckLinkConfigAnalogAudioInputScaleChannel2 = 'ais2', bmdDeckLinkConfigAnalogAudioInputScaleChannel3 = 'ais3', bmdDeckLinkConfigAnalogAudioInputScaleChannel4 = 'ais4', bmdDeckLinkConfigDigitalAudioInputScale = 'dais', bmdDeckLinkConfigMicrophoneInputGain = 'micg', /* Audio Output Integers */ bmdDeckLinkConfigAudioOutputAESAnalogSwitch = 'aoaa', /* Audio Output Floats */ bmdDeckLinkConfigAnalogAudioOutputScaleChannel1 = 'aos1', bmdDeckLinkConfigAnalogAudioOutputScaleChannel2 = 'aos2', bmdDeckLinkConfigAnalogAudioOutputScaleChannel3 = 'aos3', bmdDeckLinkConfigAnalogAudioOutputScaleChannel4 = 'aos4', bmdDeckLinkConfigDigitalAudioOutputScale = 'daos', bmdDeckLinkConfigHeadphoneVolume = 'hvol', /* Device Information Strings */ bmdDeckLinkConfigDeviceInformationLabel = 'dila', bmdDeckLinkConfigDeviceInformationSerialNumber = 'disn', bmdDeckLinkConfigDeviceInformationCompany = 'dico', bmdDeckLinkConfigDeviceInformationPhone = 'diph', bmdDeckLinkConfigDeviceInformationEmail = 'diem', bmdDeckLinkConfigDeviceInformationDate = 'dida', /* Deck Control Integers */ bmdDeckLinkConfigDeckControlConnection = 'dcco' }; /* Enum BMDDeckLinkEncoderConfigurationID - DeckLink Encoder Configuration ID */ typedef uint32_t BMDDeckLinkEncoderConfigurationID; enum _BMDDeckLinkEncoderConfigurationID { /* Video Encoder Integers */ bmdDeckLinkEncoderConfigPreferredBitDepth = 'epbr', bmdDeckLinkEncoderConfigFrameCodingMode = 'efcm', /* HEVC/H.265 Encoder Integers */ bmdDeckLinkEncoderConfigH265TargetBitrate = 'htbr', /* DNxHR/DNxHD Compression ID */ bmdDeckLinkEncoderConfigDNxHRCompressionID = 'dcid', /* DNxHR/DNxHD Level */ bmdDeckLinkEncoderConfigDNxHRLevel = 'dlev', /* Encoded Sample Decriptions */ bmdDeckLinkEncoderConfigMPEG4SampleDescription = 'stsE', // Full MPEG4 sample description (aka SampleEntry of an 'stsd' atom-box). Useful for MediaFoundation, QuickTime, MKV and more bmdDeckLinkEncoderConfigMPEG4CodecSpecificDesc = 'esds' // Sample description extensions only (atom stream, each with size and fourCC header). Useful for AVFoundation, VideoToolbox, MKV and more }; // Forward Declarations class IDeckLinkConfiguration; class IDeckLinkEncoderConfiguration; /* Interface IDeckLinkConfiguration - DeckLink Configuration interface */ class IDeckLinkConfiguration : public IUnknown { public: virtual HRESULT SetFlag (/* in */ BMDDeckLinkConfigurationID cfgID, /* in */ bool value) = 0; virtual HRESULT GetFlag (/* in */ BMDDeckLinkConfigurationID cfgID, /* out */ bool *value) = 0; virtual HRESULT SetInt (/* in */ BMDDeckLinkConfigurationID cfgID, /* in */ int64_t value) = 0; virtual HRESULT GetInt (/* in */ BMDDeckLinkConfigurationID cfgID, /* out */ int64_t *value) = 0; virtual HRESULT SetFloat (/* in */ BMDDeckLinkConfigurationID cfgID, /* in */ double value) = 0; virtual HRESULT GetFloat (/* in */ BMDDeckLinkConfigurationID cfgID, /* out */ double *value) = 0; virtual HRESULT SetString (/* in */ BMDDeckLinkConfigurationID cfgID, /* in */ CFStringRef value) = 0; virtual HRESULT GetString (/* in */ BMDDeckLinkConfigurationID cfgID, /* out */ CFStringRef *value) = 0; virtual HRESULT WriteConfigurationToPreferences (void) = 0; protected: virtual ~IDeckLinkConfiguration () {} // call Release method to drop reference count }; /* Interface IDeckLinkEncoderConfiguration - DeckLink Encoder Configuration interface. Obtained from IDeckLinkEncoderInput */ class IDeckLinkEncoderConfiguration : public IUnknown { public: virtual HRESULT SetFlag (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* in */ bool value) = 0; virtual HRESULT GetFlag (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* out */ bool *value) = 0; virtual HRESULT SetInt (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* in */ int64_t value) = 0; virtual HRESULT GetInt (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* out */ int64_t *value) = 0; virtual HRESULT SetFloat (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* in */ double value) = 0; virtual HRESULT GetFloat (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* out */ double *value) = 0; virtual HRESULT SetString (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* in */ CFStringRef value) = 0; virtual HRESULT GetString (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* out */ CFStringRef *value) = 0; virtual HRESULT GetBytes (/* in */ BMDDeckLinkEncoderConfigurationID cfgID, /* out */ void *buffer /* optional */, /* in, out */ uint32_t *bufferSize) = 0; protected: virtual ~IDeckLinkEncoderConfiguration () {} // call Release method to drop reference count }; /* Functions */ extern "C" { } #endif /* defined(BMD_DECKLINKAPICONFIGURATION_H) */
null
null
null
null
26,971
808
1,2,3,4,5,6,7,8,9,10,11,12,13
train_val
73edae623529f04c668268de49d00324b96166a2
808
Chrome
1
https://github.com/chromium/chromium
2012-05-24 21:15:17+00:00
static inline void removeElementPreservingChildren(PassRefPtr<DocumentFragment> fragment, HTMLElement* element) { ExceptionCode ignoredExceptionCode; RefPtr<Node> nextChild; for (RefPtr<Node> child = element->firstChild(); child; child = nextChild) { nextChild = child->nextSibling(); element->removeChild(child.get(), ignoredExceptionCode); ASSERT(!ignoredExceptionCode); fragment->insertBefore(child, element, ignoredExceptionCode); ASSERT(!ignoredExceptionCode); } fragment->removeChild(element, ignoredExceptionCode); ASSERT(!ignoredExceptionCode); }
CVE-2011-2795
CWE-264
https://github.com/chromium/chromium/commit/73edae623529f04c668268de49d00324b96166a2
Medium
808
40,089
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
205,084
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (c) 2008-2009 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2007-2008 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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 St - Fifth Floor, Boston, MA 02110-1301 USA. * * Maintained at www.Open-FCoE.org */ #ifndef _LIBFCOE_H #define _LIBFCOE_H #include <linux/etherdevice.h> #include <linux/if_ether.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/workqueue.h> #include <linux/random.h> #include <scsi/fc/fc_fcoe.h> #include <scsi/libfc.h> #include <scsi/fcoe_sysfs.h> #define FCOE_MAX_CMD_LEN 16 /* Supported CDB length */ /* * Max MTU for FCoE: 14 (FCoE header) + 24 (FC header) + 2112 (max FC payload) * + 4 (FC CRC) + 4 (FCoE trailer) = 2158 bytes */ #define FCOE_MTU 2158 /* * FIP tunable parameters. */ #define FCOE_CTLR_START_DELAY 2000 /* mS after first adv. to choose FCF */ #define FCOE_CTRL_SOL_TOV 2000 /* min. solicitation interval (mS) */ #define FCOE_CTLR_FCF_LIMIT 20 /* max. number of FCF entries */ #define FCOE_CTLR_VN2VN_LOGIN_LIMIT 3 /* max. VN2VN rport login retries */ /** * enum fip_state - internal state of FCoE controller. * @FIP_ST_DISABLED: controller has been disabled or not yet enabled. * @FIP_ST_LINK_WAIT: the physical link is down or unusable. * @FIP_ST_AUTO: determining whether to use FIP or non-FIP mode. * @FIP_ST_NON_FIP: non-FIP mode selected. * @FIP_ST_ENABLED: FIP mode selected. * @FIP_ST_VNMP_START: VN2VN multipath mode start, wait * @FIP_ST_VNMP_PROBE1: VN2VN sent first probe, listening * @FIP_ST_VNMP_PROBE2: VN2VN sent second probe, listening * @FIP_ST_VNMP_CLAIM: VN2VN sent claim, waiting for responses * @FIP_ST_VNMP_UP: VN2VN multipath mode operation */ enum fip_state { FIP_ST_DISABLED, FIP_ST_LINK_WAIT, FIP_ST_AUTO, FIP_ST_NON_FIP, FIP_ST_ENABLED, FIP_ST_VNMP_START, FIP_ST_VNMP_PROBE1, FIP_ST_VNMP_PROBE2, FIP_ST_VNMP_CLAIM, FIP_ST_VNMP_UP, }; /* * Modes: * The mode is the state that is to be entered after link up. * It must not change after fcoe_ctlr_init() sets it. */ enum fip_mode { FIP_MODE_AUTO = FIP_ST_AUTO, FIP_MODE_NON_FIP, FIP_MODE_FABRIC, FIP_MODE_VN2VN, }; /** * struct fcoe_ctlr - FCoE Controller and FIP state * @state: internal FIP state for network link and FIP or non-FIP mode. * @mode: LLD-selected mode. * @lp: &fc_lport: libfc local port. * @sel_fcf: currently selected FCF, or NULL. * @fcfs: list of discovered FCFs. * @cdev: (Optional) pointer to sysfs fcoe_ctlr_device. * @fcf_count: number of discovered FCF entries. * @sol_time: time when a multicast solicitation was last sent. * @sel_time: time after which to select an FCF. * @port_ka_time: time of next port keep-alive. * @ctlr_ka_time: time of next controller keep-alive. * @timer: timer struct used for all delayed events. * @timer_work: &work_struct for doing keep-alives and resets. * @recv_work: &work_struct for receiving FIP frames. * @fip_recv_list: list of received FIP frames. * @flogi_req: clone of FLOGI request sent * @rnd_state: state for pseudo-random number generator. * @port_id: proposed or selected local-port ID. * @user_mfs: configured maximum FC frame size, including FC header. * @flogi_oxid: exchange ID of most recent fabric login. * @flogi_req_send: send of FLOGI requested * @flogi_count: number of FLOGI attempts in AUTO mode. * @map_dest: use the FC_MAP mode for destination MAC addresses. * @fip_resp: start FIP VLAN discovery responder * @spma: supports SPMA server-provided MACs mode * @probe_tries: number of FC_IDs probed * @priority: DCBx FCoE APP priority * @dest_addr: MAC address of the selected FC forwarder. * @ctl_src_addr: the native MAC address of our local port. * @send: LLD-supplied function to handle sending FIP Ethernet frames * @update_mac: LLD-supplied function to handle changes to MAC addresses. * @get_src_addr: LLD-supplied function to supply a source MAC address. * @ctlr_mutex: lock protecting this structure. * @ctlr_lock: spinlock covering flogi_req * * This structure is used by all FCoE drivers. It contains information * needed by all FCoE low-level drivers (LLDs) as well as internal state * for FIP, and fields shared with the LLDS. */ struct fcoe_ctlr { enum fip_state state; enum fip_mode mode; struct fc_lport *lp; struct fcoe_fcf *sel_fcf; struct list_head fcfs; struct fcoe_ctlr_device *cdev; u16 fcf_count; unsigned long sol_time; unsigned long sel_time; unsigned long port_ka_time; unsigned long ctlr_ka_time; struct timer_list timer; struct work_struct timer_work; struct work_struct recv_work; struct sk_buff_head fip_recv_list; struct sk_buff *flogi_req; struct rnd_state rnd_state; u32 port_id; u16 user_mfs; u16 flogi_oxid; u8 flogi_req_send; u8 flogi_count; bool map_dest; bool fip_resp; u8 spma; u8 probe_tries; u8 priority; u8 dest_addr[ETH_ALEN]; u8 ctl_src_addr[ETH_ALEN]; void (*send)(struct fcoe_ctlr *, struct sk_buff *); void (*update_mac)(struct fc_lport *, u8 *addr); u8 * (*get_src_addr)(struct fc_lport *); struct mutex ctlr_mutex; spinlock_t ctlr_lock; }; /** * fcoe_ctlr_priv() - Return the private data from a fcoe_ctlr * @cltr: The fcoe_ctlr whose private data will be returned */ static inline void *fcoe_ctlr_priv(const struct fcoe_ctlr *ctlr) { return (void *)(ctlr + 1); } /* * This assumes that the fcoe_ctlr (x) is allocated with the fcoe_ctlr_device. */ #define fcoe_ctlr_to_ctlr_dev(x) \ (x)->cdev /** * struct fcoe_fcf - Fibre-Channel Forwarder * @list: list linkage * @event_work: Work for FC Transport actions queue * @event: The event to be processed * @fip: The controller that the FCF was discovered on * @fcf_dev: The associated fcoe_fcf_device instance * @time: system time (jiffies) when an advertisement was last received * @switch_name: WWN of switch from advertisement * @fabric_name: WWN of fabric from advertisement * @fc_map: FC_MAP value from advertisement * @fcf_mac: Ethernet address of the FCF for FIP traffic * @fcoe_mac: Ethernet address of the FCF for FCoE traffic * @vfid: virtual fabric ID * @pri: selection priority, smaller values are better * @flogi_sent: current FLOGI sent to this FCF * @flags: flags received from advertisement * @fka_period: keep-alive period, in jiffies * * A Fibre-Channel Forwarder (FCF) is the entity on the Ethernet that * passes FCoE frames on to an FC fabric. This structure represents * one FCF from which advertisements have been received. * * When looking up an FCF, @switch_name, @fabric_name, @fc_map, @vfid, and * @fcf_mac together form the lookup key. */ struct fcoe_fcf { struct list_head list; struct work_struct event_work; struct fcoe_ctlr *fip; struct fcoe_fcf_device *fcf_dev; unsigned long time; u64 switch_name; u64 fabric_name; u32 fc_map; u16 vfid; u8 fcf_mac[ETH_ALEN]; u8 fcoe_mac[ETH_ALEN]; u8 pri; u8 flogi_sent; u16 flags; u32 fka_period; u8 fd_flags:1; }; #define fcoe_fcf_to_fcf_dev(x) \ ((x)->fcf_dev) /** * struct fcoe_rport - VN2VN remote port * @time: time of create or last beacon packet received from node * @fcoe_len: max FCoE frame size, not including VLAN or Ethernet headers * @flags: flags from probe or claim * @login_count: number of unsuccessful rport logins to this port * @enode_mac: E_Node control MAC address * @vn_mac: VN_Node assigned MAC address for data */ struct fcoe_rport { unsigned long time; u16 fcoe_len; u16 flags; u8 login_count; u8 enode_mac[ETH_ALEN]; u8 vn_mac[ETH_ALEN]; }; /* FIP API functions */ void fcoe_ctlr_init(struct fcoe_ctlr *, enum fip_state); void fcoe_ctlr_destroy(struct fcoe_ctlr *); void fcoe_ctlr_link_up(struct fcoe_ctlr *); int fcoe_ctlr_link_down(struct fcoe_ctlr *); int fcoe_ctlr_els_send(struct fcoe_ctlr *, struct fc_lport *, struct sk_buff *); void fcoe_ctlr_recv(struct fcoe_ctlr *, struct sk_buff *); int fcoe_ctlr_recv_flogi(struct fcoe_ctlr *, struct fc_lport *, struct fc_frame *); /* libfcoe funcs */ u64 fcoe_wwn_from_mac(unsigned char mac[], unsigned int, unsigned int); int fcoe_libfc_config(struct fc_lport *, struct fcoe_ctlr *, const struct libfc_function_template *, int init_fcp); u32 fcoe_fc_crc(struct fc_frame *fp); int fcoe_start_io(struct sk_buff *skb); int fcoe_get_wwn(struct net_device *netdev, u64 *wwn, int type); void __fcoe_get_lesb(struct fc_lport *lport, struct fc_els_lesb *fc_lesb, struct net_device *netdev); void fcoe_wwn_to_str(u64 wwn, char *buf, int len); int fcoe_validate_vport_create(struct fc_vport *vport); int fcoe_link_speed_update(struct fc_lport *); void fcoe_get_lesb(struct fc_lport *, struct fc_els_lesb *); void fcoe_ctlr_get_lesb(struct fcoe_ctlr_device *ctlr_dev); /** * is_fip_mode() - returns true if FIP mode selected. * @fip: FCoE controller. */ static inline bool is_fip_mode(struct fcoe_ctlr *fip) { return fip->state == FIP_ST_ENABLED; } /* helper for FCoE SW HBA drivers, can include subven and subdev if needed. The * modpost would use pci_device_id table to auto-generate formatted module alias * into the corresponding .mod.c file, but there may or may not be a pci device * id table for FCoE drivers so we use the following helper for build the fcoe * driver module alias. */ #define MODULE_ALIAS_FCOE_PCI(ven, dev) \ MODULE_ALIAS("fcoe-pci:" \ "v" __stringify(ven) \ "d" __stringify(dev) "sv*sd*bc*sc*i*") /* the name of the default FCoE transport driver fcoe.ko */ #define FCOE_TRANSPORT_DEFAULT "fcoe" /* struct fcoe_transport - The FCoE transport interface * @name: a vendor specific name for their FCoE transport driver * @attached: whether this transport is already attached * @list: list linkage to all attached transports * @match: handler to allow the transport driver to match up a given netdev * @alloc: handler to allocate per-instance FCoE structures * (no discovery or login) * @create: handler to sysfs entry of create for FCoE instances * @destroy: handler to delete per-instance FCoE structures * (frees all memory) * @enable: handler to sysfs entry of enable for FCoE instances * @disable: handler to sysfs entry of disable for FCoE instances */ struct fcoe_transport { char name[IFNAMSIZ]; bool attached; struct list_head list; bool (*match) (struct net_device *device); int (*alloc) (struct net_device *device); int (*create) (struct net_device *device, enum fip_mode fip_mode); int (*destroy) (struct net_device *device); int (*enable) (struct net_device *device); int (*disable) (struct net_device *device); }; /** * struct fcoe_percpu_s - The context for FCoE receive thread(s) * @kthread: The thread context (used by bnx2fc) * @work: The work item (used by fcoe) * @fcoe_rx_list: The queue of pending packets to process * @page: The memory page for calculating frame trailer CRCs * @crc_eof_offset: The offset into the CRC page pointing to available * memory for a new trailer */ struct fcoe_percpu_s { struct task_struct *kthread; struct work_struct work; struct sk_buff_head fcoe_rx_list; struct page *crc_eof_page; int crc_eof_offset; }; /** * struct fcoe_port - The FCoE private structure * @priv: The associated fcoe interface. The structure is * defined by the low level driver * @lport: The associated local port * @fcoe_pending_queue: The pending Rx queue of skbs * @fcoe_pending_queue_active: Indicates if the pending queue is active * @max_queue_depth: Max queue depth of pending queue * @min_queue_depth: Min queue depth of pending queue * @timer: The queue timer * @destroy_work: Handle for work context * (to prevent RTNL deadlocks) * @data_srt_addr: Source address for data * * An instance of this structure is to be allocated along with the * Scsi_Host and libfc fc_lport structures. */ struct fcoe_port { void *priv; struct fc_lport *lport; struct sk_buff_head fcoe_pending_queue; u8 fcoe_pending_queue_active; u32 max_queue_depth; u32 min_queue_depth; struct timer_list timer; struct work_struct destroy_work; u8 data_src_addr[ETH_ALEN]; struct net_device * (*get_netdev)(const struct fc_lport *lport); }; /** * fcoe_get_netdev() - Return the net device associated with a local port * @lport: The local port to get the net device from */ static inline struct net_device *fcoe_get_netdev(const struct fc_lport *lport) { struct fcoe_port *port = ((struct fcoe_port *)lport_priv(lport)); return (port->get_netdev) ? port->get_netdev(lport) : NULL; } void fcoe_clean_pending_queue(struct fc_lport *); void fcoe_check_wait_queue(struct fc_lport *lport, struct sk_buff *skb); void fcoe_queue_timer(ulong lport); int fcoe_get_paged_crc_eof(struct sk_buff *skb, int tlen, struct fcoe_percpu_s *fps); /* FCoE Sysfs helpers */ void fcoe_fcf_get_selected(struct fcoe_fcf_device *); void fcoe_ctlr_set_fip_mode(struct fcoe_ctlr_device *); /** * struct netdev_list * A mapping from netdevice to fcoe_transport */ struct fcoe_netdev_mapping { struct list_head list; struct net_device *netdev; struct fcoe_transport *ft; }; /* fcoe transports registration and deregistration */ int fcoe_transport_attach(struct fcoe_transport *ft); int fcoe_transport_detach(struct fcoe_transport *ft); /* sysfs store handler for ctrl_control interface */ ssize_t fcoe_ctlr_create_store(struct bus_type *bus, const char *buf, size_t count); ssize_t fcoe_ctlr_destroy_store(struct bus_type *bus, const char *buf, size_t count); #endif /* _LIBFCOE_H */
null
null
null
null
113,431
40,102
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
205,097
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Common low level (register) ptrace helpers * * Copyright 2004-2011 Analog Devices Inc. * * Licensed under the GPL-2 or later. */ #ifndef __ASM_GENERIC_PTRACE_H__ #define __ASM_GENERIC_PTRACE_H__ #ifndef __ASSEMBLY__ /* Helpers for working with the instruction pointer */ #ifndef GET_IP #define GET_IP(regs) ((regs)->pc) #endif #ifndef SET_IP #define SET_IP(regs, val) (GET_IP(regs) = (val)) #endif static inline unsigned long instruction_pointer(struct pt_regs *regs) { return GET_IP(regs); } static inline void instruction_pointer_set(struct pt_regs *regs, unsigned long val) { SET_IP(regs, val); } #ifndef profile_pc #define profile_pc(regs) instruction_pointer(regs) #endif /* Helpers for working with the user stack pointer */ #ifndef GET_USP #define GET_USP(regs) ((regs)->usp) #endif #ifndef SET_USP #define SET_USP(regs, val) (GET_USP(regs) = (val)) #endif static inline unsigned long user_stack_pointer(struct pt_regs *regs) { return GET_USP(regs); } static inline void user_stack_pointer_set(struct pt_regs *regs, unsigned long val) { SET_USP(regs, val); } /* Helpers for working with the frame pointer */ #ifndef GET_FP #define GET_FP(regs) ((regs)->fp) #endif #ifndef SET_FP #define SET_FP(regs, val) (GET_FP(regs) = (val)) #endif static inline unsigned long frame_pointer(struct pt_regs *regs) { return GET_FP(regs); } static inline void frame_pointer_set(struct pt_regs *regs, unsigned long val) { SET_FP(regs, val); } #endif /* __ASSEMBLY__ */ #endif
null
null
null
null
113,444
20,213
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
20,213
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_PUBLIC_BROWSER_DEVTOOLS_MANAGER_DELEGATE_H_ #define CONTENT_PUBLIC_BROWSER_DEVTOOLS_MANAGER_DELEGATE_H_ #include <memory> #include <string> #include "base/memory/ref_counted.h" #include "content/common/content_export.h" #include "content/public/browser/devtools_agent_host.h" #include "url/gurl.h" namespace base { class DictionaryValue; } namespace content { class DevToolsAgentHostClient; class WebContents; class CONTENT_EXPORT DevToolsManagerDelegate { public: // Opens the inspector for |agent_host|. virtual void Inspect(DevToolsAgentHost* agent_host); // Returns DevToolsAgentHost type to use for given |web_contents| target. virtual std::string GetTargetType(WebContents* web_contents); // Returns DevToolsAgentHost title to use for given |web_contents| target. virtual std::string GetTargetTitle(WebContents* web_contents); // Returns DevToolsAgentHost title to use for given |web_contents| target. virtual std::string GetTargetDescription(WebContents* web_contents); // Returns all targets embedder would like to report as debuggable // remotely. virtual DevToolsAgentHost::List RemoteDebuggingTargets(); // Creates new inspectable target given the |url|. virtual scoped_refptr<DevToolsAgentHost> CreateNewTarget(const GURL& url); // Called when a new client is attached/detached. virtual void ClientAttached(DevToolsAgentHost* agent_host, DevToolsAgentHostClient* client); virtual void ClientDetached(DevToolsAgentHost* agent_host, DevToolsAgentHostClient* client); // Returns true if the command has been handled, false otherwise. virtual bool HandleCommand(DevToolsAgentHost* agent_host, DevToolsAgentHostClient* client, base::DictionaryValue* command); // Returns true if the command has been handled, false otherwise. using CommandCallback = base::Callback<void(std::unique_ptr<base::DictionaryValue> response)>; virtual bool HandleAsyncCommand(DevToolsAgentHost* agent_host, DevToolsAgentHostClient* client, base::DictionaryValue* command, const CommandCallback& callback); // Should return discovery page HTML that should list available tabs // and provide attach links. virtual std::string GetDiscoveryPageHTML(); // Returns whether frontend resources are bundled within the binary. virtual bool HasBundledFrontendResources(); // Makes browser target easily discoverable for remote debugging. // This should only return true when remote debugging endpoint is not // accessible by the web (for example in Chrome for Android where it is // exposed via UNIX named socket) or when content/ embedder is built for // running in the controlled environment (for example a special build for // the Lab testing). If you want to return true here, please get security // clearance from the devtools owners. virtual bool IsBrowserTargetDiscoverable(); virtual ~DevToolsManagerDelegate(); }; } // namespace content #endif // CONTENT_PUBLIC_BROWSER_DEVTOOLS_MANAGER_DELEGATE_H_
null
null
null
null
17,076
28,041
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
28,041
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <limits> #include <vector> #include <google/protobuf/compiler/javanano/javanano_helpers.h> #include <google/protobuf/compiler/javanano/javanano_params.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/stubs/hash.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> namespace google { namespace protobuf { namespace compiler { namespace javanano { const char kThickSeparator[] = "// ===================================================================\n"; const char kThinSeparator[] = "// -------------------------------------------------------------------\n"; class RenameKeywords { private: hash_set<string> java_keywords_set_; public: RenameKeywords() { static const char* kJavaKeywordsList[] = { // Reserved Java Keywords "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while", // Reserved Keywords for Literals "false", "null", "true" }; for (int i = 0; i < GOOGLE_ARRAYSIZE(kJavaKeywordsList); i++) { java_keywords_set_.insert(kJavaKeywordsList[i]); } } // Used to rename the a field name if it's a java keyword. Specifically // this is used to rename the ["name"] or ["capitalized_name"] field params. // (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html) string RenameJavaKeywordsImpl(const string& input) { string result = input; if (java_keywords_set_.find(result) != java_keywords_set_.end()) { result += "_"; } return result; } }; static RenameKeywords sRenameKeywords; namespace { const char* kDefaultPackage = ""; const string& FieldName(const FieldDescriptor* field) { // Groups are hacky: The name of the field is just the lower-cased name // of the group type. In Java, though, we would like to retain the original // capitalization of the type name. if (field->type() == FieldDescriptor::TYPE_GROUP) { return field->message_type()->name(); } else { return field->name(); } } string UnderscoresToCamelCaseImpl(const string& input, bool cap_next_letter) { string result; // Note: I distrust ctype.h due to locales. for (int i = 0; i < input.size(); i++) { if ('a' <= input[i] && input[i] <= 'z') { if (cap_next_letter) { result += input[i] + ('A' - 'a'); } else { result += input[i]; } cap_next_letter = false; } else if ('A' <= input[i] && input[i] <= 'Z') { if (i == 0 && !cap_next_letter) { // Force first letter to lower-case unless explicitly told to // capitalize it. result += input[i] + ('a' - 'A'); } else { // Capital letters after the first are left as-is. result += input[i]; } cap_next_letter = false; } else if ('0' <= input[i] && input[i] <= '9') { result += input[i]; cap_next_letter = true; } else { cap_next_letter = true; } } return result; } } // namespace string UnderscoresToCamelCase(const FieldDescriptor* field) { return UnderscoresToCamelCaseImpl(FieldName(field), false); } string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) { return UnderscoresToCamelCaseImpl(FieldName(field), true); } string UnderscoresToCamelCase(const MethodDescriptor* method) { return UnderscoresToCamelCaseImpl(method->name(), false); } string UnderscoresToCamelCase(const OneofDescriptor* oneof) { return UnderscoresToCamelCaseImpl(oneof->name(), false); } string UnderscoresToCapitalizedCamelCase(const OneofDescriptor* oneof) { return UnderscoresToCamelCaseImpl(oneof->name(), true); } string RenameJavaKeywords(const string& input) { return sRenameKeywords.RenameJavaKeywordsImpl(input); } string StripProto(const string& filename) { if (HasSuffixString(filename, ".protodevel")) { return StripSuffixString(filename, ".protodevel"); } else { return StripSuffixString(filename, ".proto"); } } string FileClassName(const Params& params, const FileDescriptor* file) { if (params.has_java_outer_classname(file->name())) { return params.java_outer_classname(file->name()); } else { // Use the filename itself with underscores removed // and a CamelCase style name. string basename; string::size_type last_slash = file->name().find_last_of('/'); if (last_slash == string::npos) { basename = file->name(); } else { basename = file->name().substr(last_slash + 1); } return UnderscoresToCamelCaseImpl(StripProto(basename), true); } } string FileJavaPackage(const Params& params, const FileDescriptor* file) { if (params.has_java_package(file->name())) { return params.java_package(file->name()); } else { string result = kDefaultPackage; if (!file->package().empty()) { if (!result.empty()) result += '.'; result += file->package(); } if (!result.empty()) { result += "."; } result += "nano"; return result; } } bool IsOuterClassNeeded(const Params& params, const FileDescriptor* file) { // If java_multiple_files is false, the outer class is always needed. if (!params.java_multiple_files(file->name())) { return true; } // File-scope extensions need the outer class as the scope. if (file->extension_count() != 0) { return true; } // If container interfaces are not generated, file-scope enums need the // outer class as the scope. if (file->enum_type_count() != 0 && !params.java_enum_style()) { return true; } return false; } string ToJavaName(const Params& params, const string& name, bool is_class, const Descriptor* parent, const FileDescriptor* file) { string result; if (parent != NULL) { result.append(ClassName(params, parent)); } else if (is_class && params.java_multiple_files(file->name())) { result.append(FileJavaPackage(params, file)); } else { result.append(ClassName(params, file)); } if (!result.empty()) result.append(1, '.'); result.append(RenameJavaKeywords(name)); return result; } string ClassName(const Params& params, const FileDescriptor* descriptor) { string result = FileJavaPackage(params, descriptor); if (!result.empty()) result += '.'; result += FileClassName(params, descriptor); return result; } string ClassName(const Params& params, const EnumDescriptor* descriptor) { const Descriptor* parent = descriptor->containing_type(); // When using Java enum style, an enum's class name contains the enum name. // Use the standard ToJavaName translation. if (params.java_enum_style()) { return ToJavaName(params, descriptor->name(), true, parent, descriptor->file()); } // Otherwise the enum members are accessed from the enclosing class. if (parent != NULL) { return ClassName(params, parent); } else { return ClassName(params, descriptor->file()); } } string FieldConstantName(const FieldDescriptor *field) { string name = field->name() + "_FIELD_NUMBER"; UpperString(&name); return name; } string FieldDefaultConstantName(const FieldDescriptor *field) { return "_" + RenameJavaKeywords(UnderscoresToCamelCase(field)) + "Default"; } void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field) { // We don't want to print group bodies so we cut off after the first line // (the second line for extensions). string def = field->DebugString(); string::size_type first_line_end = def.find_first_of('\n'); printer->Print("// $def$\n", "def", def.substr(0, first_line_end)); if (field->is_extension()) { string::size_type second_line_start = first_line_end + 1; string::size_type second_line_length = def.find('\n', second_line_start) - second_line_start; printer->Print("// $def$\n", "def", def.substr(second_line_start, second_line_length)); } } JavaType GetJavaType(FieldDescriptor::Type field_type) { switch (field_type) { case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_UINT32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_SFIXED32: return JAVATYPE_INT; case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_UINT64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_SFIXED64: return JAVATYPE_LONG; case FieldDescriptor::TYPE_FLOAT: return JAVATYPE_FLOAT; case FieldDescriptor::TYPE_DOUBLE: return JAVATYPE_DOUBLE; case FieldDescriptor::TYPE_BOOL: return JAVATYPE_BOOLEAN; case FieldDescriptor::TYPE_STRING: return JAVATYPE_STRING; case FieldDescriptor::TYPE_BYTES: return JAVATYPE_BYTES; case FieldDescriptor::TYPE_ENUM: return JAVATYPE_ENUM; case FieldDescriptor::TYPE_GROUP: case FieldDescriptor::TYPE_MESSAGE: return JAVATYPE_MESSAGE; // No default because we want the compiler to complain if any new // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return JAVATYPE_INT; } string PrimitiveTypeName(JavaType type) { switch (type) { case JAVATYPE_INT : return "int"; case JAVATYPE_LONG : return "long"; case JAVATYPE_FLOAT : return "float"; case JAVATYPE_DOUBLE : return "double"; case JAVATYPE_BOOLEAN: return "boolean"; case JAVATYPE_STRING : return "java.lang.String"; case JAVATYPE_BYTES : return "byte[]"; case JAVATYPE_ENUM : return "int"; case JAVATYPE_MESSAGE: return ""; // No default because we want the compiler to complain if any new // JavaTypes are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return ""; } string BoxedPrimitiveTypeName(JavaType type) { switch (type) { case JAVATYPE_INT : return "java.lang.Integer"; case JAVATYPE_LONG : return "java.lang.Long"; case JAVATYPE_FLOAT : return "java.lang.Float"; case JAVATYPE_DOUBLE : return "java.lang.Double"; case JAVATYPE_BOOLEAN: return "java.lang.Boolean"; case JAVATYPE_STRING : return "java.lang.String"; case JAVATYPE_BYTES : return "byte[]"; case JAVATYPE_ENUM : return "java.lang.Integer"; case JAVATYPE_MESSAGE: return ""; // No default because we want the compiler to complain if any new // JavaTypes are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return ""; } string EmptyArrayName(const Params& params, const FieldDescriptor* field) { switch (GetJavaType(field)) { case JAVATYPE_INT : return "com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY"; case JAVATYPE_LONG : return "com.google.protobuf.nano.WireFormatNano.EMPTY_LONG_ARRAY"; case JAVATYPE_FLOAT : return "com.google.protobuf.nano.WireFormatNano.EMPTY_FLOAT_ARRAY"; case JAVATYPE_DOUBLE : return "com.google.protobuf.nano.WireFormatNano.EMPTY_DOUBLE_ARRAY"; case JAVATYPE_BOOLEAN: return "com.google.protobuf.nano.WireFormatNano.EMPTY_BOOLEAN_ARRAY"; case JAVATYPE_STRING : return "com.google.protobuf.nano.WireFormatNano.EMPTY_STRING_ARRAY"; case JAVATYPE_BYTES : return "com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES_ARRAY"; case JAVATYPE_ENUM : return "com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY"; case JAVATYPE_MESSAGE: return ClassName(params, field->message_type()) + ".EMPTY_ARRAY"; // No default because we want the compiler to complain if any new // JavaTypes are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return ""; } string DefaultValue(const Params& params, const FieldDescriptor* field) { if (field->label() == FieldDescriptor::LABEL_REPEATED) { return EmptyArrayName(params, field); } if (params.use_reference_types_for_primitives()) { if (params.reftypes_primitive_enums() && field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { return "Integer.MIN_VALUE"; } return "null"; } // Switch on cpp_type since we need to know which default_value_* method // of FieldDescriptor to call. switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: return SimpleItoa(field->default_value_int32()); case FieldDescriptor::CPPTYPE_UINT32: // Need to print as a signed int since Java has no unsigned. return SimpleItoa(static_cast<int32>(field->default_value_uint32())); case FieldDescriptor::CPPTYPE_INT64: return SimpleItoa(field->default_value_int64()) + "L"; case FieldDescriptor::CPPTYPE_UINT64: return SimpleItoa(static_cast<int64>(field->default_value_uint64())) + "L"; case FieldDescriptor::CPPTYPE_DOUBLE: { double value = field->default_value_double(); if (value == std::numeric_limits<double>::infinity()) { return "Double.POSITIVE_INFINITY"; } else if (value == -std::numeric_limits<double>::infinity()) { return "Double.NEGATIVE_INFINITY"; } else if (value != value) { return "Double.NaN"; } else { return SimpleDtoa(value) + "D"; } } case FieldDescriptor::CPPTYPE_FLOAT: { float value = field->default_value_float(); if (value == std::numeric_limits<float>::infinity()) { return "Float.POSITIVE_INFINITY"; } else if (value == -std::numeric_limits<float>::infinity()) { return "Float.NEGATIVE_INFINITY"; } else if (value != value) { return "Float.NaN"; } else { return SimpleFtoa(value) + "F"; } } case FieldDescriptor::CPPTYPE_BOOL: return field->default_value_bool() ? "true" : "false"; case FieldDescriptor::CPPTYPE_STRING: if (!field->default_value_string().empty()) { // Point it to the static final in the generated code. return FieldDefaultConstantName(field); } else { if (field->type() == FieldDescriptor::TYPE_BYTES) { return "com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES"; } else { return "\"\""; } } case FieldDescriptor::CPPTYPE_ENUM: return ClassName(params, field->enum_type()) + "." + RenameJavaKeywords(field->default_value_enum()->name()); case FieldDescriptor::CPPTYPE_MESSAGE: return "null"; // No default because we want the compiler to complain if any new // types are added. } GOOGLE_LOG(FATAL) << "Can't get here."; return ""; } static const char* kBitMasks[] = { "0x00000001", "0x00000002", "0x00000004", "0x00000008", "0x00000010", "0x00000020", "0x00000040", "0x00000080", "0x00000100", "0x00000200", "0x00000400", "0x00000800", "0x00001000", "0x00002000", "0x00004000", "0x00008000", "0x00010000", "0x00020000", "0x00040000", "0x00080000", "0x00100000", "0x00200000", "0x00400000", "0x00800000", "0x01000000", "0x02000000", "0x04000000", "0x08000000", "0x10000000", "0x20000000", "0x40000000", "0x80000000", }; string GetBitFieldName(int index) { string var_name = "bitField"; var_name += SimpleItoa(index); var_name += "_"; return var_name; } string GetBitFieldNameForBit(int bit_index) { return GetBitFieldName(bit_index / 32); } string GenerateGetBit(int bit_index) { string var_name = GetBitFieldNameForBit(bit_index); int bit_in_var_index = bit_index % 32; string mask = kBitMasks[bit_in_var_index]; string result = "((" + var_name + " & " + mask + ") != 0)"; return result; } string GenerateSetBit(int bit_index) { string var_name = GetBitFieldNameForBit(bit_index); int bit_in_var_index = bit_index % 32; string mask = kBitMasks[bit_in_var_index]; string result = var_name + " |= " + mask; return result; } string GenerateClearBit(int bit_index) { string var_name = GetBitFieldNameForBit(bit_index); int bit_in_var_index = bit_index % 32; string mask = kBitMasks[bit_in_var_index]; string result = var_name + " = (" + var_name + " & ~" + mask + ")"; return result; } string GenerateDifferentBit(int bit_index) { string var_name = GetBitFieldNameForBit(bit_index); int bit_in_var_index = bit_index % 32; string mask = kBitMasks[bit_in_var_index]; string result = "((" + var_name + " & " + mask + ") != (other." + var_name + " & " + mask + "))"; return result; } void SetBitOperationVariables(const string name, int bitIndex, std::map<string, string>* variables) { (*variables)["get_" + name] = GenerateGetBit(bitIndex); (*variables)["set_" + name] = GenerateSetBit(bitIndex); (*variables)["clear_" + name] = GenerateClearBit(bitIndex); (*variables)["different_" + name] = GenerateDifferentBit(bitIndex); } bool HasMapField(const Descriptor* descriptor) { for (int i = 0; i < descriptor->field_count(); ++i) { const FieldDescriptor* field = descriptor->field(i); if (field->type() == FieldDescriptor::TYPE_MESSAGE && IsMapEntry(field->message_type())) { return true; } } return false; } } // namespace javanano } // namespace compiler } // namespace protobuf } // namespace google
null
null
null
null
24,904
2,833
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
167,828
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright 2011-2012, Pavel Zubarev <pavel.zubarev@gmail.com> * Copyright 2011-2012, Marco Porsch <marco.porsch@s2005.tu-chemnitz.de> * Copyright 2011-2012, cozybit 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. */ #include "ieee80211_i.h" #include "mesh.h" #include "driver-ops.h" /* This is not in the standard. It represents a tolerable tsf drift below * which we do no TSF adjustment. */ #define TOFFSET_MINIMUM_ADJUSTMENT 10 /* This is not in the standard. It is a margin added to the * Toffset setpoint to mitigate TSF overcorrection * introduced by TSF adjustment latency. */ #define TOFFSET_SET_MARGIN 20 /* This is not in the standard. It represents the maximum Toffset jump above * which we'll invalidate the Toffset setpoint and choose a new setpoint. This * could be, for instance, in case a neighbor is restarted and its TSF counter * reset. */ #define TOFFSET_MAXIMUM_ADJUSTMENT 800 /* 0.8 ms */ struct sync_method { u8 method; struct ieee80211_mesh_sync_ops ops; }; /** * mesh_peer_tbtt_adjusting - check if an mp is currently adjusting its TBTT * * @ie: information elements of a management frame from the mesh peer */ static bool mesh_peer_tbtt_adjusting(struct ieee802_11_elems *ie) { return (ie->mesh_config->meshconf_cap & IEEE80211_MESHCONF_CAPAB_TBTT_ADJUSTING) != 0; } void mesh_sync_adjust_tsf(struct ieee80211_sub_if_data *sdata) { struct ieee80211_local *local = sdata->local; struct ieee80211_if_mesh *ifmsh = &sdata->u.mesh; /* sdata->vif.bss_conf.beacon_int in 1024us units, 0.04% */ u64 beacon_int_fraction = sdata->vif.bss_conf.beacon_int * 1024 / 2500; u64 tsf; u64 tsfdelta; spin_lock_bh(&ifmsh->sync_offset_lock); if (ifmsh->sync_offset_clockdrift_max < beacon_int_fraction) { msync_dbg(sdata, "TSF : max clockdrift=%lld; adjusting\n", (long long) ifmsh->sync_offset_clockdrift_max); tsfdelta = -ifmsh->sync_offset_clockdrift_max; ifmsh->sync_offset_clockdrift_max = 0; } else { msync_dbg(sdata, "TSF : max clockdrift=%lld; adjusting by %llu\n", (long long) ifmsh->sync_offset_clockdrift_max, (unsigned long long) beacon_int_fraction); tsfdelta = -beacon_int_fraction; ifmsh->sync_offset_clockdrift_max -= beacon_int_fraction; } spin_unlock_bh(&ifmsh->sync_offset_lock); if (local->ops->offset_tsf) { drv_offset_tsf(local, sdata, tsfdelta); } else { tsf = drv_get_tsf(local, sdata); if (tsf != -1ULL) drv_set_tsf(local, sdata, tsf + tsfdelta); } } static void mesh_sync_offset_rx_bcn_presp(struct ieee80211_sub_if_data *sdata, u16 stype, struct ieee80211_mgmt *mgmt, struct ieee802_11_elems *elems, struct ieee80211_rx_status *rx_status) { struct ieee80211_if_mesh *ifmsh = &sdata->u.mesh; struct ieee80211_local *local = sdata->local; struct sta_info *sta; u64 t_t, t_r; WARN_ON(ifmsh->mesh_sp_id != IEEE80211_SYNC_METHOD_NEIGHBOR_OFFSET); /* standard mentions only beacons */ if (stype != IEEE80211_STYPE_BEACON) return; /* * Get time when timestamp field was received. If we don't * have rx timestamps, then use current tsf as an approximation. * drv_get_tsf() must be called before entering the rcu-read * section. */ if (ieee80211_have_rx_timestamp(rx_status)) t_r = ieee80211_calculate_rx_timestamp(local, rx_status, 24 + 12 + elems->total_len + FCS_LEN, 24); else t_r = drv_get_tsf(local, sdata); rcu_read_lock(); sta = sta_info_get(sdata, mgmt->sa); if (!sta) goto no_sync; /* check offset sync conditions (13.13.2.2.1) * * TODO also sync to * dot11MeshNbrOffsetMaxNeighbor non-peer non-MBSS neighbors */ if (elems->mesh_config && mesh_peer_tbtt_adjusting(elems)) { msync_dbg(sdata, "STA %pM : is adjusting TBTT\n", sta->sta.addr); goto no_sync; } /* Timing offset calculation (see 13.13.2.2.2) */ t_t = le64_to_cpu(mgmt->u.beacon.timestamp); sta->mesh->t_offset = t_t - t_r; if (test_sta_flag(sta, WLAN_STA_TOFFSET_KNOWN)) { s64 t_clockdrift = sta->mesh->t_offset_setpoint - sta->mesh->t_offset; msync_dbg(sdata, "STA %pM : t_offset=%lld, t_offset_setpoint=%lld, t_clockdrift=%lld\n", sta->sta.addr, (long long) sta->mesh->t_offset, (long long) sta->mesh->t_offset_setpoint, (long long) t_clockdrift); if (t_clockdrift > TOFFSET_MAXIMUM_ADJUSTMENT || t_clockdrift < -TOFFSET_MAXIMUM_ADJUSTMENT) { msync_dbg(sdata, "STA %pM : t_clockdrift=%lld too large, setpoint reset\n", sta->sta.addr, (long long) t_clockdrift); clear_sta_flag(sta, WLAN_STA_TOFFSET_KNOWN); goto no_sync; } spin_lock_bh(&ifmsh->sync_offset_lock); if (t_clockdrift > ifmsh->sync_offset_clockdrift_max) ifmsh->sync_offset_clockdrift_max = t_clockdrift; spin_unlock_bh(&ifmsh->sync_offset_lock); } else { sta->mesh->t_offset_setpoint = sta->mesh->t_offset - TOFFSET_SET_MARGIN; set_sta_flag(sta, WLAN_STA_TOFFSET_KNOWN); msync_dbg(sdata, "STA %pM : offset was invalid, t_offset=%lld\n", sta->sta.addr, (long long) sta->mesh->t_offset); } no_sync: rcu_read_unlock(); } static void mesh_sync_offset_adjust_tsf(struct ieee80211_sub_if_data *sdata, struct beacon_data *beacon) { struct ieee80211_if_mesh *ifmsh = &sdata->u.mesh; WARN_ON(ifmsh->mesh_sp_id != IEEE80211_SYNC_METHOD_NEIGHBOR_OFFSET); WARN_ON(!rcu_read_lock_held()); spin_lock_bh(&ifmsh->sync_offset_lock); if (ifmsh->sync_offset_clockdrift_max > TOFFSET_MINIMUM_ADJUSTMENT) { /* Since ajusting the tsf here would * require a possibly blocking call * to the driver tsf setter, we punt * the tsf adjustment to the mesh tasklet */ msync_dbg(sdata, "TSF : kicking off TSF adjustment with clockdrift_max=%lld\n", ifmsh->sync_offset_clockdrift_max); set_bit(MESH_WORK_DRIFT_ADJUST, &ifmsh->wrkq_flags); } else { msync_dbg(sdata, "TSF : max clockdrift=%lld; too small to adjust\n", (long long)ifmsh->sync_offset_clockdrift_max); ifmsh->sync_offset_clockdrift_max = 0; } spin_unlock_bh(&ifmsh->sync_offset_lock); } static const struct sync_method sync_methods[] = { { .method = IEEE80211_SYNC_METHOD_NEIGHBOR_OFFSET, .ops = { .rx_bcn_presp = &mesh_sync_offset_rx_bcn_presp, .adjust_tsf = &mesh_sync_offset_adjust_tsf, } }, }; const struct ieee80211_mesh_sync_ops *ieee80211_mesh_sync_ops_get(u8 method) { int i; for (i = 0 ; i < ARRAY_SIZE(sync_methods); ++i) { if (sync_methods[i].method == method) return &sync_methods[i].ops; } return NULL; }
null
null
null
null
76,176
1,171
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
263,739
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
#include<stdio.h> #include<assert.h> int main() { int rs, rt; int result; rs = 0xFF0055AA; rt = 0x0113421B; result = 0x02268436; __asm ("append %0, %1, 0x01\n\t" : "+r"(rt) : "r"(rs) ); assert(rt == result); rs = 0xFFFF0FFF; rt = 0x00010111; result = 0x0010111F; __asm ("append %0, %1, 0x04\n\t" : "+r"(rt) : "r"(rs) ); assert(rt == result); return 0; }
null
null
null
null
121,863
742
null
train_val
31e986bc171719c9e6d40d0c2cb1501796a69e6c
259,697
php-src
0
https://github.com/php/php-src
2016-10-24 10:37:20+01:00
/* * COPYRIGHT NOTICE * * This file is a portion of "streamable kanji code filter and converter" * library, which is distributed under GNU Lesser General Public License * version 2.1. * * The source code included in this files was separated from mbfilter.c * by Moriyoshi Koizumi <moriyoshi@php.net> on 4 Dec 2002. * */ #ifndef MBFL_MBFILTER_ISO8859_14_H #define MBFL_MBFILTER_ISO8859_14_H #include "mbfilter.h" extern const mbfl_encoding mbfl_encoding_8859_14; extern const struct mbfl_identify_vtbl vtbl_identify_8859_14; extern const struct mbfl_convert_vtbl vtbl_8859_14_wchar; extern const struct mbfl_convert_vtbl vtbl_wchar_8859_14; int mbfl_filt_conv_8859_14_wchar(int c, mbfl_convert_filter *filter); int mbfl_filt_conv_wchar_8859_14(int c, mbfl_convert_filter *filter); #endif /* MBFL_MBFILTER_ISO8859_14_H */
null
null
null
null
119,618
20,727
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
185,722
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* QLogic qed NIC Driver * Copyright (c) 2015-2017 QLogic Corporation * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and /or other materials * provided with the distribution. * * 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 <linux/types.h> #include <asm/byteorder.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/string.h> #include <linux/etherdevice.h> #include "qed.h" #include "qed_dcbx.h" #include "qed_hsi.h" #include "qed_hw.h" #include "qed_mcp.h" #include "qed_reg_addr.h" #include "qed_sriov.h" #define CHIP_MCP_RESP_ITER_US 10 #define QED_DRV_MB_MAX_RETRIES (500 * 1000) /* Account for 5 sec */ #define QED_MCP_RESET_RETRIES (50 * 1000) /* Account for 500 msec */ #define DRV_INNER_WR(_p_hwfn, _p_ptt, _ptr, _offset, _val) \ qed_wr(_p_hwfn, _p_ptt, (_p_hwfn->mcp_info->_ptr + _offset), \ _val) #define DRV_INNER_RD(_p_hwfn, _p_ptt, _ptr, _offset) \ qed_rd(_p_hwfn, _p_ptt, (_p_hwfn->mcp_info->_ptr + _offset)) #define DRV_MB_WR(_p_hwfn, _p_ptt, _field, _val) \ DRV_INNER_WR(p_hwfn, _p_ptt, drv_mb_addr, \ offsetof(struct public_drv_mb, _field), _val) #define DRV_MB_RD(_p_hwfn, _p_ptt, _field) \ DRV_INNER_RD(_p_hwfn, _p_ptt, drv_mb_addr, \ offsetof(struct public_drv_mb, _field)) #define PDA_COMP (((FW_MAJOR_VERSION) + (FW_MINOR_VERSION << 8)) << \ DRV_ID_PDA_COMP_VER_SHIFT) #define MCP_BYTES_PER_MBIT_SHIFT 17 bool qed_mcp_is_init(struct qed_hwfn *p_hwfn) { if (!p_hwfn->mcp_info || !p_hwfn->mcp_info->public_base) return false; return true; } void qed_mcp_cmd_port_init(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 addr = SECTION_OFFSIZE_ADDR(p_hwfn->mcp_info->public_base, PUBLIC_PORT); u32 mfw_mb_offsize = qed_rd(p_hwfn, p_ptt, addr); p_hwfn->mcp_info->port_addr = SECTION_ADDR(mfw_mb_offsize, MFW_PORT(p_hwfn)); DP_VERBOSE(p_hwfn, QED_MSG_SP, "port_addr = 0x%x, port_id 0x%02x\n", p_hwfn->mcp_info->port_addr, MFW_PORT(p_hwfn)); } void qed_mcp_read_mb(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 length = MFW_DRV_MSG_MAX_DWORDS(p_hwfn->mcp_info->mfw_mb_length); u32 tmp, i; if (!p_hwfn->mcp_info->public_base) return; for (i = 0; i < length; i++) { tmp = qed_rd(p_hwfn, p_ptt, p_hwfn->mcp_info->mfw_mb_addr + (i << 2) + sizeof(u32)); /* The MB data is actually BE; Need to force it to cpu */ ((u32 *)p_hwfn->mcp_info->mfw_mb_cur)[i] = be32_to_cpu((__force __be32)tmp); } } int qed_mcp_free(struct qed_hwfn *p_hwfn) { if (p_hwfn->mcp_info) { kfree(p_hwfn->mcp_info->mfw_mb_cur); kfree(p_hwfn->mcp_info->mfw_mb_shadow); } kfree(p_hwfn->mcp_info); return 0; } static int qed_load_mcp_offsets(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { struct qed_mcp_info *p_info = p_hwfn->mcp_info; u32 drv_mb_offsize, mfw_mb_offsize; u32 mcp_pf_id = MCP_PF_ID(p_hwfn); p_info->public_base = qed_rd(p_hwfn, p_ptt, MISC_REG_SHARED_MEM_ADDR); if (!p_info->public_base) return 0; p_info->public_base |= GRCBASE_MCP; /* Calculate the driver and MFW mailbox address */ drv_mb_offsize = qed_rd(p_hwfn, p_ptt, SECTION_OFFSIZE_ADDR(p_info->public_base, PUBLIC_DRV_MB)); p_info->drv_mb_addr = SECTION_ADDR(drv_mb_offsize, mcp_pf_id); DP_VERBOSE(p_hwfn, QED_MSG_SP, "drv_mb_offsiz = 0x%x, drv_mb_addr = 0x%x mcp_pf_id = 0x%x\n", drv_mb_offsize, p_info->drv_mb_addr, mcp_pf_id); /* Set the MFW MB address */ mfw_mb_offsize = qed_rd(p_hwfn, p_ptt, SECTION_OFFSIZE_ADDR(p_info->public_base, PUBLIC_MFW_MB)); p_info->mfw_mb_addr = SECTION_ADDR(mfw_mb_offsize, mcp_pf_id); p_info->mfw_mb_length = (u16)qed_rd(p_hwfn, p_ptt, p_info->mfw_mb_addr); /* Get the current driver mailbox sequence before sending * the first command */ p_info->drv_mb_seq = DRV_MB_RD(p_hwfn, p_ptt, drv_mb_header) & DRV_MSG_SEQ_NUMBER_MASK; /* Get current FW pulse sequence */ p_info->drv_pulse_seq = DRV_MB_RD(p_hwfn, p_ptt, drv_pulse_mb) & DRV_PULSE_SEQ_MASK; p_info->mcp_hist = (u16)qed_rd(p_hwfn, p_ptt, MISCS_REG_GENERIC_POR_0); return 0; } int qed_mcp_cmd_init(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { struct qed_mcp_info *p_info; u32 size; /* Allocate mcp_info structure */ p_hwfn->mcp_info = kzalloc(sizeof(*p_hwfn->mcp_info), GFP_KERNEL); if (!p_hwfn->mcp_info) goto err; p_info = p_hwfn->mcp_info; if (qed_load_mcp_offsets(p_hwfn, p_ptt) != 0) { DP_NOTICE(p_hwfn, "MCP is not initialized\n"); /* Do not free mcp_info here, since public_base indicate that * the MCP is not initialized */ return 0; } size = MFW_DRV_MSG_MAX_DWORDS(p_info->mfw_mb_length) * sizeof(u32); p_info->mfw_mb_cur = kzalloc(size, GFP_KERNEL); p_info->mfw_mb_shadow = kzalloc(size, GFP_KERNEL); if (!p_info->mfw_mb_shadow || !p_info->mfw_mb_addr) goto err; /* Initialize the MFW spinlock */ spin_lock_init(&p_info->lock); spin_lock_init(&p_info->link_lock); return 0; err: qed_mcp_free(p_hwfn); return -ENOMEM; } /* Locks the MFW mailbox of a PF to ensure a single access. * The lock is achieved in most cases by holding a spinlock, causing other * threads to wait till a previous access is done. * In some cases (currently when a [UN]LOAD_REQ commands are sent), the single * access is achieved by setting a blocking flag, which will fail other * competing contexts to send their mailboxes. */ static int qed_mcp_mb_lock(struct qed_hwfn *p_hwfn, u32 cmd) { spin_lock_bh(&p_hwfn->mcp_info->lock); /* The spinlock shouldn't be acquired when the mailbox command is * [UN]LOAD_REQ, since the engine is locked by the MFW, and a parallel * pending [UN]LOAD_REQ command of another PF together with a spinlock * (i.e. interrupts are disabled) - can lead to a deadlock. * It is assumed that for a single PF, no other mailbox commands can be * sent from another context while sending LOAD_REQ, and that any * parallel commands to UNLOAD_REQ can be cancelled. */ if (cmd == DRV_MSG_CODE_LOAD_DONE || cmd == DRV_MSG_CODE_UNLOAD_DONE) p_hwfn->mcp_info->block_mb_sending = false; if (p_hwfn->mcp_info->block_mb_sending) { DP_NOTICE(p_hwfn, "Trying to send a MFW mailbox command [0x%x] in parallel to [UN]LOAD_REQ. Aborting.\n", cmd); spin_unlock_bh(&p_hwfn->mcp_info->lock); return -EBUSY; } if (cmd == DRV_MSG_CODE_LOAD_REQ || cmd == DRV_MSG_CODE_UNLOAD_REQ) { p_hwfn->mcp_info->block_mb_sending = true; spin_unlock_bh(&p_hwfn->mcp_info->lock); } return 0; } static void qed_mcp_mb_unlock(struct qed_hwfn *p_hwfn, u32 cmd) { if (cmd != DRV_MSG_CODE_LOAD_REQ && cmd != DRV_MSG_CODE_UNLOAD_REQ) spin_unlock_bh(&p_hwfn->mcp_info->lock); } int qed_mcp_reset(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 seq = ++p_hwfn->mcp_info->drv_mb_seq; u8 delay = CHIP_MCP_RESP_ITER_US; u32 org_mcp_reset_seq, cnt = 0; int rc = 0; /* Ensure that only a single thread is accessing the mailbox at a * certain time. */ rc = qed_mcp_mb_lock(p_hwfn, DRV_MSG_CODE_MCP_RESET); if (rc != 0) return rc; /* Set drv command along with the updated sequence */ org_mcp_reset_seq = qed_rd(p_hwfn, p_ptt, MISCS_REG_GENERIC_POR_0); DRV_MB_WR(p_hwfn, p_ptt, drv_mb_header, (DRV_MSG_CODE_MCP_RESET | seq)); do { /* Wait for MFW response */ udelay(delay); /* Give the FW up to 500 second (50*1000*10usec) */ } while ((org_mcp_reset_seq == qed_rd(p_hwfn, p_ptt, MISCS_REG_GENERIC_POR_0)) && (cnt++ < QED_MCP_RESET_RETRIES)); if (org_mcp_reset_seq != qed_rd(p_hwfn, p_ptt, MISCS_REG_GENERIC_POR_0)) { DP_VERBOSE(p_hwfn, QED_MSG_SP, "MCP was reset after %d usec\n", cnt * delay); } else { DP_ERR(p_hwfn, "Failed to reset MCP\n"); rc = -EAGAIN; } qed_mcp_mb_unlock(p_hwfn, DRV_MSG_CODE_MCP_RESET); return rc; } static int qed_do_mcp_cmd(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 cmd, u32 param, u32 *o_mcp_resp, u32 *o_mcp_param) { u8 delay = CHIP_MCP_RESP_ITER_US; u32 seq, cnt = 1, actual_mb_seq; int rc = 0; /* Get actual driver mailbox sequence */ actual_mb_seq = DRV_MB_RD(p_hwfn, p_ptt, drv_mb_header) & DRV_MSG_SEQ_NUMBER_MASK; /* Use MCP history register to check if MCP reset occurred between * init time and now. */ if (p_hwfn->mcp_info->mcp_hist != qed_rd(p_hwfn, p_ptt, MISCS_REG_GENERIC_POR_0)) { DP_VERBOSE(p_hwfn, QED_MSG_SP, "Rereading MCP offsets\n"); qed_load_mcp_offsets(p_hwfn, p_ptt); qed_mcp_cmd_port_init(p_hwfn, p_ptt); } seq = ++p_hwfn->mcp_info->drv_mb_seq; /* Set drv param */ DRV_MB_WR(p_hwfn, p_ptt, drv_mb_param, param); /* Set drv command along with the updated sequence */ DRV_MB_WR(p_hwfn, p_ptt, drv_mb_header, (cmd | seq)); DP_VERBOSE(p_hwfn, QED_MSG_SP, "wrote command (%x) to MFW MB param 0x%08x\n", (cmd | seq), param); do { /* Wait for MFW response */ udelay(delay); *o_mcp_resp = DRV_MB_RD(p_hwfn, p_ptt, fw_mb_header); /* Give the FW up to 5 second (500*10ms) */ } while ((seq != (*o_mcp_resp & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < QED_DRV_MB_MAX_RETRIES)); DP_VERBOSE(p_hwfn, QED_MSG_SP, "[after %d ms] read (%x) seq is (%x) from FW MB\n", cnt * delay, *o_mcp_resp, seq); /* Is this a reply to our command? */ if (seq == (*o_mcp_resp & FW_MSG_SEQ_NUMBER_MASK)) { *o_mcp_resp &= FW_MSG_CODE_MASK; /* Get the MCP param */ *o_mcp_param = DRV_MB_RD(p_hwfn, p_ptt, fw_mb_param); } else { /* FW BUG! */ DP_ERR(p_hwfn, "MFW failed to respond [cmd 0x%x param 0x%x]\n", cmd, param); *o_mcp_resp = 0; rc = -EAGAIN; } return rc; } static int qed_mcp_cmd_and_union(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, struct qed_mcp_mb_params *p_mb_params) { u32 union_data_addr; int rc; /* MCP not initialized */ if (!qed_mcp_is_init(p_hwfn)) { DP_NOTICE(p_hwfn, "MFW is not initialized!\n"); return -EBUSY; } union_data_addr = p_hwfn->mcp_info->drv_mb_addr + offsetof(struct public_drv_mb, union_data); /* Ensure that only a single thread is accessing the mailbox at a * certain time. */ rc = qed_mcp_mb_lock(p_hwfn, p_mb_params->cmd); if (rc) return rc; if (p_mb_params->p_data_src != NULL) qed_memcpy_to(p_hwfn, p_ptt, union_data_addr, p_mb_params->p_data_src, sizeof(*p_mb_params->p_data_src)); rc = qed_do_mcp_cmd(p_hwfn, p_ptt, p_mb_params->cmd, p_mb_params->param, &p_mb_params->mcp_resp, &p_mb_params->mcp_param); if (p_mb_params->p_data_dst != NULL) qed_memcpy_from(p_hwfn, p_ptt, p_mb_params->p_data_dst, union_data_addr, sizeof(*p_mb_params->p_data_dst)); qed_mcp_mb_unlock(p_hwfn, p_mb_params->cmd); return rc; } int qed_mcp_cmd(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 cmd, u32 param, u32 *o_mcp_resp, u32 *o_mcp_param) { struct qed_mcp_mb_params mb_params; union drv_union_data data_src; int rc; memset(&mb_params, 0, sizeof(mb_params)); memset(&data_src, 0, sizeof(data_src)); mb_params.cmd = cmd; mb_params.param = param; /* In case of UNLOAD_DONE, set the primary MAC */ if ((cmd == DRV_MSG_CODE_UNLOAD_DONE) && (p_hwfn->cdev->wol_config == QED_OV_WOL_ENABLED)) { u8 *p_mac = p_hwfn->cdev->wol_mac; data_src.wol_mac.mac_upper = p_mac[0] << 8 | p_mac[1]; data_src.wol_mac.mac_lower = p_mac[2] << 24 | p_mac[3] << 16 | p_mac[4] << 8 | p_mac[5]; DP_VERBOSE(p_hwfn, (QED_MSG_SP | NETIF_MSG_IFDOWN), "Setting WoL MAC: %pM --> [%08x,%08x]\n", p_mac, data_src.wol_mac.mac_upper, data_src.wol_mac.mac_lower); mb_params.p_data_src = &data_src; } rc = qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); if (rc) return rc; *o_mcp_resp = mb_params.mcp_resp; *o_mcp_param = mb_params.mcp_param; return 0; } int qed_mcp_nvm_rd_cmd(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 cmd, u32 param, u32 *o_mcp_resp, u32 *o_mcp_param, u32 *o_txn_size, u32 *o_buf) { struct qed_mcp_mb_params mb_params; union drv_union_data union_data; int rc; memset(&mb_params, 0, sizeof(mb_params)); mb_params.cmd = cmd; mb_params.param = param; mb_params.p_data_dst = &union_data; rc = qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); if (rc) return rc; *o_mcp_resp = mb_params.mcp_resp; *o_mcp_param = mb_params.mcp_param; *o_txn_size = *o_mcp_param; memcpy(o_buf, &union_data.raw_data, *o_txn_size); return 0; } int qed_mcp_load_req(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 *p_load_code) { struct qed_dev *cdev = p_hwfn->cdev; struct qed_mcp_mb_params mb_params; union drv_union_data union_data; int rc; memset(&mb_params, 0, sizeof(mb_params)); /* Load Request */ mb_params.cmd = DRV_MSG_CODE_LOAD_REQ; mb_params.param = PDA_COMP | DRV_ID_MCP_HSI_VER_CURRENT | cdev->drv_type; memcpy(&union_data.ver_str, cdev->ver_str, MCP_DRV_VER_STR_SIZE); mb_params.p_data_src = &union_data; rc = qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); /* if mcp fails to respond we must abort */ if (rc) { DP_ERR(p_hwfn, "MCP response failure, aborting\n"); return rc; } *p_load_code = mb_params.mcp_resp; /* If MFW refused (e.g. other port is in diagnostic mode) we * must abort. This can happen in the following cases: * - Other port is in diagnostic mode * - Previously loaded function on the engine is not compliant with * the requester. * - MFW cannot cope with the requester's DRV_MFW_HSI_VERSION. * - */ if (!(*p_load_code) || ((*p_load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED_HSI) || ((*p_load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED_PDA) || ((*p_load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED_DIAG)) { DP_ERR(p_hwfn, "MCP refused load request, aborting\n"); return -EBUSY; } return 0; } static void qed_mcp_handle_vf_flr(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 addr = SECTION_OFFSIZE_ADDR(p_hwfn->mcp_info->public_base, PUBLIC_PATH); u32 mfw_path_offsize = qed_rd(p_hwfn, p_ptt, addr); u32 path_addr = SECTION_ADDR(mfw_path_offsize, QED_PATH_ID(p_hwfn)); u32 disabled_vfs[VF_MAX_STATIC / 32]; int i; DP_VERBOSE(p_hwfn, QED_MSG_SP, "Reading Disabled VF information from [offset %08x], path_addr %08x\n", mfw_path_offsize, path_addr); for (i = 0; i < (VF_MAX_STATIC / 32); i++) { disabled_vfs[i] = qed_rd(p_hwfn, p_ptt, path_addr + offsetof(struct public_path, mcp_vf_disabled) + sizeof(u32) * i); DP_VERBOSE(p_hwfn, (QED_MSG_SP | QED_MSG_IOV), "FLR-ed VFs [%08x,...,%08x] - %08x\n", i * 32, (i + 1) * 32 - 1, disabled_vfs[i]); } if (qed_iov_mark_vf_flr(p_hwfn, disabled_vfs)) qed_schedule_iov(p_hwfn, QED_IOV_WQ_FLR_FLAG); } int qed_mcp_ack_vf_flr(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 *vfs_to_ack) { u32 addr = SECTION_OFFSIZE_ADDR(p_hwfn->mcp_info->public_base, PUBLIC_FUNC); u32 mfw_func_offsize = qed_rd(p_hwfn, p_ptt, addr); u32 func_addr = SECTION_ADDR(mfw_func_offsize, MCP_PF_ID(p_hwfn)); struct qed_mcp_mb_params mb_params; union drv_union_data union_data; int rc; int i; for (i = 0; i < (VF_MAX_STATIC / 32); i++) DP_VERBOSE(p_hwfn, (QED_MSG_SP | QED_MSG_IOV), "Acking VFs [%08x,...,%08x] - %08x\n", i * 32, (i + 1) * 32 - 1, vfs_to_ack[i]); memset(&mb_params, 0, sizeof(mb_params)); mb_params.cmd = DRV_MSG_CODE_VF_DISABLED_DONE; memcpy(&union_data.ack_vf_disabled, vfs_to_ack, VF_MAX_STATIC / 8); mb_params.p_data_src = &union_data; rc = qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); if (rc) { DP_NOTICE(p_hwfn, "Failed to pass ACK for VF flr to MFW\n"); return -EBUSY; } /* Clear the ACK bits */ for (i = 0; i < (VF_MAX_STATIC / 32); i++) qed_wr(p_hwfn, p_ptt, func_addr + offsetof(struct public_func, drv_ack_vf_disabled) + i * sizeof(u32), 0); return rc; } static void qed_mcp_handle_transceiver_change(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 transceiver_state; transceiver_state = qed_rd(p_hwfn, p_ptt, p_hwfn->mcp_info->port_addr + offsetof(struct public_port, transceiver_data)); DP_VERBOSE(p_hwfn, (NETIF_MSG_HW | QED_MSG_SP), "Received transceiver state update [0x%08x] from mfw [Addr 0x%x]\n", transceiver_state, (u32)(p_hwfn->mcp_info->port_addr + offsetof(struct public_port, transceiver_data))); transceiver_state = GET_FIELD(transceiver_state, ETH_TRANSCEIVER_STATE); if (transceiver_state == ETH_TRANSCEIVER_STATE_PRESENT) DP_NOTICE(p_hwfn, "Transceiver is present.\n"); else DP_NOTICE(p_hwfn, "Transceiver is unplugged.\n"); } static void qed_mcp_handle_link_change(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, bool b_reset) { struct qed_mcp_link_state *p_link; u8 max_bw, min_bw; u32 status = 0; /* Prevent SW/attentions from doing this at the same time */ spin_lock_bh(&p_hwfn->mcp_info->link_lock); p_link = &p_hwfn->mcp_info->link_output; memset(p_link, 0, sizeof(*p_link)); if (!b_reset) { status = qed_rd(p_hwfn, p_ptt, p_hwfn->mcp_info->port_addr + offsetof(struct public_port, link_status)); DP_VERBOSE(p_hwfn, (NETIF_MSG_LINK | QED_MSG_SP), "Received link update [0x%08x] from mfw [Addr 0x%x]\n", status, (u32)(p_hwfn->mcp_info->port_addr + offsetof(struct public_port, link_status))); } else { DP_VERBOSE(p_hwfn, NETIF_MSG_LINK, "Resetting link indications\n"); goto out; } if (p_hwfn->b_drv_link_init) p_link->link_up = !!(status & LINK_STATUS_LINK_UP); else p_link->link_up = false; p_link->full_duplex = true; switch ((status & LINK_STATUS_SPEED_AND_DUPLEX_MASK)) { case LINK_STATUS_SPEED_AND_DUPLEX_100G: p_link->speed = 100000; break; case LINK_STATUS_SPEED_AND_DUPLEX_50G: p_link->speed = 50000; break; case LINK_STATUS_SPEED_AND_DUPLEX_40G: p_link->speed = 40000; break; case LINK_STATUS_SPEED_AND_DUPLEX_25G: p_link->speed = 25000; break; case LINK_STATUS_SPEED_AND_DUPLEX_20G: p_link->speed = 20000; break; case LINK_STATUS_SPEED_AND_DUPLEX_10G: p_link->speed = 10000; break; case LINK_STATUS_SPEED_AND_DUPLEX_1000THD: p_link->full_duplex = false; /* Fall-through */ case LINK_STATUS_SPEED_AND_DUPLEX_1000TFD: p_link->speed = 1000; break; default: p_link->speed = 0; } if (p_link->link_up && p_link->speed) p_link->line_speed = p_link->speed; else p_link->line_speed = 0; max_bw = p_hwfn->mcp_info->func_info.bandwidth_max; min_bw = p_hwfn->mcp_info->func_info.bandwidth_min; /* Max bandwidth configuration */ __qed_configure_pf_max_bandwidth(p_hwfn, p_ptt, p_link, max_bw); /* Min bandwidth configuration */ __qed_configure_pf_min_bandwidth(p_hwfn, p_ptt, p_link, min_bw); qed_configure_vp_wfq_on_link_change(p_hwfn->cdev, p_ptt, p_link->min_pf_rate); p_link->an = !!(status & LINK_STATUS_AUTO_NEGOTIATE_ENABLED); p_link->an_complete = !!(status & LINK_STATUS_AUTO_NEGOTIATE_COMPLETE); p_link->parallel_detection = !!(status & LINK_STATUS_PARALLEL_DETECTION_USED); p_link->pfc_enabled = !!(status & LINK_STATUS_PFC_ENABLED); p_link->partner_adv_speed |= (status & LINK_STATUS_LINK_PARTNER_1000TFD_CAPABLE) ? QED_LINK_PARTNER_SPEED_1G_FD : 0; p_link->partner_adv_speed |= (status & LINK_STATUS_LINK_PARTNER_1000THD_CAPABLE) ? QED_LINK_PARTNER_SPEED_1G_HD : 0; p_link->partner_adv_speed |= (status & LINK_STATUS_LINK_PARTNER_10G_CAPABLE) ? QED_LINK_PARTNER_SPEED_10G : 0; p_link->partner_adv_speed |= (status & LINK_STATUS_LINK_PARTNER_20G_CAPABLE) ? QED_LINK_PARTNER_SPEED_20G : 0; p_link->partner_adv_speed |= (status & LINK_STATUS_LINK_PARTNER_25G_CAPABLE) ? QED_LINK_PARTNER_SPEED_25G : 0; p_link->partner_adv_speed |= (status & LINK_STATUS_LINK_PARTNER_40G_CAPABLE) ? QED_LINK_PARTNER_SPEED_40G : 0; p_link->partner_adv_speed |= (status & LINK_STATUS_LINK_PARTNER_50G_CAPABLE) ? QED_LINK_PARTNER_SPEED_50G : 0; p_link->partner_adv_speed |= (status & LINK_STATUS_LINK_PARTNER_100G_CAPABLE) ? QED_LINK_PARTNER_SPEED_100G : 0; p_link->partner_tx_flow_ctrl_en = !!(status & LINK_STATUS_TX_FLOW_CONTROL_ENABLED); p_link->partner_rx_flow_ctrl_en = !!(status & LINK_STATUS_RX_FLOW_CONTROL_ENABLED); switch (status & LINK_STATUS_LINK_PARTNER_FLOW_CONTROL_MASK) { case LINK_STATUS_LINK_PARTNER_SYMMETRIC_PAUSE: p_link->partner_adv_pause = QED_LINK_PARTNER_SYMMETRIC_PAUSE; break; case LINK_STATUS_LINK_PARTNER_ASYMMETRIC_PAUSE: p_link->partner_adv_pause = QED_LINK_PARTNER_ASYMMETRIC_PAUSE; break; case LINK_STATUS_LINK_PARTNER_BOTH_PAUSE: p_link->partner_adv_pause = QED_LINK_PARTNER_BOTH_PAUSE; break; default: p_link->partner_adv_pause = 0; } p_link->sfp_tx_fault = !!(status & LINK_STATUS_SFP_TX_FAULT); qed_link_update(p_hwfn); out: spin_unlock_bh(&p_hwfn->mcp_info->link_lock); } int qed_mcp_set_link(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, bool b_up) { struct qed_mcp_link_params *params = &p_hwfn->mcp_info->link_input; struct qed_mcp_mb_params mb_params; union drv_union_data union_data; struct eth_phy_cfg *phy_cfg; int rc = 0; u32 cmd; /* Set the shmem configuration according to params */ phy_cfg = &union_data.drv_phy_cfg; memset(phy_cfg, 0, sizeof(*phy_cfg)); cmd = b_up ? DRV_MSG_CODE_INIT_PHY : DRV_MSG_CODE_LINK_RESET; if (!params->speed.autoneg) phy_cfg->speed = params->speed.forced_speed; phy_cfg->pause |= (params->pause.autoneg) ? ETH_PAUSE_AUTONEG : 0; phy_cfg->pause |= (params->pause.forced_rx) ? ETH_PAUSE_RX : 0; phy_cfg->pause |= (params->pause.forced_tx) ? ETH_PAUSE_TX : 0; phy_cfg->adv_speed = params->speed.advertised_speeds; phy_cfg->loopback_mode = params->loopback_mode; p_hwfn->b_drv_link_init = b_up; if (b_up) { DP_VERBOSE(p_hwfn, NETIF_MSG_LINK, "Configuring Link: Speed 0x%08x, Pause 0x%08x, adv_speed 0x%08x, loopback 0x%08x, features 0x%08x\n", phy_cfg->speed, phy_cfg->pause, phy_cfg->adv_speed, phy_cfg->loopback_mode, phy_cfg->feature_config_flags); } else { DP_VERBOSE(p_hwfn, NETIF_MSG_LINK, "Resetting link\n"); } memset(&mb_params, 0, sizeof(mb_params)); mb_params.cmd = cmd; mb_params.p_data_src = &union_data; rc = qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); /* if mcp fails to respond we must abort */ if (rc) { DP_ERR(p_hwfn, "MCP response failure, aborting\n"); return rc; } /* Mimic link-change attention, done for several reasons: * - On reset, there's no guarantee MFW would trigger * an attention. * - On initialization, older MFWs might not indicate link change * during LFA, so we'll never get an UP indication. */ qed_mcp_handle_link_change(p_hwfn, p_ptt, !b_up); return 0; } static void qed_mcp_send_protocol_stats(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum MFW_DRV_MSG_TYPE type) { enum qed_mcp_protocol_type stats_type; union qed_mcp_protocol_stats stats; struct qed_mcp_mb_params mb_params; union drv_union_data union_data; u32 hsi_param; switch (type) { case MFW_DRV_MSG_GET_LAN_STATS: stats_type = QED_MCP_LAN_STATS; hsi_param = DRV_MSG_CODE_STATS_TYPE_LAN; break; case MFW_DRV_MSG_GET_FCOE_STATS: stats_type = QED_MCP_FCOE_STATS; hsi_param = DRV_MSG_CODE_STATS_TYPE_FCOE; break; case MFW_DRV_MSG_GET_ISCSI_STATS: stats_type = QED_MCP_ISCSI_STATS; hsi_param = DRV_MSG_CODE_STATS_TYPE_ISCSI; break; case MFW_DRV_MSG_GET_RDMA_STATS: stats_type = QED_MCP_RDMA_STATS; hsi_param = DRV_MSG_CODE_STATS_TYPE_RDMA; break; default: DP_NOTICE(p_hwfn, "Invalid protocol type %d\n", type); return; } qed_get_protocol_stats(p_hwfn->cdev, stats_type, &stats); memset(&mb_params, 0, sizeof(mb_params)); mb_params.cmd = DRV_MSG_CODE_GET_STATS; mb_params.param = hsi_param; memcpy(&union_data, &stats, sizeof(stats)); mb_params.p_data_src = &union_data; qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); } static void qed_read_pf_bandwidth(struct qed_hwfn *p_hwfn, struct public_func *p_shmem_info) { struct qed_mcp_function_info *p_info; p_info = &p_hwfn->mcp_info->func_info; p_info->bandwidth_min = (p_shmem_info->config & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT; if (p_info->bandwidth_min < 1 || p_info->bandwidth_min > 100) { DP_INFO(p_hwfn, "bandwidth minimum out of bounds [%02x]. Set to 1\n", p_info->bandwidth_min); p_info->bandwidth_min = 1; } p_info->bandwidth_max = (p_shmem_info->config & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT; if (p_info->bandwidth_max < 1 || p_info->bandwidth_max > 100) { DP_INFO(p_hwfn, "bandwidth maximum out of bounds [%02x]. Set to 100\n", p_info->bandwidth_max); p_info->bandwidth_max = 100; } } static u32 qed_mcp_get_shmem_func(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, struct public_func *p_data, int pfid) { u32 addr = SECTION_OFFSIZE_ADDR(p_hwfn->mcp_info->public_base, PUBLIC_FUNC); u32 mfw_path_offsize = qed_rd(p_hwfn, p_ptt, addr); u32 func_addr = SECTION_ADDR(mfw_path_offsize, pfid); u32 i, size; memset(p_data, 0, sizeof(*p_data)); size = min_t(u32, sizeof(*p_data), QED_SECTION_SIZE(mfw_path_offsize)); for (i = 0; i < size / sizeof(u32); i++) ((u32 *)p_data)[i] = qed_rd(p_hwfn, p_ptt, func_addr + (i << 2)); return size; } static void qed_mcp_update_bw(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { struct qed_mcp_function_info *p_info; struct public_func shmem_info; u32 resp = 0, param = 0; qed_mcp_get_shmem_func(p_hwfn, p_ptt, &shmem_info, MCP_PF_ID(p_hwfn)); qed_read_pf_bandwidth(p_hwfn, &shmem_info); p_info = &p_hwfn->mcp_info->func_info; qed_configure_pf_min_bandwidth(p_hwfn->cdev, p_info->bandwidth_min); qed_configure_pf_max_bandwidth(p_hwfn->cdev, p_info->bandwidth_max); /* Acknowledge the MFW */ qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_BW_UPDATE_ACK, 0, &resp, &param); } int qed_mcp_handle_events(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { struct qed_mcp_info *info = p_hwfn->mcp_info; int rc = 0; bool found = false; u16 i; DP_VERBOSE(p_hwfn, QED_MSG_SP, "Received message from MFW\n"); /* Read Messages from MFW */ qed_mcp_read_mb(p_hwfn, p_ptt); /* Compare current messages to old ones */ for (i = 0; i < info->mfw_mb_length; i++) { if (info->mfw_mb_cur[i] == info->mfw_mb_shadow[i]) continue; found = true; DP_VERBOSE(p_hwfn, NETIF_MSG_LINK, "Msg [%d] - old CMD 0x%02x, new CMD 0x%02x\n", i, info->mfw_mb_shadow[i], info->mfw_mb_cur[i]); switch (i) { case MFW_DRV_MSG_LINK_CHANGE: qed_mcp_handle_link_change(p_hwfn, p_ptt, false); break; case MFW_DRV_MSG_VF_DISABLED: qed_mcp_handle_vf_flr(p_hwfn, p_ptt); break; case MFW_DRV_MSG_LLDP_DATA_UPDATED: qed_dcbx_mib_update_event(p_hwfn, p_ptt, QED_DCBX_REMOTE_LLDP_MIB); break; case MFW_DRV_MSG_DCBX_REMOTE_MIB_UPDATED: qed_dcbx_mib_update_event(p_hwfn, p_ptt, QED_DCBX_REMOTE_MIB); break; case MFW_DRV_MSG_DCBX_OPERATIONAL_MIB_UPDATED: qed_dcbx_mib_update_event(p_hwfn, p_ptt, QED_DCBX_OPERATIONAL_MIB); break; case MFW_DRV_MSG_TRANSCEIVER_STATE_CHANGE: qed_mcp_handle_transceiver_change(p_hwfn, p_ptt); break; case MFW_DRV_MSG_GET_LAN_STATS: case MFW_DRV_MSG_GET_FCOE_STATS: case MFW_DRV_MSG_GET_ISCSI_STATS: case MFW_DRV_MSG_GET_RDMA_STATS: qed_mcp_send_protocol_stats(p_hwfn, p_ptt, i); break; case MFW_DRV_MSG_BW_UPDATE: qed_mcp_update_bw(p_hwfn, p_ptt); break; default: DP_NOTICE(p_hwfn, "Unimplemented MFW message %d\n", i); rc = -EINVAL; } } /* ACK everything */ for (i = 0; i < MFW_DRV_MSG_MAX_DWORDS(info->mfw_mb_length); i++) { __be32 val = cpu_to_be32(((u32 *)info->mfw_mb_cur)[i]); /* MFW expect answer in BE, so we force write in that format */ qed_wr(p_hwfn, p_ptt, info->mfw_mb_addr + sizeof(u32) + MFW_DRV_MSG_MAX_DWORDS(info->mfw_mb_length) * sizeof(u32) + i * sizeof(u32), (__force u32)val); } if (!found) { DP_NOTICE(p_hwfn, "Received an MFW message indication but no new message!\n"); rc = -EINVAL; } /* Copy the new mfw messages into the shadow */ memcpy(info->mfw_mb_shadow, info->mfw_mb_cur, info->mfw_mb_length); return rc; } int qed_mcp_get_mfw_ver(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 *p_mfw_ver, u32 *p_running_bundle_id) { u32 global_offsize; if (IS_VF(p_hwfn->cdev)) { if (p_hwfn->vf_iov_info) { struct pfvf_acquire_resp_tlv *p_resp; p_resp = &p_hwfn->vf_iov_info->acquire_resp; *p_mfw_ver = p_resp->pfdev_info.mfw_ver; return 0; } else { DP_VERBOSE(p_hwfn, QED_MSG_IOV, "VF requested MFW version prior to ACQUIRE\n"); return -EINVAL; } } global_offsize = qed_rd(p_hwfn, p_ptt, SECTION_OFFSIZE_ADDR(p_hwfn-> mcp_info->public_base, PUBLIC_GLOBAL)); *p_mfw_ver = qed_rd(p_hwfn, p_ptt, SECTION_ADDR(global_offsize, 0) + offsetof(struct public_global, mfw_ver)); if (p_running_bundle_id != NULL) { *p_running_bundle_id = qed_rd(p_hwfn, p_ptt, SECTION_ADDR(global_offsize, 0) + offsetof(struct public_global, running_bundle_id)); } return 0; } int qed_mcp_get_media_type(struct qed_dev *cdev, u32 *p_media_type) { struct qed_hwfn *p_hwfn = &cdev->hwfns[0]; struct qed_ptt *p_ptt; if (IS_VF(cdev)) return -EINVAL; if (!qed_mcp_is_init(p_hwfn)) { DP_NOTICE(p_hwfn, "MFW is not initialized!\n"); return -EBUSY; } *p_media_type = MEDIA_UNSPECIFIED; p_ptt = qed_ptt_acquire(p_hwfn); if (!p_ptt) return -EBUSY; *p_media_type = qed_rd(p_hwfn, p_ptt, p_hwfn->mcp_info->port_addr + offsetof(struct public_port, media_type)); qed_ptt_release(p_hwfn, p_ptt); return 0; } /* Old MFW has a global configuration for all PFs regarding RDMA support */ static void qed_mcp_get_shmem_proto_legacy(struct qed_hwfn *p_hwfn, enum qed_pci_personality *p_proto) { /* There wasn't ever a legacy MFW that published iwarp. * So at this point, this is either plain l2 or RoCE. */ if (test_bit(QED_DEV_CAP_ROCE, &p_hwfn->hw_info.device_capabilities)) *p_proto = QED_PCI_ETH_ROCE; else *p_proto = QED_PCI_ETH; DP_VERBOSE(p_hwfn, NETIF_MSG_IFUP, "According to Legacy capabilities, L2 personality is %08x\n", (u32) *p_proto); } static int qed_mcp_get_shmem_proto_mfw(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum qed_pci_personality *p_proto) { u32 resp = 0, param = 0; int rc; rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_GET_PF_RDMA_PROTOCOL, 0, &resp, &param); if (rc) return rc; if (resp != FW_MSG_CODE_OK) { DP_VERBOSE(p_hwfn, NETIF_MSG_IFUP, "MFW lacks support for command; Returns %08x\n", resp); return -EINVAL; } switch (param) { case FW_MB_PARAM_GET_PF_RDMA_NONE: *p_proto = QED_PCI_ETH; break; case FW_MB_PARAM_GET_PF_RDMA_ROCE: *p_proto = QED_PCI_ETH_ROCE; break; case FW_MB_PARAM_GET_PF_RDMA_BOTH: DP_NOTICE(p_hwfn, "Current day drivers don't support RoCE & iWARP. Default to RoCE-only\n"); *p_proto = QED_PCI_ETH_ROCE; break; case FW_MB_PARAM_GET_PF_RDMA_IWARP: default: DP_NOTICE(p_hwfn, "MFW answers GET_PF_RDMA_PROTOCOL but param is %08x\n", param); return -EINVAL; } DP_VERBOSE(p_hwfn, NETIF_MSG_IFUP, "According to capabilities, L2 personality is %08x [resp %08x param %08x]\n", (u32) *p_proto, resp, param); return 0; } static int qed_mcp_get_shmem_proto(struct qed_hwfn *p_hwfn, struct public_func *p_info, struct qed_ptt *p_ptt, enum qed_pci_personality *p_proto) { int rc = 0; switch (p_info->config & FUNC_MF_CFG_PROTOCOL_MASK) { case FUNC_MF_CFG_PROTOCOL_ETHERNET: if (!IS_ENABLED(CONFIG_QED_RDMA)) *p_proto = QED_PCI_ETH; else if (qed_mcp_get_shmem_proto_mfw(p_hwfn, p_ptt, p_proto)) qed_mcp_get_shmem_proto_legacy(p_hwfn, p_proto); break; case FUNC_MF_CFG_PROTOCOL_ISCSI: *p_proto = QED_PCI_ISCSI; break; case FUNC_MF_CFG_PROTOCOL_FCOE: *p_proto = QED_PCI_FCOE; break; case FUNC_MF_CFG_PROTOCOL_ROCE: DP_NOTICE(p_hwfn, "RoCE personality is not a valid value!\n"); /* Fallthrough */ default: rc = -EINVAL; } return rc; } int qed_mcp_fill_shmem_func_info(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { struct qed_mcp_function_info *info; struct public_func shmem_info; qed_mcp_get_shmem_func(p_hwfn, p_ptt, &shmem_info, MCP_PF_ID(p_hwfn)); info = &p_hwfn->mcp_info->func_info; info->pause_on_host = (shmem_info.config & FUNC_MF_CFG_PAUSE_ON_HOST_RING) ? 1 : 0; if (qed_mcp_get_shmem_proto(p_hwfn, &shmem_info, p_ptt, &info->protocol)) { DP_ERR(p_hwfn, "Unknown personality %08x\n", (u32)(shmem_info.config & FUNC_MF_CFG_PROTOCOL_MASK)); return -EINVAL; } qed_read_pf_bandwidth(p_hwfn, &shmem_info); if (shmem_info.mac_upper || shmem_info.mac_lower) { info->mac[0] = (u8)(shmem_info.mac_upper >> 8); info->mac[1] = (u8)(shmem_info.mac_upper); info->mac[2] = (u8)(shmem_info.mac_lower >> 24); info->mac[3] = (u8)(shmem_info.mac_lower >> 16); info->mac[4] = (u8)(shmem_info.mac_lower >> 8); info->mac[5] = (u8)(shmem_info.mac_lower); /* Store primary MAC for later possible WoL */ memcpy(&p_hwfn->cdev->wol_mac, info->mac, ETH_ALEN); } else { DP_NOTICE(p_hwfn, "MAC is 0 in shmem\n"); } info->wwn_port = (u64)shmem_info.fcoe_wwn_port_name_upper | (((u64)shmem_info.fcoe_wwn_port_name_lower) << 32); info->wwn_node = (u64)shmem_info.fcoe_wwn_node_name_upper | (((u64)shmem_info.fcoe_wwn_node_name_lower) << 32); info->ovlan = (u16)(shmem_info.ovlan_stag & FUNC_MF_CFG_OV_STAG_MASK); info->mtu = (u16)shmem_info.mtu_size; p_hwfn->hw_info.b_wol_support = QED_WOL_SUPPORT_NONE; p_hwfn->cdev->wol_config = (u8)QED_OV_WOL_DEFAULT; if (qed_mcp_is_init(p_hwfn)) { u32 resp = 0, param = 0; int rc; rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_OS_WOL, 0, &resp, &param); if (rc) return rc; if (resp == FW_MSG_CODE_OS_WOL_SUPPORTED) p_hwfn->hw_info.b_wol_support = QED_WOL_SUPPORT_PME; } DP_VERBOSE(p_hwfn, (QED_MSG_SP | NETIF_MSG_IFUP), "Read configuration from shmem: pause_on_host %02x protocol %02x BW [%02x - %02x] MAC %02x:%02x:%02x:%02x:%02x:%02x wwn port %llx node %llx ovlan %04x wol %02x\n", info->pause_on_host, info->protocol, info->bandwidth_min, info->bandwidth_max, info->mac[0], info->mac[1], info->mac[2], info->mac[3], info->mac[4], info->mac[5], info->wwn_port, info->wwn_node, info->ovlan, (u8)p_hwfn->hw_info.b_wol_support); return 0; } struct qed_mcp_link_params *qed_mcp_get_link_params(struct qed_hwfn *p_hwfn) { if (!p_hwfn || !p_hwfn->mcp_info) return NULL; return &p_hwfn->mcp_info->link_input; } struct qed_mcp_link_state *qed_mcp_get_link_state(struct qed_hwfn *p_hwfn) { if (!p_hwfn || !p_hwfn->mcp_info) return NULL; return &p_hwfn->mcp_info->link_output; } struct qed_mcp_link_capabilities *qed_mcp_get_link_capabilities(struct qed_hwfn *p_hwfn) { if (!p_hwfn || !p_hwfn->mcp_info) return NULL; return &p_hwfn->mcp_info->link_capabilities; } int qed_mcp_drain(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 resp = 0, param = 0; int rc; rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_NIG_DRAIN, 1000, &resp, &param); /* Wait for the drain to complete before returning */ msleep(1020); return rc; } int qed_mcp_get_flash_size(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 *p_flash_size) { u32 flash_size; if (IS_VF(p_hwfn->cdev)) return -EINVAL; flash_size = qed_rd(p_hwfn, p_ptt, MCP_REG_NVM_CFG4); flash_size = (flash_size & MCP_REG_NVM_CFG4_FLASH_SIZE) >> MCP_REG_NVM_CFG4_FLASH_SIZE_SHIFT; flash_size = (1 << (flash_size + MCP_BYTES_PER_MBIT_SHIFT)); *p_flash_size = flash_size; return 0; } int qed_mcp_config_vf_msix(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u8 vf_id, u8 num) { u32 resp = 0, param = 0, rc_param = 0; int rc; /* Only Leader can configure MSIX, and need to take CMT into account */ if (!IS_LEAD_HWFN(p_hwfn)) return 0; num *= p_hwfn->cdev->num_hwfns; param |= (vf_id << DRV_MB_PARAM_CFG_VF_MSIX_VF_ID_SHIFT) & DRV_MB_PARAM_CFG_VF_MSIX_VF_ID_MASK; param |= (num << DRV_MB_PARAM_CFG_VF_MSIX_SB_NUM_SHIFT) & DRV_MB_PARAM_CFG_VF_MSIX_SB_NUM_MASK; rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_CFG_VF_MSIX, param, &resp, &rc_param); if (resp != FW_MSG_CODE_DRV_CFG_VF_MSIX_DONE) { DP_NOTICE(p_hwfn, "VF[%d]: MFW failed to set MSI-X\n", vf_id); rc = -EINVAL; } else { DP_VERBOSE(p_hwfn, QED_MSG_IOV, "Requested 0x%02x MSI-x interrupts from VF 0x%02x\n", num, vf_id); } return rc; } int qed_mcp_send_drv_version(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, struct qed_mcp_drv_version *p_ver) { struct drv_version_stc *p_drv_version; struct qed_mcp_mb_params mb_params; union drv_union_data union_data; __be32 val; u32 i; int rc; p_drv_version = &union_data.drv_version; p_drv_version->version = p_ver->version; for (i = 0; i < (MCP_DRV_VER_STR_SIZE - 4) / sizeof(u32); i++) { val = cpu_to_be32(*((u32 *)&p_ver->name[i * sizeof(u32)])); *(__be32 *)&p_drv_version->name[i * sizeof(u32)] = val; } memset(&mb_params, 0, sizeof(mb_params)); mb_params.cmd = DRV_MSG_CODE_SET_VERSION; mb_params.p_data_src = &union_data; rc = qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); if (rc) DP_ERR(p_hwfn, "MCP response failure, aborting\n"); return rc; } int qed_mcp_halt(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 resp = 0, param = 0; int rc; rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_MCP_HALT, 0, &resp, &param); if (rc) DP_ERR(p_hwfn, "MCP response failure, aborting\n"); return rc; } int qed_mcp_resume(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 value, cpu_mode; qed_wr(p_hwfn, p_ptt, MCP_REG_CPU_STATE, 0xffffffff); value = qed_rd(p_hwfn, p_ptt, MCP_REG_CPU_MODE); value &= ~MCP_REG_CPU_MODE_SOFT_HALT; qed_wr(p_hwfn, p_ptt, MCP_REG_CPU_MODE, value); cpu_mode = qed_rd(p_hwfn, p_ptt, MCP_REG_CPU_MODE); return (cpu_mode & MCP_REG_CPU_MODE_SOFT_HALT) ? -EAGAIN : 0; } int qed_mcp_ov_update_current_config(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum qed_ov_client client) { u32 resp = 0, param = 0; u32 drv_mb_param; int rc; switch (client) { case QED_OV_CLIENT_DRV: drv_mb_param = DRV_MB_PARAM_OV_CURR_CFG_OS; break; case QED_OV_CLIENT_USER: drv_mb_param = DRV_MB_PARAM_OV_CURR_CFG_OTHER; break; case QED_OV_CLIENT_VENDOR_SPEC: drv_mb_param = DRV_MB_PARAM_OV_CURR_CFG_VENDOR_SPEC; break; default: DP_NOTICE(p_hwfn, "Invalid client type %d\n", client); return -EINVAL; } rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_OV_UPDATE_CURR_CFG, drv_mb_param, &resp, &param); if (rc) DP_ERR(p_hwfn, "MCP response failure, aborting\n"); return rc; } int qed_mcp_ov_update_driver_state(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum qed_ov_driver_state drv_state) { u32 resp = 0, param = 0; u32 drv_mb_param; int rc; switch (drv_state) { case QED_OV_DRIVER_STATE_NOT_LOADED: drv_mb_param = DRV_MSG_CODE_OV_UPDATE_DRIVER_STATE_NOT_LOADED; break; case QED_OV_DRIVER_STATE_DISABLED: drv_mb_param = DRV_MSG_CODE_OV_UPDATE_DRIVER_STATE_DISABLED; break; case QED_OV_DRIVER_STATE_ACTIVE: drv_mb_param = DRV_MSG_CODE_OV_UPDATE_DRIVER_STATE_ACTIVE; break; default: DP_NOTICE(p_hwfn, "Invalid driver state %d\n", drv_state); return -EINVAL; } rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_OV_UPDATE_DRIVER_STATE, drv_mb_param, &resp, &param); if (rc) DP_ERR(p_hwfn, "Failed to send driver state\n"); return rc; } int qed_mcp_ov_update_mtu(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u16 mtu) { u32 resp = 0, param = 0; u32 drv_mb_param; int rc; drv_mb_param = (u32)mtu << DRV_MB_PARAM_OV_MTU_SIZE_SHIFT; rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_OV_UPDATE_MTU, drv_mb_param, &resp, &param); if (rc) DP_ERR(p_hwfn, "Failed to send mtu value, rc = %d\n", rc); return rc; } int qed_mcp_ov_update_mac(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u8 *mac) { struct qed_mcp_mb_params mb_params; union drv_union_data union_data; int rc; memset(&mb_params, 0, sizeof(mb_params)); mb_params.cmd = DRV_MSG_CODE_SET_VMAC; mb_params.param = DRV_MSG_CODE_VMAC_TYPE_MAC << DRV_MSG_CODE_VMAC_TYPE_SHIFT; mb_params.param |= MCP_PF_ID(p_hwfn); ether_addr_copy(&union_data.raw_data[0], mac); mb_params.p_data_src = &union_data; rc = qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); if (rc) DP_ERR(p_hwfn, "Failed to send mac address, rc = %d\n", rc); /* Store primary MAC for later possible WoL */ memcpy(p_hwfn->cdev->wol_mac, mac, ETH_ALEN); return rc; } int qed_mcp_ov_update_wol(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum qed_ov_wol wol) { u32 resp = 0, param = 0; u32 drv_mb_param; int rc; if (p_hwfn->hw_info.b_wol_support == QED_WOL_SUPPORT_NONE) { DP_VERBOSE(p_hwfn, QED_MSG_SP, "Can't change WoL configuration when WoL isn't supported\n"); return -EINVAL; } switch (wol) { case QED_OV_WOL_DEFAULT: drv_mb_param = DRV_MB_PARAM_WOL_DEFAULT; break; case QED_OV_WOL_DISABLED: drv_mb_param = DRV_MB_PARAM_WOL_DISABLED; break; case QED_OV_WOL_ENABLED: drv_mb_param = DRV_MB_PARAM_WOL_ENABLED; break; default: DP_ERR(p_hwfn, "Invalid wol state %d\n", wol); return -EINVAL; } rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_OV_UPDATE_WOL, drv_mb_param, &resp, &param); if (rc) DP_ERR(p_hwfn, "Failed to send wol mode, rc = %d\n", rc); /* Store the WoL update for a future unload */ p_hwfn->cdev->wol_config = (u8)wol; return rc; } int qed_mcp_ov_update_eswitch(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum qed_ov_eswitch eswitch) { u32 resp = 0, param = 0; u32 drv_mb_param; int rc; switch (eswitch) { case QED_OV_ESWITCH_NONE: drv_mb_param = DRV_MB_PARAM_ESWITCH_MODE_NONE; break; case QED_OV_ESWITCH_VEB: drv_mb_param = DRV_MB_PARAM_ESWITCH_MODE_VEB; break; case QED_OV_ESWITCH_VEPA: drv_mb_param = DRV_MB_PARAM_ESWITCH_MODE_VEPA; break; default: DP_ERR(p_hwfn, "Invalid eswitch mode %d\n", eswitch); return -EINVAL; } rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_OV_UPDATE_ESWITCH_MODE, drv_mb_param, &resp, &param); if (rc) DP_ERR(p_hwfn, "Failed to send eswitch mode, rc = %d\n", rc); return rc; } int qed_mcp_set_led(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, enum qed_led_mode mode) { u32 resp = 0, param = 0, drv_mb_param; int rc; switch (mode) { case QED_LED_MODE_ON: drv_mb_param = DRV_MB_PARAM_SET_LED_MODE_ON; break; case QED_LED_MODE_OFF: drv_mb_param = DRV_MB_PARAM_SET_LED_MODE_OFF; break; case QED_LED_MODE_RESTORE: drv_mb_param = DRV_MB_PARAM_SET_LED_MODE_OPER; break; default: DP_NOTICE(p_hwfn, "Invalid LED mode %d\n", mode); return -EINVAL; } rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_SET_LED_MODE, drv_mb_param, &resp, &param); return rc; } int qed_mcp_mask_parities(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 mask_parities) { u32 resp = 0, param = 0; int rc; rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_MASK_PARITIES, mask_parities, &resp, &param); if (rc) { DP_ERR(p_hwfn, "MCP response failure for mask parities, aborting\n"); } else if (resp != FW_MSG_CODE_OK) { DP_ERR(p_hwfn, "MCP did not acknowledge mask parity request. Old MFW?\n"); rc = -EINVAL; } return rc; } int qed_mcp_nvm_read(struct qed_dev *cdev, u32 addr, u8 *p_buf, u32 len) { u32 bytes_left = len, offset = 0, bytes_to_copy, read_len = 0; struct qed_hwfn *p_hwfn = QED_LEADING_HWFN(cdev); u32 resp = 0, resp_param = 0; struct qed_ptt *p_ptt; int rc = 0; p_ptt = qed_ptt_acquire(p_hwfn); if (!p_ptt) return -EBUSY; while (bytes_left > 0) { bytes_to_copy = min_t(u32, bytes_left, MCP_DRV_NVM_BUF_LEN); rc = qed_mcp_nvm_rd_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_NVM_READ_NVRAM, addr + offset + (bytes_to_copy << DRV_MB_PARAM_NVM_LEN_SHIFT), &resp, &resp_param, &read_len, (u32 *)(p_buf + offset)); if (rc || (resp != FW_MSG_CODE_NVM_OK)) { DP_NOTICE(cdev, "MCP command rc = %d\n", rc); break; } /* This can be a lengthy process, and it's possible scheduler * isn't preemptable. Sleep a bit to prevent CPU hogging. */ if (bytes_left % 0x1000 < (bytes_left - read_len) % 0x1000) usleep_range(1000, 2000); offset += read_len; bytes_left -= read_len; } cdev->mcp_nvm_resp = resp; qed_ptt_release(p_hwfn, p_ptt); return rc; } int qed_mcp_bist_register_test(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 drv_mb_param = 0, rsp, param; int rc = 0; drv_mb_param = (DRV_MB_PARAM_BIST_REGISTER_TEST << DRV_MB_PARAM_BIST_TEST_INDEX_SHIFT); rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_BIST_TEST, drv_mb_param, &rsp, &param); if (rc) return rc; if (((rsp & FW_MSG_CODE_MASK) != FW_MSG_CODE_OK) || (param != DRV_MB_PARAM_BIST_RC_PASSED)) rc = -EAGAIN; return rc; } int qed_mcp_bist_clock_test(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt) { u32 drv_mb_param, rsp, param; int rc = 0; drv_mb_param = (DRV_MB_PARAM_BIST_CLOCK_TEST << DRV_MB_PARAM_BIST_TEST_INDEX_SHIFT); rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_BIST_TEST, drv_mb_param, &rsp, &param); if (rc) return rc; if (((rsp & FW_MSG_CODE_MASK) != FW_MSG_CODE_OK) || (param != DRV_MB_PARAM_BIST_RC_PASSED)) rc = -EAGAIN; return rc; } int qed_mcp_bist_nvm_test_get_num_images(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, u32 *num_images) { u32 drv_mb_param = 0, rsp; int rc = 0; drv_mb_param = (DRV_MB_PARAM_BIST_NVM_TEST_NUM_IMAGES << DRV_MB_PARAM_BIST_TEST_INDEX_SHIFT); rc = qed_mcp_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_BIST_TEST, drv_mb_param, &rsp, num_images); if (rc) return rc; if (((rsp & FW_MSG_CODE_MASK) != FW_MSG_CODE_OK)) rc = -EINVAL; return rc; } int qed_mcp_bist_nvm_test_get_image_att(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, struct bist_nvm_image_att *p_image_att, u32 image_index) { u32 buf_size = 0, param, resp = 0, resp_param = 0; int rc; param = DRV_MB_PARAM_BIST_NVM_TEST_IMAGE_BY_INDEX << DRV_MB_PARAM_BIST_TEST_INDEX_SHIFT; param |= image_index << DRV_MB_PARAM_BIST_TEST_IMAGE_INDEX_SHIFT; rc = qed_mcp_nvm_rd_cmd(p_hwfn, p_ptt, DRV_MSG_CODE_BIST_TEST, param, &resp, &resp_param, &buf_size, (u32 *)p_image_att); if (rc) return rc; if (((resp & FW_MSG_CODE_MASK) != FW_MSG_CODE_OK) || (p_image_att->return_code != 1)) rc = -EINVAL; return rc; } #define QED_RESC_ALLOC_VERSION_MAJOR 1 #define QED_RESC_ALLOC_VERSION_MINOR 0 #define QED_RESC_ALLOC_VERSION \ ((QED_RESC_ALLOC_VERSION_MAJOR << \ DRV_MB_PARAM_RESOURCE_ALLOC_VERSION_MAJOR_SHIFT) | \ (QED_RESC_ALLOC_VERSION_MINOR << \ DRV_MB_PARAM_RESOURCE_ALLOC_VERSION_MINOR_SHIFT)) int qed_mcp_get_resc_info(struct qed_hwfn *p_hwfn, struct qed_ptt *p_ptt, struct resource_info *p_resc_info, u32 *p_mcp_resp, u32 *p_mcp_param) { struct qed_mcp_mb_params mb_params; union drv_union_data union_data; int rc; memset(&mb_params, 0, sizeof(mb_params)); memset(&union_data, 0, sizeof(union_data)); mb_params.cmd = DRV_MSG_GET_RESOURCE_ALLOC_MSG; mb_params.param = QED_RESC_ALLOC_VERSION; /* Need to have a sufficient large struct, as the cmd_and_union * is going to do memcpy from and to it. */ memcpy(&union_data.resource, p_resc_info, sizeof(*p_resc_info)); mb_params.p_data_src = &union_data; mb_params.p_data_dst = &union_data; rc = qed_mcp_cmd_and_union(p_hwfn, p_ptt, &mb_params); if (rc) return rc; /* Copy the data back */ memcpy(p_resc_info, &union_data.resource, sizeof(*p_resc_info)); *p_mcp_resp = mb_params.mcp_resp; *p_mcp_param = mb_params.mcp_param; DP_VERBOSE(p_hwfn, QED_MSG_SP, "MFW resource_info: version 0x%x, res_id 0x%x, size 0x%x, offset 0x%x, vf_size 0x%x, vf_offset 0x%x, flags 0x%x\n", *p_mcp_param, p_resc_info->res_id, p_resc_info->size, p_resc_info->offset, p_resc_info->vf_size, p_resc_info->vf_offset, p_resc_info->flags); return 0; }
null
null
null
null
94,069
70,568
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
70,568
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/fido/make_credential_task.h" #include <utility> #include "base/bind.h" #include "device/fido/ctap_empty_authenticator_request.h" #include "device/fido/device_response_converter.h" namespace device { MakeCredentialTask::MakeCredentialTask( FidoDevice* device, CtapMakeCredentialRequest request_parameter, AuthenticatorSelectionCriteria authenticator_selection_criteria, MakeCredentialTaskCallback callback) : FidoTask(device), request_parameter_(std::move(request_parameter)), authenticator_selection_criteria_( std::move(authenticator_selection_criteria)), callback_(std::move(callback)), weak_factory_(this) {} MakeCredentialTask::~MakeCredentialTask() = default; void MakeCredentialTask::StartTask() { GetAuthenticatorInfo(base::BindOnce(&MakeCredentialTask::MakeCredential, weak_factory_.GetWeakPtr()), base::BindOnce(&MakeCredentialTask::U2fRegister, weak_factory_.GetWeakPtr())); } void MakeCredentialTask::MakeCredential() { if (!CheckIfAuthenticatorSelectionCriteriaAreSatisfied()) { std::move(callback_).Run(CtapDeviceResponseCode::kCtap2ErrOther, base::nullopt); return; } device()->DeviceTransact( request_parameter_.EncodeAsCBOR(), base::BindOnce(&MakeCredentialTask::OnCtapMakeCredentialResponseReceived, weak_factory_.GetWeakPtr())); } void MakeCredentialTask::U2fRegister() { // TODO(hongjunchoi): Implement U2F register request logic to support // interoperability with U2F protocol. Currently all U2F devices are not // supported and request to U2F devices will be silently dropped. // See: https://crbug.com/798573 std::move(callback_).Run(CtapDeviceResponseCode::kCtap2ErrOther, base::nullopt); } void MakeCredentialTask::OnCtapMakeCredentialResponseReceived( base::Optional<std::vector<uint8_t>> device_response) { if (!device_response) { std::move(callback_).Run(CtapDeviceResponseCode::kCtap2ErrOther, base::nullopt); return; } std::move(callback_).Run(GetResponseCode(*device_response), ReadCTAPMakeCredentialResponse(*device_response)); } bool MakeCredentialTask::CheckIfAuthenticatorSelectionCriteriaAreSatisfied() { using AuthenticatorAttachment = AuthenticatorSelectionCriteria::AuthenticatorAttachment; using UvRequirement = AuthenticatorSelectionCriteria::UserVerificationRequirement; using UvAvailability = AuthenticatorSupportedOptions::UserVerificationAvailability; // U2F authenticators are non-platform devices that do not support resident // key or user verification. const auto& device_info = device()->device_info(); if (!device_info) { return !authenticator_selection_criteria_.require_resident_key() && authenticator_selection_criteria_.user_verification_requirement() != UvRequirement::kRequired && authenticator_selection_criteria_.authenticator_attachement() != AuthenticatorAttachment::kPlatform; } const auto& options = device_info->options(); if ((authenticator_selection_criteria_.authenticator_attachement() == AuthenticatorAttachment::kPlatform && !options.is_platform_device()) || (authenticator_selection_criteria_.authenticator_attachement() == AuthenticatorAttachment::kCrossPlatform && options.is_platform_device())) { return false; } if (authenticator_selection_criteria_.require_resident_key() && !options.supports_resident_key()) { return false; } return authenticator_selection_criteria_.user_verification_requirement() != UvRequirement::kRequired || options.user_verification_availability() == UvAvailability::kSupportedAndConfigured; } } // namespace device
null
null
null
null
67,431
12,687
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
177,682
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2008-2013 Freescale Semiconductor, Inc. All rights reserved. * * Author: Yu Liu, yu.liu@freescale.com * Scott Wood, scottwood@freescale.com * Ashish Kalra, ashish.kalra@freescale.com * Varun Sethi, varun.sethi@freescale.com * Alexander Graf, agraf@suse.de * * Description: * This file is based on arch/powerpc/kvm/44x_tlb.c, * by Hollis Blanchard <hollisb@us.ibm.com>. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/kvm.h> #include <linux/kvm_host.h> #include <linux/highmem.h> #include <linux/log2.h> #include <linux/uaccess.h> #include <linux/sched/mm.h> #include <linux/rwsem.h> #include <linux/vmalloc.h> #include <linux/hugetlb.h> #include <asm/kvm_ppc.h> #include "e500.h" #include "timing.h" #include "e500_mmu_host.h" #include "trace_booke.h" #define to_htlb1_esel(esel) (host_tlb_params[1].entries - (esel) - 1) static struct kvmppc_e500_tlb_params host_tlb_params[E500_TLB_NUM]; static inline unsigned int tlb1_max_shadow_size(void) { /* reserve one entry for magic page */ return host_tlb_params[1].entries - tlbcam_index - 1; } static inline u32 e500_shadow_mas3_attrib(u32 mas3, int usermode) { /* Mask off reserved bits. */ mas3 &= MAS3_ATTRIB_MASK; #ifndef CONFIG_KVM_BOOKE_HV if (!usermode) { /* Guest is in supervisor mode, * so we need to translate guest * supervisor permissions into user permissions. */ mas3 &= ~E500_TLB_USER_PERM_MASK; mas3 |= (mas3 & E500_TLB_SUPER_PERM_MASK) << 1; } mas3 |= E500_TLB_SUPER_PERM_MASK; #endif return mas3; } /* * writing shadow tlb entry to host TLB */ static inline void __write_host_tlbe(struct kvm_book3e_206_tlb_entry *stlbe, uint32_t mas0, uint32_t lpid) { unsigned long flags; local_irq_save(flags); mtspr(SPRN_MAS0, mas0); mtspr(SPRN_MAS1, stlbe->mas1); mtspr(SPRN_MAS2, (unsigned long)stlbe->mas2); mtspr(SPRN_MAS3, (u32)stlbe->mas7_3); mtspr(SPRN_MAS7, (u32)(stlbe->mas7_3 >> 32)); #ifdef CONFIG_KVM_BOOKE_HV mtspr(SPRN_MAS8, MAS8_TGS | get_thread_specific_lpid(lpid)); #endif asm volatile("isync; tlbwe" : : : "memory"); #ifdef CONFIG_KVM_BOOKE_HV /* Must clear mas8 for other host tlbwe's */ mtspr(SPRN_MAS8, 0); isync(); #endif local_irq_restore(flags); trace_kvm_booke206_stlb_write(mas0, stlbe->mas8, stlbe->mas1, stlbe->mas2, stlbe->mas7_3); } /* * Acquire a mas0 with victim hint, as if we just took a TLB miss. * * We don't care about the address we're searching for, other than that it's * in the right set and is not present in the TLB. Using a zero PID and a * userspace address means we don't have to set and then restore MAS5, or * calculate a proper MAS6 value. */ static u32 get_host_mas0(unsigned long eaddr) { unsigned long flags; u32 mas0; u32 mas4; local_irq_save(flags); mtspr(SPRN_MAS6, 0); mas4 = mfspr(SPRN_MAS4); mtspr(SPRN_MAS4, mas4 & ~MAS4_TLBSEL_MASK); asm volatile("tlbsx 0, %0" : : "b" (eaddr & ~CONFIG_PAGE_OFFSET)); mas0 = mfspr(SPRN_MAS0); mtspr(SPRN_MAS4, mas4); local_irq_restore(flags); return mas0; } /* sesel is for tlb1 only */ static inline void write_host_tlbe(struct kvmppc_vcpu_e500 *vcpu_e500, int tlbsel, int sesel, struct kvm_book3e_206_tlb_entry *stlbe) { u32 mas0; if (tlbsel == 0) { mas0 = get_host_mas0(stlbe->mas2); __write_host_tlbe(stlbe, mas0, vcpu_e500->vcpu.kvm->arch.lpid); } else { __write_host_tlbe(stlbe, MAS0_TLBSEL(1) | MAS0_ESEL(to_htlb1_esel(sesel)), vcpu_e500->vcpu.kvm->arch.lpid); } } /* sesel is for tlb1 only */ static void write_stlbe(struct kvmppc_vcpu_e500 *vcpu_e500, struct kvm_book3e_206_tlb_entry *gtlbe, struct kvm_book3e_206_tlb_entry *stlbe, int stlbsel, int sesel) { int stid; preempt_disable(); stid = kvmppc_e500_get_tlb_stid(&vcpu_e500->vcpu, gtlbe); stlbe->mas1 |= MAS1_TID(stid); write_host_tlbe(vcpu_e500, stlbsel, sesel, stlbe); preempt_enable(); } #ifdef CONFIG_KVM_E500V2 /* XXX should be a hook in the gva2hpa translation */ void kvmppc_map_magic(struct kvm_vcpu *vcpu) { struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu); struct kvm_book3e_206_tlb_entry magic; ulong shared_page = ((ulong)vcpu->arch.shared) & PAGE_MASK; unsigned int stid; kvm_pfn_t pfn; pfn = (kvm_pfn_t)virt_to_phys((void *)shared_page) >> PAGE_SHIFT; get_page(pfn_to_page(pfn)); preempt_disable(); stid = kvmppc_e500_get_sid(vcpu_e500, 0, 0, 0, 0); magic.mas1 = MAS1_VALID | MAS1_TS | MAS1_TID(stid) | MAS1_TSIZE(BOOK3E_PAGESZ_4K); magic.mas2 = vcpu->arch.magic_page_ea | MAS2_M; magic.mas7_3 = ((u64)pfn << PAGE_SHIFT) | MAS3_SW | MAS3_SR | MAS3_UW | MAS3_UR; magic.mas8 = 0; __write_host_tlbe(&magic, MAS0_TLBSEL(1) | MAS0_ESEL(tlbcam_index), 0); preempt_enable(); } #endif void inval_gtlbe_on_host(struct kvmppc_vcpu_e500 *vcpu_e500, int tlbsel, int esel) { struct kvm_book3e_206_tlb_entry *gtlbe = get_entry(vcpu_e500, tlbsel, esel); struct tlbe_ref *ref = &vcpu_e500->gtlb_priv[tlbsel][esel].ref; /* Don't bother with unmapped entries */ if (!(ref->flags & E500_TLB_VALID)) { WARN(ref->flags & (E500_TLB_BITMAP | E500_TLB_TLB0), "%s: flags %x\n", __func__, ref->flags); WARN_ON(tlbsel == 1 && vcpu_e500->g2h_tlb1_map[esel]); } if (tlbsel == 1 && ref->flags & E500_TLB_BITMAP) { u64 tmp = vcpu_e500->g2h_tlb1_map[esel]; int hw_tlb_indx; unsigned long flags; local_irq_save(flags); while (tmp) { hw_tlb_indx = __ilog2_u64(tmp & -tmp); mtspr(SPRN_MAS0, MAS0_TLBSEL(1) | MAS0_ESEL(to_htlb1_esel(hw_tlb_indx))); mtspr(SPRN_MAS1, 0); asm volatile("tlbwe"); vcpu_e500->h2g_tlb1_rmap[hw_tlb_indx] = 0; tmp &= tmp - 1; } mb(); vcpu_e500->g2h_tlb1_map[esel] = 0; ref->flags &= ~(E500_TLB_BITMAP | E500_TLB_VALID); local_irq_restore(flags); } if (tlbsel == 1 && ref->flags & E500_TLB_TLB0) { /* * TLB1 entry is backed by 4k pages. This should happen * rarely and is not worth optimizing. Invalidate everything. */ kvmppc_e500_tlbil_all(vcpu_e500); ref->flags &= ~(E500_TLB_TLB0 | E500_TLB_VALID); } /* * If TLB entry is still valid then it's a TLB0 entry, and thus * backed by at most one host tlbe per shadow pid */ if (ref->flags & E500_TLB_VALID) kvmppc_e500_tlbil_one(vcpu_e500, gtlbe); /* Mark the TLB as not backed by the host anymore */ ref->flags = 0; } static inline int tlbe_is_writable(struct kvm_book3e_206_tlb_entry *tlbe) { return tlbe->mas7_3 & (MAS3_SW|MAS3_UW); } static inline void kvmppc_e500_ref_setup(struct tlbe_ref *ref, struct kvm_book3e_206_tlb_entry *gtlbe, kvm_pfn_t pfn, unsigned int wimg) { ref->pfn = pfn; ref->flags = E500_TLB_VALID; /* Use guest supplied MAS2_G and MAS2_E */ ref->flags |= (gtlbe->mas2 & MAS2_ATTRIB_MASK) | wimg; /* Mark the page accessed */ kvm_set_pfn_accessed(pfn); if (tlbe_is_writable(gtlbe)) kvm_set_pfn_dirty(pfn); } static inline void kvmppc_e500_ref_release(struct tlbe_ref *ref) { if (ref->flags & E500_TLB_VALID) { /* FIXME: don't log bogus pfn for TLB1 */ trace_kvm_booke206_ref_release(ref->pfn, ref->flags); ref->flags = 0; } } static void clear_tlb1_bitmap(struct kvmppc_vcpu_e500 *vcpu_e500) { if (vcpu_e500->g2h_tlb1_map) memset(vcpu_e500->g2h_tlb1_map, 0, sizeof(u64) * vcpu_e500->gtlb_params[1].entries); if (vcpu_e500->h2g_tlb1_rmap) memset(vcpu_e500->h2g_tlb1_rmap, 0, sizeof(unsigned int) * host_tlb_params[1].entries); } static void clear_tlb_privs(struct kvmppc_vcpu_e500 *vcpu_e500) { int tlbsel; int i; for (tlbsel = 0; tlbsel <= 1; tlbsel++) { for (i = 0; i < vcpu_e500->gtlb_params[tlbsel].entries; i++) { struct tlbe_ref *ref = &vcpu_e500->gtlb_priv[tlbsel][i].ref; kvmppc_e500_ref_release(ref); } } } void kvmppc_core_flush_tlb(struct kvm_vcpu *vcpu) { struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu); kvmppc_e500_tlbil_all(vcpu_e500); clear_tlb_privs(vcpu_e500); clear_tlb1_bitmap(vcpu_e500); } /* TID must be supplied by the caller */ static void kvmppc_e500_setup_stlbe( struct kvm_vcpu *vcpu, struct kvm_book3e_206_tlb_entry *gtlbe, int tsize, struct tlbe_ref *ref, u64 gvaddr, struct kvm_book3e_206_tlb_entry *stlbe) { kvm_pfn_t pfn = ref->pfn; u32 pr = vcpu->arch.shared->msr & MSR_PR; BUG_ON(!(ref->flags & E500_TLB_VALID)); /* Force IPROT=0 for all guest mappings. */ stlbe->mas1 = MAS1_TSIZE(tsize) | get_tlb_sts(gtlbe) | MAS1_VALID; stlbe->mas2 = (gvaddr & MAS2_EPN) | (ref->flags & E500_TLB_MAS2_ATTR); stlbe->mas7_3 = ((u64)pfn << PAGE_SHIFT) | e500_shadow_mas3_attrib(gtlbe->mas7_3, pr); } static inline int kvmppc_e500_shadow_map(struct kvmppc_vcpu_e500 *vcpu_e500, u64 gvaddr, gfn_t gfn, struct kvm_book3e_206_tlb_entry *gtlbe, int tlbsel, struct kvm_book3e_206_tlb_entry *stlbe, struct tlbe_ref *ref) { struct kvm_memory_slot *slot; unsigned long pfn = 0; /* silence GCC warning */ unsigned long hva; int pfnmap = 0; int tsize = BOOK3E_PAGESZ_4K; int ret = 0; unsigned long mmu_seq; struct kvm *kvm = vcpu_e500->vcpu.kvm; unsigned long tsize_pages = 0; pte_t *ptep; unsigned int wimg = 0; pgd_t *pgdir; unsigned long flags; /* used to check for invalidations in progress */ mmu_seq = kvm->mmu_notifier_seq; smp_rmb(); /* * Translate guest physical to true physical, acquiring * a page reference if it is normal, non-reserved memory. * * gfn_to_memslot() must succeed because otherwise we wouldn't * have gotten this far. Eventually we should just pass the slot * pointer through from the first lookup. */ slot = gfn_to_memslot(vcpu_e500->vcpu.kvm, gfn); hva = gfn_to_hva_memslot(slot, gfn); if (tlbsel == 1) { struct vm_area_struct *vma; down_read(&current->mm->mmap_sem); vma = find_vma(current->mm, hva); if (vma && hva >= vma->vm_start && (vma->vm_flags & VM_PFNMAP)) { /* * This VMA is a physically contiguous region (e.g. * /dev/mem) that bypasses normal Linux page * management. Find the overlap between the * vma and the memslot. */ unsigned long start, end; unsigned long slot_start, slot_end; pfnmap = 1; start = vma->vm_pgoff; end = start + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT); pfn = start + ((hva - vma->vm_start) >> PAGE_SHIFT); slot_start = pfn - (gfn - slot->base_gfn); slot_end = slot_start + slot->npages; if (start < slot_start) start = slot_start; if (end > slot_end) end = slot_end; tsize = (gtlbe->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT; /* * e500 doesn't implement the lowest tsize bit, * or 1K pages. */ tsize = max(BOOK3E_PAGESZ_4K, tsize & ~1); /* * Now find the largest tsize (up to what the guest * requested) that will cover gfn, stay within the * range, and for which gfn and pfn are mutually * aligned. */ for (; tsize > BOOK3E_PAGESZ_4K; tsize -= 2) { unsigned long gfn_start, gfn_end; tsize_pages = 1UL << (tsize - 2); gfn_start = gfn & ~(tsize_pages - 1); gfn_end = gfn_start + tsize_pages; if (gfn_start + pfn - gfn < start) continue; if (gfn_end + pfn - gfn > end) continue; if ((gfn & (tsize_pages - 1)) != (pfn & (tsize_pages - 1))) continue; gvaddr &= ~((tsize_pages << PAGE_SHIFT) - 1); pfn &= ~(tsize_pages - 1); break; } } else if (vma && hva >= vma->vm_start && (vma->vm_flags & VM_HUGETLB)) { unsigned long psize = vma_kernel_pagesize(vma); tsize = (gtlbe->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT; /* * Take the largest page size that satisfies both host * and guest mapping */ tsize = min(__ilog2(psize) - 10, tsize); /* * e500 doesn't implement the lowest tsize bit, * or 1K pages. */ tsize = max(BOOK3E_PAGESZ_4K, tsize & ~1); } up_read(&current->mm->mmap_sem); } if (likely(!pfnmap)) { tsize_pages = 1UL << (tsize + 10 - PAGE_SHIFT); pfn = gfn_to_pfn_memslot(slot, gfn); if (is_error_noslot_pfn(pfn)) { if (printk_ratelimit()) pr_err("%s: real page not found for gfn %lx\n", __func__, (long)gfn); return -EINVAL; } /* Align guest and physical address to page map boundaries */ pfn &= ~(tsize_pages - 1); gvaddr &= ~((tsize_pages << PAGE_SHIFT) - 1); } spin_lock(&kvm->mmu_lock); if (mmu_notifier_retry(kvm, mmu_seq)) { ret = -EAGAIN; goto out; } pgdir = vcpu_e500->vcpu.arch.pgdir; /* * We are just looking at the wimg bits, so we don't * care much about the trans splitting bit. * We are holding kvm->mmu_lock so a notifier invalidate * can't run hence pfn won't change. */ local_irq_save(flags); ptep = find_linux_pte_or_hugepte(pgdir, hva, NULL, NULL); if (ptep) { pte_t pte = READ_ONCE(*ptep); if (pte_present(pte)) { wimg = (pte_val(pte) >> PTE_WIMGE_SHIFT) & MAS2_WIMGE_MASK; local_irq_restore(flags); } else { local_irq_restore(flags); pr_err_ratelimited("%s: pte not present: gfn %lx,pfn %lx\n", __func__, (long)gfn, pfn); ret = -EINVAL; goto out; } } kvmppc_e500_ref_setup(ref, gtlbe, pfn, wimg); kvmppc_e500_setup_stlbe(&vcpu_e500->vcpu, gtlbe, tsize, ref, gvaddr, stlbe); /* Clear i-cache for new pages */ kvmppc_mmu_flush_icache(pfn); out: spin_unlock(&kvm->mmu_lock); /* Drop refcount on page, so that mmu notifiers can clear it */ kvm_release_pfn_clean(pfn); return ret; } /* XXX only map the one-one case, for now use TLB0 */ static int kvmppc_e500_tlb0_map(struct kvmppc_vcpu_e500 *vcpu_e500, int esel, struct kvm_book3e_206_tlb_entry *stlbe) { struct kvm_book3e_206_tlb_entry *gtlbe; struct tlbe_ref *ref; int stlbsel = 0; int sesel = 0; int r; gtlbe = get_entry(vcpu_e500, 0, esel); ref = &vcpu_e500->gtlb_priv[0][esel].ref; r = kvmppc_e500_shadow_map(vcpu_e500, get_tlb_eaddr(gtlbe), get_tlb_raddr(gtlbe) >> PAGE_SHIFT, gtlbe, 0, stlbe, ref); if (r) return r; write_stlbe(vcpu_e500, gtlbe, stlbe, stlbsel, sesel); return 0; } static int kvmppc_e500_tlb1_map_tlb1(struct kvmppc_vcpu_e500 *vcpu_e500, struct tlbe_ref *ref, int esel) { unsigned int sesel = vcpu_e500->host_tlb1_nv++; if (unlikely(vcpu_e500->host_tlb1_nv >= tlb1_max_shadow_size())) vcpu_e500->host_tlb1_nv = 0; if (vcpu_e500->h2g_tlb1_rmap[sesel]) { unsigned int idx = vcpu_e500->h2g_tlb1_rmap[sesel] - 1; vcpu_e500->g2h_tlb1_map[idx] &= ~(1ULL << sesel); } vcpu_e500->gtlb_priv[1][esel].ref.flags |= E500_TLB_BITMAP; vcpu_e500->g2h_tlb1_map[esel] |= (u64)1 << sesel; vcpu_e500->h2g_tlb1_rmap[sesel] = esel + 1; WARN_ON(!(ref->flags & E500_TLB_VALID)); return sesel; } /* Caller must ensure that the specified guest TLB entry is safe to insert into * the shadow TLB. */ /* For both one-one and one-to-many */ static int kvmppc_e500_tlb1_map(struct kvmppc_vcpu_e500 *vcpu_e500, u64 gvaddr, gfn_t gfn, struct kvm_book3e_206_tlb_entry *gtlbe, struct kvm_book3e_206_tlb_entry *stlbe, int esel) { struct tlbe_ref *ref = &vcpu_e500->gtlb_priv[1][esel].ref; int sesel; int r; r = kvmppc_e500_shadow_map(vcpu_e500, gvaddr, gfn, gtlbe, 1, stlbe, ref); if (r) return r; /* Use TLB0 when we can only map a page with 4k */ if (get_tlb_tsize(stlbe) == BOOK3E_PAGESZ_4K) { vcpu_e500->gtlb_priv[1][esel].ref.flags |= E500_TLB_TLB0; write_stlbe(vcpu_e500, gtlbe, stlbe, 0, 0); return 0; } /* Otherwise map into TLB1 */ sesel = kvmppc_e500_tlb1_map_tlb1(vcpu_e500, ref, esel); write_stlbe(vcpu_e500, gtlbe, stlbe, 1, sesel); return 0; } void kvmppc_mmu_map(struct kvm_vcpu *vcpu, u64 eaddr, gpa_t gpaddr, unsigned int index) { struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu); struct tlbe_priv *priv; struct kvm_book3e_206_tlb_entry *gtlbe, stlbe; int tlbsel = tlbsel_of(index); int esel = esel_of(index); gtlbe = get_entry(vcpu_e500, tlbsel, esel); switch (tlbsel) { case 0: priv = &vcpu_e500->gtlb_priv[tlbsel][esel]; /* Triggers after clear_tlb_privs or on initial mapping */ if (!(priv->ref.flags & E500_TLB_VALID)) { kvmppc_e500_tlb0_map(vcpu_e500, esel, &stlbe); } else { kvmppc_e500_setup_stlbe(vcpu, gtlbe, BOOK3E_PAGESZ_4K, &priv->ref, eaddr, &stlbe); write_stlbe(vcpu_e500, gtlbe, &stlbe, 0, 0); } break; case 1: { gfn_t gfn = gpaddr >> PAGE_SHIFT; kvmppc_e500_tlb1_map(vcpu_e500, eaddr, gfn, gtlbe, &stlbe, esel); break; } default: BUG(); break; } } #ifdef CONFIG_KVM_BOOKE_HV int kvmppc_load_last_inst(struct kvm_vcpu *vcpu, enum instruction_type type, u32 *instr) { gva_t geaddr; hpa_t addr; hfn_t pfn; hva_t eaddr; u32 mas1, mas2, mas3; u64 mas7_mas3; struct page *page; unsigned int addr_space, psize_shift; bool pr; unsigned long flags; /* Search TLB for guest pc to get the real address */ geaddr = kvmppc_get_pc(vcpu); addr_space = (vcpu->arch.shared->msr & MSR_IS) >> MSR_IR_LG; local_irq_save(flags); mtspr(SPRN_MAS6, (vcpu->arch.pid << MAS6_SPID_SHIFT) | addr_space); mtspr(SPRN_MAS5, MAS5_SGS | get_lpid(vcpu)); asm volatile("tlbsx 0, %[geaddr]\n" : : [geaddr] "r" (geaddr)); mtspr(SPRN_MAS5, 0); mtspr(SPRN_MAS8, 0); mas1 = mfspr(SPRN_MAS1); mas2 = mfspr(SPRN_MAS2); mas3 = mfspr(SPRN_MAS3); #ifdef CONFIG_64BIT mas7_mas3 = mfspr(SPRN_MAS7_MAS3); #else mas7_mas3 = ((u64)mfspr(SPRN_MAS7) << 32) | mas3; #endif local_irq_restore(flags); /* * If the TLB entry for guest pc was evicted, return to the guest. * There are high chances to find a valid TLB entry next time. */ if (!(mas1 & MAS1_VALID)) return EMULATE_AGAIN; /* * Another thread may rewrite the TLB entry in parallel, don't * execute from the address if the execute permission is not set */ pr = vcpu->arch.shared->msr & MSR_PR; if (unlikely((pr && !(mas3 & MAS3_UX)) || (!pr && !(mas3 & MAS3_SX)))) { pr_err_ratelimited( "%s: Instruction emulation from guest address %08lx without execute permission\n", __func__, geaddr); return EMULATE_AGAIN; } /* * The real address will be mapped by a cacheable, memory coherent, * write-back page. Check for mismatches when LRAT is used. */ if (has_feature(vcpu, VCPU_FTR_MMU_V2) && unlikely((mas2 & MAS2_I) || (mas2 & MAS2_W) || !(mas2 & MAS2_M))) { pr_err_ratelimited( "%s: Instruction emulation from guest address %08lx mismatches storage attributes\n", __func__, geaddr); return EMULATE_AGAIN; } /* Get pfn */ psize_shift = MAS1_GET_TSIZE(mas1) + 10; addr = (mas7_mas3 & (~0ULL << psize_shift)) | (geaddr & ((1ULL << psize_shift) - 1ULL)); pfn = addr >> PAGE_SHIFT; /* Guard against emulation from devices area */ if (unlikely(!page_is_ram(pfn))) { pr_err_ratelimited("%s: Instruction emulation from non-RAM host address %08llx is not supported\n", __func__, addr); return EMULATE_AGAIN; } /* Map a page and get guest's instruction */ page = pfn_to_page(pfn); eaddr = (unsigned long)kmap_atomic(page); *instr = *(u32 *)(eaddr | (unsigned long)(addr & ~PAGE_MASK)); kunmap_atomic((u32 *)eaddr); return EMULATE_DONE; } #else int kvmppc_load_last_inst(struct kvm_vcpu *vcpu, enum instruction_type type, u32 *instr) { return EMULATE_AGAIN; } #endif /************* MMU Notifiers *************/ int kvm_unmap_hva(struct kvm *kvm, unsigned long hva) { trace_kvm_unmap_hva(hva); /* * Flush all shadow tlb entries everywhere. This is slow, but * we are 100% sure that we catch the to be unmapped page */ kvm_flush_remote_tlbs(kvm); return 0; } int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end) { /* kvm_unmap_hva flushes everything anyways */ kvm_unmap_hva(kvm, start); return 0; } int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end) { /* XXX could be more clever ;) */ return 0; } int kvm_test_age_hva(struct kvm *kvm, unsigned long hva) { /* XXX could be more clever ;) */ return 0; } void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte) { /* The page will get remapped properly on its next fault */ kvm_unmap_hva(kvm, hva); } /*****************************************/ int e500_mmu_host_init(struct kvmppc_vcpu_e500 *vcpu_e500) { host_tlb_params[0].entries = mfspr(SPRN_TLB0CFG) & TLBnCFG_N_ENTRY; host_tlb_params[1].entries = mfspr(SPRN_TLB1CFG) & TLBnCFG_N_ENTRY; /* * This should never happen on real e500 hardware, but is * architecturally possible -- e.g. in some weird nested * virtualization case. */ if (host_tlb_params[0].entries == 0 || host_tlb_params[1].entries == 0) { pr_err("%s: need to know host tlb size\n", __func__); return -ENODEV; } host_tlb_params[0].ways = (mfspr(SPRN_TLB0CFG) & TLBnCFG_ASSOC) >> TLBnCFG_ASSOC_SHIFT; host_tlb_params[1].ways = host_tlb_params[1].entries; if (!is_power_of_2(host_tlb_params[0].entries) || !is_power_of_2(host_tlb_params[0].ways) || host_tlb_params[0].entries < host_tlb_params[0].ways || host_tlb_params[0].ways == 0) { pr_err("%s: bad tlb0 host config: %u entries %u ways\n", __func__, host_tlb_params[0].entries, host_tlb_params[0].ways); return -ENODEV; } host_tlb_params[0].sets = host_tlb_params[0].entries / host_tlb_params[0].ways; host_tlb_params[1].sets = 1; vcpu_e500->h2g_tlb1_rmap = kzalloc(sizeof(unsigned int) * host_tlb_params[1].entries, GFP_KERNEL); if (!vcpu_e500->h2g_tlb1_rmap) return -EINVAL; return 0; } void e500_mmu_host_uninit(struct kvmppc_vcpu_e500 *vcpu_e500) { kfree(vcpu_e500->h2g_tlb1_rmap); }
null
null
null
null
86,029
1,350
4,5,6
train_val
4d17163f4b66be517dc49019a029e5ddbd45078c
1,350
Chrome
1
https://github.com/chromium/chromium
2013-11-16 08:44:48+00:00
void StyleResolver::matchUARules(ElementRuleCollector& collector) { collector.setMatchingUARules(true); // First we match rules from the user agent sheet. if (CSSDefaultStyleSheets::simpleDefaultStyleSheet) collector.matchedResult().isCacheable = false; RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print") ? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle; matchUARules(collector, userAgentStyleSheet); // In quirks mode, we match rules from the quirks user agent sheet. if (document().inQuirksMode()) matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle); // If document uses view source styles (in view source mode or in xml viewer mode), then we match rules from the view source style sheet. if (document().isViewSource()) matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle()); collector.setMatchingUARules(false); matchWatchSelectorRules(collector); }
CVE-2013-0828
CWE-399
https://github.com/chromium/chromium/commit/4d17163f4b66be517dc49019a029e5ddbd45078c
Medium
1,350
7,899
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
7,899
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_CERT_PEM_TOKENIZER_H_ #define NET_CERT_PEM_TOKENIZER_H_ #include <stddef.h> #include <string> #include <vector> #include "base/macros.h" #include "base/strings/string_piece.h" #include "net/base/net_export.h" namespace net { // PEMTokenizer is a utility class for the parsing of data encapsulated // using RFC 1421, Privacy Enhancement for Internet Electronic Mail. It // does not implement the full specification, most notably it does not // support the Encapsulated Header Portion described in Section 4.4. class NET_EXPORT_PRIVATE PEMTokenizer { public: // Create a new PEMTokenizer that iterates through |str| searching for // instances of PEM encoded blocks that are of the |allowed_block_types|. // |str| must remain valid for the duration of the PEMTokenizer. PEMTokenizer(const base::StringPiece& str, const std::vector<std::string>& allowed_block_types); ~PEMTokenizer(); // Attempts to decode the next PEM block in the string. Returns false if no // PEM blocks can be decoded. The decoded PEM block will be available via // data(). bool GetNext(); // Returns the PEM block type (eg: CERTIFICATE) of the last successfully // decoded PEM block. // GetNext() must have returned true before calling this method. const std::string& block_type() const { return block_type_; } // Returns the raw, Base64-decoded data of the last successfully decoded // PEM block. // GetNext() must have returned true before calling this method. const std::string& data() const { return data_; } private: void Init(const base::StringPiece& str, const std::vector<std::string>& allowed_block_types); // A simple cache of the allowed PEM header and footer for a given PEM // block type, so that it is only computed once. struct PEMType; // The string to search, which must remain valid for as long as this class // is around. base::StringPiece str_; // The current position within |str_| that searching should begin from, // or StringPiece::npos if iteration is complete base::StringPiece::size_type pos_; // The type of data that was encoded, as indicated in the PEM // Pre-Encapsulation Boundary (eg: CERTIFICATE, PKCS7, or // PRIVACY-ENHANCED MESSAGE). std::string block_type_; // The types of PEM blocks that are allowed. PEM blocks that are not of // one of these types will be skipped. std::vector<PEMType> block_types_; // The raw (Base64-decoded) data of the last successfully decoded block. std::string data_; DISALLOW_COPY_AND_ASSIGN(PEMTokenizer); }; } // namespace net #endif // NET_CERT_PEM_TOKENIZER_H_
null
null
null
null
4,762
57,347
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
57,347
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/arc/policy/arc_policy_bridge.h" #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_string_value_serializer.h" #include "base/logging.h" #include "base/memory/singleton.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/values.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chromeos/network/onc/onc_utils.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h" #include "components/arc/arc_prefs.h" #include "components/onc/onc_constants.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/policy_constants.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user.h" #include "content/public/common/service_manager_connection.h" #include "crypto/sha2.h" #include "services/data_decoder/public/cpp/safe_json_parser.h" namespace arc { namespace { constexpr char kArcCaCerts[] = "caCerts"; constexpr char kPolicyCompliantJson[] = "{ \"policyCompliant\": true }"; // invert_bool_value: If the Chrome policy and the ARC policy with boolean value // have opposite semantics, set this to true so the bool is inverted before // being added. Otherwise, set it to false. void MapBoolToBool(const std::string& arc_policy_name, const std::string& policy_name, const policy::PolicyMap& policy_map, bool invert_bool_value, base::DictionaryValue* filtered_policies) { const base::Value* const policy_value = policy_map.GetValue(policy_name); if (!policy_value) return; if (!policy_value->is_bool()) { NOTREACHED() << "Policy " << policy_name << " is not a boolean."; return; } bool bool_value; policy_value->GetAsBoolean(&bool_value); filtered_policies->SetBoolean(arc_policy_name, bool_value != invert_bool_value); } // int_true: value of Chrome OS policy for which arc policy is set to true. // It is set to false for all other values. void MapIntToBool(const std::string& arc_policy_name, const std::string& policy_name, const policy::PolicyMap& policy_map, int int_true, base::DictionaryValue* filtered_policies) { const base::Value* const policy_value = policy_map.GetValue(policy_name); if (!policy_value) return; if (!policy_value->is_int()) { NOTREACHED() << "Policy " << policy_name << " is not an integer."; return; } int int_value; policy_value->GetAsInteger(&int_value); filtered_policies->SetBoolean(arc_policy_name, int_value == int_true); } // Checks whether |policy_name| is present as an object and has all |fields|, // Sets |arc_policy_name| to true only if the condition above is satisfied. void MapObjectToPresenceBool(const std::string& arc_policy_name, const std::string& policy_name, const policy::PolicyMap& policy_map, base::DictionaryValue* filtered_policies, const std::vector<std::string>& fields) { const base::Value* const policy_value = policy_map.GetValue(policy_name); if (!policy_value) return; const base::DictionaryValue* dict = nullptr; if (!policy_value->GetAsDictionary(&dict)) { NOTREACHED() << "Policy " << policy_name << " is not an object."; return; } for (const auto& field : fields) { if (!dict->HasKey(field)) return; } filtered_policies->SetBoolean(arc_policy_name, true); } void AddOncCaCertsToPolicies(const policy::PolicyMap& policy_map, base::DictionaryValue* filtered_policies) { const base::Value* const policy_value = policy_map.GetValue(policy::key::kArcCertificatesSyncMode); int32_t mode = ArcCertsSyncMode::SYNC_DISABLED; // Old certs should be uninstalled if the sync is disabled or policy is not // set. if (!policy_value || !policy_value->GetAsInteger(&mode) || mode != ArcCertsSyncMode::COPY_CA_CERTS) { return; } // Importing CA certificates from device policy is not allowed. // Import only from user policy. const base::Value* onc_policy_value = policy_map.GetValue(policy::key::kOpenNetworkConfiguration); if (!onc_policy_value) { VLOG(1) << "onc policy is not set."; return; } std::string onc_blob; if (!onc_policy_value->GetAsString(&onc_blob)) { LOG(ERROR) << "Value of onc policy has invalid format."; return; } base::ListValue certificates; { base::ListValue unused_network_configs; base::DictionaryValue unused_global_network_config; if (!chromeos::onc::ParseAndValidateOncForImport( onc_blob, onc::ONCSource::ONC_SOURCE_USER_POLICY, "" /* no passphrase */, &unused_network_configs, &unused_global_network_config, &certificates)) { LOG(ERROR) << "Value of onc policy has invalid format =" << onc_blob; } } std::unique_ptr<base::ListValue> ca_certs( std::make_unique<base::ListValue>()); for (const auto& entry : certificates) { const base::DictionaryValue* certificate = nullptr; if (!entry.GetAsDictionary(&certificate)) { DLOG(FATAL) << "Value of a certificate entry is not a dictionary " << "value."; continue; } std::string cert_type; certificate->GetStringWithoutPathExpansion(::onc::certificate::kType, &cert_type); if (cert_type != ::onc::certificate::kAuthority) continue; const base::ListValue* trust_list = nullptr; if (!certificate->GetListWithoutPathExpansion( ::onc::certificate::kTrustBits, &trust_list)) { continue; } bool web_trust_flag = false; for (const auto& list_val : *trust_list) { std::string trust_type; if (!list_val.GetAsString(&trust_type)) NOTREACHED(); if (trust_type == ::onc::certificate::kWeb) { // "Web" implies that the certificate is to be trusted for SSL // identification. web_trust_flag = true; break; } } if (!web_trust_flag) continue; std::string x509_data; if (!certificate->GetStringWithoutPathExpansion(::onc::certificate::kX509, &x509_data)) { continue; } base::DictionaryValue data; data.SetString("X509", x509_data); ca_certs->Append(data.CreateDeepCopy()); } if (!ca_certs->GetList().empty()) filtered_policies->SetKey("credentialsConfigDisabled", base::Value(true)); filtered_policies->Set(kArcCaCerts, std::move(ca_certs)); } std::string GetFilteredJSONPolicies(const policy::PolicyMap& policy_map, const std::string& guid, bool is_affiliated) { base::DictionaryValue filtered_policies; // Parse ArcPolicy as JSON string before adding other policies to the // dictionary. const base::Value* const app_policy_value = policy_map.GetValue(policy::key::kArcPolicy); if (app_policy_value) { std::string app_policy_string; app_policy_value->GetAsString(&app_policy_string); std::unique_ptr<base::DictionaryValue> app_policy_dict = base::DictionaryValue::From(base::JSONReader::Read(app_policy_string)); if (app_policy_dict) { // Need a deep copy of all values here instead of doing a swap, because // JSONReader::Read constructs a dictionary whose StringValues are // JSONStringValues which are based on StringPiece instead of string. filtered_policies.MergeDictionary(app_policy_dict.get()); } else { LOG(ERROR) << "Value of ArcPolicy has invalid format: " << app_policy_string; } } // Keep them sorted by the ARC policy names. MapBoolToBool("cameraDisabled", policy::key::kVideoCaptureAllowed, policy_map, true, &filtered_policies); MapBoolToBool("debuggingFeaturesDisabled", policy::key::kDeveloperToolsDisabled, policy_map, false, &filtered_policies); MapBoolToBool("screenCaptureDisabled", policy::key::kDisableScreenshots, policy_map, false, &filtered_policies); MapIntToBool("shareLocationDisabled", policy::key::kDefaultGeolocationSetting, policy_map, 2 /*BlockGeolocation*/, &filtered_policies); MapBoolToBool("unmuteMicrophoneDisabled", policy::key::kAudioCaptureAllowed, policy_map, true, &filtered_policies); MapBoolToBool("mountPhysicalMediaDisabled", policy::key::kExternalStorageDisabled, policy_map, false, &filtered_policies); MapObjectToPresenceBool("setWallpaperDisabled", policy::key::kWallpaperImage, policy_map, &filtered_policies, {"url", "hash"}); // Add CA certificates. AddOncCaCertsToPolicies(policy_map, &filtered_policies); if (!is_affiliated) filtered_policies.RemoveKey("apkCacheEnabled"); filtered_policies.SetString("guid", guid); std::string policy_json; JSONStringValueSerializer serializer(&policy_json); serializer.Serialize(filtered_policies); return policy_json; } void OnReportComplianceParseFailure( base::OnceCallback<void(const std::string&)> callback, const std::string& error) { // TODO(poromov@): Report to histogram. DLOG(ERROR) << "Can't parse policy compliance report"; std::move(callback).Run(kPolicyCompliantJson); } void UpdateFirstComplianceSinceSignInTiming( const base::TimeDelta& elapsed_time) { UMA_HISTOGRAM_CUSTOM_TIMES("Arc.FirstComplianceReportTime.SinceSignIn", elapsed_time, base::TimeDelta::FromSeconds(1), base::TimeDelta::FromMinutes(10), 50); } void UpdateFirstComplianceSinceStartupTiming( const base::TimeDelta& elapsed_time) { UMA_HISTOGRAM_CUSTOM_TIMES("Arc.FirstComplianceReportTime.SinceStartup", elapsed_time, base::TimeDelta::FromSeconds(1), base::TimeDelta::FromMinutes(10), 50); } void UpdateComplianceSinceUpdateTiming(const base::TimeDelta& elapsed_time) { UMA_HISTOGRAM_CUSTOM_TIMES("Arc.ComplianceReportSinceUpdateNotificationTime", elapsed_time, base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromMinutes(10), 50); } // Returns the SHA-256 hash of the JSON dump of the ARC policies, in the textual // hex dump format. Note that no specific JSON normalization is performed, as // the spurious hash mismatches, even if they occur (which is unlikely), would // only result in some UMA metrics not being sent. std::string GetPoliciesHash(const std::string& json_policies) { const std::string hash_bits = crypto::SHA256HashString(json_policies); return base::ToLowerASCII( base::HexEncode(hash_bits.c_str(), hash_bits.length())); } // Singleton factory for ArcPolicyBridge. class ArcPolicyBridgeFactory : public internal::ArcBrowserContextKeyedServiceFactoryBase< ArcPolicyBridge, ArcPolicyBridgeFactory> { public: // Factory name used by ArcBrowserContextKeyedServiceFactoryBase. static constexpr const char* kName = "ArcPolicyBridgeFactory"; static ArcPolicyBridgeFactory* GetInstance() { return base::Singleton<ArcPolicyBridgeFactory>::get(); } private: friend base::DefaultSingletonTraits<ArcPolicyBridgeFactory>; ArcPolicyBridgeFactory() { DependsOn(policy::ProfilePolicyConnectorFactory::GetInstance()); } ~ArcPolicyBridgeFactory() override = default; }; } // namespace // static ArcPolicyBridge* ArcPolicyBridge::GetForBrowserContext( content::BrowserContext* context) { return ArcPolicyBridgeFactory::GetForBrowserContext(context); } ArcPolicyBridge::ArcPolicyBridge(content::BrowserContext* context, ArcBridgeService* bridge_service) : ArcPolicyBridge(context, bridge_service, nullptr /* policy_service */) {} ArcPolicyBridge::ArcPolicyBridge(content::BrowserContext* context, ArcBridgeService* bridge_service, policy::PolicyService* policy_service) : context_(context), arc_bridge_service_(bridge_service), policy_service_(policy_service), instance_guid_(base::GenerateGUID()), weak_ptr_factory_(this) { VLOG(2) << "ArcPolicyBridge::ArcPolicyBridge"; arc_bridge_service_->policy()->SetHost(this); arc_bridge_service_->policy()->AddObserver(this); } ArcPolicyBridge::~ArcPolicyBridge() { VLOG(2) << "ArcPolicyBridge::~ArcPolicyBridge"; arc_bridge_service_->policy()->RemoveObserver(this); arc_bridge_service_->policy()->SetHost(nullptr); } const std::string& ArcPolicyBridge::GetInstanceGuidForTesting() { return instance_guid_; } void ArcPolicyBridge::AddObserver(Observer* observer) { observers_.AddObserver(observer); } void ArcPolicyBridge::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } void ArcPolicyBridge::OverrideIsManagedForTesting(bool is_managed) { is_managed_ = is_managed; } void ArcPolicyBridge::OnConnectionReady() { VLOG(1) << "ArcPolicyBridge::OnConnectionReady"; if (policy_service_ == nullptr) { InitializePolicyService(); } policy_service_->AddObserver(policy::POLICY_DOMAIN_CHROME, this); initial_policies_hash_ = GetPoliciesHash(GetCurrentJSONPolicies()); } void ArcPolicyBridge::OnConnectionClosed() { VLOG(1) << "ArcPolicyBridge::OnConnectionClosed"; policy_service_->RemoveObserver(policy::POLICY_DOMAIN_CHROME, this); policy_service_ = nullptr; initial_policies_hash_.clear(); } void ArcPolicyBridge::GetPolicies(GetPoliciesCallback callback) { VLOG(1) << "ArcPolicyBridge::GetPolicies"; const std::string policy = GetCurrentJSONPolicies(); for (Observer& observer : observers_) { observer.OnPolicySent(policy); } std::move(callback).Run(policy); } void ArcPolicyBridge::ReportCompliance(const std::string& request, ReportComplianceCallback callback) { VLOG(1) << "ArcPolicyBridge::ReportCompliance"; // TODO(crbug.com/730593): Remove AdaptCallbackForRepeating() by updating // the callee interface. auto repeating_callback = base::AdaptCallbackForRepeating(std::move(callback)); data_decoder::SafeJsonParser::Parse( content::ServiceManagerConnection::GetForProcess()->GetConnector(), request, base::Bind(&ArcPolicyBridge::OnReportComplianceParseSuccess, weak_ptr_factory_.GetWeakPtr(), repeating_callback), base::Bind(&OnReportComplianceParseFailure, repeating_callback)); } void ArcPolicyBridge::ReportCloudDpsRequested( base::Time time, const std::vector<std::string>& package_names) { const std::set<std::string> packages_set(package_names.begin(), package_names.end()); for (Observer& observer : observers_) observer.OnCloudDpsRequested(time, packages_set); } void ArcPolicyBridge::ReportCloudDpsSucceeded( base::Time time, const std::vector<std::string>& package_names) { const std::set<std::string> packages_set(package_names.begin(), package_names.end()); for (Observer& observer : observers_) observer.OnCloudDpsSucceeded(time, packages_set); } void ArcPolicyBridge::ReportCloudDpsFailed(base::Time time, const std::string& package_name, mojom::InstallErrorReason reason) { for (Observer& observer : observers_) observer.OnCloudDpsFailed(time, package_name, reason); } void ArcPolicyBridge::OnPolicyUpdated(const policy::PolicyNamespace& ns, const policy::PolicyMap& previous, const policy::PolicyMap& current) { VLOG(1) << "ArcPolicyBridge::OnPolicyUpdated"; auto* instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->policy(), OnPolicyUpdated); if (!instance) return; const std::string policies_hash = GetPoliciesHash(GetCurrentJSONPolicies()); if (policies_hash != update_notification_policies_hash_) { update_notification_policies_hash_ = policies_hash; update_notification_time_ = base::Time::Now(); compliance_since_update_timing_reported_ = false; } instance->OnPolicyUpdated(); } void ArcPolicyBridge::InitializePolicyService() { auto* profile_policy_connector = policy::ProfilePolicyConnectorFactory::GetForBrowserContext(context_); policy_service_ = profile_policy_connector->policy_service(); is_managed_ = profile_policy_connector->IsManaged(); } std::string ArcPolicyBridge::GetCurrentJSONPolicies() const { if (!is_managed_) return std::string(); const policy::PolicyNamespace policy_namespace(policy::POLICY_DOMAIN_CHROME, std::string()); const policy::PolicyMap& policy_map = policy_service_->GetPolicies(policy_namespace); const Profile* const profile = Profile::FromBrowserContext(context_); const user_manager::User* const user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile); return GetFilteredJSONPolicies(policy_map, instance_guid_, user->IsAffiliated()); } void ArcPolicyBridge::OnReportComplianceParseSuccess( base::OnceCallback<void(const std::string&)> callback, std::unique_ptr<base::Value> parsed_json) { // Always returns "compliant". std::move(callback).Run(kPolicyCompliantJson); Profile::FromBrowserContext(context_)->GetPrefs()->SetBoolean( prefs::kArcPolicyComplianceReported, true); const base::DictionaryValue* dict = nullptr; if (parsed_json->GetAsDictionary(&dict)) { UpdateComplianceReportMetrics(dict); for (Observer& observer : observers_) { observer.OnComplianceReportReceived(parsed_json.get()); } } } void ArcPolicyBridge::UpdateComplianceReportMetrics( const base::DictionaryValue* report) { bool is_arc_plus_plus_report_successful = false; report->GetBoolean("isArcPlusPlusReportSuccessful", &is_arc_plus_plus_report_successful); std::string reported_policies_hash; report->GetString("policyHash", &reported_policies_hash); if (!is_arc_plus_plus_report_successful || reported_policies_hash.empty()) return; const base::Time now = base::Time::Now(); ArcSessionManager* const session_manager = ArcSessionManager::Get(); if (reported_policies_hash == initial_policies_hash_ && !first_compliance_timing_reported_) { const base::Time sign_in_start_time = session_manager->sign_in_start_time(); if (!sign_in_start_time.is_null()) { UpdateFirstComplianceSinceSignInTiming(now - sign_in_start_time); } else { UpdateFirstComplianceSinceStartupTiming( now - session_manager->arc_start_time()); } first_compliance_timing_reported_ = true; } if (reported_policies_hash == update_notification_policies_hash_ && !compliance_since_update_timing_reported_) { UpdateComplianceSinceUpdateTiming(now - update_notification_time_); compliance_since_update_timing_reported_ = true; } } } // namespace arc
null
null
null
null
54,210
3,583
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
168,578
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * btnode.h - NILFS B-tree node cache * * Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation. * * 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. * * Written by Seiji Kihara. * Revised by Ryusuke Konishi. */ #ifndef _NILFS_BTNODE_H #define _NILFS_BTNODE_H #include <linux/types.h> #include <linux/buffer_head.h> #include <linux/fs.h> #include <linux/backing-dev.h> /** * struct nilfs_btnode_chkey_ctxt - change key context * @oldkey: old key of block's moving content * @newkey: new key for block's content * @bh: buffer head of old buffer * @newbh: buffer head of new buffer */ struct nilfs_btnode_chkey_ctxt { __u64 oldkey; __u64 newkey; struct buffer_head *bh; struct buffer_head *newbh; }; void nilfs_btnode_cache_clear(struct address_space *); struct buffer_head *nilfs_btnode_create_block(struct address_space *btnc, __u64 blocknr); int nilfs_btnode_submit_block(struct address_space *, __u64, sector_t, int, int, struct buffer_head **, sector_t *); void nilfs_btnode_delete(struct buffer_head *); int nilfs_btnode_prepare_change_key(struct address_space *, struct nilfs_btnode_chkey_ctxt *); void nilfs_btnode_commit_change_key(struct address_space *, struct nilfs_btnode_chkey_ctxt *); void nilfs_btnode_abort_change_key(struct address_space *, struct nilfs_btnode_chkey_ctxt *); #endif /* _NILFS_BTNODE_H */
null
null
null
null
76,925
315
null
train_val
31e986bc171719c9e6d40d0c2cb1501796a69e6c
259,270
php-src
0
https://github.com/php/php-src
2016-10-24 10:37:20+01:00
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2016 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@zend.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <andi@zend.com> | | Zeev Suraski <zeev@zend.com> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "zend.h" #include "zend_ptr_stack.h" #ifdef HAVE_STDARG_H # include <stdarg.h> #endif ZEND_API void zend_ptr_stack_init_ex(zend_ptr_stack *stack, zend_bool persistent) { stack->top_element = stack->elements = NULL; stack->top = stack->max = 0; stack->persistent = persistent; } ZEND_API void zend_ptr_stack_init(zend_ptr_stack *stack) { zend_ptr_stack_init_ex(stack, 0); } ZEND_API void zend_ptr_stack_n_push(zend_ptr_stack *stack, int count, ...) { va_list ptr; void *elem; ZEND_PTR_STACK_RESIZE_IF_NEEDED(stack, count) va_start(ptr, count); while (count>0) { elem = va_arg(ptr, void *); stack->top++; *(stack->top_element++) = elem; count--; } va_end(ptr); } ZEND_API void zend_ptr_stack_n_pop(zend_ptr_stack *stack, int count, ...) { va_list ptr; void **elem; va_start(ptr, count); while (count>0) { elem = va_arg(ptr, void **); *elem = *(--stack->top_element); stack->top--; count--; } va_end(ptr); } ZEND_API void zend_ptr_stack_destroy(zend_ptr_stack *stack) { if (stack->elements) { pefree(stack->elements, stack->persistent); } } ZEND_API void zend_ptr_stack_apply(zend_ptr_stack *stack, void (*func)(void *)) { int i = stack->top; while (--i >= 0) { func(stack->elements[i]); } } ZEND_API void zend_ptr_stack_clean(zend_ptr_stack *stack, void (*func)(void *), zend_bool free_elements) { zend_ptr_stack_apply(stack, func); if (free_elements) { int i = stack->top; while (--i >= 0) { pefree(stack->elements[i], stack->persistent); } } stack->top = 0; stack->top_element = stack->elements; } ZEND_API int zend_ptr_stack_num_elements(zend_ptr_stack *stack) { return stack->top; } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
null
null
null
null
119,191
68,912
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
68,912
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include "remoting/client/input/normalizing_input_filter_win.h" #include "remoting/proto/event.pb.h" #include "remoting/protocol/protocol_mock_objects.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::InSequence; using remoting::protocol::InputStub; using remoting::protocol::KeyEvent; using remoting::protocol::MockInputStub; using remoting::protocol::MouseEvent; namespace remoting { namespace { const unsigned int kUsbKeyA = 0x070004; const unsigned int kUsbLeftControl = 0x0700e0; const unsigned int kUsbRightAlt = 0x0700e6; // A hardcoded value used to verify |lock_states| is preserved. static const uint32_t kTestLockStates = protocol::KeyEvent::LOCK_STATES_NUMLOCK; MATCHER_P2(EqualsKeyEvent, usb_keycode, pressed, "") { return arg.usb_keycode() == static_cast<uint32_t>(usb_keycode) && arg.pressed() == pressed && arg.lock_states() == kTestLockStates; } KeyEvent MakeKeyEvent(uint32_t keycode, bool pressed) { KeyEvent event; event.set_usb_keycode(keycode); event.set_pressed(pressed); event.set_lock_states(kTestLockStates); return event; } void PressAndReleaseKey(InputStub* input_stub, uint32_t keycode) { input_stub->InjectKeyEvent(MakeKeyEvent(keycode, true)); input_stub->InjectKeyEvent(MakeKeyEvent(keycode, false)); } MATCHER_P2(EqualsMouseMoveEvent, x, y, "") { return arg.x() == x && arg.y() == y; } static MouseEvent MakeMouseMoveEvent(int x, int y) { MouseEvent event; event.set_x(x); event.set_y(y); return event; } } // namespace // Test press/release of LeftControl, RightAlt, then LeftControl again. TEST(NormalizingInputFilterWinTest, PressReleaseSequence) { MockInputStub stub; NormalizingInputFilterWin processor(&stub); { InSequence s; EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, false))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, false))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, false))); } // Inject press & release events. PressAndReleaseKey(&processor, kUsbLeftControl); PressAndReleaseKey(&processor, kUsbRightAlt); PressAndReleaseKey(&processor, kUsbLeftControl); } // Test LeftControl key repeat causes it to be treated as LeftControl. TEST(NormalizingInputFilterWinTest, LeftControlRepeats) { MockInputStub stub; NormalizingInputFilterWin processor(&stub); { InSequence s; EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, false))); } // Inject a press and repeats for LeftControl, and verify that the repeats // result in press events. processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, true)); processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, true)); processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, false)); } // Test LeftControl key pressed while pressing & releasing a printable key and // then RightAlt treats it as LeftControl, not AltGr combo. TEST(NormalizingInputFilterWinTest, LeftControlAndPrintableKey) { MockInputStub stub; NormalizingInputFilterWin processor(&stub); { InSequence s; EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbKeyA, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbKeyA, false))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, false))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, false))); } // Inject a press for LeftControl, press and release a character key, then // press RightAlt, and finally release LeftControl. processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, true)); PressAndReleaseKey(&processor, kUsbKeyA); PressAndReleaseKey(&processor, kUsbRightAlt); processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, false)); } // Test LeftControl press followed by RightAlt press results in // it being interpreted as AltGr, so only RightAlt events generated. // Also press a printable key while AltGr is down to verify that doesn't // confuse things. TEST(NormalizingInputFilterWinTest, AltGr) { MockInputStub stub; NormalizingInputFilterWin processor(&stub); { InSequence s; EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbKeyA, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbKeyA, false))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, false))); } // Hold LeftControl and then RightAlt, then release. processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, true)); processor.InjectKeyEvent(MakeKeyEvent(kUsbRightAlt, true)); PressAndReleaseKey(&processor, kUsbKeyA); processor.InjectKeyEvent(MakeKeyEvent(kUsbRightAlt, false)); processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, false)); } // Test LeftControl press followed by RightAlt press, and repeats results in // it being interpreted as AltGr, so only RightAlt events generated. TEST(NormalizingInputFilterWinTest, AltGrRepeats) { MockInputStub stub; NormalizingInputFilterWin processor(&stub); { InSequence s; EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, false))); } // Hold LeftControl and then RightAlt, repeat, then release. Sequence // reflects the order of events generated by Windows. processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, true)); processor.InjectKeyEvent(MakeKeyEvent(kUsbRightAlt, true)); processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, true)); processor.InjectKeyEvent(MakeKeyEvent(kUsbRightAlt, true)); processor.InjectKeyEvent(MakeKeyEvent(kUsbRightAlt, false)); processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, false)); } // Test LeftControl held during mouse event treats it as LeftControl. TEST(NormalizingInputFilterWinTest, LeftControlAndMouseEvent) { MockInputStub stub; NormalizingInputFilterWin processor(&stub); { InSequence s; EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, true))); EXPECT_CALL(stub, InjectMouseEvent(EqualsMouseMoveEvent(0, 0))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, true))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, false))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbLeftControl, false))); } // Hold the left Control while moving the mouse. processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, true)); processor.InjectMouseEvent(MakeMouseMoveEvent(0, 0)); PressAndReleaseKey(&processor, kUsbRightAlt); processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, false)); } // Test LeftControl & RightAlt held during mouse event treats it as AltGr. TEST(NormalizingInputFilterWinTest, AltGrAndMouseEvent) { MockInputStub stub; NormalizingInputFilterWin processor(&stub); { InSequence s; EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, true))); EXPECT_CALL(stub, InjectMouseEvent(EqualsMouseMoveEvent(0, 0))); EXPECT_CALL(stub, InjectKeyEvent(EqualsKeyEvent(kUsbRightAlt, false))); } // Hold the left Control while moving the mouse. processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, true)); processor.InjectKeyEvent(MakeKeyEvent(kUsbRightAlt, true)); processor.InjectMouseEvent(MakeMouseMoveEvent(0, 0)); processor.InjectKeyEvent(MakeKeyEvent(kUsbRightAlt, false)); processor.InjectKeyEvent(MakeKeyEvent(kUsbLeftControl, false)); } } // namespace remoting
null
null
null
null
65,775