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
71,855
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
71,855
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 SERVICES_UI_COMMON_ACCELERATOR_UTIL_H_ #define SERVICES_UI_COMMON_ACCELERATOR_UTIL_H_ #include "services/ui/public/interfaces/event_matcher.mojom.h" #include "services/ui/public/interfaces/window_manager.mojom.h" #include "ui/events/mojo/event_constants.mojom.h" #include "ui/events/mojo/keyboard_codes.mojom.h" namespace ui { // |flags| is a bitfield of kEventFlag* and kMouseEventFlag* values in // input_event_constants.mojom. mojom::EventMatcherPtr CreateKeyMatcher(ui::mojom::KeyboardCode code, int flags); // Construct accelerator vector from the provided |id| and |event_matcher| std::vector<ui::mojom::WmAcceleratorPtr> CreateAcceleratorVector( uint32_t id, ui::mojom::EventMatcherPtr event_matcher); // Construct accelerator from the provided |id| and |event_matcher| ui::mojom::WmAcceleratorPtr CreateAccelerator( uint32_t id, ui::mojom::EventMatcherPtr event_matcher); } // namespace ui #endif // SERVICES_UI_COMMON_ACCELERATOR_UTIL_H_
null
null
null
null
68,718
22,728
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
22,728
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 CONTENT_BROWSER_RENDERER_HOST_INPUT_INPUT_ROUTER_H_ #define CONTENT_BROWSER_RENDERER_HOST_INPUT_INPUT_ROUTER_H_ #include "cc/input/touch_action.h" #include "content/browser/renderer_host/event_with_latency_info.h" #include "content/browser/renderer_host/input/gesture_event_queue.h" #include "content/browser/renderer_host/input/passthrough_touch_event_queue.h" #include "content/common/widget.mojom.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/common/input_event_ack_state.h" #include "ipc/ipc_listener.h" #include "third_party/blink/public/platform/web_input_event.h" namespace content { // The InputRouter allows the embedder to customize how input events are // sent to the renderer, and how responses are dispatched to the browser. // While the router should respect the relative order in which events are // received, it is free to customize when those events are dispatched. class InputRouter : public IPC::Listener { public: struct CONTENT_EXPORT Config { Config(); GestureEventQueue::Config gesture_config; PassthroughTouchEventQueue::Config touch_config; }; ~InputRouter() override {} // WebInputEvents virtual void SendMouseEvent( const MouseEventWithLatencyInfo& mouse_event) = 0; virtual void SendWheelEvent( const MouseWheelEventWithLatencyInfo& wheel_event) = 0; virtual void SendKeyboardEvent( const NativeWebKeyboardEventWithLatencyInfo& key_event) = 0; virtual void SendGestureEvent( const GestureEventWithLatencyInfo& gesture_event) = 0; virtual void SendTouchEvent( const TouchEventWithLatencyInfo& touch_event) = 0; // Notify the router about whether the current page is mobile-optimized (i.e., // the site has a mobile-friendly viewport). virtual void NotifySiteIsMobileOptimized(bool is_mobile_optimized) = 0; // Whether there are any events pending dispatch to or ack from the renderer. virtual bool HasPendingEvents() const = 0; // A scale factor to scale the coordinate in WebInputEvent from DIP // to viewport. virtual void SetDeviceScaleFactor(float device_scale_factor) = 0; // Sets the frame tree node id of associated frame, used when tracing // input event latencies to relate events to their target frames. Since // input always flows to Local Frame Roots, the |frameTreeNodeId| is // relative to the Frame associated with the Local Frame Root for the // widget owning this InputRouter. virtual void SetFrameTreeNodeId(int frameTreeNodeId) = 0; // Return the currently allowed touch-action. virtual cc::TouchAction AllowedTouchAction() = 0; virtual void SetForceEnableZoom(bool enabled) = 0; // Associate this InputRouter with a remote host channel. virtual void BindHost(mojom::WidgetInputHandlerHostRequest request, bool frame_handler) = 0; // Used to progress an active fling on every begin frame. virtual void ProgressFling(base::TimeTicks current_time) = 0; // Used to stop an active fling if such exists. virtual void StopFling() = 0; // Used to check if a fling cancellation is deferred due to boosting or not. virtual bool FlingCancellationIsDeferred() = 0; }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_INPUT_INPUT_ROUTER_H_
null
null
null
null
19,591
25,046
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
25,046
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 EXTENSIONS_COMMON_URL_PATTERN_SET_H_ #define EXTENSIONS_COMMON_URL_PATTERN_SET_H_ #include <stddef.h> #include <iosfwd> #include <memory> #include <set> #include "extensions/common/url_pattern.h" class GURL; namespace base { class ListValue; class Value; } namespace extensions { // Represents the set of URLs an extension uses for web content. class URLPatternSet { public: typedef std::set<URLPattern>::const_iterator const_iterator; typedef std::set<URLPattern>::iterator iterator; // Returns |set1| - |set2|. static URLPatternSet CreateDifference(const URLPatternSet& set1, const URLPatternSet& set2); // Returns the intersection of |set1| and |set2|. static URLPatternSet CreateIntersection(const URLPatternSet& set1, const URLPatternSet& set2); // Creates an intersection result where result has every element that is // contained by both |set1| and |set2|. This is different than // CreateIntersection(), which does string comparisons. For example, the // semantic intersection of ("http://*.google.com/*") and // ("http://google.com/*") is ("http://google.com/*"), but the result from // CreateIntersection() would be (). // TODO(devlin): This is weird. We probably want to use mostly // CreateSemanticIntersection(). static URLPatternSet CreateSemanticIntersection(const URLPatternSet& set1, const URLPatternSet& set2); // Returns the union of |set1| and |set2|. static URLPatternSet CreateUnion(const URLPatternSet& set1, const URLPatternSet& set2); // Returns the union of all sets in |sets|. static URLPatternSet CreateUnion(const std::vector<URLPatternSet>& sets); URLPatternSet(); URLPatternSet(const URLPatternSet& rhs); URLPatternSet(URLPatternSet&& rhs); explicit URLPatternSet(const std::set<URLPattern>& patterns); ~URLPatternSet(); URLPatternSet& operator=(const URLPatternSet& rhs); URLPatternSet& operator=(URLPatternSet&& rhs); bool operator==(const URLPatternSet& rhs) const; bool is_empty() const; size_t size() const; const std::set<URLPattern>& patterns() const { return patterns_; } const_iterator begin() const { return patterns_.begin(); } const_iterator end() const { return patterns_.end(); } // Adds a pattern to the set. Returns true if a new pattern was inserted, // false if the pattern was already in the set. bool AddPattern(const URLPattern& pattern); // Adds all patterns from |set| into this. void AddPatterns(const URLPatternSet& set); void ClearPatterns(); // Adds a pattern based on |origin| to the set. bool AddOrigin(int valid_schemes, const GURL& origin); // Returns true if every URL that matches |set| is matched by this. In other // words, if every pattern in |set| is encompassed by a pattern in this. bool Contains(const URLPatternSet& set) const; // Returns true if any pattern in this set encompasses |pattern|. bool ContainsPattern(const URLPattern& pattern) const; // Test if the extent contains a URL. bool MatchesURL(const GURL& url) const; // Test if the extent matches all URLs (for example, <all_urls>). bool MatchesAllURLs() const; bool MatchesSecurityOrigin(const GURL& origin) const; // Returns true if there is a single URL that would be in two extents. bool OverlapsWith(const URLPatternSet& other) const; // Converts to and from Value for serialization to preferences. std::unique_ptr<base::ListValue> ToValue() const; bool Populate(const base::ListValue& value, int valid_schemes, bool allow_file_access, std::string* error); // Converts to and from a vector of strings. std::unique_ptr<std::vector<std::string>> ToStringVector() const; bool Populate(const std::vector<std::string>& patterns, int valid_schemes, bool allow_file_access, std::string* error); private: // The list of URL patterns that comprise the extent. std::set<URLPattern> patterns_; }; std::ostream& operator<<(std::ostream& out, const URLPatternSet& url_pattern_set); } // namespace extensions #endif // EXTENSIONS_COMMON_URL_PATTERN_SET_H_
null
null
null
null
21,909
2,819
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
167,814
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Interface handling * * Copyright 2002-2005, Instant802 Networks, Inc. * Copyright 2005-2006, Devicescape Software, Inc. * Copyright (c) 2006 Jiri Benc <[email protected]> * Copyright 2008, Johannes Berg <[email protected]> * Copyright 2013-2014 Intel Mobile Communications GmbH * Copyright (c) 2016 Intel Deutschland GmbH * * 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/slab.h> #include <linux/kernel.h> #include <linux/if_arp.h> #include <linux/netdevice.h> #include <linux/rtnetlink.h> #include <net/mac80211.h> #include <net/ieee80211_radiotap.h> #include "ieee80211_i.h" #include "sta_info.h" #include "debugfs_netdev.h" #include "mesh.h" #include "led.h" #include "driver-ops.h" #include "wme.h" #include "rate.h" /** * DOC: Interface list locking * * The interface list in each struct ieee80211_local is protected * three-fold: * * (1) modifications may only be done under the RTNL * (2) modifications and readers are protected against each other by * the iflist_mtx. * (3) modifications are done in an RCU manner so atomic readers * can traverse the list in RCU-safe blocks. * * As a consequence, reads (traversals) of the list can be protected * by either the RTNL, the iflist_mtx or RCU. */ static void ieee80211_iface_work(struct work_struct *work); bool __ieee80211_recalc_txpower(struct ieee80211_sub_if_data *sdata) { struct ieee80211_chanctx_conf *chanctx_conf; int power; rcu_read_lock(); chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) { rcu_read_unlock(); return false; } power = ieee80211_chandef_max_power(&chanctx_conf->def); rcu_read_unlock(); if (sdata->user_power_level != IEEE80211_UNSET_POWER_LEVEL) power = min(power, sdata->user_power_level); if (sdata->ap_power_level != IEEE80211_UNSET_POWER_LEVEL) power = min(power, sdata->ap_power_level); if (power != sdata->vif.bss_conf.txpower) { sdata->vif.bss_conf.txpower = power; ieee80211_hw_config(sdata->local, 0); return true; } return false; } void ieee80211_recalc_txpower(struct ieee80211_sub_if_data *sdata, bool update_bss) { if (__ieee80211_recalc_txpower(sdata) || (update_bss && ieee80211_sdata_running(sdata))) ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_TXPOWER); } static u32 __ieee80211_idle_off(struct ieee80211_local *local) { if (!(local->hw.conf.flags & IEEE80211_CONF_IDLE)) return 0; local->hw.conf.flags &= ~IEEE80211_CONF_IDLE; return IEEE80211_CONF_CHANGE_IDLE; } static u32 __ieee80211_idle_on(struct ieee80211_local *local) { if (local->hw.conf.flags & IEEE80211_CONF_IDLE) return 0; ieee80211_flush_queues(local, NULL, false); local->hw.conf.flags |= IEEE80211_CONF_IDLE; return IEEE80211_CONF_CHANGE_IDLE; } static u32 __ieee80211_recalc_idle(struct ieee80211_local *local, bool force_active) { bool working, scanning, active; unsigned int led_trig_start = 0, led_trig_stop = 0; lockdep_assert_held(&local->mtx); active = force_active || !list_empty(&local->chanctx_list) || local->monitors; working = !local->ops->remain_on_channel && !list_empty(&local->roc_list); scanning = test_bit(SCAN_SW_SCANNING, &local->scanning) || test_bit(SCAN_ONCHANNEL_SCANNING, &local->scanning); if (working || scanning) led_trig_start |= IEEE80211_TPT_LEDTRIG_FL_WORK; else led_trig_stop |= IEEE80211_TPT_LEDTRIG_FL_WORK; if (active) led_trig_start |= IEEE80211_TPT_LEDTRIG_FL_CONNECTED; else led_trig_stop |= IEEE80211_TPT_LEDTRIG_FL_CONNECTED; ieee80211_mod_tpt_led_trig(local, led_trig_start, led_trig_stop); if (working || scanning || active) return __ieee80211_idle_off(local); return __ieee80211_idle_on(local); } u32 ieee80211_idle_off(struct ieee80211_local *local) { return __ieee80211_recalc_idle(local, true); } void ieee80211_recalc_idle(struct ieee80211_local *local) { u32 change = __ieee80211_recalc_idle(local, false); if (change) ieee80211_hw_config(local, change); } static int ieee80211_verify_mac(struct ieee80211_sub_if_data *sdata, u8 *addr, bool check_dup) { struct ieee80211_local *local = sdata->local; struct ieee80211_sub_if_data *iter; u64 new, mask, tmp; u8 *m; int ret = 0; if (is_zero_ether_addr(local->hw.wiphy->addr_mask)) return 0; m = addr; new = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); m = local->hw.wiphy->addr_mask; mask = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); if (!check_dup) return ret; mutex_lock(&local->iflist_mtx); list_for_each_entry(iter, &local->interfaces, list) { if (iter == sdata) continue; if (iter->vif.type == NL80211_IFTYPE_MONITOR && !(iter->u.mntr.flags & MONITOR_FLAG_ACTIVE)) continue; m = iter->vif.addr; tmp = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); if ((new & ~mask) != (tmp & ~mask)) { ret = -EINVAL; break; } } mutex_unlock(&local->iflist_mtx); return ret; } static int ieee80211_change_mac(struct net_device *dev, void *addr) { struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev); struct sockaddr *sa = addr; bool check_dup = true; int ret; if (ieee80211_sdata_running(sdata)) return -EBUSY; if (sdata->vif.type == NL80211_IFTYPE_MONITOR && !(sdata->u.mntr.flags & MONITOR_FLAG_ACTIVE)) check_dup = false; ret = ieee80211_verify_mac(sdata, sa->sa_data, check_dup); if (ret) return ret; ret = eth_mac_addr(dev, sa); if (ret == 0) memcpy(sdata->vif.addr, sa->sa_data, ETH_ALEN); return ret; } static inline int identical_mac_addr_allowed(int type1, int type2) { return type1 == NL80211_IFTYPE_MONITOR || type2 == NL80211_IFTYPE_MONITOR || type1 == NL80211_IFTYPE_P2P_DEVICE || type2 == NL80211_IFTYPE_P2P_DEVICE || (type1 == NL80211_IFTYPE_AP && type2 == NL80211_IFTYPE_WDS) || (type1 == NL80211_IFTYPE_WDS && (type2 == NL80211_IFTYPE_WDS || type2 == NL80211_IFTYPE_AP)) || (type1 == NL80211_IFTYPE_AP && type2 == NL80211_IFTYPE_AP_VLAN) || (type1 == NL80211_IFTYPE_AP_VLAN && (type2 == NL80211_IFTYPE_AP || type2 == NL80211_IFTYPE_AP_VLAN)); } static int ieee80211_check_concurrent_iface(struct ieee80211_sub_if_data *sdata, enum nl80211_iftype iftype) { struct ieee80211_local *local = sdata->local; struct ieee80211_sub_if_data *nsdata; int ret; ASSERT_RTNL(); /* we hold the RTNL here so can safely walk the list */ list_for_each_entry(nsdata, &local->interfaces, list) { if (nsdata != sdata && ieee80211_sdata_running(nsdata)) { /* * Only OCB and monitor mode may coexist */ if ((sdata->vif.type == NL80211_IFTYPE_OCB && nsdata->vif.type != NL80211_IFTYPE_MONITOR) || (sdata->vif.type != NL80211_IFTYPE_MONITOR && nsdata->vif.type == NL80211_IFTYPE_OCB)) return -EBUSY; /* * Allow only a single IBSS interface to be up at any * time. This is restricted because beacon distribution * cannot work properly if both are in the same IBSS. * * To remove this restriction we'd have to disallow them * from setting the same SSID on different IBSS interfaces * belonging to the same hardware. Then, however, we're * faced with having to adopt two different TSF timers... */ if (iftype == NL80211_IFTYPE_ADHOC && nsdata->vif.type == NL80211_IFTYPE_ADHOC) return -EBUSY; /* * will not add another interface while any channel * switch is active. */ if (nsdata->vif.csa_active) return -EBUSY; /* * The remaining checks are only performed for interfaces * with the same MAC address. */ if (!ether_addr_equal(sdata->vif.addr, nsdata->vif.addr)) continue; /* * check whether it may have the same address */ if (!identical_mac_addr_allowed(iftype, nsdata->vif.type)) return -ENOTUNIQ; /* * can only add VLANs to enabled APs */ if (iftype == NL80211_IFTYPE_AP_VLAN && nsdata->vif.type == NL80211_IFTYPE_AP) sdata->bss = &nsdata->u.ap; } } mutex_lock(&local->chanctx_mtx); ret = ieee80211_check_combinations(sdata, NULL, 0, 0); mutex_unlock(&local->chanctx_mtx); return ret; } static int ieee80211_check_queues(struct ieee80211_sub_if_data *sdata, enum nl80211_iftype iftype) { int n_queues = sdata->local->hw.queues; int i; if (iftype == NL80211_IFTYPE_NAN) return 0; if (iftype != NL80211_IFTYPE_P2P_DEVICE) { for (i = 0; i < IEEE80211_NUM_ACS; i++) { if (WARN_ON_ONCE(sdata->vif.hw_queue[i] == IEEE80211_INVAL_HW_QUEUE)) return -EINVAL; if (WARN_ON_ONCE(sdata->vif.hw_queue[i] >= n_queues)) return -EINVAL; } } if ((iftype != NL80211_IFTYPE_AP && iftype != NL80211_IFTYPE_P2P_GO && iftype != NL80211_IFTYPE_MESH_POINT) || !ieee80211_hw_check(&sdata->local->hw, QUEUE_CONTROL)) { sdata->vif.cab_queue = IEEE80211_INVAL_HW_QUEUE; return 0; } if (WARN_ON_ONCE(sdata->vif.cab_queue == IEEE80211_INVAL_HW_QUEUE)) return -EINVAL; if (WARN_ON_ONCE(sdata->vif.cab_queue >= n_queues)) return -EINVAL; return 0; } void ieee80211_adjust_monitor_flags(struct ieee80211_sub_if_data *sdata, const int offset) { struct ieee80211_local *local = sdata->local; u32 flags = sdata->u.mntr.flags; #define ADJUST(_f, _s) do { \ if (flags & MONITOR_FLAG_##_f) \ local->fif_##_s += offset; \ } while (0) ADJUST(FCSFAIL, fcsfail); ADJUST(PLCPFAIL, plcpfail); ADJUST(CONTROL, control); ADJUST(CONTROL, pspoll); ADJUST(OTHER_BSS, other_bss); #undef ADJUST } static void ieee80211_set_default_queues(struct ieee80211_sub_if_data *sdata) { struct ieee80211_local *local = sdata->local; int i; for (i = 0; i < IEEE80211_NUM_ACS; i++) { if (ieee80211_hw_check(&local->hw, QUEUE_CONTROL)) sdata->vif.hw_queue[i] = IEEE80211_INVAL_HW_QUEUE; else if (local->hw.queues >= IEEE80211_NUM_ACS) sdata->vif.hw_queue[i] = i; else sdata->vif.hw_queue[i] = 0; } sdata->vif.cab_queue = IEEE80211_INVAL_HW_QUEUE; } int ieee80211_add_virtual_monitor(struct ieee80211_local *local) { struct ieee80211_sub_if_data *sdata; int ret; if (!ieee80211_hw_check(&local->hw, WANT_MONITOR_VIF)) return 0; ASSERT_RTNL(); if (local->monitor_sdata) return 0; sdata = kzalloc(sizeof(*sdata) + local->hw.vif_data_size, GFP_KERNEL); if (!sdata) return -ENOMEM; /* set up data */ sdata->local = local; sdata->vif.type = NL80211_IFTYPE_MONITOR; snprintf(sdata->name, IFNAMSIZ, "%s-monitor", wiphy_name(local->hw.wiphy)); sdata->wdev.iftype = NL80211_IFTYPE_MONITOR; sdata->encrypt_headroom = IEEE80211_ENCRYPT_HEADROOM; ieee80211_set_default_queues(sdata); ret = drv_add_interface(local, sdata); if (WARN_ON(ret)) { /* ok .. stupid driver, it asked for this! */ kfree(sdata); return ret; } ret = ieee80211_check_queues(sdata, NL80211_IFTYPE_MONITOR); if (ret) { kfree(sdata); return ret; } mutex_lock(&local->iflist_mtx); rcu_assign_pointer(local->monitor_sdata, sdata); mutex_unlock(&local->iflist_mtx); mutex_lock(&local->mtx); ret = ieee80211_vif_use_channel(sdata, &local->monitor_chandef, IEEE80211_CHANCTX_EXCLUSIVE); mutex_unlock(&local->mtx); if (ret) { mutex_lock(&local->iflist_mtx); RCU_INIT_POINTER(local->monitor_sdata, NULL); mutex_unlock(&local->iflist_mtx); synchronize_net(); drv_remove_interface(local, sdata); kfree(sdata); return ret; } skb_queue_head_init(&sdata->skb_queue); INIT_WORK(&sdata->work, ieee80211_iface_work); return 0; } void ieee80211_del_virtual_monitor(struct ieee80211_local *local) { struct ieee80211_sub_if_data *sdata; if (!ieee80211_hw_check(&local->hw, WANT_MONITOR_VIF)) return; ASSERT_RTNL(); mutex_lock(&local->iflist_mtx); sdata = rcu_dereference_protected(local->monitor_sdata, lockdep_is_held(&local->iflist_mtx)); if (!sdata) { mutex_unlock(&local->iflist_mtx); return; } RCU_INIT_POINTER(local->monitor_sdata, NULL); mutex_unlock(&local->iflist_mtx); synchronize_net(); mutex_lock(&local->mtx); ieee80211_vif_release_channel(sdata); mutex_unlock(&local->mtx); drv_remove_interface(local, sdata); kfree(sdata); } /* * NOTE: Be very careful when changing this function, it must NOT return * an error on interface type changes that have been pre-checked, so most * checks should be in ieee80211_check_concurrent_iface. */ int ieee80211_do_open(struct wireless_dev *wdev, bool coming_up) { struct ieee80211_sub_if_data *sdata = IEEE80211_WDEV_TO_SUB_IF(wdev); struct net_device *dev = wdev->netdev; struct ieee80211_local *local = sdata->local; struct sta_info *sta; u32 changed = 0; int res; u32 hw_reconf_flags = 0; switch (sdata->vif.type) { case NL80211_IFTYPE_WDS: if (!is_valid_ether_addr(sdata->u.wds.remote_addr)) return -ENOLINK; break; case NL80211_IFTYPE_AP_VLAN: { struct ieee80211_sub_if_data *master; if (!sdata->bss) return -ENOLINK; mutex_lock(&local->mtx); list_add(&sdata->u.vlan.list, &sdata->bss->vlans); mutex_unlock(&local->mtx); master = container_of(sdata->bss, struct ieee80211_sub_if_data, u.ap); sdata->control_port_protocol = master->control_port_protocol; sdata->control_port_no_encrypt = master->control_port_no_encrypt; sdata->vif.cab_queue = master->vif.cab_queue; memcpy(sdata->vif.hw_queue, master->vif.hw_queue, sizeof(sdata->vif.hw_queue)); sdata->vif.bss_conf.chandef = master->vif.bss_conf.chandef; mutex_lock(&local->key_mtx); sdata->crypto_tx_tailroom_needed_cnt += master->crypto_tx_tailroom_needed_cnt; mutex_unlock(&local->key_mtx); break; } case NL80211_IFTYPE_AP: sdata->bss = &sdata->u.ap; break; case NL80211_IFTYPE_MESH_POINT: case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_MONITOR: case NL80211_IFTYPE_ADHOC: case NL80211_IFTYPE_P2P_DEVICE: case NL80211_IFTYPE_OCB: case NL80211_IFTYPE_NAN: /* no special treatment */ break; case NL80211_IFTYPE_UNSPECIFIED: case NUM_NL80211_IFTYPES: case NL80211_IFTYPE_P2P_CLIENT: case NL80211_IFTYPE_P2P_GO: /* cannot happen */ WARN_ON(1); break; } if (local->open_count == 0) { res = drv_start(local); if (res) goto err_del_bss; /* we're brought up, everything changes */ hw_reconf_flags = ~0; ieee80211_led_radio(local, true); ieee80211_mod_tpt_led_trig(local, IEEE80211_TPT_LEDTRIG_FL_RADIO, 0); } /* * Copy the hopefully now-present MAC address to * this interface, if it has the special null one. */ if (dev && is_zero_ether_addr(dev->dev_addr)) { memcpy(dev->dev_addr, local->hw.wiphy->perm_addr, ETH_ALEN); memcpy(dev->perm_addr, dev->dev_addr, ETH_ALEN); if (!is_valid_ether_addr(dev->dev_addr)) { res = -EADDRNOTAVAIL; goto err_stop; } } switch (sdata->vif.type) { case NL80211_IFTYPE_AP_VLAN: /* no need to tell driver, but set carrier and chanctx */ if (rtnl_dereference(sdata->bss->beacon)) { ieee80211_vif_vlan_copy_chanctx(sdata); netif_carrier_on(dev); } else { netif_carrier_off(dev); } break; case NL80211_IFTYPE_MONITOR: if (sdata->u.mntr.flags & MONITOR_FLAG_COOK_FRAMES) { local->cooked_mntrs++; break; } if (sdata->u.mntr.flags & MONITOR_FLAG_ACTIVE) { res = drv_add_interface(local, sdata); if (res) goto err_stop; } else if (local->monitors == 0 && local->open_count == 0) { res = ieee80211_add_virtual_monitor(local); if (res) goto err_stop; } /* must be before the call to ieee80211_configure_filter */ local->monitors++; if (local->monitors == 1) { local->hw.conf.flags |= IEEE80211_CONF_MONITOR; hw_reconf_flags |= IEEE80211_CONF_CHANGE_MONITOR; } ieee80211_adjust_monitor_flags(sdata, 1); ieee80211_configure_filter(local); mutex_lock(&local->mtx); ieee80211_recalc_idle(local); mutex_unlock(&local->mtx); netif_carrier_on(dev); break; default: if (coming_up) { ieee80211_del_virtual_monitor(local); res = drv_add_interface(local, sdata); if (res) goto err_stop; res = ieee80211_check_queues(sdata, ieee80211_vif_type_p2p(&sdata->vif)); if (res) goto err_del_interface; } if (sdata->vif.type == NL80211_IFTYPE_AP) { local->fif_pspoll++; local->fif_probe_req++; ieee80211_configure_filter(local); } else if (sdata->vif.type == NL80211_IFTYPE_ADHOC) { local->fif_probe_req++; } if (sdata->vif.type != NL80211_IFTYPE_P2P_DEVICE && sdata->vif.type != NL80211_IFTYPE_NAN) changed |= ieee80211_reset_erp_info(sdata); ieee80211_bss_info_change_notify(sdata, changed); switch (sdata->vif.type) { case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_ADHOC: case NL80211_IFTYPE_AP: case NL80211_IFTYPE_MESH_POINT: case NL80211_IFTYPE_OCB: netif_carrier_off(dev); break; case NL80211_IFTYPE_WDS: case NL80211_IFTYPE_P2P_DEVICE: case NL80211_IFTYPE_NAN: break; default: /* not reached */ WARN_ON(1); } /* * Set default queue parameters so drivers don't * need to initialise the hardware if the hardware * doesn't start up with sane defaults. * Enable QoS for anything but station interfaces. */ ieee80211_set_wmm_default(sdata, true, sdata->vif.type != NL80211_IFTYPE_STATION); } set_bit(SDATA_STATE_RUNNING, &sdata->state); if (sdata->vif.type == NL80211_IFTYPE_WDS) { /* Create STA entry for the WDS peer */ sta = sta_info_alloc(sdata, sdata->u.wds.remote_addr, GFP_KERNEL); if (!sta) { res = -ENOMEM; goto err_del_interface; } sta_info_pre_move_state(sta, IEEE80211_STA_AUTH); sta_info_pre_move_state(sta, IEEE80211_STA_ASSOC); sta_info_pre_move_state(sta, IEEE80211_STA_AUTHORIZED); res = sta_info_insert(sta); if (res) { /* STA has been freed */ goto err_del_interface; } rate_control_rate_init(sta); netif_carrier_on(dev); } else if (sdata->vif.type == NL80211_IFTYPE_P2P_DEVICE) { rcu_assign_pointer(local->p2p_sdata, sdata); } /* * set_multicast_list will be invoked by the networking core * which will check whether any increments here were done in * error and sync them down to the hardware as filter flags. */ if (sdata->flags & IEEE80211_SDATA_ALLMULTI) atomic_inc(&local->iff_allmultis); if (coming_up) local->open_count++; if (hw_reconf_flags) ieee80211_hw_config(local, hw_reconf_flags); ieee80211_recalc_ps(local); if (sdata->vif.type == NL80211_IFTYPE_MONITOR || sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { /* XXX: for AP_VLAN, actually track AP queues */ netif_tx_start_all_queues(dev); } else if (dev) { unsigned long flags; int n_acs = IEEE80211_NUM_ACS; int ac; if (local->hw.queues < IEEE80211_NUM_ACS) n_acs = 1; spin_lock_irqsave(&local->queue_stop_reason_lock, flags); if (sdata->vif.cab_queue == IEEE80211_INVAL_HW_QUEUE || (local->queue_stop_reasons[sdata->vif.cab_queue] == 0 && skb_queue_empty(&local->pending[sdata->vif.cab_queue]))) { for (ac = 0; ac < n_acs; ac++) { int ac_queue = sdata->vif.hw_queue[ac]; if (local->queue_stop_reasons[ac_queue] == 0 && skb_queue_empty(&local->pending[ac_queue])) netif_start_subqueue(dev, ac); } } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); } return 0; err_del_interface: drv_remove_interface(local, sdata); err_stop: if (!local->open_count) drv_stop(local); err_del_bss: sdata->bss = NULL; if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { mutex_lock(&local->mtx); list_del(&sdata->u.vlan.list); mutex_unlock(&local->mtx); } /* might already be clear but that doesn't matter */ clear_bit(SDATA_STATE_RUNNING, &sdata->state); return res; } static int ieee80211_open(struct net_device *dev) { struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev); int err; /* fail early if user set an invalid address */ if (!is_valid_ether_addr(dev->dev_addr)) return -EADDRNOTAVAIL; err = ieee80211_check_concurrent_iface(sdata, sdata->vif.type); if (err) return err; return ieee80211_do_open(&sdata->wdev, true); } static void ieee80211_do_stop(struct ieee80211_sub_if_data *sdata, bool going_down) { struct ieee80211_local *local = sdata->local; struct fq *fq = &local->fq; unsigned long flags; struct sk_buff *skb, *tmp; u32 hw_reconf_flags = 0; int i, flushed; struct ps_data *ps; struct cfg80211_chan_def chandef; bool cancel_scan; struct cfg80211_nan_func *func; clear_bit(SDATA_STATE_RUNNING, &sdata->state); cancel_scan = rcu_access_pointer(local->scan_sdata) == sdata; if (cancel_scan) ieee80211_scan_cancel(local); /* * Stop TX on this interface first. */ if (sdata->dev) netif_tx_stop_all_queues(sdata->dev); ieee80211_roc_purge(local, sdata); switch (sdata->vif.type) { case NL80211_IFTYPE_STATION: ieee80211_mgd_stop(sdata); break; case NL80211_IFTYPE_ADHOC: ieee80211_ibss_stop(sdata); break; case NL80211_IFTYPE_AP: cancel_work_sync(&sdata->u.ap.request_smps_work); break; default: break; } /* * Remove all stations associated with this interface. * * This must be done before calling ops->remove_interface() * because otherwise we can later invoke ops->sta_notify() * whenever the STAs are removed, and that invalidates driver * assumptions about always getting a vif pointer that is valid * (because if we remove a STA after ops->remove_interface() * the driver will have removed the vif info already!) * * In WDS mode a station must exist here and be flushed, for * AP_VLANs stations may exist since there's nothing else that * would have removed them, but in other modes there shouldn't * be any stations. */ flushed = sta_info_flush(sdata); WARN_ON_ONCE(sdata->vif.type != NL80211_IFTYPE_AP_VLAN && ((sdata->vif.type != NL80211_IFTYPE_WDS && flushed > 0) || (sdata->vif.type == NL80211_IFTYPE_WDS && flushed != 1))); /* don't count this interface for allmulti while it is down */ if (sdata->flags & IEEE80211_SDATA_ALLMULTI) atomic_dec(&local->iff_allmultis); if (sdata->vif.type == NL80211_IFTYPE_AP) { local->fif_pspoll--; local->fif_probe_req--; } else if (sdata->vif.type == NL80211_IFTYPE_ADHOC) { local->fif_probe_req--; } if (sdata->dev) { netif_addr_lock_bh(sdata->dev); spin_lock_bh(&local->filter_lock); __hw_addr_unsync(&local->mc_list, &sdata->dev->mc, sdata->dev->addr_len); spin_unlock_bh(&local->filter_lock); netif_addr_unlock_bh(sdata->dev); } del_timer_sync(&local->dynamic_ps_timer); cancel_work_sync(&local->dynamic_ps_enable_work); cancel_work_sync(&sdata->recalc_smps); sdata_lock(sdata); mutex_lock(&local->mtx); sdata->vif.csa_active = false; if (sdata->vif.type == NL80211_IFTYPE_STATION) sdata->u.mgd.csa_waiting_bcn = false; if (sdata->csa_block_tx) { ieee80211_wake_vif_queues(local, sdata, IEEE80211_QUEUE_STOP_REASON_CSA); sdata->csa_block_tx = false; } mutex_unlock(&local->mtx); sdata_unlock(sdata); cancel_work_sync(&sdata->csa_finalize_work); cancel_delayed_work_sync(&sdata->dfs_cac_timer_work); if (sdata->wdev.cac_started) { chandef = sdata->vif.bss_conf.chandef; WARN_ON(local->suspended); mutex_lock(&local->mtx); ieee80211_vif_release_channel(sdata); mutex_unlock(&local->mtx); cfg80211_cac_event(sdata->dev, &chandef, NL80211_RADAR_CAC_ABORTED, GFP_KERNEL); } /* APs need special treatment */ if (sdata->vif.type == NL80211_IFTYPE_AP) { struct ieee80211_sub_if_data *vlan, *tmpsdata; /* down all dependent devices, that is VLANs */ list_for_each_entry_safe(vlan, tmpsdata, &sdata->u.ap.vlans, u.vlan.list) dev_close(vlan->dev); WARN_ON(!list_empty(&sdata->u.ap.vlans)); } else if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { /* remove all packets in parent bc_buf pointing to this dev */ ps = &sdata->bss->ps; spin_lock_irqsave(&ps->bc_buf.lock, flags); skb_queue_walk_safe(&ps->bc_buf, skb, tmp) { if (skb->dev == sdata->dev) { __skb_unlink(skb, &ps->bc_buf); local->total_ps_buffered--; ieee80211_free_txskb(&local->hw, skb); } } spin_unlock_irqrestore(&ps->bc_buf.lock, flags); } if (going_down) local->open_count--; switch (sdata->vif.type) { case NL80211_IFTYPE_AP_VLAN: mutex_lock(&local->mtx); list_del(&sdata->u.vlan.list); mutex_unlock(&local->mtx); RCU_INIT_POINTER(sdata->vif.chanctx_conf, NULL); /* see comment in the default case below */ ieee80211_free_keys(sdata, true); /* no need to tell driver */ break; case NL80211_IFTYPE_MONITOR: if (sdata->u.mntr.flags & MONITOR_FLAG_COOK_FRAMES) { local->cooked_mntrs--; break; } local->monitors--; if (local->monitors == 0) { local->hw.conf.flags &= ~IEEE80211_CONF_MONITOR; hw_reconf_flags |= IEEE80211_CONF_CHANGE_MONITOR; } ieee80211_adjust_monitor_flags(sdata, -1); break; case NL80211_IFTYPE_NAN: /* clean all the functions */ spin_lock_bh(&sdata->u.nan.func_lock); idr_for_each_entry(&sdata->u.nan.function_inst_ids, func, i) { idr_remove(&sdata->u.nan.function_inst_ids, i); cfg80211_free_nan_func(func); } idr_destroy(&sdata->u.nan.function_inst_ids); spin_unlock_bh(&sdata->u.nan.func_lock); break; case NL80211_IFTYPE_P2P_DEVICE: /* relies on synchronize_rcu() below */ RCU_INIT_POINTER(local->p2p_sdata, NULL); /* fall through */ default: cancel_work_sync(&sdata->work); /* * When we get here, the interface is marked down. * Free the remaining keys, if there are any * (which can happen in AP mode if userspace sets * keys before the interface is operating, and maybe * also in WDS mode) * * Force the key freeing to always synchronize_net() * to wait for the RX path in case it is using this * interface enqueuing frames at this very time on * another CPU. */ ieee80211_free_keys(sdata, true); skb_queue_purge(&sdata->skb_queue); } sdata->bss = NULL; spin_lock_irqsave(&local->queue_stop_reason_lock, flags); for (i = 0; i < IEEE80211_MAX_QUEUES; i++) { skb_queue_walk_safe(&local->pending[i], skb, tmp) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); if (info->control.vif == &sdata->vif) { __skb_unlink(skb, &local->pending[i]); ieee80211_free_txskb(&local->hw, skb); } } } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); if (sdata->vif.txq) { struct txq_info *txqi = to_txq_info(sdata->vif.txq); spin_lock_bh(&fq->lock); ieee80211_txq_purge(local, txqi); spin_unlock_bh(&fq->lock); } if (local->open_count == 0) ieee80211_clear_tx_pending(local); /* * If the interface goes down while suspended, presumably because * the device was unplugged and that happens before our resume, * then the driver is already unconfigured and the remainder of * this function isn't needed. * XXX: what about WoWLAN? If the device has software state, e.g. * memory allocated, it might expect teardown commands from * mac80211 here? */ if (local->suspended) { WARN_ON(local->wowlan); WARN_ON(rtnl_dereference(local->monitor_sdata)); return; } switch (sdata->vif.type) { case NL80211_IFTYPE_AP_VLAN: break; case NL80211_IFTYPE_MONITOR: if (local->monitors == 0) ieee80211_del_virtual_monitor(local); mutex_lock(&local->mtx); ieee80211_recalc_idle(local); mutex_unlock(&local->mtx); if (!(sdata->u.mntr.flags & MONITOR_FLAG_ACTIVE)) break; /* fall through */ default: if (going_down) drv_remove_interface(local, sdata); } ieee80211_recalc_ps(local); if (cancel_scan) flush_delayed_work(&local->scan_work); if (local->open_count == 0) { ieee80211_stop_device(local); /* no reconfiguring after stop! */ return; } /* do after stop to avoid reconfiguring when we stop anyway */ ieee80211_configure_filter(local); ieee80211_hw_config(local, hw_reconf_flags); if (local->monitors == local->open_count) ieee80211_add_virtual_monitor(local); } static int ieee80211_stop(struct net_device *dev) { struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev); ieee80211_do_stop(sdata, true); return 0; } static void ieee80211_set_multicast_list(struct net_device *dev) { struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev); struct ieee80211_local *local = sdata->local; int allmulti, sdata_allmulti; allmulti = !!(dev->flags & IFF_ALLMULTI); sdata_allmulti = !!(sdata->flags & IEEE80211_SDATA_ALLMULTI); if (allmulti != sdata_allmulti) { if (dev->flags & IFF_ALLMULTI) atomic_inc(&local->iff_allmultis); else atomic_dec(&local->iff_allmultis); sdata->flags ^= IEEE80211_SDATA_ALLMULTI; } spin_lock_bh(&local->filter_lock); __hw_addr_sync(&local->mc_list, &dev->mc, dev->addr_len); spin_unlock_bh(&local->filter_lock); ieee80211_queue_work(&local->hw, &local->reconfig_filter); } /* * Called when the netdev is removed or, by the code below, before * the interface type changes. */ static void ieee80211_teardown_sdata(struct ieee80211_sub_if_data *sdata) { int i; /* free extra data */ ieee80211_free_keys(sdata, false); ieee80211_debugfs_remove_netdev(sdata); for (i = 0; i < IEEE80211_FRAGMENT_MAX; i++) __skb_queue_purge(&sdata->fragments[i].skb_list); sdata->fragment_next = 0; if (ieee80211_vif_is_mesh(&sdata->vif)) ieee80211_mesh_teardown_sdata(sdata); } static void ieee80211_uninit(struct net_device *dev) { ieee80211_teardown_sdata(IEEE80211_DEV_TO_SUB_IF(dev)); } static u16 ieee80211_netdev_select_queue(struct net_device *dev, struct sk_buff *skb, void *accel_priv, select_queue_fallback_t fallback) { return ieee80211_select_queue(IEEE80211_DEV_TO_SUB_IF(dev), skb); } static void ieee80211_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) { int i; for_each_possible_cpu(i) { const struct pcpu_sw_netstats *tstats; u64 rx_packets, rx_bytes, tx_packets, tx_bytes; unsigned int start; tstats = per_cpu_ptr(dev->tstats, i); do { start = u64_stats_fetch_begin_irq(&tstats->syncp); rx_packets = tstats->rx_packets; tx_packets = tstats->tx_packets; rx_bytes = tstats->rx_bytes; tx_bytes = tstats->tx_bytes; } while (u64_stats_fetch_retry_irq(&tstats->syncp, start)); stats->rx_packets += rx_packets; stats->tx_packets += tx_packets; stats->rx_bytes += rx_bytes; stats->tx_bytes += tx_bytes; } } static const struct net_device_ops ieee80211_dataif_ops = { .ndo_open = ieee80211_open, .ndo_stop = ieee80211_stop, .ndo_uninit = ieee80211_uninit, .ndo_start_xmit = ieee80211_subif_start_xmit, .ndo_set_rx_mode = ieee80211_set_multicast_list, .ndo_set_mac_address = ieee80211_change_mac, .ndo_select_queue = ieee80211_netdev_select_queue, .ndo_get_stats64 = ieee80211_get_stats64, }; static u16 ieee80211_monitor_select_queue(struct net_device *dev, struct sk_buff *skb, void *accel_priv, select_queue_fallback_t fallback) { struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev); struct ieee80211_local *local = sdata->local; struct ieee80211_hdr *hdr; struct ieee80211_radiotap_header *rtap = (void *)skb->data; if (local->hw.queues < IEEE80211_NUM_ACS) return 0; if (skb->len < 4 || skb->len < le16_to_cpu(rtap->it_len) + 2 /* frame control */) return 0; /* doesn't matter, frame will be dropped */ hdr = (void *)((u8 *)skb->data + le16_to_cpu(rtap->it_len)); return ieee80211_select_queue_80211(sdata, skb, hdr); } static const struct net_device_ops ieee80211_monitorif_ops = { .ndo_open = ieee80211_open, .ndo_stop = ieee80211_stop, .ndo_uninit = ieee80211_uninit, .ndo_start_xmit = ieee80211_monitor_start_xmit, .ndo_set_rx_mode = ieee80211_set_multicast_list, .ndo_set_mac_address = ieee80211_change_mac, .ndo_select_queue = ieee80211_monitor_select_queue, .ndo_get_stats64 = ieee80211_get_stats64, }; static void ieee80211_if_free(struct net_device *dev) { free_percpu(dev->tstats); free_netdev(dev); } static void ieee80211_if_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags &= ~IFF_TX_SKB_SHARING; dev->netdev_ops = &ieee80211_dataif_ops; dev->destructor = ieee80211_if_free; } static void ieee80211_if_setup_no_queue(struct net_device *dev) { ieee80211_if_setup(dev); dev->priv_flags |= IFF_NO_QUEUE; } static void ieee80211_iface_work(struct work_struct *work) { struct ieee80211_sub_if_data *sdata = container_of(work, struct ieee80211_sub_if_data, work); struct ieee80211_local *local = sdata->local; struct sk_buff *skb; struct sta_info *sta; struct ieee80211_ra_tid *ra_tid; struct ieee80211_rx_agg *rx_agg; if (!ieee80211_sdata_running(sdata)) return; if (test_bit(SCAN_SW_SCANNING, &local->scanning)) return; if (!ieee80211_can_run_worker(local)) return; /* first process frames */ while ((skb = skb_dequeue(&sdata->skb_queue))) { struct ieee80211_mgmt *mgmt = (void *)skb->data; if (skb->pkt_type == IEEE80211_SDATA_QUEUE_AGG_START) { ra_tid = (void *)&skb->cb; ieee80211_start_tx_ba_cb(&sdata->vif, ra_tid->ra, ra_tid->tid); } else if (skb->pkt_type == IEEE80211_SDATA_QUEUE_AGG_STOP) { ra_tid = (void *)&skb->cb; ieee80211_stop_tx_ba_cb(&sdata->vif, ra_tid->ra, ra_tid->tid); } else if (skb->pkt_type == IEEE80211_SDATA_QUEUE_RX_AGG_START) { rx_agg = (void *)&skb->cb; mutex_lock(&local->sta_mtx); sta = sta_info_get_bss(sdata, rx_agg->addr); if (sta) __ieee80211_start_rx_ba_session(sta, 0, 0, 0, 1, rx_agg->tid, IEEE80211_MAX_AMPDU_BUF, false, true); mutex_unlock(&local->sta_mtx); } else if (skb->pkt_type == IEEE80211_SDATA_QUEUE_RX_AGG_STOP) { rx_agg = (void *)&skb->cb; mutex_lock(&local->sta_mtx); sta = sta_info_get_bss(sdata, rx_agg->addr); if (sta) __ieee80211_stop_rx_ba_session(sta, rx_agg->tid, WLAN_BACK_RECIPIENT, 0, false); mutex_unlock(&local->sta_mtx); } else if (ieee80211_is_action(mgmt->frame_control) && mgmt->u.action.category == WLAN_CATEGORY_BACK) { int len = skb->len; mutex_lock(&local->sta_mtx); sta = sta_info_get_bss(sdata, mgmt->sa); if (sta) { switch (mgmt->u.action.u.addba_req.action_code) { case WLAN_ACTION_ADDBA_REQ: ieee80211_process_addba_request( local, sta, mgmt, len); break; case WLAN_ACTION_ADDBA_RESP: ieee80211_process_addba_resp(local, sta, mgmt, len); break; case WLAN_ACTION_DELBA: ieee80211_process_delba(sdata, sta, mgmt, len); break; default: WARN_ON(1); break; } } mutex_unlock(&local->sta_mtx); } else if (ieee80211_is_action(mgmt->frame_control) && mgmt->u.action.category == WLAN_CATEGORY_VHT) { switch (mgmt->u.action.u.vht_group_notif.action_code) { case WLAN_VHT_ACTION_OPMODE_NOTIF: { struct ieee80211_rx_status *status; enum nl80211_band band; u8 opmode; status = IEEE80211_SKB_RXCB(skb); band = status->band; opmode = mgmt->u.action.u.vht_opmode_notif.operating_mode; mutex_lock(&local->sta_mtx); sta = sta_info_get_bss(sdata, mgmt->sa); if (sta) ieee80211_vht_handle_opmode(sdata, sta, opmode, band); mutex_unlock(&local->sta_mtx); break; } case WLAN_VHT_ACTION_GROUPID_MGMT: ieee80211_process_mu_groups(sdata, mgmt); break; default: WARN_ON(1); break; } } else if (ieee80211_is_data_qos(mgmt->frame_control)) { struct ieee80211_hdr *hdr = (void *)mgmt; /* * So the frame isn't mgmt, but frame_control * is at the right place anyway, of course, so * the if statement is correct. * * Warn if we have other data frame types here, * they must not get here. */ WARN_ON(hdr->frame_control & cpu_to_le16(IEEE80211_STYPE_NULLFUNC)); WARN_ON(!(hdr->seq_ctrl & cpu_to_le16(IEEE80211_SCTL_FRAG))); /* * This was a fragment of a frame, received while * a block-ack session was active. That cannot be * right, so terminate the session. */ mutex_lock(&local->sta_mtx); sta = sta_info_get_bss(sdata, mgmt->sa); if (sta) { u16 tid = *ieee80211_get_qos_ctl(hdr) & IEEE80211_QOS_CTL_TID_MASK; __ieee80211_stop_rx_ba_session( sta, tid, WLAN_BACK_RECIPIENT, WLAN_REASON_QSTA_REQUIRE_SETUP, true); } mutex_unlock(&local->sta_mtx); } else switch (sdata->vif.type) { case NL80211_IFTYPE_STATION: ieee80211_sta_rx_queued_mgmt(sdata, skb); break; case NL80211_IFTYPE_ADHOC: ieee80211_ibss_rx_queued_mgmt(sdata, skb); break; case NL80211_IFTYPE_MESH_POINT: if (!ieee80211_vif_is_mesh(&sdata->vif)) break; ieee80211_mesh_rx_queued_mgmt(sdata, skb); break; default: WARN(1, "frame for unexpected interface type"); break; } kfree_skb(skb); } /* then other type-dependent work */ switch (sdata->vif.type) { case NL80211_IFTYPE_STATION: ieee80211_sta_work(sdata); break; case NL80211_IFTYPE_ADHOC: ieee80211_ibss_work(sdata); break; case NL80211_IFTYPE_MESH_POINT: if (!ieee80211_vif_is_mesh(&sdata->vif)) break; ieee80211_mesh_work(sdata); break; case NL80211_IFTYPE_OCB: ieee80211_ocb_work(sdata); break; default: break; } } static void ieee80211_recalc_smps_work(struct work_struct *work) { struct ieee80211_sub_if_data *sdata = container_of(work, struct ieee80211_sub_if_data, recalc_smps); ieee80211_recalc_smps(sdata); } /* * Helper function to initialise an interface to a specific type. */ static void ieee80211_setup_sdata(struct ieee80211_sub_if_data *sdata, enum nl80211_iftype type) { static const u8 bssid_wildcard[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; /* clear type-dependent union */ memset(&sdata->u, 0, sizeof(sdata->u)); /* and set some type-dependent values */ sdata->vif.type = type; sdata->vif.p2p = false; sdata->wdev.iftype = type; sdata->control_port_protocol = cpu_to_be16(ETH_P_PAE); sdata->control_port_no_encrypt = false; sdata->encrypt_headroom = IEEE80211_ENCRYPT_HEADROOM; sdata->vif.bss_conf.idle = true; sdata->noack_map = 0; /* only monitor/p2p-device differ */ if (sdata->dev) { sdata->dev->netdev_ops = &ieee80211_dataif_ops; sdata->dev->type = ARPHRD_ETHER; } skb_queue_head_init(&sdata->skb_queue); INIT_WORK(&sdata->work, ieee80211_iface_work); INIT_WORK(&sdata->recalc_smps, ieee80211_recalc_smps_work); INIT_WORK(&sdata->csa_finalize_work, ieee80211_csa_finalize_work); INIT_LIST_HEAD(&sdata->assigned_chanctx_list); INIT_LIST_HEAD(&sdata->reserved_chanctx_list); switch (type) { case NL80211_IFTYPE_P2P_GO: type = NL80211_IFTYPE_AP; sdata->vif.type = type; sdata->vif.p2p = true; /* fall through */ case NL80211_IFTYPE_AP: skb_queue_head_init(&sdata->u.ap.ps.bc_buf); INIT_LIST_HEAD(&sdata->u.ap.vlans); INIT_WORK(&sdata->u.ap.request_smps_work, ieee80211_request_smps_ap_work); sdata->vif.bss_conf.bssid = sdata->vif.addr; sdata->u.ap.req_smps = IEEE80211_SMPS_OFF; break; case NL80211_IFTYPE_P2P_CLIENT: type = NL80211_IFTYPE_STATION; sdata->vif.type = type; sdata->vif.p2p = true; /* fall through */ case NL80211_IFTYPE_STATION: sdata->vif.bss_conf.bssid = sdata->u.mgd.bssid; ieee80211_sta_setup_sdata(sdata); break; case NL80211_IFTYPE_OCB: sdata->vif.bss_conf.bssid = bssid_wildcard; ieee80211_ocb_setup_sdata(sdata); break; case NL80211_IFTYPE_ADHOC: sdata->vif.bss_conf.bssid = sdata->u.ibss.bssid; ieee80211_ibss_setup_sdata(sdata); break; case NL80211_IFTYPE_MESH_POINT: if (ieee80211_vif_is_mesh(&sdata->vif)) ieee80211_mesh_init_sdata(sdata); break; case NL80211_IFTYPE_MONITOR: sdata->dev->type = ARPHRD_IEEE80211_RADIOTAP; sdata->dev->netdev_ops = &ieee80211_monitorif_ops; sdata->u.mntr.flags = MONITOR_FLAG_CONTROL | MONITOR_FLAG_OTHER_BSS; break; case NL80211_IFTYPE_WDS: sdata->vif.bss_conf.bssid = NULL; break; case NL80211_IFTYPE_NAN: idr_init(&sdata->u.nan.function_inst_ids); spin_lock_init(&sdata->u.nan.func_lock); sdata->vif.bss_conf.bssid = sdata->vif.addr; break; case NL80211_IFTYPE_AP_VLAN: case NL80211_IFTYPE_P2P_DEVICE: sdata->vif.bss_conf.bssid = sdata->vif.addr; break; case NL80211_IFTYPE_UNSPECIFIED: case NUM_NL80211_IFTYPES: BUG(); break; } ieee80211_debugfs_add_netdev(sdata); } static int ieee80211_runtime_change_iftype(struct ieee80211_sub_if_data *sdata, enum nl80211_iftype type) { struct ieee80211_local *local = sdata->local; int ret, err; enum nl80211_iftype internal_type = type; bool p2p = false; ASSERT_RTNL(); if (!local->ops->change_interface) return -EBUSY; switch (sdata->vif.type) { case NL80211_IFTYPE_AP: case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_ADHOC: case NL80211_IFTYPE_OCB: /* * Could maybe also all others here? * Just not sure how that interacts * with the RX/config path e.g. for * mesh. */ break; default: return -EBUSY; } switch (type) { case NL80211_IFTYPE_AP: case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_ADHOC: case NL80211_IFTYPE_OCB: /* * Could probably support everything * but WDS here (WDS do_open can fail * under memory pressure, which this * code isn't prepared to handle). */ break; case NL80211_IFTYPE_P2P_CLIENT: p2p = true; internal_type = NL80211_IFTYPE_STATION; break; case NL80211_IFTYPE_P2P_GO: p2p = true; internal_type = NL80211_IFTYPE_AP; break; default: return -EBUSY; } ret = ieee80211_check_concurrent_iface(sdata, internal_type); if (ret) return ret; ieee80211_do_stop(sdata, false); ieee80211_teardown_sdata(sdata); ret = drv_change_interface(local, sdata, internal_type, p2p); if (ret) type = ieee80211_vif_type_p2p(&sdata->vif); /* * Ignore return value here, there's not much we can do since * the driver changed the interface type internally already. * The warnings will hopefully make driver authors fix it :-) */ ieee80211_check_queues(sdata, type); ieee80211_setup_sdata(sdata, type); err = ieee80211_do_open(&sdata->wdev, false); WARN(err, "type change: do_open returned %d", err); return ret; } int ieee80211_if_change_type(struct ieee80211_sub_if_data *sdata, enum nl80211_iftype type) { int ret; ASSERT_RTNL(); if (type == ieee80211_vif_type_p2p(&sdata->vif)) return 0; if (ieee80211_sdata_running(sdata)) { ret = ieee80211_runtime_change_iftype(sdata, type); if (ret) return ret; } else { /* Purge and reset type-dependent state. */ ieee80211_teardown_sdata(sdata); ieee80211_setup_sdata(sdata, type); } /* reset some values that shouldn't be kept across type changes */ if (type == NL80211_IFTYPE_STATION) sdata->u.mgd.use_4addr = false; return 0; } static void ieee80211_assign_perm_addr(struct ieee80211_local *local, u8 *perm_addr, enum nl80211_iftype type) { struct ieee80211_sub_if_data *sdata; u64 mask, start, addr, val, inc; u8 *m; u8 tmp_addr[ETH_ALEN]; int i; /* default ... something at least */ memcpy(perm_addr, local->hw.wiphy->perm_addr, ETH_ALEN); if (is_zero_ether_addr(local->hw.wiphy->addr_mask) && local->hw.wiphy->n_addresses <= 1) return; mutex_lock(&local->iflist_mtx); switch (type) { case NL80211_IFTYPE_MONITOR: /* doesn't matter */ break; case NL80211_IFTYPE_WDS: case NL80211_IFTYPE_AP_VLAN: /* match up with an AP interface */ list_for_each_entry(sdata, &local->interfaces, list) { if (sdata->vif.type != NL80211_IFTYPE_AP) continue; memcpy(perm_addr, sdata->vif.addr, ETH_ALEN); break; } /* keep default if no AP interface present */ break; case NL80211_IFTYPE_P2P_CLIENT: case NL80211_IFTYPE_P2P_GO: if (ieee80211_hw_check(&local->hw, P2P_DEV_ADDR_FOR_INTF)) { list_for_each_entry(sdata, &local->interfaces, list) { if (sdata->vif.type != NL80211_IFTYPE_P2P_DEVICE) continue; if (!ieee80211_sdata_running(sdata)) continue; memcpy(perm_addr, sdata->vif.addr, ETH_ALEN); goto out_unlock; } } /* otherwise fall through */ default: /* assign a new address if possible -- try n_addresses first */ for (i = 0; i < local->hw.wiphy->n_addresses; i++) { bool used = false; list_for_each_entry(sdata, &local->interfaces, list) { if (ether_addr_equal(local->hw.wiphy->addresses[i].addr, sdata->vif.addr)) { used = true; break; } } if (!used) { memcpy(perm_addr, local->hw.wiphy->addresses[i].addr, ETH_ALEN); break; } } /* try mask if available */ if (is_zero_ether_addr(local->hw.wiphy->addr_mask)) break; m = local->hw.wiphy->addr_mask; mask = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); if (__ffs64(mask) + hweight64(mask) != fls64(mask)) { /* not a contiguous mask ... not handled now! */ pr_info("not contiguous\n"); break; } /* * Pick address of existing interface in case user changed * MAC address manually, default to perm_addr. */ m = local->hw.wiphy->perm_addr; list_for_each_entry(sdata, &local->interfaces, list) { if (sdata->vif.type == NL80211_IFTYPE_MONITOR) continue; m = sdata->vif.addr; break; } start = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); inc = 1ULL<<__ffs64(mask); val = (start & mask); addr = (start & ~mask) | (val & mask); do { bool used = false; tmp_addr[5] = addr >> 0*8; tmp_addr[4] = addr >> 1*8; tmp_addr[3] = addr >> 2*8; tmp_addr[2] = addr >> 3*8; tmp_addr[1] = addr >> 4*8; tmp_addr[0] = addr >> 5*8; val += inc; list_for_each_entry(sdata, &local->interfaces, list) { if (ether_addr_equal(tmp_addr, sdata->vif.addr)) { used = true; break; } } if (!used) { memcpy(perm_addr, tmp_addr, ETH_ALEN); break; } addr = (start & ~mask) | (val & mask); } while (addr != start); break; } out_unlock: mutex_unlock(&local->iflist_mtx); } int ieee80211_if_add(struct ieee80211_local *local, const char *name, unsigned char name_assign_type, struct wireless_dev **new_wdev, enum nl80211_iftype type, struct vif_params *params) { struct net_device *ndev = NULL; struct ieee80211_sub_if_data *sdata = NULL; struct txq_info *txqi; void (*if_setup)(struct net_device *dev); int ret, i; int txqs = 1; ASSERT_RTNL(); if (type == NL80211_IFTYPE_P2P_DEVICE || type == NL80211_IFTYPE_NAN) { struct wireless_dev *wdev; sdata = kzalloc(sizeof(*sdata) + local->hw.vif_data_size, GFP_KERNEL); if (!sdata) return -ENOMEM; wdev = &sdata->wdev; sdata->dev = NULL; strlcpy(sdata->name, name, IFNAMSIZ); ieee80211_assign_perm_addr(local, wdev->address, type); memcpy(sdata->vif.addr, wdev->address, ETH_ALEN); } else { int size = ALIGN(sizeof(*sdata) + local->hw.vif_data_size, sizeof(void *)); int txq_size = 0; if (local->ops->wake_tx_queue) txq_size += sizeof(struct txq_info) + local->hw.txq_data_size; if (local->ops->wake_tx_queue) if_setup = ieee80211_if_setup_no_queue; else if_setup = ieee80211_if_setup; if (local->hw.queues >= IEEE80211_NUM_ACS) txqs = IEEE80211_NUM_ACS; ndev = alloc_netdev_mqs(size + txq_size, name, name_assign_type, if_setup, txqs, 1); if (!ndev) return -ENOMEM; dev_net_set(ndev, wiphy_net(local->hw.wiphy)); ndev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats); if (!ndev->tstats) { free_netdev(ndev); return -ENOMEM; } ndev->needed_headroom = local->tx_headroom + 4*6 /* four MAC addresses */ + 2 + 2 + 2 + 2 /* ctl, dur, seq, qos */ + 6 /* mesh */ + 8 /* rfc1042/bridge tunnel */ - ETH_HLEN /* ethernet hard_header_len */ + IEEE80211_ENCRYPT_HEADROOM; ndev->needed_tailroom = IEEE80211_ENCRYPT_TAILROOM; ret = dev_alloc_name(ndev, ndev->name); if (ret < 0) { ieee80211_if_free(ndev); return ret; } ieee80211_assign_perm_addr(local, ndev->perm_addr, type); if (params && is_valid_ether_addr(params->macaddr)) memcpy(ndev->dev_addr, params->macaddr, ETH_ALEN); else memcpy(ndev->dev_addr, ndev->perm_addr, ETH_ALEN); SET_NETDEV_DEV(ndev, wiphy_dev(local->hw.wiphy)); /* don't use IEEE80211_DEV_TO_SUB_IF -- it checks too much */ sdata = netdev_priv(ndev); ndev->ieee80211_ptr = &sdata->wdev; memcpy(sdata->vif.addr, ndev->dev_addr, ETH_ALEN); memcpy(sdata->name, ndev->name, IFNAMSIZ); if (txq_size) { txqi = netdev_priv(ndev) + size; ieee80211_txq_init(sdata, NULL, txqi, 0); } sdata->dev = ndev; } /* initialise type-independent data */ sdata->wdev.wiphy = local->hw.wiphy; sdata->local = local; for (i = 0; i < IEEE80211_FRAGMENT_MAX; i++) skb_queue_head_init(&sdata->fragments[i].skb_list); INIT_LIST_HEAD(&sdata->key_list); INIT_DELAYED_WORK(&sdata->dfs_cac_timer_work, ieee80211_dfs_cac_timer_work); INIT_DELAYED_WORK(&sdata->dec_tailroom_needed_wk, ieee80211_delayed_tailroom_dec); for (i = 0; i < NUM_NL80211_BANDS; i++) { struct ieee80211_supported_band *sband; sband = local->hw.wiphy->bands[i]; sdata->rc_rateidx_mask[i] = sband ? (1 << sband->n_bitrates) - 1 : 0; if (sband) { __le16 cap; u16 *vht_rate_mask; memcpy(sdata->rc_rateidx_mcs_mask[i], sband->ht_cap.mcs.rx_mask, sizeof(sdata->rc_rateidx_mcs_mask[i])); cap = sband->vht_cap.vht_mcs.rx_mcs_map; vht_rate_mask = sdata->rc_rateidx_vht_mcs_mask[i]; ieee80211_get_vht_mask_from_cap(cap, vht_rate_mask); } else { memset(sdata->rc_rateidx_mcs_mask[i], 0, sizeof(sdata->rc_rateidx_mcs_mask[i])); memset(sdata->rc_rateidx_vht_mcs_mask[i], 0, sizeof(sdata->rc_rateidx_vht_mcs_mask[i])); } } ieee80211_set_default_queues(sdata); sdata->ap_power_level = IEEE80211_UNSET_POWER_LEVEL; sdata->user_power_level = local->user_power_level; sdata->encrypt_headroom = IEEE80211_ENCRYPT_HEADROOM; /* setup type-dependent data */ ieee80211_setup_sdata(sdata, type); if (ndev) { if (params) { ndev->ieee80211_ptr->use_4addr = params->use_4addr; if (type == NL80211_IFTYPE_STATION) sdata->u.mgd.use_4addr = params->use_4addr; } ndev->features |= local->hw.netdev_features; netdev_set_default_ethtool_ops(ndev, &ieee80211_ethtool_ops); /* MTU range: 256 - 2304 */ ndev->min_mtu = 256; ndev->max_mtu = IEEE80211_MAX_DATA_LEN; ret = register_netdevice(ndev); if (ret) { ieee80211_if_free(ndev); return ret; } } mutex_lock(&local->iflist_mtx); list_add_tail_rcu(&sdata->list, &local->interfaces); mutex_unlock(&local->iflist_mtx); if (new_wdev) *new_wdev = &sdata->wdev; return 0; } void ieee80211_if_remove(struct ieee80211_sub_if_data *sdata) { ASSERT_RTNL(); mutex_lock(&sdata->local->iflist_mtx); list_del_rcu(&sdata->list); mutex_unlock(&sdata->local->iflist_mtx); synchronize_rcu(); if (sdata->dev) { unregister_netdevice(sdata->dev); } else { cfg80211_unregister_wdev(&sdata->wdev); ieee80211_teardown_sdata(sdata); kfree(sdata); } } void ieee80211_sdata_stop(struct ieee80211_sub_if_data *sdata) { if (WARN_ON_ONCE(!test_bit(SDATA_STATE_RUNNING, &sdata->state))) return; ieee80211_do_stop(sdata, true); } void ieee80211_remove_interfaces(struct ieee80211_local *local) { struct ieee80211_sub_if_data *sdata, *tmp; LIST_HEAD(unreg_list); LIST_HEAD(wdev_list); ASSERT_RTNL(); /* Before destroying the interfaces, make sure they're all stopped so * that the hardware is stopped. Otherwise, the driver might still be * iterating the interfaces during the shutdown, e.g. from a worker * or from RX processing or similar, and if it does so (using atomic * iteration) while we're manipulating the list, the iteration will * crash. * * After this, the hardware should be stopped and the driver should * have stopped all of its activities, so that we can do RCU-unaware * manipulations of the interface list below. */ cfg80211_shutdown_all_interfaces(local->hw.wiphy); WARN(local->open_count, "%s: open count remains %d\n", wiphy_name(local->hw.wiphy), local->open_count); mutex_lock(&local->iflist_mtx); list_for_each_entry_safe(sdata, tmp, &local->interfaces, list) { list_del(&sdata->list); if (sdata->dev) unregister_netdevice_queue(sdata->dev, &unreg_list); else list_add(&sdata->list, &wdev_list); } mutex_unlock(&local->iflist_mtx); unregister_netdevice_many(&unreg_list); list_for_each_entry_safe(sdata, tmp, &wdev_list, list) { list_del(&sdata->list); cfg80211_unregister_wdev(&sdata->wdev); kfree(sdata); } } static int netdev_notify(struct notifier_block *nb, unsigned long state, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct ieee80211_sub_if_data *sdata; if (state != NETDEV_CHANGENAME) return NOTIFY_DONE; if (!dev->ieee80211_ptr || !dev->ieee80211_ptr->wiphy) return NOTIFY_DONE; if (dev->ieee80211_ptr->wiphy->privid != mac80211_wiphy_privid) return NOTIFY_DONE; sdata = IEEE80211_DEV_TO_SUB_IF(dev); memcpy(sdata->name, dev->name, IFNAMSIZ); ieee80211_debugfs_rename_netdev(sdata); return NOTIFY_OK; } static struct notifier_block mac80211_netdev_notifier = { .notifier_call = netdev_notify, }; int ieee80211_iface_init(void) { return register_netdevice_notifier(&mac80211_netdev_notifier); } void ieee80211_iface_exit(void) { unregister_netdevice_notifier(&mac80211_netdev_notifier); } void ieee80211_vif_inc_num_mcast(struct ieee80211_sub_if_data *sdata) { if (sdata->vif.type == NL80211_IFTYPE_AP) atomic_inc(&sdata->u.ap.num_mcast_sta); else if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) atomic_inc(&sdata->u.vlan.num_mcast_sta); } void ieee80211_vif_dec_num_mcast(struct ieee80211_sub_if_data *sdata) { if (sdata->vif.type == NL80211_IFTYPE_AP) atomic_dec(&sdata->u.ap.num_mcast_sta); else if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) atomic_dec(&sdata->u.vlan.num_mcast_sta); }
null
null
null
null
76,162
39,626
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
204,621
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Generic wait-for-completion handler; * * It differs from semaphores in that their default case is the opposite, * wait_for_completion default blocks whereas semaphore default non-block. The * interface also makes it easy to 'complete' multiple waiting threads, * something which isn't entirely natural for semaphores. * * But more importantly, the primitive documents the usage. Semaphores would * typically be used for exclusion which gives rise to priority inversion. * Waiting for completion is a typically sync point, but not an exclusion point. */ #include <linux/sched/signal.h> #include <linux/sched/debug.h> #include <linux/completion.h> /** * complete: - signals a single thread waiting on this completion * @x: holds the state of this particular completion * * This will wake up a single thread waiting on this completion. Threads will be * awakened in the same order in which they were queued. * * See also complete_all(), wait_for_completion() and related routines. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void complete(struct completion *x) { unsigned long flags; spin_lock_irqsave(&x->wait.lock, flags); if (x->done != UINT_MAX) x->done++; __wake_up_locked(&x->wait, TASK_NORMAL, 1); spin_unlock_irqrestore(&x->wait.lock, flags); } EXPORT_SYMBOL(complete); /** * complete_all: - signals all threads waiting on this completion * @x: holds the state of this particular completion * * This will wake up all threads waiting on this particular completion event. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void complete_all(struct completion *x) { unsigned long flags; spin_lock_irqsave(&x->wait.lock, flags); x->done = UINT_MAX; __wake_up_locked(&x->wait, TASK_NORMAL, 0); spin_unlock_irqrestore(&x->wait.lock, flags); } EXPORT_SYMBOL(complete_all); static inline long __sched do_wait_for_common(struct completion *x, long (*action)(long), long timeout, int state) { if (!x->done) { DECLARE_WAITQUEUE(wait, current); __add_wait_queue_tail_exclusive(&x->wait, &wait); do { if (signal_pending_state(state, current)) { timeout = -ERESTARTSYS; break; } __set_current_state(state); spin_unlock_irq(&x->wait.lock); timeout = action(timeout); spin_lock_irq(&x->wait.lock); } while (!x->done && timeout); __remove_wait_queue(&x->wait, &wait); if (!x->done) return timeout; } if (x->done != UINT_MAX) x->done--; return timeout ?: 1; } static inline long __sched __wait_for_common(struct completion *x, long (*action)(long), long timeout, int state) { might_sleep(); spin_lock_irq(&x->wait.lock); timeout = do_wait_for_common(x, action, timeout, state); spin_unlock_irq(&x->wait.lock); return timeout; } static long __sched wait_for_common(struct completion *x, long timeout, int state) { return __wait_for_common(x, schedule_timeout, timeout, state); } static long __sched wait_for_common_io(struct completion *x, long timeout, int state) { return __wait_for_common(x, io_schedule_timeout, timeout, state); } /** * wait_for_completion: - waits for completion of a task * @x: holds the state of this particular completion * * This waits to be signaled for completion of a specific task. It is NOT * interruptible and there is no timeout. * * See also similar routines (i.e. wait_for_completion_timeout()) with timeout * and interrupt capability. Also see complete(). */ void __sched wait_for_completion(struct completion *x) { wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE); } EXPORT_SYMBOL(wait_for_completion); /** * wait_for_completion_timeout: - waits for completion of a task (w/timeout) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be signaled or for a * specified timeout to expire. The timeout is in jiffies. It is not * interruptible. * * Return: 0 if timed out, and positive (at least 1, or number of jiffies left * till timeout) if completed. */ unsigned long __sched wait_for_completion_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE); } EXPORT_SYMBOL(wait_for_completion_timeout); /** * wait_for_completion_io: - waits for completion of a task * @x: holds the state of this particular completion * * This waits to be signaled for completion of a specific task. It is NOT * interruptible and there is no timeout. The caller is accounted as waiting * for IO (which traditionally means blkio only). */ void __sched wait_for_completion_io(struct completion *x) { wait_for_common_io(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE); } EXPORT_SYMBOL(wait_for_completion_io); /** * wait_for_completion_io_timeout: - waits for completion of a task (w/timeout) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be signaled or for a * specified timeout to expire. The timeout is in jiffies. It is not * interruptible. The caller is accounted as waiting for IO (which traditionally * means blkio only). * * Return: 0 if timed out, and positive (at least 1, or number of jiffies left * till timeout) if completed. */ unsigned long __sched wait_for_completion_io_timeout(struct completion *x, unsigned long timeout) { return wait_for_common_io(x, timeout, TASK_UNINTERRUPTIBLE); } EXPORT_SYMBOL(wait_for_completion_io_timeout); /** * wait_for_completion_interruptible: - waits for completion of a task (w/intr) * @x: holds the state of this particular completion * * This waits for completion of a specific task to be signaled. It is * interruptible. * * Return: -ERESTARTSYS if interrupted, 0 if completed. */ int __sched wait_for_completion_interruptible(struct completion *x) { long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE); if (t == -ERESTARTSYS) return t; return 0; } EXPORT_SYMBOL(wait_for_completion_interruptible); /** * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr)) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be signaled or for a * specified timeout to expire. It is interruptible. The timeout is in jiffies. * * Return: -ERESTARTSYS if interrupted, 0 if timed out, positive (at least 1, * or number of jiffies left till timeout) if completed. */ long __sched wait_for_completion_interruptible_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_INTERRUPTIBLE); } EXPORT_SYMBOL(wait_for_completion_interruptible_timeout); /** * wait_for_completion_killable: - waits for completion of a task (killable) * @x: holds the state of this particular completion * * This waits to be signaled for completion of a specific task. It can be * interrupted by a kill signal. * * Return: -ERESTARTSYS if interrupted, 0 if completed. */ int __sched wait_for_completion_killable(struct completion *x) { long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE); if (t == -ERESTARTSYS) return t; return 0; } EXPORT_SYMBOL(wait_for_completion_killable); /** * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable)) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be * signaled or for a specified timeout to expire. It can be * interrupted by a kill signal. The timeout is in jiffies. * * Return: -ERESTARTSYS if interrupted, 0 if timed out, positive (at least 1, * or number of jiffies left till timeout) if completed. */ long __sched wait_for_completion_killable_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_KILLABLE); } EXPORT_SYMBOL(wait_for_completion_killable_timeout); /** * try_wait_for_completion - try to decrement a completion without blocking * @x: completion structure * * Return: 0 if a decrement cannot be done without blocking * 1 if a decrement succeeded. * * If a completion is being used as a counting completion, * attempt to decrement the counter without blocking. This * enables us to avoid waiting if the resource the completion * is protecting is not available. */ bool try_wait_for_completion(struct completion *x) { unsigned long flags; int ret = 1; /* * Since x->done will need to be locked only * in the non-blocking case, we check x->done * first without taking the lock so we can * return early in the blocking case. */ if (!READ_ONCE(x->done)) return 0; spin_lock_irqsave(&x->wait.lock, flags); if (!x->done) ret = 0; else if (x->done != UINT_MAX) x->done--; spin_unlock_irqrestore(&x->wait.lock, flags); return ret; } EXPORT_SYMBOL(try_wait_for_completion); /** * completion_done - Test to see if a completion has any waiters * @x: completion structure * * Return: 0 if there are waiters (wait_for_completion() in progress) * 1 if there are no waiters. * */ bool completion_done(struct completion *x) { if (!READ_ONCE(x->done)) return false; /* * If ->done, we need to wait for complete() to release ->wait.lock * otherwise we can end up freeing the completion before complete() * is done referencing it. * * The RMB pairs with complete()'s RELEASE of ->wait.lock and orders * the loads of ->done and ->wait.lock such that we cannot observe * the lock before complete() acquires it while observing the ->done * after it's acquired the lock. */ smp_rmb(); spin_unlock_wait(&x->wait.lock); return true; } EXPORT_SYMBOL(completion_done);
null
null
null
null
112,968
72,152
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
72,152
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 "services/network/upload_progress_tracker.h" #include "base/logging.h" #include "net/base/upload_progress.h" #include "net/url_request/url_request.h" namespace network { namespace { // The interval for calls to ReportUploadProgress. constexpr base::TimeDelta kUploadProgressInterval = base::TimeDelta::FromMilliseconds(100); } // namespace UploadProgressTracker::UploadProgressTracker( const base::Location& location, UploadProgressReportCallback report_progress, net::URLRequest* request, scoped_refptr<base::SequencedTaskRunner> task_runner) : request_(request), report_progress_(std::move(report_progress)) { DCHECK(report_progress_); progress_timer_.SetTaskRunner(std::move(task_runner)); progress_timer_.Start(location, kUploadProgressInterval, this, &UploadProgressTracker::ReportUploadProgressIfNeeded); } UploadProgressTracker::~UploadProgressTracker() {} void UploadProgressTracker::OnAckReceived() { waiting_for_upload_progress_ack_ = false; } void UploadProgressTracker::OnUploadCompleted() { waiting_for_upload_progress_ack_ = false; ReportUploadProgressIfNeeded(); progress_timer_.Stop(); } // static base::TimeDelta UploadProgressTracker::GetUploadProgressIntervalForTesting() { return kUploadProgressInterval; } base::TimeTicks UploadProgressTracker::GetCurrentTime() const { return base::TimeTicks::Now(); } net::UploadProgress UploadProgressTracker::GetUploadProgress() const { return request_->GetUploadProgress(); } void UploadProgressTracker::ReportUploadProgressIfNeeded() { if (waiting_for_upload_progress_ack_) return; net::UploadProgress progress = GetUploadProgress(); if (!progress.size()) return; // Nothing to upload, or in the chunked upload mode. // No progress made since last time, or the progress was reset by a redirect // or a retry. if (progress.position() <= last_upload_position_) return; const uint64_t kHalfPercentIncrements = 200; const base::TimeDelta kOneSecond = base::TimeDelta::FromMilliseconds(1000); uint64_t amt_since_last = progress.position() - last_upload_position_; base::TimeTicks now = GetCurrentTime(); base::TimeDelta time_since_last = now - last_upload_ticks_; bool is_finished = (progress.size() == progress.position()); bool enough_new_progress = (amt_since_last > (progress.size() / kHalfPercentIncrements)); bool too_much_time_passed = time_since_last > kOneSecond; if (is_finished || enough_new_progress || too_much_time_passed) { report_progress_.Run(progress); waiting_for_upload_progress_ack_ = true; last_upload_ticks_ = now; last_upload_position_ = progress.position(); } } } // namespace network
null
null
null
null
69,015
31,703
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
31,703
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_CSS_CSSOM_CSS_STYLE_IMAGE_VALUE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_STYLE_IMAGE_VALUE_H_ #include "base/macros.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/css/cssom/css_resource_value.h" #include "third_party/blink/renderer/core/html/canvas/canvas_image_source.h" #include "third_party/blink/renderer/platform/wtf/optional.h" namespace blink { // CSSStyleImageValue is the base class for Typed OM representations of images. // The corresponding idl file is CSSImageValue.idl. class CORE_EXPORT CSSStyleImageValue : public CSSResourceValue, public CanvasImageSource { DEFINE_WRAPPERTYPEINFO(); public: virtual ~CSSStyleImageValue() = default; // IDL double intrinsicWidth(bool& is_null) const; double intrinsicHeight(bool& is_null) const; double intrinsicRatio(bool& is_null) const; // CanvasImageSource bool IsCSSImageValue() const final { return true; } bool WouldTaintOrigin( const SecurityOrigin* destination_security_origin) const final { return true; } FloatSize ElementSize(const FloatSize& default_object_size) const final; protected: CSSStyleImageValue() = default; virtual WTF::Optional<IntSize> IntrinsicSize() const = 0; private: DISALLOW_COPY_AND_ASSIGN(CSSStyleImageValue); }; } // namespace blink #endif // CSSResourceValue_h
null
null
null
null
28,566
33,266
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
33,266
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 THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_SHUTDOWN_NOTIFIER_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_SHUTDOWN_NOTIFIER_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/lifecycle_notifier.h" namespace blink { class Document; class DocumentShutdownObserver; // Sibling class of DocumentShutdownObserver; implemented by Document to notify // subclasses of DocumentShutdownObserver of Document shutdown. class CORE_EXPORT DocumentShutdownNotifier : public LifecycleNotifier<Document, DocumentShutdownObserver> { protected: DocumentShutdownNotifier(); private: DISALLOW_COPY_AND_ASSIGN(DocumentShutdownNotifier); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_SHUTDOWN_NOTIFIER_H_
null
null
null
null
30,129
3,052
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
156,109
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/** Copyright (C) 2005 Michael Ahlberg, Måns Rullgård Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #include <stdlib.h> #include "libavutil/intreadwrite.h" #include "libavcodec/bytestream.h" #include "avformat.h" #include "internal.h" #include "oggdec.h" #include "riff.h" static int ogm_header(AVFormatContext *s, int idx) { struct ogg *ogg = s->priv_data; struct ogg_stream *os = ogg->streams + idx; AVStream *st = s->streams[idx]; GetByteContext p; uint64_t time_unit; uint64_t spu; uint32_t size; bytestream2_init(&p, os->buf + os->pstart, os->psize); if (!(bytestream2_peek_byte(&p) & 1)) return 0; if (bytestream2_peek_byte(&p) == 1) { bytestream2_skip(&p, 1); if (bytestream2_peek_byte(&p) == 'v'){ int tag; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; bytestream2_skip(&p, 8); tag = bytestream2_get_le32(&p); st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag); st->codecpar->codec_tag = tag; if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4) st->need_parsing = AVSTREAM_PARSE_HEADERS; } else if (bytestream2_peek_byte(&p) == 't') { st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; st->codecpar->codec_id = AV_CODEC_ID_TEXT; bytestream2_skip(&p, 12); } else { uint8_t acid[5] = { 0 }; int cid; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; bytestream2_skip(&p, 8); bytestream2_get_buffer(&p, acid, 4); acid[4] = 0; cid = strtol(acid, NULL, 16); st->codecpar->codec_id = ff_codec_get_id(ff_codec_wav_tags, cid); // our parser completely breaks AAC in Ogg if (st->codecpar->codec_id != AV_CODEC_ID_AAC) st->need_parsing = AVSTREAM_PARSE_FULL; } size = bytestream2_get_le32(&p); size = FFMIN(size, os->psize); time_unit = bytestream2_get_le64(&p); spu = bytestream2_get_le64(&p); if (!time_unit || !spu) { av_log(s, AV_LOG_ERROR, "Invalid timing values.\n"); return AVERROR_INVALIDDATA; } bytestream2_skip(&p, 4); /* default_len */ bytestream2_skip(&p, 8); /* buffersize + bits_per_sample */ if(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO){ st->codecpar->width = bytestream2_get_le32(&p); st->codecpar->height = bytestream2_get_le32(&p); avpriv_set_pts_info(st, 64, time_unit, spu * 10000000); } else { st->codecpar->channels = bytestream2_get_le16(&p); bytestream2_skip(&p, 2); /* block_align */ st->codecpar->bit_rate = bytestream2_get_le32(&p) * 8; st->codecpar->sample_rate = spu * 10000000 / time_unit; avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate); if (size >= 56 && st->codecpar->codec_id == AV_CODEC_ID_AAC) { bytestream2_skip(&p, 4); size -= 4; } if (size > 52) { size -= 52; if (bytestream2_get_bytes_left(&p) < size) return AVERROR_INVALIDDATA; av_freep(&st->codecpar->extradata); if (ff_alloc_extradata(st->codecpar, size) < 0) return AVERROR(ENOMEM); bytestream2_get_buffer(&p, st->codecpar->extradata, st->codecpar->extradata_size); } } } else if (bytestream2_peek_byte(&p) == 3) { bytestream2_skip(&p, 7); if (bytestream2_get_bytes_left(&p) > 1) ff_vorbis_stream_comment(s, st, p.buffer, bytestream2_get_bytes_left(&p) - 1); } return 1; } static int ogm_dshow_header(AVFormatContext *s, int idx) { struct ogg *ogg = s->priv_data; struct ogg_stream *os = ogg->streams + idx; AVStream *st = s->streams[idx]; uint8_t *p = os->buf + os->pstart; uint32_t t; if(!(*p & 1)) return 0; if(*p != 1) return 1; if (os->psize < 100) return AVERROR_INVALIDDATA; t = AV_RL32(p + 96); if(t == 0x05589f80){ if (os->psize < 184) return AVERROR_INVALIDDATA; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, AV_RL32(p + 68)); avpriv_set_pts_info(st, 64, AV_RL64(p + 164), 10000000); st->codecpar->width = AV_RL32(p + 176); st->codecpar->height = AV_RL32(p + 180); } else if(t == 0x05589f81){ if (os->psize < 136) return AVERROR_INVALIDDATA; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = ff_codec_get_id(ff_codec_wav_tags, AV_RL16(p + 124)); st->codecpar->channels = AV_RL16(p + 126); st->codecpar->sample_rate = AV_RL32(p + 128); st->codecpar->bit_rate = AV_RL32(p + 132) * 8; } return 1; } static int ogm_packet(AVFormatContext *s, int idx) { struct ogg *ogg = s->priv_data; struct ogg_stream *os = ogg->streams + idx; uint8_t *p = os->buf + os->pstart; int lb; if(*p & 8) os->pflags |= AV_PKT_FLAG_KEY; lb = ((*p & 2) << 1) | ((*p >> 6) & 3); if (os->psize < lb + 1) return AVERROR_INVALIDDATA; os->pstart += lb + 1; os->psize -= lb + 1; while (lb--) os->pduration += (uint64_t)p[lb+1] << (lb*8); return 0; } const struct ogg_codec ff_ogm_video_codec = { .magic = "\001video", .magicsize = 6, .header = ogm_header, .packet = ogm_packet, .granule_is_start = 1, .nb_header = 2, }; const struct ogg_codec ff_ogm_audio_codec = { .magic = "\001audio", .magicsize = 6, .header = ogm_header, .packet = ogm_packet, .granule_is_start = 1, .nb_header = 2, }; const struct ogg_codec ff_ogm_text_codec = { .magic = "\001text", .magicsize = 5, .header = ogm_header, .packet = ogm_packet, .granule_is_start = 1, .nb_header = 2, }; const struct ogg_codec ff_ogm_old_codec = { .magic = "\001Direct Show Samples embedded in Ogg", .magicsize = 35, .header = ogm_dshow_header, .packet = ogm_packet, .granule_is_start = 1, .nb_header = 1, };
null
null
null
null
72,164
14,038
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
14,038
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 "components/offline_pages/core/prefetch/stale_entry_finalizer_task.h" #include <array> #include "base/bind.h" #include "base/metrics/histogram_functions.h" #include "components/offline_pages/core/offline_store_utils.h" #include "components/offline_pages/core/prefetch/prefetch_dispatcher.h" #include "components/offline_pages/core/prefetch/prefetch_downloader.h" #include "components/offline_pages/core/prefetch/prefetch_types.h" #include "components/offline_pages/core/prefetch/store/prefetch_store.h" #include "sql/connection.h" #include "sql/statement.h" #include "sql/transaction.h" namespace offline_pages { using Result = StaleEntryFinalizerTask::Result; namespace { // If this time changes, we need to update the desciption in histograms.xml // for OfflinePages.Prefetching.StuckItemState. const int kStuckTimeLimitInDays = 7; const base::TimeDelta FreshnessPeriodForState(PrefetchItemState state) { switch (state) { // Bucket 1. case PrefetchItemState::NEW_REQUEST: return base::TimeDelta::FromDays(1); // Bucket 2. case PrefetchItemState::AWAITING_GCM: case PrefetchItemState::RECEIVED_GCM: case PrefetchItemState::RECEIVED_BUNDLE: return base::TimeDelta::FromDays(1); // Bucket 3. case PrefetchItemState::DOWNLOADING: case PrefetchItemState::IMPORTING: return kPrefetchDownloadLifetime; // The following states do not expire based on per bucket freshness so they // are not expected to be passed into this function. case PrefetchItemState::SENT_GENERATE_PAGE_BUNDLE: case PrefetchItemState::SENT_GET_OPERATION: case PrefetchItemState::DOWNLOADED: case PrefetchItemState::FINISHED: case PrefetchItemState::ZOMBIE: NOTREACHED(); } return base::TimeDelta::FromDays(1); } PrefetchItemErrorCode ErrorCodeForState(PrefetchItemState state) { switch (state) { // Valid values. case PrefetchItemState::NEW_REQUEST: return PrefetchItemErrorCode::STALE_AT_NEW_REQUEST; case PrefetchItemState::AWAITING_GCM: return PrefetchItemErrorCode::STALE_AT_AWAITING_GCM; case PrefetchItemState::RECEIVED_GCM: return PrefetchItemErrorCode::STALE_AT_RECEIVED_GCM; case PrefetchItemState::RECEIVED_BUNDLE: return PrefetchItemErrorCode::STALE_AT_RECEIVED_BUNDLE; case PrefetchItemState::DOWNLOADING: return PrefetchItemErrorCode::STALE_AT_DOWNLOADING; case PrefetchItemState::IMPORTING: return PrefetchItemErrorCode::STALE_AT_IMPORTING; // The following states do not expire based on per bucket freshness so they // are not expected to be passed into this function. case PrefetchItemState::SENT_GENERATE_PAGE_BUNDLE: case PrefetchItemState::SENT_GET_OPERATION: case PrefetchItemState::DOWNLOADED: case PrefetchItemState::FINISHED: case PrefetchItemState::ZOMBIE: NOTREACHED(); } return PrefetchItemErrorCode::STALE_AT_UNKNOWN; } bool FinalizeStaleItems(PrefetchItemState state, base::Time now, sql::Connection* db) { static const char kSql[] = "UPDATE prefetch_items SET state = ?, error_code = ?" " WHERE state = ? AND freshness_time < ?"; const int64_t earliest_fresh_db_time = store_utils::ToDatabaseTime(now - FreshnessPeriodForState(state)); sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt(0, static_cast<int>(PrefetchItemState::FINISHED)); statement.BindInt(1, static_cast<int>(ErrorCodeForState(state))); statement.BindInt(2, static_cast<int>(state)); statement.BindInt64(3, earliest_fresh_db_time); return statement.Run(); } bool MoreWorkInQueue(sql::Connection* db) { static const char kSql[] = "SELECT COUNT(*) FROM prefetch_items" " WHERE state NOT IN (?, ?)"; sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt(0, static_cast<int>(PrefetchItemState::ZOMBIE)); statement.BindInt(1, static_cast<int>(PrefetchItemState::AWAITING_GCM)); // In event of failure, assume more work exists. if (!statement.Step()) return true; return statement.ColumnInt(0) > 0; } // If the user shifted the clock backwards too far, our items will stay around // for a very long time. Don't allow that so we don't waste resources with // potentially outdated content. bool FinalizeFutureItems(PrefetchItemState state, base::Time now, sql::Connection* db) { static const char kSql[] = "UPDATE prefetch_items SET state = ?, error_code = ?" " WHERE state = ? AND freshness_time > ?"; const int64_t future_fresh_db_time_limit = store_utils::ToDatabaseTime(now + base::TimeDelta::FromDays(1)); sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt(0, static_cast<int>(PrefetchItemState::FINISHED)); statement.BindInt( 1, static_cast<int>( PrefetchItemErrorCode::MAXIMUM_CLOCK_BACKWARD_SKEW_EXCEEDED)); statement.BindInt(2, static_cast<int>(state)); statement.BindInt64(3, future_fresh_db_time_limit); return statement.Run(); } // If there is a bug in our code, an item might be stuck in the queue waiting // on an event that didn't happen. If so, report that item. void ReportStuckItems(base::Time now, sql::Connection* db) { static constexpr char kSql[] = "SELECT state FROM prefetch_items" " WHERE creation_time < ?"; const int64_t earliest_valid_creation_time = store_utils::ToDatabaseTime( now - base::TimeDelta::FromDays(kStuckTimeLimitInDays)); sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, earliest_valid_creation_time); while (statement.Step()) { base::UmaHistogramSparse("OfflinePages.Prefetching.StuckItemState", statement.ColumnInt(0)); } } Result FinalizeStaleEntriesSync(StaleEntryFinalizerTask::NowGetter now_getter, sql::Connection* db) { if (!db) return Result::NO_MORE_WORK; sql::Transaction transaction(db); if (!transaction.Begin()) return Result::NO_MORE_WORK; // Only the following states are supposed to expire based on per bucket // freshness. static constexpr std::array<PrefetchItemState, 6> expirable_states = {{ // Bucket 1. PrefetchItemState::NEW_REQUEST, // Bucket 2. PrefetchItemState::AWAITING_GCM, PrefetchItemState::RECEIVED_GCM, PrefetchItemState::RECEIVED_BUNDLE, // Bucket 3. PrefetchItemState::DOWNLOADING, PrefetchItemState::IMPORTING, }}; base::Time now = now_getter.Run(); for (PrefetchItemState state : expirable_states) { if (!FinalizeStaleItems(state, now, db)) return Result::NO_MORE_WORK; if (!FinalizeFutureItems(state, now, db)) return Result::NO_MORE_WORK; } // Items could also be stuck in a non-expirable state due to a bug, report // them. ReportStuckItems(now, db); Result result = Result::MORE_WORK_NEEDED; if (!MoreWorkInQueue(db)) result = Result::NO_MORE_WORK; // If all FinalizeStaleItems calls succeeded the transaction is committed. return transaction.Commit() ? result : Result::NO_MORE_WORK; } } // namespace StaleEntryFinalizerTask::StaleEntryFinalizerTask( PrefetchDispatcher* prefetch_dispatcher, PrefetchStore* prefetch_store) : prefetch_dispatcher_(prefetch_dispatcher), prefetch_store_(prefetch_store), now_getter_(base::BindRepeating(&base::Time::Now)), weak_ptr_factory_(this) { DCHECK(prefetch_dispatcher_); DCHECK(prefetch_store_); } StaleEntryFinalizerTask::~StaleEntryFinalizerTask() {} void StaleEntryFinalizerTask::Run() { prefetch_store_->Execute( base::BindOnce(&FinalizeStaleEntriesSync, now_getter_), base::BindOnce(&StaleEntryFinalizerTask::OnFinished, weak_ptr_factory_.GetWeakPtr())); } void StaleEntryFinalizerTask::SetNowGetterForTesting(NowGetter now_getter) { now_getter_ = now_getter; } void StaleEntryFinalizerTask::OnFinished(Result result) { final_status_ = result; if (final_status_ == Result::MORE_WORK_NEEDED) prefetch_dispatcher_->EnsureTaskScheduled(); DVLOG(1) << "Finalization task " << (result == Result::NO_MORE_WORK ? "not " : "") << "scheduling background processing."; TaskComplete(); } } // namespace offline_pages
null
null
null
null
10,901
46,105
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
46,105
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 "ash/wm/drag_window_controller.h" #include <algorithm> #include <memory> #include "ash/public/cpp/shell_window_ids.h" #include "ash/shell.h" #include "ash/wm/window_util.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_tree_owner.h" #include "ui/compositor/paint_context.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/display/display.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/wm/core/coordinate_conversion.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" namespace ash { // This keeps track of the drag window's state. It creates/destroys/updates // bounds and opacity based on the current bounds. class DragWindowController::DragWindowDetails : public aura::WindowDelegate { public: DragWindowDetails(const display::Display& display, aura::Window* original_window) : root_window_(Shell::GetRootWindowForDisplayId(display.id())) {} ~DragWindowDetails() override { delete drag_window_; DCHECK(!drag_window_); } void Update(aura::Window* original_window, const gfx::Rect& bounds_in_screen, const gfx::Point& drag_location_in_screen) { gfx::Rect root_bounds_in_screen = root_window_->GetBoundsInScreen(); if (!root_bounds_in_screen.Intersects(bounds_in_screen)) { delete drag_window_; // Make sure drag_window_ is reset so that new drag window will be created // when it becomes necessary again. DCHECK(!drag_window_); layer_owner_.reset(); return; } if (!drag_window_) CreateDragWindow(original_window, bounds_in_screen); gfx::Rect bounds_in_root = bounds_in_screen; ::wm::ConvertRectFromScreen(drag_window_->parent(), &bounds_in_root); drag_window_->SetBounds(bounds_in_root); if (root_bounds_in_screen.Contains(drag_location_in_screen)) { SetOpacity(original_window, 1.f); } else { drag_window_->SetBounds(bounds_in_root); gfx::Rect visible_bounds = root_bounds_in_screen; visible_bounds.Intersect(bounds_in_screen); SetOpacity(original_window, GetDragWindowOpacity(bounds_in_screen, visible_bounds)); } } private: friend class DragWindowController; void CreateDragWindow(aura::Window* original_window, const gfx::Rect& bounds_in_screen) { DCHECK(!drag_window_); original_window_ = original_window; drag_window_ = new aura::Window(this); int parent_id = original_window->parent()->id(); aura::Window* container = root_window_->GetChildById(parent_id); drag_window_->SetType(aura::client::WINDOW_TYPE_POPUP); drag_window_->SetTransparent(true); drag_window_->Init(ui::LAYER_TEXTURED); drag_window_->SetName("DragWindow"); drag_window_->set_id(kShellWindowId_PhantomWindow); drag_window_->SetProperty(aura::client::kAnimationsDisabledKey, true); container->AddChild(drag_window_); drag_window_->SetBounds(bounds_in_screen); ::wm::SetShadowElevation(drag_window_, ::wm::kShadowElevationActiveWindow); RecreateWindowLayers(original_window); layer_owner_->root()->SetVisible(true); drag_window_->layer()->Add(layer_owner_->root()); drag_window_->layer()->StackAtTop(layer_owner_->root()); // Show the widget after all the setups. drag_window_->Show(); // Fade the window in. ui::Layer* drag_layer = drag_window_->layer(); drag_layer->SetOpacity(0); ui::ScopedLayerAnimationSettings scoped_setter(drag_layer->GetAnimator()); drag_layer->SetOpacity(1); } void RecreateWindowLayers(aura::Window* original_window) { DCHECK(!layer_owner_.get()); layer_owner_ = ::wm::MirrorLayers(original_window, true /* sync_bounds */); // Place the layer at (0, 0) of the DragWindowController's window. gfx::Rect layer_bounds = layer_owner_->root()->bounds(); layer_bounds.set_origin(gfx::Point(0, 0)); layer_owner_->root()->SetBounds(layer_bounds); layer_owner_->root()->SetVisible(false); } void SetOpacity(const aura::Window* original_window, float opacity) { ui::Layer* layer = drag_window_->layer(); ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator()); layer->SetOpacity(opacity); layer_owner_->root()->SetOpacity(1.0f); } // aura::WindowDelegate: gfx::Size GetMinimumSize() const override { return gfx::Size(); } gfx::Size GetMaximumSize() const override { return gfx::Size(); } void OnBoundsChanged(const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) override {} gfx::NativeCursor GetCursor(const gfx::Point& point) override { return gfx::kNullCursor; } int GetNonClientComponent(const gfx::Point& point) const override { return HTNOWHERE; } bool ShouldDescendIntoChildForEventHandling( aura::Window* child, const gfx::Point& location) override { return false; } bool CanFocus() override { return false; } void OnCaptureLost() override {} void OnPaint(const ui::PaintContext& context) override {} void OnDeviceScaleFactorChanged(float old_device_scale_factor, float new_device_scale_factor) override {} void OnWindowDestroyed(aura::Window* window) override {} void OnWindowTargetVisibilityChanged(bool visible) override {} bool HasHitTestMask() const override { return false; } void GetHitTestMask(gfx::Path* mask) const override {} void OnWindowDestroying(aura::Window* window) override { DCHECK_EQ(drag_window_, window); drag_window_ = nullptr; } aura::Window* root_window_; aura::Window* drag_window_ = nullptr; // Owned by the container. aura::Window* original_window_ = nullptr; // The copy of window_->layer() and its descendants. std::unique_ptr<ui::LayerTreeOwner> layer_owner_; DISALLOW_COPY_AND_ASSIGN(DragWindowDetails); }; // static float DragWindowController::GetDragWindowOpacity( const gfx::Rect& window_bounds, const gfx::Rect& visible_bounds) { // The maximum opacity of the drag phantom window. static const float kMaxOpacity = 0.8f; return kMaxOpacity * visible_bounds.size().GetArea() / window_bounds.size().GetArea(); } DragWindowController::DragWindowController(aura::Window* window) : window_(window) { DCHECK(drag_windows_.empty()); display::Screen* screen = display::Screen::GetScreen(); display::Display current = screen->GetDisplayNearestWindow(window_); for (const display::Display& display : screen->GetAllDisplays()) { if (current.id() == display.id()) continue; drag_windows_.push_back( std::make_unique<DragWindowDetails>(display, window_)); } } DragWindowController::~DragWindowController() = default; void DragWindowController::Update(const gfx::Rect& bounds_in_screen, const gfx::Point& drag_location_in_screen) { for (std::unique_ptr<DragWindowDetails>& details : drag_windows_) details->Update(window_, bounds_in_screen, drag_location_in_screen); } int DragWindowController::GetDragWindowsCountForTest() const { int count = 0; for (const std::unique_ptr<DragWindowDetails>& details : drag_windows_) { if (details->drag_window_) count++; } return count; } const aura::Window* DragWindowController::GetDragWindowForTest( size_t index) const { for (const std::unique_ptr<DragWindowDetails>& details : drag_windows_) { if (details->drag_window_) { if (index == 0) return details->drag_window_; index--; } } return nullptr; } const ui::LayerTreeOwner* DragWindowController::GetDragLayerOwnerForTest( size_t index) const { for (const std::unique_ptr<DragWindowDetails>& details : drag_windows_) { if (details->layer_owner_) { if (index == 0) return details->layer_owner_.get(); index--; } } return nullptr; } void DragWindowController::RequestLayerPaintForTest() { ui::PaintContext context(nullptr, 1.0f, gfx::Rect(), window_->GetHost()->compositor()->is_pixel_canvas()); for (auto& details : drag_windows_) { std::vector<ui::Layer*> layers; layers.push_back(details->drag_window_->layer()); while (layers.size()) { ui::Layer* layer = layers.back(); layers.pop_back(); if (layer->delegate()) layer->delegate()->OnPaintLayer(context); for (auto* child : layer->children()) layers.push_back(child); } } } } // namespace ash
null
null
null
null
42,968
9,538
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
9,538
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 "net/nqe/network_quality_store.h" #include "base/location.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/network_change_notifier.h" namespace net { namespace nqe { namespace internal { NetworkQualityStore::NetworkQualityStore() : weak_ptr_factory_(this) { static_assert(kMaximumNetworkQualityCacheSize > 0, "Size of the network quality cache must be > 0"); // This limit should not be increased unless the logic for removing the // oldest cache entry is rewritten to use a doubly-linked-list LRU queue. static_assert(kMaximumNetworkQualityCacheSize <= 20, "Size of the network quality cache must <= 20"); } NetworkQualityStore::~NetworkQualityStore() { DCHECK(thread_checker_.CalledOnValidThread()); } void NetworkQualityStore::Add( const nqe::internal::NetworkID& network_id, const nqe::internal::CachedNetworkQuality& cached_network_quality) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_LE(cached_network_qualities_.size(), static_cast<size_t>(kMaximumNetworkQualityCacheSize)); if (cached_network_quality.effective_connection_type() == EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { return; } // Remove the entry from the map, if it is already present. cached_network_qualities_.erase(network_id); if (cached_network_qualities_.size() == kMaximumNetworkQualityCacheSize) { // Remove the oldest entry. CachedNetworkQualities::iterator oldest_entry_iterator = cached_network_qualities_.begin(); for (CachedNetworkQualities::iterator it = cached_network_qualities_.begin(); it != cached_network_qualities_.end(); ++it) { if ((it->second).OlderThan(oldest_entry_iterator->second)) oldest_entry_iterator = it; } cached_network_qualities_.erase(oldest_entry_iterator); } cached_network_qualities_.insert( std::make_pair(network_id, cached_network_quality)); DCHECK_LE(cached_network_qualities_.size(), static_cast<size_t>(kMaximumNetworkQualityCacheSize)); for (auto& observer : network_qualities_cache_observer_list_) observer.OnChangeInCachedNetworkQuality(network_id, cached_network_quality); } bool NetworkQualityStore::GetById( const nqe::internal::NetworkID& network_id, nqe::internal::CachedNetworkQuality* cached_network_quality) const { DCHECK(thread_checker_.CalledOnValidThread()); // First check if an exact match can be found. for (CachedNetworkQualities::const_iterator it = cached_network_qualities_.begin(); it != cached_network_qualities_.end(); ++it) { if (network_id.type != it->first.type || network_id.id != it->first.id) { // The |type| and |id| must match. continue; } // Check for an exact match, and return immediately if one is found. // It's possible that the current network does not have signal strength // available. In that case, return the cached network quality when the // signal strength was unavailable. if (network_id.signal_strength == it->first.signal_strength) { *cached_network_quality = it->second; return true; } } // Handle the case when current network does not have signal strength // available. Return the cached network quality that corresponds to the // highest signal strength. This ensures that the method returns the fastest // network quality possible for the current network, and serves as a // conservative estimate. if (network_id.signal_strength == INT32_MIN) { CachedNetworkQualities::const_iterator matching_it = cached_network_qualities_.end(); for (CachedNetworkQualities::const_iterator it = cached_network_qualities_.begin(); it != cached_network_qualities_.end(); ++it) { if (network_id.type != it->first.type || network_id.id != it->first.id) { // The |type| and |id| must match. continue; } // The cached network must have signal strength available. If the cached // signal strength is unavailable, then this case would have been handled // above. DCHECK_NE(INT32_MIN, it->first.signal_strength); if (matching_it == cached_network_qualities_.end() || it->first.signal_strength > matching_it->first.signal_strength) { matching_it = it; } } if (matching_it == cached_network_qualities_.end()) return false; *cached_network_quality = matching_it->second; return true; } // Finally, handle the case where the current network has a valid signal // strength, but there is no exact match. // |matching_it| points to the entry that has the same connection type and // id as |network_id|, and has the signal strength closest to the signal // stength of |network_id|. CachedNetworkQualities::const_iterator matching_it = cached_network_qualities_.end(); int matching_it_diff_signal_strength = INT32_MAX; // Find the closest estimate. for (CachedNetworkQualities::const_iterator it = cached_network_qualities_.begin(); it != cached_network_qualities_.end(); ++it) { if (network_id.type != it->first.type || network_id.id != it->first.id) { // The |type| and |id| must match. continue; } DCHECK_LE(0, network_id.signal_strength); // Determine if the signal strength of |network_id| is closer to the // signal strength of the network at |it| then that of the network at // |matching_it|. int diff_signal_strength = std::abs(network_id.signal_strength - it->first.signal_strength); if (it->first.signal_strength == INT32_MIN) { // Current network has signal strength available. However, the persisted // network does not. Set the |diff_signal_strength| to INT32_MAX. This // ensures that if an entry with a valid signal strength is found later // during iteration, then that entry will be used. If no entry with valid // signal strength is found, then this entry will be used. diff_signal_strength = INT32_MAX; } if (matching_it == cached_network_qualities_.end() || diff_signal_strength < matching_it_diff_signal_strength) { matching_it = it; matching_it_diff_signal_strength = diff_signal_strength; } } if (matching_it == cached_network_qualities_.end()) return false; *cached_network_quality = matching_it->second; return true; } void NetworkQualityStore::AddNetworkQualitiesCacheObserver( NetworkQualitiesCacheObserver* observer) { DCHECK(thread_checker_.CalledOnValidThread()); network_qualities_cache_observer_list_.AddObserver(observer); // Notify the |observer| on the next message pump since |observer| may not // be completely set up for receiving the callbacks. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&NetworkQualityStore::NotifyCacheObserverIfPresent, weak_ptr_factory_.GetWeakPtr(), observer)); } void NetworkQualityStore::RemoveNetworkQualitiesCacheObserver( NetworkQualitiesCacheObserver* observer) { DCHECK(thread_checker_.CalledOnValidThread()); network_qualities_cache_observer_list_.RemoveObserver(observer); } void NetworkQualityStore::NotifyCacheObserverIfPresent( NetworkQualitiesCacheObserver* observer) const { DCHECK(thread_checker_.CalledOnValidThread()); if (!network_qualities_cache_observer_list_.HasObserver(observer)) return; for (const auto it : cached_network_qualities_) observer->OnChangeInCachedNetworkQuality(it.first, it.second); } } // namespace internal } // namespace nqe } // namespace net
null
null
null
null
6,401
9,601
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
174,596
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* NetWinder Floating Point Emulator (c) Rebel.COM, 1998,1999 (c) Philip Blundell, 2001 Direct questions, comments to Scott Bambrough <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __FPOPCODE_H__ #define __FPOPCODE_H__ /* ARM Floating Point Instruction Classes | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |c o n d|1 1 0 P|U|u|W|L| Rn |v| Fd |0|0|0|1| o f f s e t | CPDT |c o n d|1 1 0 P|U|w|W|L| Rn |x| Fd |0|0|1|0| o f f s e t | CPDT (copro 2) | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |c o n d|1 1 1 0|a|b|c|d|e| Fn |j| Fd |0|0|0|1|f|g|h|0|i| Fm | CPDO |c o n d|1 1 1 0|a|b|c|L|e| Fn | Rd |0|0|0|1|f|g|h|1|i| Fm | CPRT |c o n d|1 1 1 0|a|b|c|1|e| Fn |1|1|1|1|0|0|0|1|f|g|h|1|i| Fm | comparisons | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | CPDT data transfer instructions LDF, STF, LFM (copro 2), SFM (copro 2) CPDO dyadic arithmetic instructions ADF, MUF, SUF, RSF, DVF, RDF, POW, RPW, RMF, FML, FDV, FRD, POL CPDO monadic arithmetic instructions MVF, MNF, ABS, RND, SQT, LOG, LGN, EXP, SIN, COS, TAN, ASN, ACS, ATN, URD, NRM CPRT joint arithmetic/data transfer instructions FIX (arithmetic followed by load/store) FLT (load/store followed by arithmetic) CMF, CNF CMFE, CNFE (comparisons) WFS, RFS (write/read floating point status register) WFC, RFC (write/read floating point control register) cond condition codes P pre/post index bit: 0 = postindex, 1 = preindex U up/down bit: 0 = stack grows down, 1 = stack grows up W write back bit: 1 = update base register (Rn) L load/store bit: 0 = store, 1 = load Rn base register Rd destination/source register Fd floating point destination register Fn floating point source register Fm floating point source register or floating point constant uv transfer length (TABLE 1) wx register count (TABLE 2) abcd arithmetic opcode (TABLES 3 & 4) ef destination size (rounding precision) (TABLE 5) gh rounding mode (TABLE 6) j dyadic/monadic bit: 0 = dyadic, 1 = monadic i constant bit: 1 = constant (TABLE 6) */ /* TABLE 1 +-------------------------+---+---+---------+---------+ | Precision | u | v | FPSR.EP | length | +-------------------------+---+---+---------+---------+ | Single | 0 | 0 | x | 1 words | | Double | 1 | 1 | x | 2 words | | Extended | 1 | 1 | x | 3 words | | Packed decimal | 1 | 1 | 0 | 3 words | | Expanded packed decimal | 1 | 1 | 1 | 4 words | +-------------------------+---+---+---------+---------+ Note: x = don't care */ /* TABLE 2 +---+---+---------------------------------+ | w | x | Number of registers to transfer | +---+---+---------------------------------+ | 0 | 1 | 1 | | 1 | 0 | 2 | | 1 | 1 | 3 | | 0 | 0 | 4 | +---+---+---------------------------------+ */ /* TABLE 3: Dyadic Floating Point Opcodes +---+---+---+---+----------+-----------------------+-----------------------+ | a | b | c | d | Mnemonic | Description | Operation | +---+---+---+---+----------+-----------------------+-----------------------+ | 0 | 0 | 0 | 0 | ADF | Add | Fd := Fn + Fm | | 0 | 0 | 0 | 1 | MUF | Multiply | Fd := Fn * Fm | | 0 | 0 | 1 | 0 | SUF | Subtract | Fd := Fn - Fm | | 0 | 0 | 1 | 1 | RSF | Reverse subtract | Fd := Fm - Fn | | 0 | 1 | 0 | 0 | DVF | Divide | Fd := Fn / Fm | | 0 | 1 | 0 | 1 | RDF | Reverse divide | Fd := Fm / Fn | | 0 | 1 | 1 | 0 | POW | Power | Fd := Fn ^ Fm | | 0 | 1 | 1 | 1 | RPW | Reverse power | Fd := Fm ^ Fn | | 1 | 0 | 0 | 0 | RMF | Remainder | Fd := IEEE rem(Fn/Fm) | | 1 | 0 | 0 | 1 | FML | Fast Multiply | Fd := Fn * Fm | | 1 | 0 | 1 | 0 | FDV | Fast Divide | Fd := Fn / Fm | | 1 | 0 | 1 | 1 | FRD | Fast reverse divide | Fd := Fm / Fn | | 1 | 1 | 0 | 0 | POL | Polar angle (ArcTan2) | Fd := arctan2(Fn,Fm) | | 1 | 1 | 0 | 1 | | undefined instruction | trap | | 1 | 1 | 1 | 0 | | undefined instruction | trap | | 1 | 1 | 1 | 1 | | undefined instruction | trap | +---+---+---+---+----------+-----------------------+-----------------------+ Note: POW, RPW, POL are deprecated, and are available for backwards compatibility only. */ /* TABLE 4: Monadic Floating Point Opcodes +---+---+---+---+----------+-----------------------+-----------------------+ | a | b | c | d | Mnemonic | Description | Operation | +---+---+---+---+----------+-----------------------+-----------------------+ | 0 | 0 | 0 | 0 | MVF | Move | Fd := Fm | | 0 | 0 | 0 | 1 | MNF | Move negated | Fd := - Fm | | 0 | 0 | 1 | 0 | ABS | Absolute value | Fd := abs(Fm) | | 0 | 0 | 1 | 1 | RND | Round to integer | Fd := int(Fm) | | 0 | 1 | 0 | 0 | SQT | Square root | Fd := sqrt(Fm) | | 0 | 1 | 0 | 1 | LOG | Log base 10 | Fd := log10(Fm) | | 0 | 1 | 1 | 0 | LGN | Log base e | Fd := ln(Fm) | | 0 | 1 | 1 | 1 | EXP | Exponent | Fd := e ^ Fm | | 1 | 0 | 0 | 0 | SIN | Sine | Fd := sin(Fm) | | 1 | 0 | 0 | 1 | COS | Cosine | Fd := cos(Fm) | | 1 | 0 | 1 | 0 | TAN | Tangent | Fd := tan(Fm) | | 1 | 0 | 1 | 1 | ASN | Arc Sine | Fd := arcsin(Fm) | | 1 | 1 | 0 | 0 | ACS | Arc Cosine | Fd := arccos(Fm) | | 1 | 1 | 0 | 1 | ATN | Arc Tangent | Fd := arctan(Fm) | | 1 | 1 | 1 | 0 | URD | Unnormalized round | Fd := int(Fm) | | 1 | 1 | 1 | 1 | NRM | Normalize | Fd := norm(Fm) | +---+---+---+---+----------+-----------------------+-----------------------+ Note: LOG, LGN, EXP, SIN, COS, TAN, ASN, ACS, ATN are deprecated, and are available for backwards compatibility only. */ /* TABLE 5 +-------------------------+---+---+ | Rounding Precision | e | f | +-------------------------+---+---+ | IEEE Single precision | 0 | 0 | | IEEE Double precision | 0 | 1 | | IEEE Extended precision | 1 | 0 | | undefined (trap) | 1 | 1 | +-------------------------+---+---+ */ /* TABLE 5 +---------------------------------+---+---+ | Rounding Mode | g | h | +---------------------------------+---+---+ | Round to nearest (default) | 0 | 0 | | Round toward plus infinity | 0 | 1 | | Round toward negative infinity | 1 | 0 | | Round toward zero | 1 | 1 | +---------------------------------+---+---+ */ /* === === Definitions for load and store instructions === */ /* bit masks */ #define BIT_PREINDEX 0x01000000 #define BIT_UP 0x00800000 #define BIT_WRITE_BACK 0x00200000 #define BIT_LOAD 0x00100000 /* masks for load/store */ #define MASK_CPDT 0x0c000000 /* data processing opcode */ #define MASK_OFFSET 0x000000ff #define MASK_TRANSFER_LENGTH 0x00408000 #define MASK_REGISTER_COUNT MASK_TRANSFER_LENGTH #define MASK_COPROCESSOR 0x00000f00 /* Tests for transfer length */ #define TRANSFER_SINGLE 0x00000000 #define TRANSFER_DOUBLE 0x00008000 #define TRANSFER_EXTENDED 0x00400000 #define TRANSFER_PACKED MASK_TRANSFER_LENGTH /* Get the coprocessor number from the opcode. */ #define getCoprocessorNumber(opcode) ((opcode & MASK_COPROCESSOR) >> 8) /* Get the offset from the opcode. */ #define getOffset(opcode) (opcode & MASK_OFFSET) /* Tests for specific data transfer load/store opcodes. */ #define TEST_OPCODE(opcode,mask) (((opcode) & (mask)) == (mask)) #define LOAD_OP(opcode) TEST_OPCODE((opcode),MASK_CPDT | BIT_LOAD) #define STORE_OP(opcode) ((opcode & (MASK_CPDT | BIT_LOAD)) == MASK_CPDT) #define LDF_OP(opcode) (LOAD_OP(opcode) && (getCoprocessorNumber(opcode) == 1)) #define LFM_OP(opcode) (LOAD_OP(opcode) && (getCoprocessorNumber(opcode) == 2)) #define STF_OP(opcode) (STORE_OP(opcode) && (getCoprocessorNumber(opcode) == 1)) #define SFM_OP(opcode) (STORE_OP(opcode) && (getCoprocessorNumber(opcode) == 2)) #define PREINDEXED(opcode) ((opcode & BIT_PREINDEX) != 0) #define POSTINDEXED(opcode) ((opcode & BIT_PREINDEX) == 0) #define BIT_UP_SET(opcode) ((opcode & BIT_UP) != 0) #define BIT_UP_CLEAR(opcode) ((opcode & BIT_DOWN) == 0) #define WRITE_BACK(opcode) ((opcode & BIT_WRITE_BACK) != 0) #define LOAD(opcode) ((opcode & BIT_LOAD) != 0) #define STORE(opcode) ((opcode & BIT_LOAD) == 0) /* === === Definitions for arithmetic instructions === */ /* bit masks */ #define BIT_MONADIC 0x00008000 #define BIT_CONSTANT 0x00000008 #define CONSTANT_FM(opcode) ((opcode & BIT_CONSTANT) != 0) #define MONADIC_INSTRUCTION(opcode) ((opcode & BIT_MONADIC) != 0) /* instruction identification masks */ #define MASK_CPDO 0x0e000000 /* arithmetic opcode */ #define MASK_ARITHMETIC_OPCODE 0x00f08000 #define MASK_DESTINATION_SIZE 0x00080080 /* dyadic arithmetic opcodes. */ #define ADF_CODE 0x00000000 #define MUF_CODE 0x00100000 #define SUF_CODE 0x00200000 #define RSF_CODE 0x00300000 #define DVF_CODE 0x00400000 #define RDF_CODE 0x00500000 #define POW_CODE 0x00600000 #define RPW_CODE 0x00700000 #define RMF_CODE 0x00800000 #define FML_CODE 0x00900000 #define FDV_CODE 0x00a00000 #define FRD_CODE 0x00b00000 #define POL_CODE 0x00c00000 /* 0x00d00000 is an invalid dyadic arithmetic opcode */ /* 0x00e00000 is an invalid dyadic arithmetic opcode */ /* 0x00f00000 is an invalid dyadic arithmetic opcode */ /* monadic arithmetic opcodes. */ #define MVF_CODE 0x00008000 #define MNF_CODE 0x00108000 #define ABS_CODE 0x00208000 #define RND_CODE 0x00308000 #define SQT_CODE 0x00408000 #define LOG_CODE 0x00508000 #define LGN_CODE 0x00608000 #define EXP_CODE 0x00708000 #define SIN_CODE 0x00808000 #define COS_CODE 0x00908000 #define TAN_CODE 0x00a08000 #define ASN_CODE 0x00b08000 #define ACS_CODE 0x00c08000 #define ATN_CODE 0x00d08000 #define URD_CODE 0x00e08000 #define NRM_CODE 0x00f08000 /* === === Definitions for register transfer and comparison instructions === */ #define MASK_CPRT 0x0e000010 /* register transfer opcode */ #define MASK_CPRT_CODE 0x00f00000 #define FLT_CODE 0x00000000 #define FIX_CODE 0x00100000 #define WFS_CODE 0x00200000 #define RFS_CODE 0x00300000 #define WFC_CODE 0x00400000 #define RFC_CODE 0x00500000 #define CMF_CODE 0x00900000 #define CNF_CODE 0x00b00000 #define CMFE_CODE 0x00d00000 #define CNFE_CODE 0x00f00000 /* === === Common definitions === */ /* register masks */ #define MASK_Rd 0x0000f000 #define MASK_Rn 0x000f0000 #define MASK_Fd 0x00007000 #define MASK_Fm 0x00000007 #define MASK_Fn 0x00070000 /* condition code masks */ #define CC_MASK 0xf0000000 #define CC_NEGATIVE 0x80000000 #define CC_ZERO 0x40000000 #define CC_CARRY 0x20000000 #define CC_OVERFLOW 0x10000000 #define CC_EQ 0x00000000 #define CC_NE 0x10000000 #define CC_CS 0x20000000 #define CC_HS CC_CS #define CC_CC 0x30000000 #define CC_LO CC_CC #define CC_MI 0x40000000 #define CC_PL 0x50000000 #define CC_VS 0x60000000 #define CC_VC 0x70000000 #define CC_HI 0x80000000 #define CC_LS 0x90000000 #define CC_GE 0xa0000000 #define CC_LT 0xb0000000 #define CC_GT 0xc0000000 #define CC_LE 0xd0000000 #define CC_AL 0xe0000000 #define CC_NV 0xf0000000 /* rounding masks/values */ #define MASK_ROUNDING_MODE 0x00000060 #define ROUND_TO_NEAREST 0x00000000 #define ROUND_TO_PLUS_INFINITY 0x00000020 #define ROUND_TO_MINUS_INFINITY 0x00000040 #define ROUND_TO_ZERO 0x00000060 #define MASK_ROUNDING_PRECISION 0x00080080 #define ROUND_SINGLE 0x00000000 #define ROUND_DOUBLE 0x00000080 #define ROUND_EXTENDED 0x00080000 /* Get the condition code from the opcode. */ #define getCondition(opcode) (opcode >> 28) /* Get the source register from the opcode. */ #define getRn(opcode) ((opcode & MASK_Rn) >> 16) /* Get the destination floating point register from the opcode. */ #define getFd(opcode) ((opcode & MASK_Fd) >> 12) /* Get the first source floating point register from the opcode. */ #define getFn(opcode) ((opcode & MASK_Fn) >> 16) /* Get the second source floating point register from the opcode. */ #define getFm(opcode) (opcode & MASK_Fm) /* Get the destination register from the opcode. */ #define getRd(opcode) ((opcode & MASK_Rd) >> 12) /* Get the rounding mode from the opcode. */ #define getRoundingMode(opcode) ((opcode & MASK_ROUNDING_MODE) >> 5) #ifdef CONFIG_FPE_NWFPE_XP static inline floatx80 __pure getExtendedConstant(const unsigned int nIndex) { extern const floatx80 floatx80Constant[]; return floatx80Constant[nIndex]; } #endif static inline float64 __pure getDoubleConstant(const unsigned int nIndex) { extern const float64 float64Constant[]; return float64Constant[nIndex]; } static inline float32 __pure getSingleConstant(const unsigned int nIndex) { extern const float32 float32Constant[]; return float32Constant[nIndex]; } static inline unsigned int getTransferLength(const unsigned int opcode) { unsigned int nRc; switch (opcode & MASK_TRANSFER_LENGTH) { case 0x00000000: nRc = 1; break; /* single precision */ case 0x00008000: nRc = 2; break; /* double precision */ case 0x00400000: nRc = 3; break; /* extended precision */ default: nRc = 0; } return (nRc); } static inline unsigned int getRegisterCount(const unsigned int opcode) { unsigned int nRc; switch (opcode & MASK_REGISTER_COUNT) { case 0x00000000: nRc = 4; break; case 0x00008000: nRc = 1; break; case 0x00400000: nRc = 2; break; case 0x00408000: nRc = 3; break; default: nRc = 0; } return (nRc); } static inline unsigned int getRoundingPrecision(const unsigned int opcode) { unsigned int nRc; switch (opcode & MASK_ROUNDING_PRECISION) { case 0x00000000: nRc = 1; break; case 0x00000080: nRc = 2; break; case 0x00080000: nRc = 3; break; default: nRc = 0; } return (nRc); } static inline unsigned int getDestinationSize(const unsigned int opcode) { unsigned int nRc; switch (opcode & MASK_DESTINATION_SIZE) { case 0x00000000: nRc = typeSingle; break; case 0x00000080: nRc = typeDouble; break; case 0x00080000: nRc = typeExtended; break; default: nRc = typeNone; } return (nRc); } extern const float64 float64Constant[]; extern const float32 float32Constant[]; #endif
null
null
null
null
82,943
21,822
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
21,822
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 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 "content/renderer/accessibility/aom_content_ax_tree.h" #include <string> #include "content/common/ax_content_node_data.h" #include "content/renderer/accessibility/render_accessibility_impl.h" #include "third_party/blink/public/web/web_ax_enums.h" #include "ui/accessibility/ax_enum_util.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node.h" namespace { ax::mojom::BoolAttribute GetCorrespondingAXAttribute( blink::WebAOMBoolAttribute attr) { switch (attr) { case blink::WebAOMBoolAttribute::AOM_ATTR_ATOMIC: return ax::mojom::BoolAttribute::kLiveAtomic; case blink::WebAOMBoolAttribute::AOM_ATTR_BUSY: return ax::mojom::BoolAttribute::kBusy; case blink::WebAOMBoolAttribute::AOM_ATTR_MODAL: return ax::mojom::BoolAttribute::kModal; case blink::WebAOMBoolAttribute::AOM_ATTR_SELECTED: return ax::mojom::BoolAttribute::kSelected; default: return ax::mojom::BoolAttribute::kNone; } } ax::mojom::IntAttribute GetCorrespondingAXAttribute( blink::WebAOMIntAttribute attr) { switch (attr) { case blink::WebAOMIntAttribute::AOM_ATTR_COLUMN_COUNT: return ax::mojom::IntAttribute::kTableColumnCount; case blink::WebAOMIntAttribute::AOM_ATTR_COLUMN_INDEX: return ax::mojom::IntAttribute::kTableColumnIndex; case blink::WebAOMIntAttribute::AOM_ATTR_COLUMN_SPAN: return ax::mojom::IntAttribute::kTableCellColumnSpan; case blink::WebAOMIntAttribute::AOM_ATTR_HIERARCHICAL_LEVEL: return ax::mojom::IntAttribute::kHierarchicalLevel; case blink::WebAOMIntAttribute::AOM_ATTR_POS_IN_SET: return ax::mojom::IntAttribute::kPosInSet; case blink::WebAOMIntAttribute::AOM_ATTR_ROW_COUNT: return ax::mojom::IntAttribute::kTableRowCount; case blink::WebAOMIntAttribute::AOM_ATTR_ROW_INDEX: return ax::mojom::IntAttribute::kTableRowIndex; case blink::WebAOMIntAttribute::AOM_ATTR_ROW_SPAN: return ax::mojom::IntAttribute::kTableCellRowSpan; case blink::WebAOMIntAttribute::AOM_ATTR_SET_SIZE: return ax::mojom::IntAttribute::kSetSize; default: return ax::mojom::IntAttribute::kNone; } } ax::mojom::FloatAttribute GetCorrespondingAXAttribute( blink::WebAOMFloatAttribute attr) { switch (attr) { case blink::WebAOMFloatAttribute::AOM_ATTR_VALUE_MIN: return ax::mojom::FloatAttribute::kMinValueForRange; case blink::WebAOMFloatAttribute::AOM_ATTR_VALUE_MAX: return ax::mojom::FloatAttribute::kMaxValueForRange; case blink::WebAOMFloatAttribute::AOM_ATTR_VALUE_NOW: return ax::mojom::FloatAttribute::kValueForRange; default: return ax::mojom::FloatAttribute::kNone; } } ax::mojom::StringAttribute GetCorrespondingAXAttribute( blink::WebAOMStringAttribute attr) { switch (attr) { case blink::WebAOMStringAttribute::AOM_ATTR_AUTOCOMPLETE: return ax::mojom::StringAttribute::kAutoComplete; case blink::WebAOMStringAttribute::AOM_ATTR_KEY_SHORTCUTS: return ax::mojom::StringAttribute::kKeyShortcuts; case blink::WebAOMStringAttribute::AOM_ATTR_NAME: return ax::mojom::StringAttribute::kName; case blink::WebAOMStringAttribute::AOM_ATTR_PLACEHOLDER: return ax::mojom::StringAttribute::kPlaceholder; case blink::WebAOMStringAttribute::AOM_ATTR_ROLE_DESCRIPTION: return ax::mojom::StringAttribute::kRoleDescription; case blink::WebAOMStringAttribute::AOM_ATTR_VALUE_TEXT: return ax::mojom::StringAttribute::kValue; default: return ax::mojom::StringAttribute::kNone; } } ax::mojom::Restriction GetCorrespondingRestrictionFlag( blink::WebAOMBoolAttribute attr) { switch (attr) { case blink::WebAOMBoolAttribute::AOM_ATTR_DISABLED: return ax::mojom::Restriction::kDisabled; case blink::WebAOMBoolAttribute::AOM_ATTR_READONLY: return ax::mojom::Restriction::kReadOnly; default: return ax::mojom::Restriction::kNone; } } ax::mojom::State GetCorrespondingStateFlag(blink::WebAOMBoolAttribute attr) { switch (attr) { case blink::WebAOMBoolAttribute::AOM_ATTR_EXPANDED: return ax::mojom::State::kExpanded; case blink::WebAOMBoolAttribute::AOM_ATTR_MULTILINE: return ax::mojom::State::kMultiline; case blink::WebAOMBoolAttribute::AOM_ATTR_MULTISELECTABLE: return ax::mojom::State::kMultiselectable; case blink::WebAOMBoolAttribute::AOM_ATTR_REQUIRED: return ax::mojom::State::kRequired; default: return ax::mojom::State::kNone; } } } // namespace namespace content { AomContentAxTree::AomContentAxTree(RenderFrameImpl* render_frame) : render_frame_(render_frame) {} bool AomContentAxTree::ComputeAccessibilityTree() { AXContentTreeUpdate content_tree_update; RenderAccessibilityImpl::SnapshotAccessibilityTree( render_frame_, &content_tree_update, ui::kAXModeComplete); // Hack to convert between AXContentNodeData and AXContentTreeData to just // AXNodeData and AXTreeData to preserve content specific attributes while // still being able to use AXTree's Unserialize method. ui::AXTreeUpdate tree_update; tree_update.has_tree_data = content_tree_update.has_tree_data; ui::AXTreeData* tree_data = &(content_tree_update.tree_data); tree_update.tree_data = *tree_data; tree_update.node_id_to_clear = content_tree_update.node_id_to_clear; tree_update.root_id = content_tree_update.root_id; tree_update.nodes.assign(content_tree_update.nodes.begin(), content_tree_update.nodes.end()); return tree_.Unserialize(tree_update); } bool AomContentAxTree::GetBoolAttributeForAXNode( int32_t ax_id, blink::WebAOMBoolAttribute attr, bool* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; if (GetCorrespondingRestrictionFlag(attr) != ax::mojom::Restriction::kNone) { return GetRestrictionAttributeForAXNode(ax_id, attr, out_param); } else if (GetCorrespondingStateFlag(attr) != ax::mojom::State::kNone) { return GetStateAttributeForAXNode(ax_id, attr, out_param); } ax::mojom::BoolAttribute ax_attr = GetCorrespondingAXAttribute(attr); return node->data().GetBoolAttribute(ax_attr, out_param); } bool AomContentAxTree::GetCheckedStateForAXNode(int32_t ax_id, blink::WebString* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; ax::mojom::CheckedState checked_state = static_cast<ax::mojom::CheckedState>( node->data().GetIntAttribute(ax::mojom::IntAttribute::kCheckedState)); *out_param = blink::WebString::FromUTF8(ui::ToString(checked_state)); return true; } bool AomContentAxTree::GetIntAttributeForAXNode(int32_t ax_id, blink::WebAOMIntAttribute attr, int32_t* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; ax::mojom::IntAttribute ax_attr = GetCorrespondingAXAttribute(attr); return node->data().GetIntAttribute(ax_attr, out_param); } bool AomContentAxTree::GetRestrictionAttributeForAXNode( int32_t ax_id, blink::WebAOMBoolAttribute attr, bool* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; // Disabled and readOnly are stored on the node data as an int attribute, // which indicates which type of kRestriction applies. ax::mojom::Restriction restriction = static_cast<ax::mojom::Restriction>( node->data().GetIntAttribute(ax::mojom::IntAttribute::kRestriction)); ax::mojom::Restriction ax_attr = GetCorrespondingRestrictionFlag(attr); *out_param = (restriction == ax_attr); return true; } bool AomContentAxTree::GetFloatAttributeForAXNode( int32_t ax_id, blink::WebAOMFloatAttribute attr, float* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; ax::mojom::FloatAttribute ax_attr = GetCorrespondingAXAttribute(attr); return node->data().GetFloatAttribute(ax_attr, out_param); } bool AomContentAxTree::GetStateAttributeForAXNode( int32_t ax_id, blink::WebAOMBoolAttribute attr, bool* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; *out_param = node->data().HasState(GetCorrespondingStateFlag(attr)); return true; } bool AomContentAxTree::GetStringAttributeForAXNode( int32_t ax_id, blink::WebAOMStringAttribute attr, blink::WebString* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); std::string out_string; if (node && node->data().GetStringAttribute(GetCorrespondingAXAttribute(attr), &out_string)) { *out_param = blink::WebString::FromUTF8(out_string.c_str()); return true; } return false; } bool AomContentAxTree::GetRoleForAXNode(int32_t ax_id, blink::WebString* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; *out_param = blink::WebString::FromUTF8(ui::ToString(node->data().role)); return true; } bool AomContentAxTree::GetParentIdForAXNode(int32_t ax_id, int32_t* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node || !node->parent()) return false; *out_param = node->parent()->id(); return true; } bool AomContentAxTree::GetFirstChildIdForAXNode(int32_t ax_id, int32_t* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node || !node->child_count()) return false; ui::AXNode* child = node->ChildAtIndex(0); DCHECK(child); *out_param = child->id(); return true; } bool AomContentAxTree::GetLastChildIdForAXNode(int32_t ax_id, int32_t* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node || !node->child_count()) return false; ui::AXNode* child = node->ChildAtIndex(node->child_count() - 1); DCHECK(child); *out_param = child->id(); return true; } bool AomContentAxTree::GetPreviousSiblingIdForAXNode(int32_t ax_id, int32_t* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; int index_in_parent = node->index_in_parent(); // Assumption: only when this node is the first child, does it not have a // previous sibling. if (index_in_parent == 0) return false; ui::AXNode* sibling = node->parent()->ChildAtIndex(index_in_parent - 1); DCHECK(sibling); *out_param = sibling->id(); return true; } bool AomContentAxTree::GetNextSiblingIdForAXNode(int32_t ax_id, int32_t* out_param) { ui::AXNode* node = tree_.GetFromId(ax_id); if (!node) return false; int index_in_parent = node->index_in_parent(); // Assumption: When this node is the last child, it does not have a next // sibling. if (index_in_parent == (node->parent()->child_count() - 1)) return false; ui::AXNode* sibling = node->parent()->ChildAtIndex(index_in_parent + 1); DCHECK(sibling); *out_param = sibling->id(); return true; } } // namespace content
null
null
null
null
18,685
1,115
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
263,683
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
#include "io.h" int main(void) { long long rt, ach, acl, dsp; long long result; ach = 0x05; acl = 0xB4CB; dsp = 0x07; result = 0x000C; __asm ("wrdsp %1, 0x01\n\t" "mthi %2, $ac1\n\t" "mtlo %3, $ac1\n\t" "extp %0, $ac1, 0x03\n\t" "rddsp %1\n\t" : "=r"(rt), "+r"(dsp) : "r"(ach), "r"(acl) ); dsp = (dsp >> 14) & 0x01; if ((dsp != 0) || (result != rt)) { printf("extp wrong\n"); return -1; } ach = 0x05; acl = 0xB4CB; dsp = 0x01; __asm ("wrdsp %1, 0x01\n\t" "mthi %2, $ac1\n\t" "mtlo %3, $ac1\n\t" "extp %0, $ac1, 0x03\n\t" "rddsp %1\n\t" : "=r"(rt), "+r"(dsp) : "r"(ach), "r"(acl) ); dsp = (dsp >> 14) & 0x01; if (dsp != 1) { printf("extp wrong\n"); return -1; } return 0; }
null
null
null
null
121,807
57,648
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
57,648
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 "chrome/browser/chromeos/policy/temp_certs_cache_nss.h" #include <cert.h> #include <certdb.h> #include <secitem.h> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/macros.h" #include "base/run_loop.h" #include "net/cert/internal/cert_errors.h" #include "net/cert/internal/parse_certificate.h" #include "net/cert/pem_tokenizer.h" #include "net/der/input.h" #include "net/test/test_data_directory.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy { namespace { class TempCertsCacheNSSTest : public testing::Test { public: TempCertsCacheNSSTest() {} ~TempCertsCacheNSSTest() override {} protected: // Reads the certificates from |pem_cert_files|, assuming that each file // contains one CERTIFICATE block. Returns all certificates. // Note: This funcion uses ASSERT_ macros, so the caller must verify for // failures after it returns. void GetCertificatesFromFiles(std::vector<base::FilePath> pem_cert_files, std::vector<std::string>* out_x509_certs) { for (const auto& pem_cert_file : pem_cert_files) { std::string x509_cert; ASSERT_TRUE(base::ReadFileToString(pem_cert_file, &x509_cert)); out_x509_certs->push_back(std::move(x509_cert)); } } // Checks if the certificate stored in |pem_cert_file| can be found in the // default NSS certificate database using CERT_FindCertByName. // Stores the result in *|out_available|. // Note: This funcion uses ASSERT_ macros, so the caller must verify for // failures after it returns. void CheckIsCertificateAvailable(const base::FilePath& pem_cert_file, bool* out_available) { std::string cert_contents_buffer; net::der::Input subject; ASSERT_NO_FATAL_FAILURE(GetCertificateSubjectDN( pem_cert_file, &cert_contents_buffer, &subject)); SECItem subject_item; subject_item.len = subject.Length(); subject_item.data = const_cast<unsigned char*>(subject.UnsafeData()); net::ScopedCERTCertificate found_cert( CERT_FindCertByName(CERT_GetDefaultCertDB(), &subject_item)); *out_available = static_cast<bool>(found_cert); } // Determines the subject DN of the certificate stored in // |pem_cert_file|. Stores the result in *|out_subject|. // The der::Input data structure contains unowned pointers into the // certificate data buffer. The caller must pass a buffer in // |cert_contents_buffer| and ensure to only use *|out_subject| while // *|cert_contents_buffer| is in scope. // Note: This funcion uses ASSERT_ macros, so the caller must verify for // failures after it returns. void GetCertificateSubjectDN(const base::FilePath& pem_cert_file, std::string* cert_contents_buffer, net::der::Input* out_subject) { std::string file_data; ASSERT_TRUE(base::ReadFileToString(pem_cert_file, &file_data)); std::vector<std::string> pem_headers; pem_headers.push_back("CERTIFICATE"); net::PEMTokenizer pem_tokenizer(file_data, pem_headers); ASSERT_TRUE(pem_tokenizer.GetNext()); *cert_contents_buffer = pem_tokenizer.data(); // Parsing the certificate. net::der::Input tbs_certificate_tlv; net::der::Input signature_algorithm_tlv; net::der::BitString signature_value; net::CertErrors errors; ASSERT_TRUE(net::ParseCertificate( net::der::Input(cert_contents_buffer), &tbs_certificate_tlv, &signature_algorithm_tlv, &signature_value, &errors)); net::ParsedTbsCertificate tbs; net::ParseCertificateOptions options; options.allow_invalid_serial_numbers = true; ASSERT_TRUE( net::ParseTbsCertificate(tbs_certificate_tlv, options, &tbs, nullptr)); *out_subject = tbs.subject_tlv; } private: DISALLOW_COPY_AND_ASSIGN(TempCertsCacheNSSTest); }; // Checks that a certificate made available through the // TempCertsCacheNSS can be found by NSS. We specifically check for // lookup through the CERT_FindCertByName function, as this is what is used in // client certificate matching (see MatchClientCertificateIssuers in // net/third_party/nss/ssl/cmpcert.cc). Additionally, checks that the // certificate is not available after the TempCertsCacheNSS goes out of // scope. TEST_F(TempCertsCacheNSSTest, CertMadeAvailable) { base::FilePath cert_file_path = net::GetTestCertsDirectory().AppendASCII("client_1_ca.pem"); { std::vector<std::string> x509_certs; ASSERT_NO_FATAL_FAILURE( GetCertificatesFromFiles({cert_file_path}, &x509_certs)); TempCertsCacheNSS cache(x509_certs); bool cert_available = false; ASSERT_NO_FATAL_FAILURE( CheckIsCertificateAvailable(cert_file_path, &cert_available)); EXPECT_TRUE(cert_available); } bool cert_available_no_cache = true; ASSERT_NO_FATAL_FAILURE( CheckIsCertificateAvailable(cert_file_path, &cert_available_no_cache)); EXPECT_FALSE(cert_available_no_cache); } } // namespace } // namespace policy
null
null
null
null
54,511
61,763
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
61,763
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. #include "chrome/browser/themes/theme_service.h" #include "base/macros.h" #include "base/task_scheduler/task_scheduler.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/test/test_utils.h" namespace { // The toolbar color specified in the theme. const SkColor kThemeToolbarColor = 0xFFCFDDC0; bool UsingCustomTheme(const ThemeService& theme_service) { return !theme_service.UsingSystemTheme() && !theme_service.UsingDefaultTheme(); } class ThemeServiceBrowserTest : public ExtensionBrowserTest { public: ThemeServiceBrowserTest() { } ~ThemeServiceBrowserTest() override {} void SetUp() override { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ExtensionBrowserTest::SetUp(); } private: DISALLOW_COPY_AND_ASSIGN(ThemeServiceBrowserTest); }; // Test that the theme is recreated from the extension when the data pack is // unavailable or invalid (such as when the theme pack version is incremented). // The PRE_ part of the test installs the theme and changes where Chrome looks // for the theme data pack to make sure that Chrome does not find it. IN_PROC_BROWSER_TEST_F(ThemeServiceBrowserTest, PRE_ThemeDataPackInvalid) { Profile* profile = browser()->profile(); ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile); const ui::ThemeProvider& theme_provider = ThemeService::GetThemeProviderForProfile(profile); // Test initial state. EXPECT_FALSE(UsingCustomTheme(*theme_service)); EXPECT_NE(kThemeToolbarColor, theme_provider.GetColor(ThemeProperties::COLOR_TOOLBAR)); EXPECT_EQ(base::FilePath(), profile->GetPrefs()->GetFilePath(prefs::kCurrentThemePackFilename)); content::WindowedNotificationObserver theme_change_observer( chrome::NOTIFICATION_BROWSER_THEME_CHANGED, content::Source<ThemeService>(theme_service)); InstallExtension(test_data_dir_.AppendASCII("theme"), 1); theme_change_observer.Wait(); // Check that the theme was installed. EXPECT_TRUE(UsingCustomTheme(*theme_service)); EXPECT_EQ(kThemeToolbarColor, theme_provider.GetColor(ThemeProperties::COLOR_TOOLBAR)); EXPECT_NE(base::FilePath(), profile->GetPrefs()->GetFilePath(prefs::kCurrentThemePackFilename)); // Add a vestigial .pak file that should be removed when the new one is // created. // TODO(estade): remove when vestigial .pak file deletion is removed. base::ScopedAllowBlockingForTesting allow_blocking; EXPECT_EQ( 1, base::WriteFile(profile->GetPrefs() ->GetFilePath(prefs::kCurrentThemePackFilename) .AppendASCII("Cached Theme Material Design.pak"), "a", 1)); // Change the theme data pack path to an invalid location such that second // part of the test is forced to recreate the theme pack when the theme // service is initialized. profile->GetPrefs()->SetFilePath( prefs::kCurrentThemePackFilename, base::FilePath()); } IN_PROC_BROWSER_TEST_F(ThemeServiceBrowserTest, ThemeDataPackInvalid) { ThemeService* theme_service = ThemeServiceFactory::GetForProfile( browser()->profile()); const ui::ThemeProvider& theme_provider = ThemeService::GetThemeProviderForProfile(browser()->profile()); EXPECT_TRUE(UsingCustomTheme(*theme_service)); EXPECT_EQ(kThemeToolbarColor, theme_provider.GetColor(ThemeProperties::COLOR_TOOLBAR)); // TODO(estade): remove when vestigial .pak file deletion is removed. base::TaskScheduler::GetInstance()->FlushForTesting(); base::FilePath old_path = browser() ->profile() ->GetPrefs() ->GetFilePath(prefs::kCurrentThemePackFilename) .AppendASCII("Cached Theme Material Design.pak"); base::ScopedAllowBlockingForTesting allow_blocking; EXPECT_FALSE(base::PathExists(old_path)) << "File not deleted: " << old_path.value(); } } // namespace
null
null
null
null
58,626
29,262
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
29,262
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright (c) 2009-2017 The OTS 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 "ots.h" #include <sys/types.h> #include <zlib.h> #include <algorithm> #include <cstdlib> #include <cstring> #include <limits> #include <map> #include <vector> #include <woff2/decode.h> // The OpenType Font File // http://www.microsoft.com/typography/otspec/otff.htm #include "cff.h" #include "cmap.h" #include "cvt.h" #include "fpgm.h" #include "gasp.h" #include "gdef.h" #include "glyf.h" #include "gpos.h" #include "gsub.h" #include "hdmx.h" #include "head.h" #include "hhea.h" #include "hmtx.h" #include "kern.h" #include "loca.h" #include "ltsh.h" #include "math_.h" #include "maxp.h" #include "name.h" #include "os2.h" #include "ots.h" #include "post.h" #include "prep.h" #include "vdmx.h" #include "vhea.h" #include "vmtx.h" #include "vorg.h" // Graphite tables #ifdef OTS_GRAPHITE #include "feat.h" #include "glat.h" #include "gloc.h" #include "sile.h" #include "silf.h" #include "sill.h" #endif namespace ots { struct Arena { public: ~Arena() { for (std::vector<uint8_t*>::iterator i = hunks_.begin(); i != hunks_.end(); ++i) { delete[] *i; } } uint8_t* Allocate(size_t length) { uint8_t* p = new uint8_t[length]; hunks_.push_back(p); return p; } private: std::vector<uint8_t*> hunks_; }; }; // namespace ots namespace { #define OTS_MSG_TAG_(level,otf_,msg_,tag_) \ (OTS_MESSAGE_(level,otf_,"%c%c%c%c: %s", OTS_UNTAG(tag_), msg_), false) // Generate a message with or without a table tag, when 'header' is the FontFile pointer #define OTS_FAILURE_MSG_TAG(msg_,tag_) OTS_MSG_TAG_(0, header, msg_, tag_) #define OTS_FAILURE_MSG_HDR(...) OTS_FAILURE_MSG_(header, __VA_ARGS__) #define OTS_WARNING_MSG_HDR(...) OTS_WARNING_MSG_(header, __VA_ARGS__) bool CheckTag(uint32_t tag_value) { for (unsigned i = 0; i < 4; ++i) { const uint32_t check = tag_value & 0xff; if (check < 32 || check > 126) { return false; // non-ASCII character found. } tag_value >>= 8; } return true; } const struct { uint32_t tag; bool required; } supported_tables[] = { { OTS_TAG_MAXP, true }, { OTS_TAG_HEAD, true }, { OTS_TAG_OS2, true }, { OTS_TAG_CMAP, true }, { OTS_TAG_HHEA, true }, { OTS_TAG_HMTX, true }, { OTS_TAG_NAME, true }, { OTS_TAG_POST, true }, { OTS_TAG_LOCA, false }, { OTS_TAG_GLYF, false }, { OTS_TAG_CFF, false }, { OTS_TAG_VDMX, false }, { OTS_TAG_HDMX, false }, { OTS_TAG_GASP, false }, { OTS_TAG_CVT, false }, { OTS_TAG_FPGM, false }, { OTS_TAG_PREP, false }, { OTS_TAG_LTSH, false }, { OTS_TAG_VORG, false }, { OTS_TAG_KERN, false }, // We need to parse GDEF table in advance of parsing GSUB/GPOS tables // because they could refer GDEF table. { OTS_TAG_GDEF, false }, { OTS_TAG_GPOS, false }, { OTS_TAG_GSUB, false }, { OTS_TAG_VHEA, false }, { OTS_TAG_VMTX, false }, { OTS_TAG_MATH, false }, // Graphite tables #ifdef OTS_GRAPHITE { OTS_TAG_GLOC, false }, { OTS_TAG_GLAT, false }, { OTS_TAG_FEAT, false }, { OTS_TAG_SILF, false }, { OTS_TAG_SILE, false }, { OTS_TAG_SILL, false }, #endif { 0, false }, }; bool ProcessGeneric(ots::FontFile *header, ots::Font *font, uint32_t signature, ots::OTSStream *output, const uint8_t *data, size_t length, const std::vector<ots::TableEntry>& tables, ots::Buffer& file); bool ProcessTTF(ots::FontFile *header, ots::Font *font, ots::OTSStream *output, const uint8_t *data, size_t length, uint32_t offset = 0) { ots::Buffer file(data + offset, length - offset); if (offset > length) { return OTS_FAILURE_MSG_HDR("offset beyond end of file"); } // we disallow all files > 1GB in size for sanity. if (length > 1024 * 1024 * 1024) { return OTS_FAILURE_MSG_HDR("file exceeds 1GB"); } if (!file.ReadU32(&font->version)) { return OTS_FAILURE_MSG_HDR("error reading version tag"); } if (!ots::IsValidVersionTag(font->version)) { return OTS_FAILURE_MSG_HDR("invalid version tag"); } if (!file.ReadU16(&font->num_tables) || !file.ReadU16(&font->search_range) || !file.ReadU16(&font->entry_selector) || !file.ReadU16(&font->range_shift)) { return OTS_FAILURE_MSG_HDR("error reading table directory search header"); } // search_range is (Maximum power of 2 <= numTables) x 16. Thus, to avoid // overflow num_tables is, at most, 2^16 / 16 = 2^12 if (font->num_tables >= 4096 || font->num_tables < 1) { return OTS_FAILURE_MSG_HDR("excessive (or zero) number of tables"); } unsigned max_pow2 = 0; while (1u << (max_pow2 + 1) <= font->num_tables) { max_pow2++; } const uint16_t expected_search_range = (1u << max_pow2) << 4; // Don't call ots_failure() here since ~25% of fonts (250+ fonts) in // http://www.princexml.com/fonts/ have unexpected search_range value. if (font->search_range != expected_search_range) { OTS_WARNING_MSG_HDR("bad search range"); font->search_range = expected_search_range; // Fix the value. } // entry_selector is Log2(maximum power of 2 <= numTables) if (font->entry_selector != max_pow2) { return OTS_FAILURE_MSG_HDR("incorrect entrySelector for table directory"); } // range_shift is NumTables x 16-searchRange. We know that 16*num_tables // doesn't over flow because we range checked it above. Also, we know that // it's > font->search_range by construction of search_range. const uint16_t expected_range_shift = 16 * font->num_tables - font->search_range; if (font->range_shift != expected_range_shift) { OTS_WARNING_MSG_HDR("bad range shift"); font->range_shift = expected_range_shift; // the same as above. } // Next up is the list of tables. std::vector<ots::TableEntry> tables; for (unsigned i = 0; i < font->num_tables; ++i) { ots::TableEntry table; if (!file.ReadU32(&table.tag) || !file.ReadU32(&table.chksum) || !file.ReadU32(&table.offset) || !file.ReadU32(&table.length)) { return OTS_FAILURE_MSG_HDR("error reading table directory"); } table.uncompressed_length = table.length; tables.push_back(table); } return ProcessGeneric(header, font, font->version, output, data, length, tables, file); } bool ProcessTTC(ots::FontFile *header, ots::OTSStream *output, const uint8_t *data, size_t length, uint32_t index) { ots::Buffer file(data, length); // we disallow all files > 1GB in size for sanity. if (length > 1024 * 1024 * 1024) { return OTS_FAILURE_MSG_HDR("file exceeds 1GB"); } uint32_t ttc_tag; if (!file.ReadU32(&ttc_tag)) { return OTS_FAILURE_MSG_HDR("Error reading TTC tag"); } if (ttc_tag != OTS_TAG('t','t','c','f')) { return OTS_FAILURE_MSG_HDR("Invalid TTC tag"); } uint32_t ttc_version; if (!file.ReadU32(&ttc_version)) { return OTS_FAILURE_MSG_HDR("Error reading TTC version"); } if (ttc_version != 0x00010000 && ttc_version != 0x00020000) { return OTS_FAILURE_MSG_HDR("Invalid TTC version"); } uint32_t num_fonts; if (!file.ReadU32(&num_fonts)) { return OTS_FAILURE_MSG_HDR("Error reading number of TTC fonts"); } // Limit the allowed number of subfonts to have same memory allocation. if (num_fonts > 0x10000) { return OTS_FAILURE_MSG_HDR("Too many fonts in TTC"); } std::vector<uint32_t> offsets(num_fonts); for (unsigned i = 0; i < num_fonts; i++) { if (!file.ReadU32(&offsets[i])) { return OTS_FAILURE_MSG_HDR("Error reading offset to OffsetTable"); } } if (ttc_version == 0x00020000) { // We don't care about these fields of the header: // uint32_t dsig_tag, dsig_length, dsig_offset if (!file.Skip(3 * 4)) { return OTS_FAILURE_MSG_HDR("Error reading DSIG offset and length in TTC font"); } } if (index == static_cast<uint32_t>(-1)) { if (!output->WriteU32(ttc_tag) || !output->WriteU32(0x00010000) || !output->WriteU32(num_fonts) || !output->Seek((3 + num_fonts) * 4)) { return OTS_FAILURE_MSG_HDR("Error writing output"); } // Keep references to the fonts processed in the loop below, as we need // them for reused tables. std::vector<ots::Font> fonts(num_fonts, ots::Font(header)); for (unsigned i = 0; i < num_fonts; i++) { uint32_t out_offset = output->Tell(); if (!output->Seek((3 + i) * 4) || !output->WriteU32(out_offset) || !output->Seek(out_offset)) { return OTS_FAILURE_MSG_HDR("Error writing output"); } if (!ProcessTTF(header, &fonts[i], output, data, length, offsets[i])) { return false; } } return true; } else { if (index >= num_fonts) { return OTS_FAILURE_MSG_HDR("Requested font index is bigger than the number of fonts in the TTC file"); } ots::Font font(header); return ProcessTTF(header, &font, output, data, length, offsets[index]); } } bool ProcessWOFF(ots::FontFile *header, ots::Font *font, ots::OTSStream *output, const uint8_t *data, size_t length) { ots::Buffer file(data, length); // we disallow all files > 1GB in size for sanity. if (length > 1024 * 1024 * 1024) { return OTS_FAILURE_MSG_HDR("file exceeds 1GB"); } uint32_t woff_tag; if (!file.ReadU32(&woff_tag)) { return OTS_FAILURE_MSG_HDR("error reading WOFF marker"); } if (woff_tag != OTS_TAG('w','O','F','F')) { return OTS_FAILURE_MSG_HDR("invalid WOFF marker"); } if (!file.ReadU32(&font->version)) { return OTS_FAILURE_MSG_HDR("error reading version tag"); } if (!ots::IsValidVersionTag(font->version)) { return OTS_FAILURE_MSG_HDR("invalid version tag"); } uint32_t reported_length; if (!file.ReadU32(&reported_length) || length != reported_length) { return OTS_FAILURE_MSG_HDR("incorrect file size in WOFF header"); } if (!file.ReadU16(&font->num_tables) || !font->num_tables) { return OTS_FAILURE_MSG_HDR("error reading number of tables"); } uint16_t reserved_value; if (!file.ReadU16(&reserved_value) || reserved_value) { return OTS_FAILURE_MSG_HDR("error in reserved field of WOFF header"); } uint32_t reported_total_sfnt_size; if (!file.ReadU32(&reported_total_sfnt_size)) { return OTS_FAILURE_MSG_HDR("error reading total sfnt size"); } // We don't care about these fields of the header: // uint16_t major_version, minor_version if (!file.Skip(2 * 2)) { return OTS_FAILURE_MSG_HDR("Failed to read 'majorVersion' or 'minorVersion'"); } // Checks metadata block size. uint32_t meta_offset; uint32_t meta_length; uint32_t meta_length_orig; if (!file.ReadU32(&meta_offset) || !file.ReadU32(&meta_length) || !file.ReadU32(&meta_length_orig)) { return OTS_FAILURE_MSG_HDR("Failed to read header metadata block fields"); } if (meta_offset) { if (meta_offset >= length || length - meta_offset < meta_length) { return OTS_FAILURE_MSG_HDR("Invalid metadata block offset or length"); } } // Checks private data block size. uint32_t priv_offset; uint32_t priv_length; if (!file.ReadU32(&priv_offset) || !file.ReadU32(&priv_length)) { return OTS_FAILURE_MSG_HDR("Failed to read header private block fields"); } if (priv_offset) { if (priv_offset >= length || length - priv_offset < priv_length) { return OTS_FAILURE_MSG_HDR("Invalid private block offset or length"); } } // Next up is the list of tables. std::vector<ots::TableEntry> tables; uint32_t first_index = 0; uint32_t last_index = 0; // Size of sfnt header plus size of table records. uint64_t total_sfnt_size = 12 + 16 * font->num_tables; for (unsigned i = 0; i < font->num_tables; ++i) { ots::TableEntry table; if (!file.ReadU32(&table.tag) || !file.ReadU32(&table.offset) || !file.ReadU32(&table.length) || !file.ReadU32(&table.uncompressed_length) || !file.ReadU32(&table.chksum)) { return OTS_FAILURE_MSG_HDR("error reading table directory"); } total_sfnt_size += ots::Round4(table.uncompressed_length); if (total_sfnt_size > std::numeric_limits<uint32_t>::max()) { return OTS_FAILURE_MSG_HDR("sfnt size overflow"); } tables.push_back(table); if (i == 0 || tables[first_index].offset > table.offset) first_index = i; if (i == 0 || tables[last_index].offset < table.offset) last_index = i; } if (reported_total_sfnt_size != total_sfnt_size) { return OTS_FAILURE_MSG_HDR("uncompressed sfnt size mismatch"); } // Table data must follow immediately after the header. if (tables[first_index].offset != ots::Round4(file.offset())) { return OTS_FAILURE_MSG_HDR("junk before tables in WOFF file"); } if (tables[last_index].offset >= length || length - tables[last_index].offset < tables[last_index].length) { return OTS_FAILURE_MSG_HDR("invalid table location/size"); } // Blocks must follow immediately after the previous block. // (Except for padding with a maximum of three null bytes) uint64_t block_end = ots::Round4( static_cast<uint64_t>(tables[last_index].offset) + static_cast<uint64_t>(tables[last_index].length)); if (block_end > std::numeric_limits<uint32_t>::max()) { return OTS_FAILURE_MSG_HDR("invalid table location/size"); } if (meta_offset) { if (block_end != meta_offset) { return OTS_FAILURE_MSG_HDR("Invalid metadata block offset"); } block_end = ots::Round4(static_cast<uint64_t>(meta_offset) + static_cast<uint64_t>(meta_length)); if (block_end > std::numeric_limits<uint32_t>::max()) { return OTS_FAILURE_MSG_HDR("Invalid metadata block length"); } } if (priv_offset) { if (block_end != priv_offset) { return OTS_FAILURE_MSG_HDR("Invalid private block offset"); } block_end = ots::Round4(static_cast<uint64_t>(priv_offset) + static_cast<uint64_t>(priv_length)); if (block_end > std::numeric_limits<uint32_t>::max()) { return OTS_FAILURE_MSG_HDR("Invalid private block length"); } } if (block_end != ots::Round4(length)) { return OTS_FAILURE_MSG_HDR("File length mismatch (trailing junk?)"); } return ProcessGeneric(header, font, woff_tag, output, data, length, tables, file); } bool ProcessWOFF2(ots::FontFile *header, ots::OTSStream *output, const uint8_t *data, size_t length, uint32_t index) { size_t decompressed_size = woff2::ComputeWOFF2FinalSize(data, length); if (decompressed_size < length) { return OTS_FAILURE_MSG_HDR("Size of decompressed WOFF 2.0 is less than compressed size"); } if (decompressed_size == 0) { return OTS_FAILURE_MSG_HDR("Size of decompressed WOFF 2.0 is set to 0"); } // decompressed font must be <= 30MB if (decompressed_size > 30 * 1024 * 1024) { return OTS_FAILURE_MSG_HDR("Size of decompressed WOFF 2.0 font exceeds 30MB"); } std::string buf(decompressed_size, 0); woff2::WOFF2StringOut out(&buf); if (!woff2::ConvertWOFF2ToTTF(data, length, &out)) { return OTS_FAILURE_MSG_HDR("Failed to convert WOFF 2.0 font to SFNT"); } const uint8_t *decompressed = reinterpret_cast<const uint8_t*>(buf.data()); if (data[4] == 't' && data[5] == 't' && data[6] == 'c' && data[7] == 'f') { return ProcessTTC(header, output, decompressed, out.Size(), index); } else { ots::Font font(header); return ProcessTTF(header, &font, output, decompressed, out.Size()); } } ots::TableAction GetTableAction(const ots::FontFile *header, uint32_t tag) { ots::TableAction action = header->context->GetTableAction(tag); if (action == ots::TABLE_ACTION_DEFAULT) { action = ots::TABLE_ACTION_DROP; for (unsigned i = 0; ; ++i) { if (supported_tables[i].tag == 0) break; if (supported_tables[i].tag == tag) { action = ots::TABLE_ACTION_SANITIZE; break; } } } assert(action != ots::TABLE_ACTION_DEFAULT); // Should never return this. return action; } bool GetTableData(const uint8_t *data, const ots::TableEntry& table, ots::Arena &arena, size_t *table_length, const uint8_t **table_data) { if (table.uncompressed_length != table.length) { // Compressed table. Need to uncompress into memory first. *table_length = table.uncompressed_length; *table_data = arena.Allocate(*table_length); uLongf dest_len = *table_length; int r = uncompress((Bytef*) *table_data, &dest_len, data + table.offset, table.length); if (r != Z_OK || dest_len != *table_length) { return false; } } else { // Uncompressed table. We can process directly from memory. *table_data = data + table.offset; *table_length = table.length; } return true; } bool ProcessGeneric(ots::FontFile *header, ots::Font *font, uint32_t signature, ots::OTSStream *output, const uint8_t *data, size_t length, const std::vector<ots::TableEntry>& tables, ots::Buffer& file) { const size_t data_offset = file.offset(); uint32_t uncompressed_sum = 0; for (unsigned i = 0; i < font->num_tables; ++i) { // the tables must be sorted by tag (when taken as big-endian numbers). // This also remove the possibility of duplicate tables. if (i) { const uint32_t this_tag = tables[i].tag; const uint32_t prev_tag = tables[i - 1].tag; if (this_tag <= prev_tag) { OTS_WARNING_MSG_HDR("Table directory is not correctly ordered"); } } // all tag names must be built from printable ASCII characters if (!CheckTag(tables[i].tag)) { OTS_WARNING_MSG_HDR("Invalid table tag: 0x%X", tables[i].tag); } // tables must be 4-byte aligned if (tables[i].offset & 3) { return OTS_FAILURE_MSG_TAG("misaligned table", tables[i].tag); } // and must be within the file if (tables[i].offset < data_offset || tables[i].offset >= length) { return OTS_FAILURE_MSG_TAG("invalid table offset", tables[i].tag); } // disallow all tables with a zero length if (tables[i].length < 1) { // Note: malayalam.ttf has zero length CVT table... return OTS_FAILURE_MSG_TAG("zero-length table", tables[i].tag); } // disallow all tables with a length > 1GB if (tables[i].length > 1024 * 1024 * 1024) { return OTS_FAILURE_MSG_TAG("table length exceeds 1GB", tables[i].tag); } // disallow tables where the uncompressed size is < the compressed size. if (tables[i].uncompressed_length < tables[i].length) { return OTS_FAILURE_MSG_TAG("invalid compressed table", tables[i].tag); } if (tables[i].uncompressed_length > tables[i].length) { // We'll probably be decompressing this table. // disallow all tables which uncompress to > 30 MB if (tables[i].uncompressed_length > 30 * 1024 * 1024) { return OTS_FAILURE_MSG_TAG("uncompressed length exceeds 30MB", tables[i].tag); } if (uncompressed_sum + tables[i].uncompressed_length < uncompressed_sum) { return OTS_FAILURE_MSG_TAG("overflow of uncompressed sum", tables[i].tag); } uncompressed_sum += tables[i].uncompressed_length; } // since we required that the file be < 1GB in length, and that the table // length is < 1GB, the following addtion doesn't overflow uint32_t end_byte = tables[i].offset + tables[i].length; // Tables in the WOFF file must be aligned 4-byte boundary. if (signature == OTS_TAG('w','O','F','F')) { end_byte = ots::Round4(end_byte); } if (!end_byte || end_byte > length) { return OTS_FAILURE_MSG_TAG("table overruns end of file", tables[i].tag); } } // All decompressed tables uncompressed must be <= 30MB. if (uncompressed_sum > 30 * 1024 * 1024) { return OTS_FAILURE_MSG_HDR("uncompressed sum exceeds 30MB"); } // check that the tables are not overlapping. std::vector<std::pair<uint32_t, uint8_t> > overlap_checker; for (unsigned i = 0; i < font->num_tables; ++i) { overlap_checker.push_back( std::make_pair(tables[i].offset, static_cast<uint8_t>(1) /* start */)); overlap_checker.push_back( std::make_pair(tables[i].offset + tables[i].length, static_cast<uint8_t>(0) /* end */)); } std::sort(overlap_checker.begin(), overlap_checker.end()); int overlap_count = 0; for (unsigned i = 0; i < overlap_checker.size(); ++i) { overlap_count += (overlap_checker[i].second ? 1 : -1); if (overlap_count > 1) { return OTS_FAILURE_MSG_HDR("overlapping tables"); } } std::map<uint32_t, ots::TableEntry> table_map; for (unsigned i = 0; i < font->num_tables; ++i) { table_map[tables[i].tag] = tables[i]; } ots::Arena arena; // Parse known tables first as we need to parse them in specific order. for (unsigned i = 0; ; ++i) { if (supported_tables[i].tag == 0) break; uint32_t tag = supported_tables[i].tag; const auto &it = table_map.find(tag); if (it == table_map.cend()) { if (supported_tables[i].required) { return OTS_FAILURE_MSG_TAG("missing required table", tag); } } else { if (!font->ParseTable(it->second, data, arena)) { return OTS_FAILURE_MSG_TAG("Failed to parse table", tag); } } } // Then parse any tables left. for (const auto &table_entry : tables) { if (!font->GetTable(table_entry.tag)) { if (!font->ParseTable(table_entry, data, arena)) { return OTS_FAILURE_MSG_TAG("Failed to parse table", table_entry.tag); } } } if (font->GetTable(OTS_TAG_CFF) || font->GetTable(OTS_TAG('C', 'F', 'F', '2'))) { // font with PostScript glyph if (font->version != OTS_TAG('O','T','T','O')) { return OTS_FAILURE_MSG_HDR("wrong font version for PostScript glyph data"); } if (font->GetTable(OTS_TAG_GLYF) || font->GetTable(OTS_TAG_LOCA)) { // mixing outline formats is not recommended return OTS_FAILURE_MSG_HDR("font contains both PS and TT glyphs"); } } else { if (!font->GetTable(OTS_TAG_GLYF) || !font->GetTable(OTS_TAG_LOCA)) { // No TrueType glyph found. // // We don't sanitize bitmap tables, but don’t reject bitmap-only fonts if // we are asked to pass them thru. // Also don’t reject if we are asked to pass glyf/loca thru. if (!font->GetTable(OTS_TAG('C','B','D','T')) && !font->GetTable(OTS_TAG('C','B','L','C'))) { return OTS_FAILURE_MSG_HDR("no supported glyph shapes table(s) present"); } } } uint16_t num_output_tables = 0; for (const auto &it : table_map) { ots::Table *table = font->GetTable(it.first); if (table != NULL && table->ShouldSerialize()) num_output_tables++; } uint16_t max_pow2 = 0; while (1u << (max_pow2 + 1) <= num_output_tables) { max_pow2++; } const uint16_t output_search_range = (1u << max_pow2) << 4; // most of the errors here are highly unlikely - they'd only occur if the // output stream returns a failure, e.g. lack of space to write output->ResetChecksum(); if (!output->WriteU32(font->version) || !output->WriteU16(num_output_tables) || !output->WriteU16(output_search_range) || !output->WriteU16(max_pow2) || !output->WriteU16((num_output_tables << 4) - output_search_range)) { return OTS_FAILURE_MSG_HDR("error writing output"); } const uint32_t offset_table_chksum = output->chksum(); const size_t table_record_offset = output->Tell(); if (!output->Pad(16 * num_output_tables)) { return OTS_FAILURE_MSG_HDR("error writing output"); } std::vector<ots::TableEntry> out_tables; size_t head_table_offset = 0; for (const auto &it : table_map) { uint32_t input_offset = it.second.offset; const auto &ot = header->table_entries.find(input_offset); if (ot != header->table_entries.end()) { ots::TableEntry out = ot->second; if (out.tag == OTS_TAG('h','e','a','d')) { head_table_offset = out.offset; } out_tables.push_back(out); } else { ots::TableEntry out; out.tag = it.first; out.offset = output->Tell(); if (out.tag == OTS_TAG('h','e','a','d')) { head_table_offset = out.offset; } ots::Table *table = font->GetTable(out.tag); if (table != NULL && table->ShouldSerialize()) { output->ResetChecksum(); if (!table->Serialize(output)) { return OTS_FAILURE_MSG_TAG("Failed to serialize table", out.tag); } const size_t end_offset = output->Tell(); if (end_offset <= out.offset) { // paranoid check. |end_offset| is supposed to be greater than the offset, // as long as the Tell() interface is implemented correctly. return OTS_FAILURE_MSG_TAG("Table is empty or have -ve size", out.tag); } out.length = end_offset - out.offset; // align tables to four bytes if (!output->Pad((4 - (end_offset & 3)) % 4)) { return OTS_FAILURE_MSG_TAG("Failed to pad table to 4 bytes", out.tag); } out.chksum = output->chksum(); out_tables.push_back(out); header->table_entries[input_offset] = out; } } } const size_t end_of_file = output->Tell(); // Need to sort the output tables for inclusion in the file std::sort(out_tables.begin(), out_tables.end()); if (!output->Seek(table_record_offset)) { return OTS_FAILURE_MSG_HDR("error writing output"); } output->ResetChecksum(); uint32_t tables_chksum = 0; for (unsigned i = 0; i < out_tables.size(); ++i) { if (!output->WriteU32(out_tables[i].tag) || !output->WriteU32(out_tables[i].chksum) || !output->WriteU32(out_tables[i].offset) || !output->WriteU32(out_tables[i].length)) { return OTS_FAILURE_MSG_HDR("error writing output"); } tables_chksum += out_tables[i].chksum; } const uint32_t table_record_chksum = output->chksum(); // http://www.microsoft.com/typography/otspec/otff.htm const uint32_t file_chksum = offset_table_chksum + tables_chksum + table_record_chksum; const uint32_t chksum_magic = static_cast<uint32_t>(0xb1b0afba) - file_chksum; // seek into the 'head' table and write in the checksum magic value if (!head_table_offset) { return OTS_FAILURE_MSG_HDR("internal error!"); } if (!output->Seek(head_table_offset + 8)) { return OTS_FAILURE_MSG_HDR("error writing output"); } if (!output->WriteU32(chksum_magic)) { return OTS_FAILURE_MSG_HDR("error writing output"); } if (!output->Seek(end_of_file)) { return OTS_FAILURE_MSG_HDR("error writing output"); } return true; } } // namespace namespace ots { FontFile::~FontFile() { for (const auto& it : tables) { delete it.second; } tables.clear(); } bool Font::ParseTable(const TableEntry& table_entry, const uint8_t* data, Arena &arena) { uint32_t tag = table_entry.tag; TableAction action = GetTableAction(file, tag); if (action == TABLE_ACTION_DROP) { return true; } const auto &it = file->tables.find(table_entry); if (it != file->tables.end()) { m_tables[tag] = it->second; return true; } Table *table = NULL; bool ret = false; if (action == TABLE_ACTION_PASSTHRU) { table = new TablePassthru(this, tag); } else { switch (tag) { case OTS_TAG_CFF: table = new OpenTypeCFF(this, tag); break; case OTS_TAG_CMAP: table = new OpenTypeCMAP(this, tag); break; case OTS_TAG_CVT: table = new OpenTypeCVT(this, tag); break; case OTS_TAG_FPGM: table = new OpenTypeFPGM(this, tag); break; case OTS_TAG_GASP: table = new OpenTypeGASP(this, tag); break; case OTS_TAG_GDEF: table = new OpenTypeGDEF(this, tag); break; case OTS_TAG_GLYF: table = new OpenTypeGLYF(this, tag); break; case OTS_TAG_GPOS: table = new OpenTypeGPOS(this, tag); break; case OTS_TAG_GSUB: table = new OpenTypeGSUB(this, tag); break; case OTS_TAG_HDMX: table = new OpenTypeHDMX(this, tag); break; case OTS_TAG_HEAD: table = new OpenTypeHEAD(this, tag); break; case OTS_TAG_HHEA: table = new OpenTypeHHEA(this, tag); break; case OTS_TAG_HMTX: table = new OpenTypeHMTX(this, tag); break; case OTS_TAG_KERN: table = new OpenTypeKERN(this, tag); break; case OTS_TAG_LOCA: table = new OpenTypeLOCA(this, tag); break; case OTS_TAG_LTSH: table = new OpenTypeLTSH(this, tag); break; case OTS_TAG_MATH: table = new OpenTypeMATH(this, tag); break; case OTS_TAG_MAXP: table = new OpenTypeMAXP(this, tag); break; case OTS_TAG_NAME: table = new OpenTypeNAME(this, tag); break; case OTS_TAG_OS2: table = new OpenTypeOS2(this, tag); break; case OTS_TAG_POST: table = new OpenTypePOST(this, tag); break; case OTS_TAG_PREP: table = new OpenTypePREP(this, tag); break; case OTS_TAG_VDMX: table = new OpenTypeVDMX(this, tag); break; case OTS_TAG_VORG: table = new OpenTypeVORG(this, tag); break; case OTS_TAG_VHEA: table = new OpenTypeVHEA(this, tag); break; case OTS_TAG_VMTX: table = new OpenTypeVMTX(this, tag); break; // Graphite tables #ifdef OTS_GRAPHITE case OTS_TAG_FEAT: table = new OpenTypeFEAT(this, tag); break; case OTS_TAG_GLAT: table = new OpenTypeGLAT(this, tag); break; case OTS_TAG_GLOC: table = new OpenTypeGLOC(this, tag); break; case OTS_TAG_SILE: table = new OpenTypeSILE(this, tag); break; case OTS_TAG_SILF: table = new OpenTypeSILF(this, tag); break; case OTS_TAG_SILL: table = new OpenTypeSILL(this, tag); break; #endif default: break; } } if (table) { const uint8_t* table_data; size_t table_length; ret = GetTableData(data, table_entry, arena, &table_length, &table_data); if (ret) { // FIXME: Parsing some tables will fail if the table is not added to // m_tables first. m_tables[tag] = table; ret = table->Parse(table_data, table_length); if (ret) file->tables[table_entry] = table; else m_tables.erase(tag); } } if (!ret) delete table; return ret; } Table* Font::GetTable(uint32_t tag) const { const auto &it = m_tables.find(tag); if (it != m_tables.end()) return it->second; return NULL; } Table* Font::GetTypedTable(uint32_t tag) const { Table* t = GetTable(tag); if (t && t->Type() == tag) return t; return NULL; } void Font::DropGraphite() { file->context->Message(0, "Dropping all Graphite tables"); for (const std::pair<uint32_t, Table*> entry : m_tables) { if (entry.first == OTS_TAG_FEAT || entry.first == OTS_TAG_GLAT || entry.first == OTS_TAG_GLOC || entry.first == OTS_TAG_SILE || entry.first == OTS_TAG_SILF || entry.first == OTS_TAG_SILL) { entry.second->Drop("Discarding Graphite table"); } } dropped_graphite = true; } bool Table::ShouldSerialize() { return m_shouldSerialize; } void Table::Message(int level, const char *format, va_list va) { char msg[206] = { OTS_UNTAG(m_tag), ':', ' ' }; std::vsnprintf(msg + 6, 200, format, va); m_font->file->context->Message(level, msg); } bool Table::Error(const char *format, ...) { va_list va; va_start(va, format); Message(0, format, va); va_end(va); return false; } bool Table::Warning(const char *format, ...) { va_list va; va_start(va, format); Message(1, format, va); va_end(va); return true; } bool Table::Drop(const char *format, ...) { m_shouldSerialize = false; va_list va; va_start(va, format); Message(0, format, va); m_font->file->context->Message(0, "Table discarded"); va_end(va); return true; } bool Table::DropGraphite(const char *format, ...) { va_list va; va_start(va, format); Message(0, format, va); va_end(va); m_font->DropGraphite(); return true; } bool TablePassthru::Parse(const uint8_t *data, size_t length) { m_data = data; m_length = length; return true; } bool TablePassthru::Serialize(OTSStream *out) { if (!out->Write(m_data, m_length)) { return Error("Failed to write table"); } return true; } bool IsValidVersionTag(uint32_t tag) { return tag == 0x000010000 || // OpenType fonts with CFF data have 'OTTO' tag. tag == OTS_TAG('O','T','T','O') || // Older Mac fonts might have 'true' or 'typ1' tag. tag == OTS_TAG('t','r','u','e') || tag == OTS_TAG('t','y','p','1'); } bool OTSContext::Process(OTSStream *output, const uint8_t *data, size_t length, uint32_t index) { FontFile header; Font font(&header); header.context = this; if (length < 4) { return OTS_FAILURE_MSG_(&header, "file less than 4 bytes"); } bool result; if (data[0] == 'w' && data[1] == 'O' && data[2] == 'F' && data[3] == 'F') { result = ProcessWOFF(&header, &font, output, data, length); } else if (data[0] == 'w' && data[1] == 'O' && data[2] == 'F' && data[3] == '2') { result = ProcessWOFF2(&header, output, data, length, index); } else if (data[0] == 't' && data[1] == 't' && data[2] == 'c' && data[3] == 'f') { result = ProcessTTC(&header, output, data, length, index); } else { result = ProcessTTF(&header, &font, output, data, length); } return result; } } // namespace ots
null
null
null
null
26,125
26,179
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
191,174
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright 2016 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * */ #ifndef __VEGA10_IH_H__ #define __VEGA10_IH_H__ extern const struct amd_ip_funcs vega10_ih_ip_funcs; extern const struct amdgpu_ip_block_version vega10_ih_ip_block; #endif
null
null
null
null
99,521
39,806
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
204,801
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* Manage a process's keyrings * * Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved. * Written by David Howells ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/sched/user.h> #include <linux/keyctl.h> #include <linux/fs.h> #include <linux/err.h> #include <linux/mutex.h> #include <linux/security.h> #include <linux/user_namespace.h> #include <linux/uaccess.h> #include "internal.h" /* Session keyring create vs join semaphore */ static DEFINE_MUTEX(key_session_mutex); /* User keyring creation semaphore */ static DEFINE_MUTEX(key_user_keyring_mutex); /* The root user's tracking struct */ struct key_user root_key_user = { .usage = ATOMIC_INIT(3), .cons_lock = __MUTEX_INITIALIZER(root_key_user.cons_lock), .lock = __SPIN_LOCK_UNLOCKED(root_key_user.lock), .nkeys = ATOMIC_INIT(2), .nikeys = ATOMIC_INIT(2), .uid = GLOBAL_ROOT_UID, }; /* * Install the user and user session keyrings for the current process's UID. */ /* * Install a fresh thread keyring directly to new credentials. This keyring is * allowed to overrun the quota. */ int install_thread_keyring_to_cred(struct cred *new) { struct key *keyring; keyring = keyring_alloc("_tid", new->uid, new->gid, new, KEY_POS_ALL | KEY_USR_VIEW, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); if (IS_ERR(keyring)) return PTR_ERR(keyring); new->thread_keyring = keyring; return 0; } /* * Install a fresh thread keyring, discarding the old one. */ /* * Install a process keyring directly to a credentials struct. * * Returns -EEXIST if there was already a process keyring, 0 if one installed, * and other value on any other error */ /* * Make sure a process keyring is installed for the current process. The * existing process keyring is not replaced. * * Returns 0 if there is a process keyring by the end of this function, some * error otherwise. */ /* * Install a session keyring directly to a credentials struct. */ int install_session_keyring_to_cred(struct cred *cred, struct key *keyring) { unsigned long flags; struct key *old; might_sleep(); /* create an empty session keyring */ if (!keyring) { flags = KEY_ALLOC_QUOTA_OVERRUN; if (cred->session_keyring) flags = KEY_ALLOC_IN_QUOTA; keyring = keyring_alloc("_ses", cred->uid, cred->gid, cred, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, flags, NULL, NULL); if (IS_ERR(keyring)) return PTR_ERR(keyring); } else { __key_get(keyring); } /* install the keyring */ old = cred->session_keyring; rcu_assign_pointer(cred->session_keyring, keyring); if (old) key_put(old); return 0; } /* * Install a session keyring, discarding the old one. If a keyring is not * supplied, an empty one is invented. */ static int install_session_keyring(struct key *keyring) { struct cred *new; int ret; new = prepare_creds(); if (!new) return -ENOMEM; ret = install_session_keyring_to_cred(new, keyring); if (ret < 0) { abort_creds(new); return ret; } return commit_creds(new); } /* * Handle the fsuid changing. */ void key_fsuid_changed(struct task_struct *tsk) { /* update the ownership of the thread keyring */ BUG_ON(!tsk->cred); if (tsk->cred->thread_keyring) { down_write(&tsk->cred->thread_keyring->sem); tsk->cred->thread_keyring->uid = tsk->cred->fsuid; up_write(&tsk->cred->thread_keyring->sem); } } /* * Handle the fsgid changing. */ void key_fsgid_changed(struct task_struct *tsk) { /* update the ownership of the thread keyring */ BUG_ON(!tsk->cred); if (tsk->cred->thread_keyring) { down_write(&tsk->cred->thread_keyring->sem); tsk->cred->thread_keyring->gid = tsk->cred->fsgid; up_write(&tsk->cred->thread_keyring->sem); } } /* * Search the process keyrings attached to the supplied cred for the first * matching key. * * The search criteria are the type and the match function. The description is * given to the match function as a parameter, but doesn't otherwise influence * the search. Typically the match function will compare the description * parameter to the key's description. * * This can only search keyrings that grant Search permission to the supplied * credentials. Keyrings linked to searched keyrings will also be searched if * they grant Search permission too. Keys can only be found if they grant * Search permission to the credentials. * * Returns a pointer to the key with the key usage count incremented if * successful, -EAGAIN if we didn't find any matching key or -ENOKEY if we only * matched negative keys. * * In the case of a successful return, the possession attribute is set on the * returned key reference. */ key_ref_t search_my_process_keyrings(struct keyring_search_context *ctx) { key_ref_t key_ref, ret, err; /* we want to return -EAGAIN or -ENOKEY if any of the keyrings were * searchable, but we failed to find a key or we found a negative key; * otherwise we want to return a sample error (probably -EACCES) if * none of the keyrings were searchable * * in terms of priority: success > -ENOKEY > -EAGAIN > other error */ key_ref = NULL; ret = NULL; err = ERR_PTR(-EAGAIN); /* search the thread keyring first */ if (ctx->cred->thread_keyring) { key_ref = keyring_search_aux( make_key_ref(ctx->cred->thread_keyring, 1), ctx); if (!IS_ERR(key_ref)) goto found; switch (PTR_ERR(key_ref)) { case -EAGAIN: /* no key */ case -ENOKEY: /* negative key */ ret = key_ref; break; default: err = key_ref; break; } } /* search the process keyring second */ if (ctx->cred->process_keyring) { key_ref = keyring_search_aux( make_key_ref(ctx->cred->process_keyring, 1), ctx); if (!IS_ERR(key_ref)) goto found; switch (PTR_ERR(key_ref)) { case -EAGAIN: /* no key */ if (ret) break; case -ENOKEY: /* negative key */ ret = key_ref; break; default: err = key_ref; break; } } /* search the session keyring */ if (ctx->cred->session_keyring) { rcu_read_lock(); key_ref = keyring_search_aux( make_key_ref(rcu_dereference(ctx->cred->session_keyring), 1), ctx); rcu_read_unlock(); if (!IS_ERR(key_ref)) goto found; switch (PTR_ERR(key_ref)) { case -EAGAIN: /* no key */ if (ret) break; case -ENOKEY: /* negative key */ ret = key_ref; break; default: err = key_ref; break; } } /* or search the user-session keyring */ else if (ctx->cred->user->session_keyring) { key_ref = keyring_search_aux( make_key_ref(ctx->cred->user->session_keyring, 1), ctx); if (!IS_ERR(key_ref)) goto found; switch (PTR_ERR(key_ref)) { case -EAGAIN: /* no key */ if (ret) break; case -ENOKEY: /* negative key */ ret = key_ref; break; default: err = key_ref; break; } } /* no key - decide on the error we're going to go for */ key_ref = ret ? ret : err; found: return key_ref; } /* * Search the process keyrings attached to the supplied cred for the first * matching key in the manner of search_my_process_keyrings(), but also search * the keys attached to the assumed authorisation key using its credentials if * one is available. * * Return same as search_my_process_keyrings(). */ key_ref_t search_process_keyrings(struct keyring_search_context *ctx) { struct request_key_auth *rka; key_ref_t key_ref, ret = ERR_PTR(-EACCES), err; might_sleep(); key_ref = search_my_process_keyrings(ctx); if (!IS_ERR(key_ref)) goto found; err = key_ref; /* if this process has an instantiation authorisation key, then we also * search the keyrings of the process mentioned there * - we don't permit access to request_key auth keys via this method */ if (ctx->cred->request_key_auth && ctx->cred == current_cred() && ctx->index_key.type != &key_type_request_key_auth ) { const struct cred *cred = ctx->cred; /* defend against the auth key being revoked */ down_read(&cred->request_key_auth->sem); if (key_validate(ctx->cred->request_key_auth) == 0) { rka = ctx->cred->request_key_auth->payload.data[0]; ctx->cred = rka->cred; key_ref = search_process_keyrings(ctx); ctx->cred = cred; up_read(&cred->request_key_auth->sem); if (!IS_ERR(key_ref)) goto found; ret = key_ref; } else { up_read(&cred->request_key_auth->sem); } } /* no key - decide on the error we're going to go for */ if (err == ERR_PTR(-ENOKEY) || ret == ERR_PTR(-ENOKEY)) key_ref = ERR_PTR(-ENOKEY); else if (err == ERR_PTR(-EACCES)) key_ref = ret; else key_ref = err; found: return key_ref; } /* * See if the key we're looking at is the target key. */ bool lookup_user_key_possessed(const struct key *key, const struct key_match_data *match_data) { return key == match_data->raw_data; } /* * Look up a key ID given us by userspace with a given permissions mask to get * the key it refers to. * * Flags can be passed to request that special keyrings be created if referred * to directly, to permit partially constructed keys to be found and to skip * validity and permission checks on the found key. * * Returns a pointer to the key with an incremented usage count if successful; * -EINVAL if the key ID is invalid; -ENOKEY if the key ID does not correspond * to a key or the best found key was a negative key; -EKEYREVOKED or * -EKEYEXPIRED if the best found key was revoked or expired; -EACCES if the * found key doesn't grant the requested permit or the LSM denied access to it; * or -ENOMEM if a special keyring couldn't be created. * * In the case of a successful return, the possession attribute is set on the * returned key reference. */ /* * Join the named keyring as the session keyring if possible else attempt to * create a new one of that name and join that. * * If the name is NULL, an empty anonymous keyring will be installed as the * session keyring. * * Named session keyrings are joined with a semaphore held to prevent the * keyrings from going away whilst the attempt is made to going them and also * to prevent a race in creating compatible session keyrings. */ long join_session_keyring(const char *name) { const struct cred *old; struct cred *new; struct key *keyring; long ret, serial; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); /* if no name is provided, install an anonymous keyring */ if (!name) { ret = install_session_keyring_to_cred(new, NULL); if (ret < 0) goto error; serial = new->session_keyring->serial; ret = commit_creds(new); if (ret == 0) ret = serial; goto okay; } /* allow the user to join or create a named keyring */ mutex_lock(&key_session_mutex); /* look for an existing keyring of this name */ keyring = find_keyring_by_name(name, false); if (PTR_ERR(keyring) == -ENOKEY) { /* not found - try and create a new one */ keyring = keyring_alloc( name, old->uid, old->gid, old, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK, KEY_ALLOC_IN_QUOTA, NULL, NULL); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error2; } } else if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error2; } else if (keyring == new->session_keyring) { key_put(keyring); ret = 0; goto error2; } /* we've got a keyring - now to install it */ ret = install_session_keyring_to_cred(new, keyring); if (ret < 0) goto error2; commit_creds(new); mutex_unlock(&key_session_mutex); ret = keyring->serial; key_put(keyring); okay: return ret; error2: mutex_unlock(&key_session_mutex); error: abort_creds(new); return ret; } /* * Replace a process's session keyring on behalf of one of its children when * the target process is about to resume userspace execution. */ void key_change_session_keyring(struct callback_head *twork) { const struct cred *old = current_cred(); struct cred *new = container_of(twork, struct cred, rcu); if (unlikely(current->flags & PF_EXITING)) { put_cred(new); return; } new-> uid = old-> uid; new-> euid = old-> euid; new-> suid = old-> suid; new->fsuid = old->fsuid; new-> gid = old-> gid; new-> egid = old-> egid; new-> sgid = old-> sgid; new->fsgid = old->fsgid; new->user = get_uid(old->user); new->user_ns = get_user_ns(old->user_ns); new->group_info = get_group_info(old->group_info); new->securebits = old->securebits; new->cap_inheritable = old->cap_inheritable; new->cap_permitted = old->cap_permitted; new->cap_effective = old->cap_effective; new->cap_ambient = old->cap_ambient; new->cap_bset = old->cap_bset; new->jit_keyring = old->jit_keyring; new->thread_keyring = key_get(old->thread_keyring); new->process_keyring = key_get(old->process_keyring); security_transfer_creds(new, old); commit_creds(new); } /* * Make sure that root's user and user-session keyrings exist. */ static int __init init_root_keyring(void) { return install_user_keyrings(); } late_initcall(init_root_keyring);
null
null
null
null
113,148
32,480
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
197,475
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * JZ4780 BCH controller * * Copyright (c) 2015 Imagination Technologies * Author: Alex Smith <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #ifndef __DRIVERS_MTD_NAND_JZ4780_BCH_H__ #define __DRIVERS_MTD_NAND_JZ4780_BCH_H__ #include <linux/types.h> struct device; struct device_node; struct jz4780_bch; /** * struct jz4780_bch_params - BCH parameters * @size: data bytes per ECC step. * @bytes: ECC bytes per step. * @strength: number of correctable bits per ECC step. */ struct jz4780_bch_params { int size; int bytes; int strength; }; int jz4780_bch_calculate(struct jz4780_bch *bch, struct jz4780_bch_params *params, const u8 *buf, u8 *ecc_code); int jz4780_bch_correct(struct jz4780_bch *bch, struct jz4780_bch_params *params, u8 *buf, u8 *ecc_code); void jz4780_bch_release(struct jz4780_bch *bch); struct jz4780_bch *of_jz4780_bch_get(struct device_node *np); #endif /* __DRIVERS_MTD_NAND_JZ4780_BCH_H__ */
null
null
null
null
105,822
1,341
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
154,398
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * 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 */ #ifndef AVCODEC_VERSION_H #define AVCODEC_VERSION_H /** * @file * @ingroup libavc * Libavcodec version macros. */ #include "libavutil/version.h" #define LIBAVCODEC_VERSION_MAJOR 58 #define LIBAVCODEC_VERSION_MINOR 19 #define LIBAVCODEC_VERSION_MICRO 104 #define LIBAVCODEC_VERSION_INT AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \ LIBAVCODEC_VERSION_MINOR, \ LIBAVCODEC_VERSION_MICRO) #define LIBAVCODEC_VERSION AV_VERSION(LIBAVCODEC_VERSION_MAJOR, \ LIBAVCODEC_VERSION_MINOR, \ LIBAVCODEC_VERSION_MICRO) #define LIBAVCODEC_BUILD LIBAVCODEC_VERSION_INT #define LIBAVCODEC_IDENT "Lavc" AV_STRINGIFY(LIBAVCODEC_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. * * @note, when bumping the major version it is recommended to manually * disable each FF_API_* in its own commit instead of disabling them all * at once through the bump. This improves the git bisect-ability of the change. */ #ifndef FF_API_LOWRES #define FF_API_LOWRES (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_DEBUG_MV #define FF_API_DEBUG_MV (LIBAVCODEC_VERSION_MAJOR < 58) #endif #ifndef FF_API_AVCTX_TIMEBASE #define FF_API_AVCTX_TIMEBASE (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_CODED_FRAME #define FF_API_CODED_FRAME (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_SIDEDATA_ONLY_PKT #define FF_API_SIDEDATA_ONLY_PKT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_VDPAU_PROFILE #define FF_API_VDPAU_PROFILE (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_CONVERGENCE_DURATION #define FF_API_CONVERGENCE_DURATION (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_AVPICTURE #define FF_API_AVPICTURE (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_AVPACKET_OLD_API #define FF_API_AVPACKET_OLD_API (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_RTP_CALLBACK #define FF_API_RTP_CALLBACK (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_VBV_DELAY #define FF_API_VBV_DELAY (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_CODER_TYPE #define FF_API_CODER_TYPE (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_STAT_BITS #define FF_API_STAT_BITS (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_PRIVATE_OPT #define FF_API_PRIVATE_OPT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_ASS_TIMING #define FF_API_ASS_TIMING (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_OLD_BSF #define FF_API_OLD_BSF (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_COPY_CONTEXT #define FF_API_COPY_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_GET_CONTEXT_DEFAULTS #define FF_API_GET_CONTEXT_DEFAULTS (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_NVENC_OLD_NAME #define FF_API_NVENC_OLD_NAME (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_STRUCT_VAAPI_CONTEXT #define FF_API_STRUCT_VAAPI_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_MERGE_SD_API #define FF_API_MERGE_SD_API (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_TAG_STRING #define FF_API_TAG_STRING (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_GETCHROMA #define FF_API_GETCHROMA (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_CODEC_GET_SET #define FF_API_CODEC_GET_SET (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_USER_VISIBLE_AVHWACCEL #define FF_API_USER_VISIBLE_AVHWACCEL (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_LOCKMGR #define FF_API_LOCKMGR (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_NEXT #define FF_API_NEXT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #endif /* AVCODEC_VERSION_H */
null
null
null
null
70,453
36,407
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
36,407
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2012 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_FILE_SYSTEM_TYPE_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FILE_SYSTEM_TYPE_H_ namespace blink { // For file system types used in FileSystem API. // // WARNING: These enumerators can be serialized to disk (with IndexedDB). // If you have to update this list, also modify deserialization logic to handle // the previous version of this enum. enum FileSystemType { kFileSystemTypeTemporary, kFileSystemTypePersistent, // Transient isolated non-sandboxed filesystem. kFileSystemTypeIsolated, // Non-sandbox filesystem. kFileSystemTypeExternal, kFileSystemTypeLast = kFileSystemTypeExternal, }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_FILE_SYSTEM_TYPE_H_
null
null
null
null
33,270
11,271
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
11,271
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 "gpu/command_buffer/service/vertex_attrib_manager.h" #include <stdint.h> #include <list> #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" #include "gpu/command_buffer/common/gles2_cmd_format.h" #include "gpu/command_buffer/common/gles2_cmd_utils.h" #include "gpu/command_buffer/service/buffer_manager.h" #include "gpu/command_buffer/service/error_state.h" #include "gpu/command_buffer/service/feature_info.h" #include "gpu/command_buffer/service/gl_utils.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "gpu/command_buffer/service/program_manager.h" #include "gpu/command_buffer/service/vertex_array_manager.h" namespace gpu { namespace gles2 { VertexAttrib::VertexAttrib() : index_(0), enabled_(false), enabled_in_driver_(false), size_(4), type_(GL_FLOAT), offset_(0), normalized_(GL_FALSE), gl_stride_(0), real_stride_(16), divisor_(0), integer_(GL_FALSE), is_client_side_array_(false), list_(NULL) {} VertexAttrib::VertexAttrib(const VertexAttrib& other) = default; VertexAttrib::~VertexAttrib() = default; void VertexAttrib::SetInfo( Buffer* buffer, GLint size, GLenum type, GLboolean normalized, GLsizei gl_stride, GLsizei real_stride, GLsizei offset, GLboolean integer) { DCHECK_GT(real_stride, 0); buffer_ = buffer; size_ = size; type_ = type; normalized_ = normalized; gl_stride_ = gl_stride; real_stride_ = real_stride; offset_ = offset; integer_ = integer; } bool VertexAttrib::CanAccess(GLuint index) const { if (!enabled_) { return true; } DCHECK(buffer_.get() && !buffer_->IsDeleted()); // The number of elements that can be accessed. GLsizeiptr buffer_size = buffer_->size(); if (offset_ > buffer_size || real_stride_ == 0) { return false; } uint32_t usable_size = buffer_size - offset_; GLuint num_elements = usable_size / real_stride_ + ((usable_size % real_stride_) >= (GLES2Util::GetGroupSizeForBufferType(size_, type_)) ? 1 : 0); return index < num_elements; } VertexAttribManager::VertexAttribManager(bool do_buffer_refcounting) : num_fixed_attribs_(0), element_array_buffer_(NULL), manager_(NULL), deleted_(false), is_bound_(false), do_buffer_refcounting_(do_buffer_refcounting), service_id_(0) {} VertexAttribManager::VertexAttribManager(VertexArrayManager* manager, GLuint service_id, uint32_t num_vertex_attribs, bool do_buffer_refcounting) : num_fixed_attribs_(0), element_array_buffer_(NULL), manager_(manager), deleted_(false), is_bound_(false), do_buffer_refcounting_(do_buffer_refcounting), service_id_(service_id) { manager_->StartTracking(this); Initialize(num_vertex_attribs, false); } VertexAttribManager::~VertexAttribManager() { if (manager_) { if (manager_->have_context_) { if (service_id_ != 0) // 0 indicates an emulated VAO glDeleteVertexArraysOES(1, &service_id_); } manager_->StopTracking(this); manager_ = NULL; } } void VertexAttribManager::Initialize(uint32_t max_vertex_attribs, bool init_attribs) { vertex_attribs_.resize(max_vertex_attribs); uint32_t packed_size = (max_vertex_attribs + 15) / 16; attrib_base_type_mask_.resize(packed_size); attrib_enabled_mask_.resize(packed_size); for (uint32_t ii = 0; ii < packed_size; ++ii) { attrib_enabled_mask_[ii] = 0u; attrib_base_type_mask_[ii] = 0u; } for (uint32_t vv = 0; vv < vertex_attribs_.size(); ++vv) { vertex_attribs_[vv].set_index(vv); vertex_attribs_[vv].SetList(&disabled_vertex_attribs_); if (init_attribs) { glVertexAttrib4f(vv, 0.0f, 0.0f, 0.0f, 1.0f); } } } void VertexAttribManager::SetElementArrayBuffer(Buffer* buffer) { if (do_buffer_refcounting_ && is_bound_ && element_array_buffer_) element_array_buffer_->OnUnbind(GL_ELEMENT_ARRAY_BUFFER); element_array_buffer_ = buffer; if (do_buffer_refcounting_ && is_bound_ && buffer) buffer->OnBind(GL_ELEMENT_ARRAY_BUFFER); } bool VertexAttribManager::Enable(GLuint index, bool enable) { if (index >= vertex_attribs_.size()) { return false; } VertexAttrib& info = vertex_attribs_[index]; if (info.enabled() != enable) { info.set_enabled(enable); info.SetList(enable ? &enabled_vertex_attribs_ : &disabled_vertex_attribs_); GLuint shift_bits = (index % 16) * 2; if (enable) { attrib_enabled_mask_[index / 16] |= (0x3 << shift_bits); } else { attrib_enabled_mask_[index / 16] &= ~(0x3 << shift_bits); } } return true; } void VertexAttribManager::Unbind(Buffer* buffer, Buffer* bound_array_buffer) { DCHECK(buffer); DCHECK(is_bound_); if (element_array_buffer_.get() == buffer) { if (do_buffer_refcounting_) buffer->OnUnbind(GL_ELEMENT_ARRAY_BUFFER); if (manager_ && manager_->have_context_) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); element_array_buffer_ = nullptr; } // When a vertex array object is bound, some drivers (AMD Linux, // Qualcomm, etc.) have a bug where it incorrectly generates an // GL_INVALID_OPERATION on glVertexAttribPointer() if pointer is // NULL, no buffer is bound on GL_ARRAY_BUFFER. Therefore, in order // to clear the buffer bindings, we create a new array buffer, // redirect all bindings to the new buffer, and then delete the // buffer. GLuint new_buffer = 0; for (uint32_t vv = 0; vv < vertex_attribs_.size(); ++vv) { if (vertex_attribs_[vv].buffer_ == buffer) { if (do_buffer_refcounting_) buffer->OnUnbind(GL_ARRAY_BUFFER); vertex_attribs_[vv].buffer_ = nullptr; if (manager_ && manager_->have_context_) { if (!new_buffer) { glGenBuffersARB(1, &new_buffer); DCHECK_NE(0u, new_buffer); glBindBuffer(GL_ARRAY_BUFFER, new_buffer); // TODO(zmo): Do we need to also call glBufferData() here? } glVertexAttribPointer( vv, vertex_attribs_[vv].size_, vertex_attribs_[vv].type_, vertex_attribs_[vv].normalized_, vertex_attribs_[vv].gl_stride_, 0); } } } if (new_buffer) { glDeleteBuffersARB(1, &new_buffer); glBindBuffer(GL_ARRAY_BUFFER, bound_array_buffer ? bound_array_buffer->service_id() : 0u); } } void VertexAttribManager::SetIsBound(bool is_bound) { if (is_bound == is_bound_) return; is_bound_ = is_bound; if (do_buffer_refcounting_) { if (element_array_buffer_) { if (is_bound) element_array_buffer_->OnBind(GL_ELEMENT_ARRAY_BUFFER); else element_array_buffer_->OnUnbind(GL_ELEMENT_ARRAY_BUFFER); } for (const auto& va : vertex_attribs_) { if (va.buffer_) { if (is_bound) { va.buffer_->OnBind(GL_ARRAY_BUFFER); } else { va.buffer_->OnUnbind(GL_ARRAY_BUFFER); } } } } } bool VertexAttribManager::ValidateBindings( const char* function_name, GLES2Decoder* decoder, FeatureInfo* feature_info, BufferManager* buffer_manager, Program* current_program, GLuint max_vertex_accessed, bool instanced, GLsizei primcount) { DCHECK(primcount); ErrorState* error_state = decoder->GetErrorState(); // true if any enabled, used divisor is zero bool divisor0 = false; bool have_enabled_active_attribs = false; const GLuint kInitialBufferId = 0xFFFFFFFFU; GLuint current_buffer_id = kInitialBufferId; bool use_client_side_arrays_for_stream_buffers = feature_info->workarounds( ).use_client_side_arrays_for_stream_buffers; // Validate all attribs currently enabled. If they are used by the current // program then check that they have enough elements to handle the draw call. // If they are not used by the current program check that they have a buffer // assigned. for (VertexAttribList::iterator it = enabled_vertex_attribs_.begin(); it != enabled_vertex_attribs_.end(); ++it) { VertexAttrib* attrib = *it; Buffer* buffer = attrib->buffer(); if (!buffer_manager->RequestBufferAccess(error_state, buffer, function_name, "attached to enabled attrib %u", attrib->index())) { return false; } const Program::VertexAttrib* attrib_info = current_program->GetAttribInfoByLocation(attrib->index()); // Make sure that every attrib in enabled_vertex_attribs_ is really enabled // in the driver, if AND ONLY IF it is consumed by the current shader // program. (Note that since the containing loop is over // enabled_vertex_attribs_, not all vertex attribs, it doesn't erroneously // enable any attribs that should be disabled.) // This is for http://crbug.com/756293 but also subsumes some workaround // code for use_client_side_arrays_for_stream_buffers. SetDriverVertexAttribEnabled(attrib->index(), attrib_info != nullptr); if (attrib_info) { divisor0 |= (attrib->divisor() == 0); have_enabled_active_attribs = true; GLuint count = attrib->MaxVertexAccessed(primcount, max_vertex_accessed); // This attrib is used in the current program. if (!attrib->CanAccess(count)) { ERRORSTATE_SET_GL_ERROR( error_state, GL_INVALID_OPERATION, function_name, (std::string( "attempt to access out of range vertices in attribute ") + base::UintToString(attrib->index())).c_str()); return false; } if (use_client_side_arrays_for_stream_buffers) { if (buffer->IsClientSideArray()) { if (current_buffer_id != 0) { current_buffer_id = 0; glBindBuffer(GL_ARRAY_BUFFER, 0); } attrib->set_is_client_side_array(true); const void* ptr = buffer->GetRange(attrib->offset(), 0); DCHECK(ptr); glVertexAttribPointer( attrib->index(), attrib->size(), attrib->type(), attrib->normalized(), attrib->gl_stride(), ptr); } else if (attrib->is_client_side_array()) { attrib->set_is_client_side_array(false); GLuint new_buffer_id = buffer->service_id(); if (new_buffer_id != current_buffer_id) { current_buffer_id = new_buffer_id; glBindBuffer(GL_ARRAY_BUFFER, current_buffer_id); } const void* ptr = reinterpret_cast<const void*>(attrib->offset()); glVertexAttribPointer( attrib->index(), attrib->size(), attrib->type(), attrib->normalized(), attrib->gl_stride(), ptr); } } } } // Due to D3D9 limitation, in ES2/WebGL1, instanced drawing needs at least // one enabled attribute with divisor zero. This does not apply to D3D11, // therefore, it also does not apply to ES3/WebGL2. // Non-instanced drawing is fine with having no attributes at all, but if // there are attributes, at least one should have divisor zero. // (See ANGLE_instanced_arrays spec) if (feature_info->IsWebGL1OrES2Context() && !divisor0 && (instanced || have_enabled_active_attribs)) { ERRORSTATE_SET_GL_ERROR( error_state, GL_INVALID_OPERATION, function_name, "attempt to draw with all attributes having non-zero divisors"); return false; } if (current_buffer_id != kInitialBufferId) { // Restore the buffer binding. decoder->RestoreBufferBindings(); } return true; } } // namespace gles2 } // namespace gpu
null
null
null
null
8,134
25,026
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
25,026
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 EXTENSIONS_RENDERER_API_DISPLAY_SOURCE_WIFI_DISPLAY_WIFI_DISPLAY_MEDIA_PIPELINE_H_ #define EXTENSIONS_RENDERER_API_DISPLAY_SOURCE_WIFI_DISPLAY_WIFI_DISPLAY_MEDIA_PIPELINE_H_ #include <memory> #include <string> #include <utility> #include <vector> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/synchronization/lock.h" #include "extensions/common/mojo/wifi_display_session_service.mojom.h" #include "extensions/renderer/api/display_source/wifi_display/wifi_display_audio_encoder.h" #include "extensions/renderer/api/display_source/wifi_display/wifi_display_media_packetizer.h" #include "extensions/renderer/api/display_source/wifi_display/wifi_display_video_encoder.h" #include "third_party/blink/public/platform/web_media_stream_track.h" #include "third_party/wds/src/libwds/public/media_manager.h" namespace extensions { // This class encapsulates the WiFi Display media pipeline including // - encoding // - AV multiplexing/packetization // - sending // Threading: should belong to IO thread. class WiFiDisplayMediaPipeline { public: using ErrorCallback = base::Callback<void(const std::string&)>; using InitCompletionCallback = base::Callback<void(bool)>; using RegisterMediaServiceCallback = base::Callback<void(mojom::WiFiDisplayMediaServiceRequest, const base::Closure&)>; static std::unique_ptr<WiFiDisplayMediaPipeline> Create( wds::SessionType type, const WiFiDisplayVideoEncoder::InitParameters& video_parameters, const wds::AudioCodec& audio_codec, const std::string& sink_ip_address, const std::pair<int, int>& sink_rtp_ports, const RegisterMediaServiceCallback& service_callback, const ErrorCallback& error_callback); ~WiFiDisplayMediaPipeline(); // Note: to be called only once. void Initialize(const InitCompletionCallback& callback); void InsertRawVideoFrame( const scoped_refptr<media::VideoFrame>& video_frame, base::TimeTicks reference_time); void RequestIDRPicture(); WiFiDisplayAudioEncoder* audio_sink() { return audio_encoder_.get(); } private: using InitStepCompletionCallback = InitCompletionCallback; enum class InitializationStep : unsigned; WiFiDisplayMediaPipeline( wds::SessionType type, const WiFiDisplayVideoEncoder::InitParameters& video_parameters, const wds::AudioCodec& audio_codec, const std::string& sink_ip_address, const std::pair<int, int>& sink_rtp_ports, const RegisterMediaServiceCallback& service_callback, const ErrorCallback& error_callback); void CreateMediaPacketizer(); void OnInitialize(const InitCompletionCallback& callback, InitializationStep current_step, bool success); void OnAudioEncoderCreated( const InitStepCompletionCallback& callback, scoped_refptr<WiFiDisplayAudioEncoder> audio_encoder); void OnVideoEncoderCreated( const InitStepCompletionCallback& callback, scoped_refptr<WiFiDisplayVideoEncoder> video_encoder); void OnMediaServiceRegistered(const InitCompletionCallback& callback); void OnEncodedAudioUnit(std::unique_ptr<WiFiDisplayEncodedUnit> unit); void OnEncodedVideoFrame(std::unique_ptr<WiFiDisplayEncodedFrame> frame); bool OnPacketizedMediaDatagramPacket( WiFiDisplayMediaDatagramPacket media_datagram_packet); scoped_refptr<WiFiDisplayAudioEncoder> audio_encoder_; scoped_refptr<WiFiDisplayVideoEncoder> video_encoder_; std::unique_ptr<WiFiDisplayMediaPacketizer> packetizer_; wds::SessionType type_; WiFiDisplayVideoEncoder::InitParameters video_parameters_; wds::AudioCodec audio_codec_; std::string sink_ip_address_; std::pair<int, int> sink_rtp_ports_; RegisterMediaServiceCallback service_callback_; ErrorCallback error_callback_; mojom::WiFiDisplayMediaServicePtr media_service_; base::WeakPtrFactory<WiFiDisplayMediaPipeline> weak_factory_; DISALLOW_COPY_AND_ASSIGN(WiFiDisplayMediaPipeline); }; } // namespace extensions #endif // EXTENSIONS_RENDERER_API_DISPLAY_SOURCE_WIFI_DISPLAY_WIFI_DISPLAY_MEDIA_PIPELINE_H_
null
null
null
null
21,889
45,798
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
45,798
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 "ash/metrics/task_switch_time_tracker.h" #include <string> #include "ash/metrics/task_switch_time_tracker_test_api.h" #include "base/test/histogram_tester.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash { namespace { // A dummy histogram name. const std::string kHistogramName = "Dummy.Histogram"; } // namespace class TaskSwitchTimeTrackerTest : public testing::Test { public: TaskSwitchTimeTrackerTest(); ~TaskSwitchTimeTrackerTest() override; // testing::Test: void SetUp() override; void TearDown() override; // Wrapper to the test targets OnTaskSwitch() method. void OnTaskSwitch(); TaskSwitchTimeTracker* time_tracker() { return time_tracker_test_api_->time_tracker(); } protected: // Used to verify recorded histogram data. std::unique_ptr<base::HistogramTester> histogram_tester_; // A Test API that wraps the test target. std::unique_ptr<TaskSwitchTimeTrackerTestAPI> time_tracker_test_api_; private: DISALLOW_COPY_AND_ASSIGN(TaskSwitchTimeTrackerTest); }; TaskSwitchTimeTrackerTest::TaskSwitchTimeTrackerTest() = default; TaskSwitchTimeTrackerTest::~TaskSwitchTimeTrackerTest() = default; void TaskSwitchTimeTrackerTest::SetUp() { testing::Test::SetUp(); histogram_tester_.reset(new base::HistogramTester()); time_tracker_test_api_.reset( new TaskSwitchTimeTrackerTestAPI(kHistogramName)); // The TaskSwitchTimeTracker interprets a value of base::TimeTicks() as if the // |last_action_time_| has not been set. time_tracker_test_api_->Advance(base::TimeDelta::FromMilliseconds(1)); } void TaskSwitchTimeTrackerTest::TearDown() { testing::Test::TearDown(); time_tracker_test_api_.reset(); histogram_tester_.reset(); } void TaskSwitchTimeTrackerTest::OnTaskSwitch() { time_tracker()->OnTaskSwitch(); } // Verifies TaskSwitchTimeTracker::HasLastActionTime() returns false after // construction. TEST_F(TaskSwitchTimeTrackerTest, HasLastActionTimeShouldBeFalseAfterConstruction) { EXPECT_FALSE(time_tracker_test_api_->HasLastActionTime()); } // Verifies TaskSwitchTimeTracker::HasLastActionTime() returns true after the // first call to TaskSwitchTimeTracker::OnTaskSwitch() and no histogram data was // recorded. TEST_F(TaskSwitchTimeTrackerTest, HasLastActionTimeShouldBeTrueAfterOnTaskSwitch) { OnTaskSwitch(); histogram_tester_->ExpectTotalCount(kHistogramName, 0); } // Verfies that the histogram data is recorded in the correct buckets. TEST_F(TaskSwitchTimeTrackerTest, RecordAfterTwoTaskSwitches) { OnTaskSwitch(); time_tracker_test_api_->Advance(base::TimeDelta::FromMilliseconds(2)); OnTaskSwitch(); histogram_tester_->ExpectTotalCount(kHistogramName, 1); histogram_tester_->ExpectBucketCount(kHistogramName, 0, 1); time_tracker_test_api_->Advance(base::TimeDelta::FromSeconds(1)); OnTaskSwitch(); histogram_tester_->ExpectTotalCount(kHistogramName, 2); histogram_tester_->ExpectBucketCount(kHistogramName, 1, 1); } } // namespace ash
null
null
null
null
42,661
38,982
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
203,977
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Access kernel memory without faulting. */ #include <linux/export.h> #include <linux/mm.h> #include <linux/uaccess.h> /** * probe_kernel_read(): safely attempt to read from a location * @dst: pointer to the buffer that shall take the data * @src: address to read from * @size: size of the data chunk * * Safely read from address @src to the buffer at @dst. If a kernel fault * happens, handle that and return -EFAULT. * * We ensure that the copy_from_user is executed in atomic context so that * do_page_fault() doesn't attempt to take mmap_sem. This makes * probe_kernel_read() suitable for use within regions where the caller * already holds mmap_sem, or other locks which nest inside mmap_sem. */ long __weak probe_kernel_read(void *dst, const void *src, size_t size) __attribute__((alias("__probe_kernel_read"))); long __probe_kernel_read(void *dst, const void *src, size_t size) { long ret; mm_segment_t old_fs = get_fs(); set_fs(KERNEL_DS); pagefault_disable(); ret = __copy_from_user_inatomic(dst, (__force const void __user *)src, size); pagefault_enable(); set_fs(old_fs); return ret ? -EFAULT : 0; } EXPORT_SYMBOL_GPL(probe_kernel_read); /** * probe_kernel_write(): safely attempt to write to a location * @dst: address to write to * @src: pointer to the data that shall be written * @size: size of the data chunk * * Safely write to address @dst from the buffer at @src. If a kernel fault * happens, handle that and return -EFAULT. */ long __weak probe_kernel_write(void *dst, const void *src, size_t size) __attribute__((alias("__probe_kernel_write"))); long __probe_kernel_write(void *dst, const void *src, size_t size) { long ret; mm_segment_t old_fs = get_fs(); set_fs(KERNEL_DS); pagefault_disable(); ret = __copy_to_user_inatomic((__force void __user *)dst, src, size); pagefault_enable(); set_fs(old_fs); return ret ? -EFAULT : 0; } EXPORT_SYMBOL_GPL(probe_kernel_write); /** * strncpy_from_unsafe: - Copy a NUL terminated string from unsafe address. * @dst: Destination address, in kernel space. This buffer must be at * least @count bytes long. * @src: Unsafe address. * @count: Maximum number of bytes to copy, including the trailing NUL. * * Copies a NUL-terminated string from unsafe address to kernel buffer. * * On success, returns the length of the string INCLUDING the trailing NUL. * * If access fails, returns -EFAULT (some data may have been copied * and the trailing NUL added). * * If @count is smaller than the length of the string, copies @count-1 bytes, * sets the last byte of @dst buffer to NUL and returns @count. */ long strncpy_from_unsafe(char *dst, const void *unsafe_addr, long count) { mm_segment_t old_fs = get_fs(); const void *src = unsafe_addr; long ret; if (unlikely(count <= 0)) return 0; set_fs(KERNEL_DS); pagefault_disable(); do { ret = __get_user(*dst++, (const char __user __force *)src++); } while (dst[-1] && ret == 0 && src - unsafe_addr < count); dst[-1] = '\0'; pagefault_enable(); set_fs(old_fs); return ret ? -EFAULT : src - unsafe_addr; }
null
null
null
null
112,324
31,475
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
196,470
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Disk Array driver for Compaq SMART2 Controllers * Copyright 1998 Compaq Computer 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, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Questions/Comments/Bugfixes to [email protected] * * If you want to make changes, improve or add functionality to this * driver, you'll probably need the Compaq Array Controller Interface * Specificiation (Document number ECG086/1198) */ /* * This file contains the controller communication implementation for * Compaq SMART-1 and SMART-2 controllers. To the best of my knowledge, * this should support: * * PCI: * SMART-2/P, SMART-2DH, SMART-2SL, SMART-221, SMART-3100ES, SMART-3200 * Integerated SMART Array Controller, SMART-4200, SMART-4250ES * * EISA: * SMART-2/E, SMART, IAES, IDA-2, IDA */ /* * Memory mapped FIFO interface (SMART 42xx cards) */ static void smart4_submit_command(ctlr_info_t *h, cmdlist_t *c) { writel(c->busaddr, h->vaddr + S42XX_REQUEST_PORT_OFFSET); } /* * This card is the opposite of the other cards. * 0 turns interrupts on... * 0x08 turns them off... */ static void smart4_intr_mask(ctlr_info_t *h, unsigned long val) { if (val) { /* Turn interrupts on */ writel(0, h->vaddr + S42XX_REPLY_INTR_MASK_OFFSET); } else /* Turn them off */ { writel( S42XX_INTR_OFF, h->vaddr + S42XX_REPLY_INTR_MASK_OFFSET); } } /* * For older cards FIFO Full = 0. * On this card 0 means there is room, anything else FIFO Full. * */ static unsigned long smart4_fifo_full(ctlr_info_t *h) { return (!readl(h->vaddr + S42XX_REQUEST_PORT_OFFSET)); } /* This type of controller returns -1 if the fifo is empty, * Not 0 like the others. * And we need to let it know we read a value out */ static unsigned long smart4_completed(ctlr_info_t *h) { long register_value = readl(h->vaddr + S42XX_REPLY_PORT_OFFSET); /* Fifo is empty */ if( register_value == 0xffffffff) return 0; /* Need to let it know we got the reply */ /* We do this by writing a 0 to the port we just read from */ writel(0, h->vaddr + S42XX_REPLY_PORT_OFFSET); return ((unsigned long) register_value); } /* * This hardware returns interrupt pending at a different place and * it does not tell us if the fifo is empty, we will have check * that by getting a 0 back from the command_completed call. */ static unsigned long smart4_intr_pending(ctlr_info_t *h) { unsigned long register_value = readl(h->vaddr + S42XX_INTR_STATUS); if( register_value & S42XX_INTR_PENDING) return FIFO_NOT_EMPTY; return 0 ; } static struct access_method smart4_access = { smart4_submit_command, smart4_intr_mask, smart4_fifo_full, smart4_intr_pending, smart4_completed, }; /* * Memory mapped FIFO interface (PCI SMART2 and SMART 3xxx cards) */ static void smart2_submit_command(ctlr_info_t *h, cmdlist_t *c) { writel(c->busaddr, h->vaddr + COMMAND_FIFO); } static void smart2_intr_mask(ctlr_info_t *h, unsigned long val) { writel(val, h->vaddr + INTR_MASK); } static unsigned long smart2_fifo_full(ctlr_info_t *h) { return readl(h->vaddr + COMMAND_FIFO); } static unsigned long smart2_completed(ctlr_info_t *h) { return readl(h->vaddr + COMMAND_COMPLETE_FIFO); } static unsigned long smart2_intr_pending(ctlr_info_t *h) { return readl(h->vaddr + INTR_PENDING); } static struct access_method smart2_access = { smart2_submit_command, smart2_intr_mask, smart2_fifo_full, smart2_intr_pending, smart2_completed, }; /* * IO access for SMART-2/E cards */ static void smart2e_submit_command(ctlr_info_t *h, cmdlist_t *c) { outl(c->busaddr, h->io_mem_addr + COMMAND_FIFO); } static void smart2e_intr_mask(ctlr_info_t *h, unsigned long val) { outl(val, h->io_mem_addr + INTR_MASK); } static unsigned long smart2e_fifo_full(ctlr_info_t *h) { return inl(h->io_mem_addr + COMMAND_FIFO); } static unsigned long smart2e_completed(ctlr_info_t *h) { return inl(h->io_mem_addr + COMMAND_COMPLETE_FIFO); } static unsigned long smart2e_intr_pending(ctlr_info_t *h) { return inl(h->io_mem_addr + INTR_PENDING); } static struct access_method smart2e_access = { smart2e_submit_command, smart2e_intr_mask, smart2e_fifo_full, smart2e_intr_pending, smart2e_completed, }; /* * IO access for older SMART-1 type cards */ #define SMART1_SYSTEM_MASK 0xC8E #define SMART1_SYSTEM_DOORBELL 0xC8F #define SMART1_LOCAL_MASK 0xC8C #define SMART1_LOCAL_DOORBELL 0xC8D #define SMART1_INTR_MASK 0xC89 #define SMART1_LISTADDR 0xC90 #define SMART1_LISTLEN 0xC94 #define SMART1_TAG 0xC97 #define SMART1_COMPLETE_ADDR 0xC98 #define SMART1_LISTSTATUS 0xC9E #define CHANNEL_BUSY 0x01 #define CHANNEL_CLEAR 0x02 static void smart1_submit_command(ctlr_info_t *h, cmdlist_t *c) { /* * This __u16 is actually a bunch of control flags on SMART * and below. We want them all to be zero. */ c->hdr.size = 0; outb(CHANNEL_CLEAR, h->io_mem_addr + SMART1_SYSTEM_DOORBELL); outl(c->busaddr, h->io_mem_addr + SMART1_LISTADDR); outw(c->size, h->io_mem_addr + SMART1_LISTLEN); outb(CHANNEL_BUSY, h->io_mem_addr + SMART1_LOCAL_DOORBELL); } static void smart1_intr_mask(ctlr_info_t *h, unsigned long val) { if (val == 1) { outb(0xFD, h->io_mem_addr + SMART1_SYSTEM_DOORBELL); outb(CHANNEL_BUSY, h->io_mem_addr + SMART1_LOCAL_DOORBELL); outb(0x01, h->io_mem_addr + SMART1_INTR_MASK); outb(0x01, h->io_mem_addr + SMART1_SYSTEM_MASK); } else { outb(0, h->io_mem_addr + 0xC8E); } } static unsigned long smart1_fifo_full(ctlr_info_t *h) { unsigned char chan; chan = inb(h->io_mem_addr + SMART1_SYSTEM_DOORBELL) & CHANNEL_CLEAR; return chan; } static unsigned long smart1_completed(ctlr_info_t *h) { unsigned char status; unsigned long cmd; if (inb(h->io_mem_addr + SMART1_SYSTEM_DOORBELL) & CHANNEL_BUSY) { outb(CHANNEL_BUSY, h->io_mem_addr + SMART1_SYSTEM_DOORBELL); cmd = inl(h->io_mem_addr + SMART1_COMPLETE_ADDR); status = inb(h->io_mem_addr + SMART1_LISTSTATUS); outb(CHANNEL_CLEAR, h->io_mem_addr + SMART1_LOCAL_DOORBELL); /* * this is x86 (actually compaq x86) only, so it's ok */ if (cmd) ((cmdlist_t*)bus_to_virt(cmd))->req.hdr.rcode = status; } else { cmd = 0; } return cmd; } static unsigned long smart1_intr_pending(ctlr_info_t *h) { unsigned char chan; chan = inb(h->io_mem_addr + SMART1_SYSTEM_DOORBELL) & CHANNEL_BUSY; return chan; } static struct access_method smart1_access = { smart1_submit_command, smart1_intr_mask, smart1_fifo_full, smart1_intr_pending, smart1_completed, };
null
null
null
null
104,817
19,167
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
19,167
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 COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_INIT_AWARE_EVENT_MODEL_H_ #define COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_INIT_AWARE_EVENT_MODEL_H_ #include <stdint.h> #include <memory> #include <string> #include <tuple> #include <vector> #include "base/memory/weak_ptr.h" #include "components/feature_engagement/internal/event_model.h" namespace feature_engagement { class InitAwareEventModel : public EventModel { public: InitAwareEventModel(std::unique_ptr<EventModel> event_model); ~InitAwareEventModel() override; // EventModel implementation. void Initialize(const OnModelInitializationFinished& callback, uint32_t current_day) override; bool IsReady() const override; const Event* GetEvent(const std::string& event_name) const override; void IncrementEvent(const std::string& event_name, uint32_t current_day) override; size_t GetQueuedEventCountForTesting(); private: void OnInitializeComplete(const OnModelInitializationFinished& callback, bool success); std::unique_ptr<EventModel> event_model_; std::vector<std::tuple<std::string, uint32_t>> queued_events_; // Whether the initialization has completed. This will be set to true once // the underlying event model has been initialized, regardless of whether the // result was a success or not. bool initialization_complete_; base::WeakPtrFactory<InitAwareEventModel> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(InitAwareEventModel); }; } // namespace feature_engagement #endif // COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_INIT_AWARE_EVENT_MODEL_H_
null
null
null
null
16,030
8,066
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
173,061
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Generate .byte code for some instructions not supported by old * binutils. */ #ifndef X86_ASM_INST_H #define X86_ASM_INST_H #ifdef __ASSEMBLY__ #define REG_NUM_INVALID 100 #define REG_TYPE_R32 0 #define REG_TYPE_R64 1 #define REG_TYPE_XMM 2 #define REG_TYPE_INVALID 100 .macro R32_NUM opd r32 \opd = REG_NUM_INVALID .ifc \r32,%eax \opd = 0 .endif .ifc \r32,%ecx \opd = 1 .endif .ifc \r32,%edx \opd = 2 .endif .ifc \r32,%ebx \opd = 3 .endif .ifc \r32,%esp \opd = 4 .endif .ifc \r32,%ebp \opd = 5 .endif .ifc \r32,%esi \opd = 6 .endif .ifc \r32,%edi \opd = 7 .endif #ifdef CONFIG_X86_64 .ifc \r32,%r8d \opd = 8 .endif .ifc \r32,%r9d \opd = 9 .endif .ifc \r32,%r10d \opd = 10 .endif .ifc \r32,%r11d \opd = 11 .endif .ifc \r32,%r12d \opd = 12 .endif .ifc \r32,%r13d \opd = 13 .endif .ifc \r32,%r14d \opd = 14 .endif .ifc \r32,%r15d \opd = 15 .endif #endif .endm .macro R64_NUM opd r64 \opd = REG_NUM_INVALID #ifdef CONFIG_X86_64 .ifc \r64,%rax \opd = 0 .endif .ifc \r64,%rcx \opd = 1 .endif .ifc \r64,%rdx \opd = 2 .endif .ifc \r64,%rbx \opd = 3 .endif .ifc \r64,%rsp \opd = 4 .endif .ifc \r64,%rbp \opd = 5 .endif .ifc \r64,%rsi \opd = 6 .endif .ifc \r64,%rdi \opd = 7 .endif .ifc \r64,%r8 \opd = 8 .endif .ifc \r64,%r9 \opd = 9 .endif .ifc \r64,%r10 \opd = 10 .endif .ifc \r64,%r11 \opd = 11 .endif .ifc \r64,%r12 \opd = 12 .endif .ifc \r64,%r13 \opd = 13 .endif .ifc \r64,%r14 \opd = 14 .endif .ifc \r64,%r15 \opd = 15 .endif #endif .endm .macro XMM_NUM opd xmm \opd = REG_NUM_INVALID .ifc \xmm,%xmm0 \opd = 0 .endif .ifc \xmm,%xmm1 \opd = 1 .endif .ifc \xmm,%xmm2 \opd = 2 .endif .ifc \xmm,%xmm3 \opd = 3 .endif .ifc \xmm,%xmm4 \opd = 4 .endif .ifc \xmm,%xmm5 \opd = 5 .endif .ifc \xmm,%xmm6 \opd = 6 .endif .ifc \xmm,%xmm7 \opd = 7 .endif .ifc \xmm,%xmm8 \opd = 8 .endif .ifc \xmm,%xmm9 \opd = 9 .endif .ifc \xmm,%xmm10 \opd = 10 .endif .ifc \xmm,%xmm11 \opd = 11 .endif .ifc \xmm,%xmm12 \opd = 12 .endif .ifc \xmm,%xmm13 \opd = 13 .endif .ifc \xmm,%xmm14 \opd = 14 .endif .ifc \xmm,%xmm15 \opd = 15 .endif .endm .macro REG_TYPE type reg R32_NUM reg_type_r32 \reg R64_NUM reg_type_r64 \reg XMM_NUM reg_type_xmm \reg .if reg_type_r64 <> REG_NUM_INVALID \type = REG_TYPE_R64 .elseif reg_type_r32 <> REG_NUM_INVALID \type = REG_TYPE_R32 .elseif reg_type_xmm <> REG_NUM_INVALID \type = REG_TYPE_XMM .else \type = REG_TYPE_INVALID .endif .endm .macro PFX_OPD_SIZE .byte 0x66 .endm .macro PFX_REX opd1 opd2 W=0 .if ((\opd1 | \opd2) & 8) || \W .byte 0x40 | ((\opd1 & 8) >> 3) | ((\opd2 & 8) >> 1) | (\W << 3) .endif .endm .macro MODRM mod opd1 opd2 .byte \mod | (\opd1 & 7) | ((\opd2 & 7) << 3) .endm .macro PSHUFB_XMM xmm1 xmm2 XMM_NUM pshufb_opd1 \xmm1 XMM_NUM pshufb_opd2 \xmm2 PFX_OPD_SIZE PFX_REX pshufb_opd1 pshufb_opd2 .byte 0x0f, 0x38, 0x00 MODRM 0xc0 pshufb_opd1 pshufb_opd2 .endm .macro PCLMULQDQ imm8 xmm1 xmm2 XMM_NUM clmul_opd1 \xmm1 XMM_NUM clmul_opd2 \xmm2 PFX_OPD_SIZE PFX_REX clmul_opd1 clmul_opd2 .byte 0x0f, 0x3a, 0x44 MODRM 0xc0 clmul_opd1 clmul_opd2 .byte \imm8 .endm .macro PEXTRD imm8 xmm gpr R32_NUM extrd_opd1 \gpr XMM_NUM extrd_opd2 \xmm PFX_OPD_SIZE PFX_REX extrd_opd1 extrd_opd2 .byte 0x0f, 0x3a, 0x16 MODRM 0xc0 extrd_opd1 extrd_opd2 .byte \imm8 .endm .macro AESKEYGENASSIST rcon xmm1 xmm2 XMM_NUM aeskeygen_opd1 \xmm1 XMM_NUM aeskeygen_opd2 \xmm2 PFX_OPD_SIZE PFX_REX aeskeygen_opd1 aeskeygen_opd2 .byte 0x0f, 0x3a, 0xdf MODRM 0xc0 aeskeygen_opd1 aeskeygen_opd2 .byte \rcon .endm .macro AESIMC xmm1 xmm2 XMM_NUM aesimc_opd1 \xmm1 XMM_NUM aesimc_opd2 \xmm2 PFX_OPD_SIZE PFX_REX aesimc_opd1 aesimc_opd2 .byte 0x0f, 0x38, 0xdb MODRM 0xc0 aesimc_opd1 aesimc_opd2 .endm .macro AESENC xmm1 xmm2 XMM_NUM aesenc_opd1 \xmm1 XMM_NUM aesenc_opd2 \xmm2 PFX_OPD_SIZE PFX_REX aesenc_opd1 aesenc_opd2 .byte 0x0f, 0x38, 0xdc MODRM 0xc0 aesenc_opd1 aesenc_opd2 .endm .macro AESENCLAST xmm1 xmm2 XMM_NUM aesenclast_opd1 \xmm1 XMM_NUM aesenclast_opd2 \xmm2 PFX_OPD_SIZE PFX_REX aesenclast_opd1 aesenclast_opd2 .byte 0x0f, 0x38, 0xdd MODRM 0xc0 aesenclast_opd1 aesenclast_opd2 .endm .macro AESDEC xmm1 xmm2 XMM_NUM aesdec_opd1 \xmm1 XMM_NUM aesdec_opd2 \xmm2 PFX_OPD_SIZE PFX_REX aesdec_opd1 aesdec_opd2 .byte 0x0f, 0x38, 0xde MODRM 0xc0 aesdec_opd1 aesdec_opd2 .endm .macro AESDECLAST xmm1 xmm2 XMM_NUM aesdeclast_opd1 \xmm1 XMM_NUM aesdeclast_opd2 \xmm2 PFX_OPD_SIZE PFX_REX aesdeclast_opd1 aesdeclast_opd2 .byte 0x0f, 0x38, 0xdf MODRM 0xc0 aesdeclast_opd1 aesdeclast_opd2 .endm .macro MOVQ_R64_XMM opd1 opd2 REG_TYPE movq_r64_xmm_opd1_type \opd1 .if movq_r64_xmm_opd1_type == REG_TYPE_XMM XMM_NUM movq_r64_xmm_opd1 \opd1 R64_NUM movq_r64_xmm_opd2 \opd2 .else R64_NUM movq_r64_xmm_opd1 \opd1 XMM_NUM movq_r64_xmm_opd2 \opd2 .endif PFX_OPD_SIZE PFX_REX movq_r64_xmm_opd1 movq_r64_xmm_opd2 1 .if movq_r64_xmm_opd1_type == REG_TYPE_XMM .byte 0x0f, 0x7e .else .byte 0x0f, 0x6e .endif MODRM 0xc0 movq_r64_xmm_opd1 movq_r64_xmm_opd2 .endm #endif #endif
null
null
null
null
81,408
35,049
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
200,044
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* evga-indtube.h - Keytable for evga_indtube Remote Controller * * keymap imported from ir-keymaps.c * * Copyright (c) 2010 by Mauro Carvalho Chehab * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <media/rc-map.h> #include <linux/module.h> /* EVGA inDtube Devin Heitmueller <[email protected]> */ static struct rc_map_table evga_indtube[] = { { 0x12, KEY_POWER}, { 0x02, KEY_MODE}, /* TV */ { 0x14, KEY_MUTE}, { 0x1a, KEY_CHANNELUP}, { 0x16, KEY_TV2}, /* PIP */ { 0x1d, KEY_VOLUMEUP}, { 0x05, KEY_CHANNELDOWN}, { 0x0f, KEY_PLAYPAUSE}, { 0x19, KEY_VOLUMEDOWN}, { 0x1c, KEY_REWIND}, { 0x0d, KEY_RECORD}, { 0x18, KEY_FORWARD}, { 0x1e, KEY_PREVIOUS}, { 0x1b, KEY_STOP}, { 0x1f, KEY_NEXT}, { 0x13, KEY_CAMERA}, }; static struct rc_map_list evga_indtube_map = { .map = { .scan = evga_indtube, .size = ARRAY_SIZE(evga_indtube), .rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */ .name = RC_MAP_EVGA_INDTUBE, } }; static int __init init_rc_map_evga_indtube(void) { return rc_map_register(&evga_indtube_map); } static void __exit exit_rc_map_evga_indtube(void) { rc_map_unregister(&evga_indtube_map); } module_init(init_rc_map_evga_indtube) module_exit(exit_rc_map_evga_indtube) MODULE_LICENSE("GPL"); MODULE_AUTHOR("Mauro Carvalho Chehab");
null
null
null
null
108,391
1,552
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
154,609
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * SVQ1/SVQ3 decoder common code * * 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 <stdint.h> #include "svq1.h" static const uint16_t checksum_table[256] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 }; uint16_t ff_svq1_packet_checksum (const uint8_t *data, const int length, int value) { int i; for (i = 0; i < length; i++) value = checksum_table[data[i] ^ (value >> 8)] ^ ((value & 0xFF) << 8); return value; }
null
null
null
null
70,664
9,399
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
174,394
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * TI DA830/OMAP L137 chip specific setup * * Author: Mark A. Greer <[email protected]> * * 2009 (c) MontaVista Software, Inc. This file is licensed under * the terms of the GNU General Public License version 2. This program * is licensed "as is" without any warranty of any kind, whether express * or implied. */ #include <linux/gpio.h> #include <linux/init.h> #include <linux/clk.h> #include <linux/platform_data/gpio-davinci.h> #include <asm/mach/map.h> #include "psc.h" #include <mach/irqs.h> #include <mach/cputype.h> #include <mach/common.h> #include <mach/time.h> #include <mach/da8xx.h> #include "clock.h" #include "mux.h" /* Offsets of the 8 compare registers on the da830 */ #define DA830_CMP12_0 0x60 #define DA830_CMP12_1 0x64 #define DA830_CMP12_2 0x68 #define DA830_CMP12_3 0x6c #define DA830_CMP12_4 0x70 #define DA830_CMP12_5 0x74 #define DA830_CMP12_6 0x78 #define DA830_CMP12_7 0x7c #define DA830_REF_FREQ 24000000 static struct pll_data pll0_data = { .num = 1, .phys_base = DA8XX_PLL0_BASE, .flags = PLL_HAS_PREDIV | PLL_HAS_POSTDIV, }; static struct clk ref_clk = { .name = "ref_clk", .rate = DA830_REF_FREQ, }; static struct clk pll0_clk = { .name = "pll0", .parent = &ref_clk, .pll_data = &pll0_data, .flags = CLK_PLL, }; static struct clk pll0_aux_clk = { .name = "pll0_aux_clk", .parent = &pll0_clk, .flags = CLK_PLL | PRE_PLL, }; static struct clk pll0_sysclk2 = { .name = "pll0_sysclk2", .parent = &pll0_clk, .flags = CLK_PLL, .div_reg = PLLDIV2, }; static struct clk pll0_sysclk3 = { .name = "pll0_sysclk3", .parent = &pll0_clk, .flags = CLK_PLL, .div_reg = PLLDIV3, }; static struct clk pll0_sysclk4 = { .name = "pll0_sysclk4", .parent = &pll0_clk, .flags = CLK_PLL, .div_reg = PLLDIV4, }; static struct clk pll0_sysclk5 = { .name = "pll0_sysclk5", .parent = &pll0_clk, .flags = CLK_PLL, .div_reg = PLLDIV5, }; static struct clk pll0_sysclk6 = { .name = "pll0_sysclk6", .parent = &pll0_clk, .flags = CLK_PLL, .div_reg = PLLDIV6, }; static struct clk pll0_sysclk7 = { .name = "pll0_sysclk7", .parent = &pll0_clk, .flags = CLK_PLL, .div_reg = PLLDIV7, }; static struct clk i2c0_clk = { .name = "i2c0", .parent = &pll0_aux_clk, }; static struct clk timerp64_0_clk = { .name = "timer0", .parent = &pll0_aux_clk, }; static struct clk timerp64_1_clk = { .name = "timer1", .parent = &pll0_aux_clk, }; static struct clk arm_rom_clk = { .name = "arm_rom", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_ARM_RAM_ROM, .flags = ALWAYS_ENABLED, }; static struct clk scr0_ss_clk = { .name = "scr0_ss", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_SCR0_SS, .flags = ALWAYS_ENABLED, }; static struct clk scr1_ss_clk = { .name = "scr1_ss", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_SCR1_SS, .flags = ALWAYS_ENABLED, }; static struct clk scr2_ss_clk = { .name = "scr2_ss", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_SCR2_SS, .flags = ALWAYS_ENABLED, }; static struct clk dmax_clk = { .name = "dmax", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_PRUSS, .flags = ALWAYS_ENABLED, }; static struct clk tpcc_clk = { .name = "tpcc", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_TPCC, .flags = ALWAYS_ENABLED | CLK_PSC, }; static struct clk tptc0_clk = { .name = "tptc0", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_TPTC0, .flags = ALWAYS_ENABLED, }; static struct clk tptc1_clk = { .name = "tptc1", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_TPTC1, .flags = ALWAYS_ENABLED, }; static struct clk mmcsd_clk = { .name = "mmcsd", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_MMC_SD, }; static struct clk uart0_clk = { .name = "uart0", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_UART0, }; static struct clk uart1_clk = { .name = "uart1", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_UART1, .gpsc = 1, }; static struct clk uart2_clk = { .name = "uart2", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_UART2, .gpsc = 1, }; static struct clk spi0_clk = { .name = "spi0", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC0_SPI0, }; static struct clk spi1_clk = { .name = "spi1", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_SPI1, .gpsc = 1, }; static struct clk ecap0_clk = { .name = "ecap0", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_ECAP, .gpsc = 1, }; static struct clk ecap1_clk = { .name = "ecap1", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_ECAP, .gpsc = 1, }; static struct clk ecap2_clk = { .name = "ecap2", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_ECAP, .gpsc = 1, }; static struct clk pwm0_clk = { .name = "pwm0", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_PWM, .gpsc = 1, }; static struct clk pwm1_clk = { .name = "pwm1", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_PWM, .gpsc = 1, }; static struct clk pwm2_clk = { .name = "pwm2", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_PWM, .gpsc = 1, }; static struct clk eqep0_clk = { .name = "eqep0", .parent = &pll0_sysclk2, .lpsc = DA830_LPSC1_EQEP, .gpsc = 1, }; static struct clk eqep1_clk = { .name = "eqep1", .parent = &pll0_sysclk2, .lpsc = DA830_LPSC1_EQEP, .gpsc = 1, }; static struct clk lcdc_clk = { .name = "lcdc", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_LCDC, .gpsc = 1, }; static struct clk mcasp0_clk = { .name = "mcasp0", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_McASP0, .gpsc = 1, }; static struct clk mcasp1_clk = { .name = "mcasp1", .parent = &pll0_sysclk2, .lpsc = DA830_LPSC1_McASP1, .gpsc = 1, }; static struct clk mcasp2_clk = { .name = "mcasp2", .parent = &pll0_sysclk2, .lpsc = DA830_LPSC1_McASP2, .gpsc = 1, }; static struct clk usb20_clk = { .name = "usb20", .parent = &pll0_sysclk2, .lpsc = DA8XX_LPSC1_USB20, .gpsc = 1, }; static struct clk aemif_clk = { .name = "aemif", .parent = &pll0_sysclk3, .lpsc = DA8XX_LPSC0_EMIF25, .flags = ALWAYS_ENABLED, }; static struct clk aintc_clk = { .name = "aintc", .parent = &pll0_sysclk4, .lpsc = DA8XX_LPSC0_AINTC, .flags = ALWAYS_ENABLED, }; static struct clk secu_mgr_clk = { .name = "secu_mgr", .parent = &pll0_sysclk4, .lpsc = DA8XX_LPSC0_SECU_MGR, .flags = ALWAYS_ENABLED, }; static struct clk emac_clk = { .name = "emac", .parent = &pll0_sysclk4, .lpsc = DA8XX_LPSC1_CPGMAC, .gpsc = 1, }; static struct clk gpio_clk = { .name = "gpio", .parent = &pll0_sysclk4, .lpsc = DA8XX_LPSC1_GPIO, .gpsc = 1, }; static struct clk i2c1_clk = { .name = "i2c1", .parent = &pll0_sysclk4, .lpsc = DA8XX_LPSC1_I2C, .gpsc = 1, }; static struct clk usb11_clk = { .name = "usb11", .parent = &pll0_sysclk4, .lpsc = DA8XX_LPSC1_USB11, .gpsc = 1, }; static struct clk emif3_clk = { .name = "emif3", .parent = &pll0_sysclk5, .lpsc = DA8XX_LPSC1_EMIF3C, .gpsc = 1, .flags = ALWAYS_ENABLED, }; static struct clk arm_clk = { .name = "arm", .parent = &pll0_sysclk6, .lpsc = DA8XX_LPSC0_ARM, .flags = ALWAYS_ENABLED, }; static struct clk rmii_clk = { .name = "rmii", .parent = &pll0_sysclk7, }; static struct clk_lookup da830_clks[] = { CLK(NULL, "ref", &ref_clk), CLK(NULL, "pll0", &pll0_clk), CLK(NULL, "pll0_aux", &pll0_aux_clk), CLK(NULL, "pll0_sysclk2", &pll0_sysclk2), CLK(NULL, "pll0_sysclk3", &pll0_sysclk3), CLK(NULL, "pll0_sysclk4", &pll0_sysclk4), CLK(NULL, "pll0_sysclk5", &pll0_sysclk5), CLK(NULL, "pll0_sysclk6", &pll0_sysclk6), CLK(NULL, "pll0_sysclk7", &pll0_sysclk7), CLK("i2c_davinci.1", NULL, &i2c0_clk), CLK(NULL, "timer0", &timerp64_0_clk), CLK("davinci-wdt", NULL, &timerp64_1_clk), CLK(NULL, "arm_rom", &arm_rom_clk), CLK(NULL, "scr0_ss", &scr0_ss_clk), CLK(NULL, "scr1_ss", &scr1_ss_clk), CLK(NULL, "scr2_ss", &scr2_ss_clk), CLK(NULL, "dmax", &dmax_clk), CLK(NULL, "tpcc", &tpcc_clk), CLK(NULL, "tptc0", &tptc0_clk), CLK(NULL, "tptc1", &tptc1_clk), CLK("da830-mmc.0", NULL, &mmcsd_clk), CLK("serial8250.0", NULL, &uart0_clk), CLK("serial8250.1", NULL, &uart1_clk), CLK("serial8250.2", NULL, &uart2_clk), CLK("spi_davinci.0", NULL, &spi0_clk), CLK("spi_davinci.1", NULL, &spi1_clk), CLK(NULL, "ecap0", &ecap0_clk), CLK(NULL, "ecap1", &ecap1_clk), CLK(NULL, "ecap2", &ecap2_clk), CLK(NULL, "pwm0", &pwm0_clk), CLK(NULL, "pwm1", &pwm1_clk), CLK(NULL, "pwm2", &pwm2_clk), CLK("eqep.0", NULL, &eqep0_clk), CLK("eqep.1", NULL, &eqep1_clk), CLK("da8xx_lcdc.0", "fck", &lcdc_clk), CLK("davinci-mcasp.0", NULL, &mcasp0_clk), CLK("davinci-mcasp.1", NULL, &mcasp1_clk), CLK("davinci-mcasp.2", NULL, &mcasp2_clk), CLK("musb-da8xx", "usb20", &usb20_clk), CLK(NULL, "aemif", &aemif_clk), CLK(NULL, "aintc", &aintc_clk), CLK(NULL, "secu_mgr", &secu_mgr_clk), CLK("davinci_emac.1", NULL, &emac_clk), CLK("davinci_mdio.0", "fck", &emac_clk), CLK(NULL, "gpio", &gpio_clk), CLK("i2c_davinci.2", NULL, &i2c1_clk), CLK("ohci-da8xx", "usb11", &usb11_clk), CLK(NULL, "emif3", &emif3_clk), CLK(NULL, "arm", &arm_clk), CLK(NULL, "rmii", &rmii_clk), CLK(NULL, NULL, NULL), }; /* * Device specific mux setup * * soc description mux mode mode mux dbg * reg offset mask mode */ static const struct mux_config da830_pins[] = { #ifdef CONFIG_DAVINCI_MUX MUX_CFG(DA830, GPIO7_14, 0, 0, 0xf, 1, false) MUX_CFG(DA830, RTCK, 0, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO7_15, 0, 4, 0xf, 1, false) MUX_CFG(DA830, EMU_0, 0, 4, 0xf, 8, false) MUX_CFG(DA830, EMB_SDCKE, 0, 8, 0xf, 1, false) MUX_CFG(DA830, EMB_CLK_GLUE, 0, 12, 0xf, 1, false) MUX_CFG(DA830, EMB_CLK, 0, 12, 0xf, 2, false) MUX_CFG(DA830, NEMB_CS_0, 0, 16, 0xf, 1, false) MUX_CFG(DA830, NEMB_CAS, 0, 20, 0xf, 1, false) MUX_CFG(DA830, NEMB_RAS, 0, 24, 0xf, 1, false) MUX_CFG(DA830, NEMB_WE, 0, 28, 0xf, 1, false) MUX_CFG(DA830, EMB_BA_1, 1, 0, 0xf, 1, false) MUX_CFG(DA830, EMB_BA_0, 1, 4, 0xf, 1, false) MUX_CFG(DA830, EMB_A_0, 1, 8, 0xf, 1, false) MUX_CFG(DA830, EMB_A_1, 1, 12, 0xf, 1, false) MUX_CFG(DA830, EMB_A_2, 1, 16, 0xf, 1, false) MUX_CFG(DA830, EMB_A_3, 1, 20, 0xf, 1, false) MUX_CFG(DA830, EMB_A_4, 1, 24, 0xf, 1, false) MUX_CFG(DA830, EMB_A_5, 1, 28, 0xf, 1, false) MUX_CFG(DA830, GPIO7_0, 1, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO7_1, 1, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO7_2, 1, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO7_3, 1, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO7_4, 1, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO7_5, 1, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO7_6, 1, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO7_7, 1, 28, 0xf, 8, false) MUX_CFG(DA830, EMB_A_6, 2, 0, 0xf, 1, false) MUX_CFG(DA830, EMB_A_7, 2, 4, 0xf, 1, false) MUX_CFG(DA830, EMB_A_8, 2, 8, 0xf, 1, false) MUX_CFG(DA830, EMB_A_9, 2, 12, 0xf, 1, false) MUX_CFG(DA830, EMB_A_10, 2, 16, 0xf, 1, false) MUX_CFG(DA830, EMB_A_11, 2, 20, 0xf, 1, false) MUX_CFG(DA830, EMB_A_12, 2, 24, 0xf, 1, false) MUX_CFG(DA830, EMB_D_31, 2, 28, 0xf, 1, false) MUX_CFG(DA830, GPIO7_8, 2, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO7_9, 2, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO7_10, 2, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO7_11, 2, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO7_12, 2, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO7_13, 2, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO3_13, 2, 24, 0xf, 8, false) MUX_CFG(DA830, EMB_D_30, 3, 0, 0xf, 1, false) MUX_CFG(DA830, EMB_D_29, 3, 4, 0xf, 1, false) MUX_CFG(DA830, EMB_D_28, 3, 8, 0xf, 1, false) MUX_CFG(DA830, EMB_D_27, 3, 12, 0xf, 1, false) MUX_CFG(DA830, EMB_D_26, 3, 16, 0xf, 1, false) MUX_CFG(DA830, EMB_D_25, 3, 20, 0xf, 1, false) MUX_CFG(DA830, EMB_D_24, 3, 24, 0xf, 1, false) MUX_CFG(DA830, EMB_D_23, 3, 28, 0xf, 1, false) MUX_CFG(DA830, EMB_D_22, 4, 0, 0xf, 1, false) MUX_CFG(DA830, EMB_D_21, 4, 4, 0xf, 1, false) MUX_CFG(DA830, EMB_D_20, 4, 8, 0xf, 1, false) MUX_CFG(DA830, EMB_D_19, 4, 12, 0xf, 1, false) MUX_CFG(DA830, EMB_D_18, 4, 16, 0xf, 1, false) MUX_CFG(DA830, EMB_D_17, 4, 20, 0xf, 1, false) MUX_CFG(DA830, EMB_D_16, 4, 24, 0xf, 1, false) MUX_CFG(DA830, NEMB_WE_DQM_3, 4, 28, 0xf, 1, false) MUX_CFG(DA830, NEMB_WE_DQM_2, 5, 0, 0xf, 1, false) MUX_CFG(DA830, EMB_D_0, 5, 4, 0xf, 1, false) MUX_CFG(DA830, EMB_D_1, 5, 8, 0xf, 1, false) MUX_CFG(DA830, EMB_D_2, 5, 12, 0xf, 1, false) MUX_CFG(DA830, EMB_D_3, 5, 16, 0xf, 1, false) MUX_CFG(DA830, EMB_D_4, 5, 20, 0xf, 1, false) MUX_CFG(DA830, EMB_D_5, 5, 24, 0xf, 1, false) MUX_CFG(DA830, EMB_D_6, 5, 28, 0xf, 1, false) MUX_CFG(DA830, GPIO6_0, 5, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO6_1, 5, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO6_2, 5, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO6_3, 5, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO6_4, 5, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO6_5, 5, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO6_6, 5, 28, 0xf, 8, false) MUX_CFG(DA830, EMB_D_7, 6, 0, 0xf, 1, false) MUX_CFG(DA830, EMB_D_8, 6, 4, 0xf, 1, false) MUX_CFG(DA830, EMB_D_9, 6, 8, 0xf, 1, false) MUX_CFG(DA830, EMB_D_10, 6, 12, 0xf, 1, false) MUX_CFG(DA830, EMB_D_11, 6, 16, 0xf, 1, false) MUX_CFG(DA830, EMB_D_12, 6, 20, 0xf, 1, false) MUX_CFG(DA830, EMB_D_13, 6, 24, 0xf, 1, false) MUX_CFG(DA830, EMB_D_14, 6, 28, 0xf, 1, false) MUX_CFG(DA830, GPIO6_7, 6, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO6_8, 6, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO6_9, 6, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO6_10, 6, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO6_11, 6, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO6_12, 6, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO6_13, 6, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO6_14, 6, 28, 0xf, 8, false) MUX_CFG(DA830, EMB_D_15, 7, 0, 0xf, 1, false) MUX_CFG(DA830, NEMB_WE_DQM_1, 7, 4, 0xf, 1, false) MUX_CFG(DA830, NEMB_WE_DQM_0, 7, 8, 0xf, 1, false) MUX_CFG(DA830, SPI0_SOMI_0, 7, 12, 0xf, 1, false) MUX_CFG(DA830, SPI0_SIMO_0, 7, 16, 0xf, 1, false) MUX_CFG(DA830, SPI0_CLK, 7, 20, 0xf, 1, false) MUX_CFG(DA830, NSPI0_ENA, 7, 24, 0xf, 1, false) MUX_CFG(DA830, NSPI0_SCS_0, 7, 28, 0xf, 1, false) MUX_CFG(DA830, EQEP0I, 7, 12, 0xf, 2, false) MUX_CFG(DA830, EQEP0S, 7, 16, 0xf, 2, false) MUX_CFG(DA830, EQEP1I, 7, 20, 0xf, 2, false) MUX_CFG(DA830, NUART0_CTS, 7, 24, 0xf, 2, false) MUX_CFG(DA830, NUART0_RTS, 7, 28, 0xf, 2, false) MUX_CFG(DA830, EQEP0A, 7, 24, 0xf, 4, false) MUX_CFG(DA830, EQEP0B, 7, 28, 0xf, 4, false) MUX_CFG(DA830, GPIO6_15, 7, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO5_14, 7, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO5_15, 7, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO5_0, 7, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO5_1, 7, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO5_2, 7, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO5_3, 7, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO5_4, 7, 28, 0xf, 8, false) MUX_CFG(DA830, SPI1_SOMI_0, 8, 0, 0xf, 1, false) MUX_CFG(DA830, SPI1_SIMO_0, 8, 4, 0xf, 1, false) MUX_CFG(DA830, SPI1_CLK, 8, 8, 0xf, 1, false) MUX_CFG(DA830, UART0_RXD, 8, 12, 0xf, 1, false) MUX_CFG(DA830, UART0_TXD, 8, 16, 0xf, 1, false) MUX_CFG(DA830, AXR1_10, 8, 20, 0xf, 1, false) MUX_CFG(DA830, AXR1_11, 8, 24, 0xf, 1, false) MUX_CFG(DA830, NSPI1_ENA, 8, 28, 0xf, 1, false) MUX_CFG(DA830, I2C1_SCL, 8, 0, 0xf, 2, false) MUX_CFG(DA830, I2C1_SDA, 8, 4, 0xf, 2, false) MUX_CFG(DA830, EQEP1S, 8, 8, 0xf, 2, false) MUX_CFG(DA830, I2C0_SDA, 8, 12, 0xf, 2, false) MUX_CFG(DA830, I2C0_SCL, 8, 16, 0xf, 2, false) MUX_CFG(DA830, UART2_RXD, 8, 28, 0xf, 2, false) MUX_CFG(DA830, TM64P0_IN12, 8, 12, 0xf, 4, false) MUX_CFG(DA830, TM64P0_OUT12, 8, 16, 0xf, 4, false) MUX_CFG(DA830, GPIO5_5, 8, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO5_6, 8, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO5_7, 8, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO5_8, 8, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO5_9, 8, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO5_10, 8, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO5_11, 8, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO5_12, 8, 28, 0xf, 8, false) MUX_CFG(DA830, NSPI1_SCS_0, 9, 0, 0xf, 1, false) MUX_CFG(DA830, USB0_DRVVBUS, 9, 4, 0xf, 1, false) MUX_CFG(DA830, AHCLKX0, 9, 8, 0xf, 1, false) MUX_CFG(DA830, ACLKX0, 9, 12, 0xf, 1, false) MUX_CFG(DA830, AFSX0, 9, 16, 0xf, 1, false) MUX_CFG(DA830, AHCLKR0, 9, 20, 0xf, 1, false) MUX_CFG(DA830, ACLKR0, 9, 24, 0xf, 1, false) MUX_CFG(DA830, AFSR0, 9, 28, 0xf, 1, false) MUX_CFG(DA830, UART2_TXD, 9, 0, 0xf, 2, false) MUX_CFG(DA830, AHCLKX2, 9, 8, 0xf, 2, false) MUX_CFG(DA830, ECAP0_APWM0, 9, 12, 0xf, 2, false) MUX_CFG(DA830, RMII_MHZ_50_CLK, 9, 20, 0xf, 2, false) MUX_CFG(DA830, ECAP1_APWM1, 9, 24, 0xf, 2, false) MUX_CFG(DA830, USB_REFCLKIN, 9, 8, 0xf, 4, false) MUX_CFG(DA830, GPIO5_13, 9, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO4_15, 9, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO2_11, 9, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO2_12, 9, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO2_13, 9, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO2_14, 9, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO2_15, 9, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO3_12, 9, 28, 0xf, 8, false) MUX_CFG(DA830, AMUTE0, 10, 0, 0xf, 1, false) MUX_CFG(DA830, AXR0_0, 10, 4, 0xf, 1, false) MUX_CFG(DA830, AXR0_1, 10, 8, 0xf, 1, false) MUX_CFG(DA830, AXR0_2, 10, 12, 0xf, 1, false) MUX_CFG(DA830, AXR0_3, 10, 16, 0xf, 1, false) MUX_CFG(DA830, AXR0_4, 10, 20, 0xf, 1, false) MUX_CFG(DA830, AXR0_5, 10, 24, 0xf, 1, false) MUX_CFG(DA830, AXR0_6, 10, 28, 0xf, 1, false) MUX_CFG(DA830, RMII_TXD_0, 10, 4, 0xf, 2, false) MUX_CFG(DA830, RMII_TXD_1, 10, 8, 0xf, 2, false) MUX_CFG(DA830, RMII_TXEN, 10, 12, 0xf, 2, false) MUX_CFG(DA830, RMII_CRS_DV, 10, 16, 0xf, 2, false) MUX_CFG(DA830, RMII_RXD_0, 10, 20, 0xf, 2, false) MUX_CFG(DA830, RMII_RXD_1, 10, 24, 0xf, 2, false) MUX_CFG(DA830, RMII_RXER, 10, 28, 0xf, 2, false) MUX_CFG(DA830, AFSR2, 10, 4, 0xf, 4, false) MUX_CFG(DA830, ACLKX2, 10, 8, 0xf, 4, false) MUX_CFG(DA830, AXR2_3, 10, 12, 0xf, 4, false) MUX_CFG(DA830, AXR2_2, 10, 16, 0xf, 4, false) MUX_CFG(DA830, AXR2_1, 10, 20, 0xf, 4, false) MUX_CFG(DA830, AFSX2, 10, 24, 0xf, 4, false) MUX_CFG(DA830, ACLKR2, 10, 28, 0xf, 4, false) MUX_CFG(DA830, NRESETOUT, 10, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO3_0, 10, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO3_1, 10, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO3_2, 10, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO3_3, 10, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO3_4, 10, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO3_5, 10, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO3_6, 10, 28, 0xf, 8, false) MUX_CFG(DA830, AXR0_7, 11, 0, 0xf, 1, false) MUX_CFG(DA830, AXR0_8, 11, 4, 0xf, 1, false) MUX_CFG(DA830, UART1_RXD, 11, 8, 0xf, 1, false) MUX_CFG(DA830, UART1_TXD, 11, 12, 0xf, 1, false) MUX_CFG(DA830, AXR0_11, 11, 16, 0xf, 1, false) MUX_CFG(DA830, AHCLKX1, 11, 20, 0xf, 1, false) MUX_CFG(DA830, ACLKX1, 11, 24, 0xf, 1, false) MUX_CFG(DA830, AFSX1, 11, 28, 0xf, 1, false) MUX_CFG(DA830, MDIO_CLK, 11, 0, 0xf, 2, false) MUX_CFG(DA830, MDIO_D, 11, 4, 0xf, 2, false) MUX_CFG(DA830, AXR0_9, 11, 8, 0xf, 2, false) MUX_CFG(DA830, AXR0_10, 11, 12, 0xf, 2, false) MUX_CFG(DA830, EPWM0B, 11, 20, 0xf, 2, false) MUX_CFG(DA830, EPWM0A, 11, 24, 0xf, 2, false) MUX_CFG(DA830, EPWMSYNCI, 11, 28, 0xf, 2, false) MUX_CFG(DA830, AXR2_0, 11, 16, 0xf, 4, false) MUX_CFG(DA830, EPWMSYNC0, 11, 28, 0xf, 4, false) MUX_CFG(DA830, GPIO3_7, 11, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO3_8, 11, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO3_9, 11, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO3_10, 11, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO3_11, 11, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO3_14, 11, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO3_15, 11, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO4_10, 11, 28, 0xf, 8, false) MUX_CFG(DA830, AHCLKR1, 12, 0, 0xf, 1, false) MUX_CFG(DA830, ACLKR1, 12, 4, 0xf, 1, false) MUX_CFG(DA830, AFSR1, 12, 8, 0xf, 1, false) MUX_CFG(DA830, AMUTE1, 12, 12, 0xf, 1, false) MUX_CFG(DA830, AXR1_0, 12, 16, 0xf, 1, false) MUX_CFG(DA830, AXR1_1, 12, 20, 0xf, 1, false) MUX_CFG(DA830, AXR1_2, 12, 24, 0xf, 1, false) MUX_CFG(DA830, AXR1_3, 12, 28, 0xf, 1, false) MUX_CFG(DA830, ECAP2_APWM2, 12, 4, 0xf, 2, false) MUX_CFG(DA830, EHRPWMGLUETZ, 12, 12, 0xf, 2, false) MUX_CFG(DA830, EQEP1A, 12, 28, 0xf, 2, false) MUX_CFG(DA830, GPIO4_11, 12, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO4_12, 12, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO4_13, 12, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO4_14, 12, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO4_0, 12, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO4_1, 12, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO4_2, 12, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO4_3, 12, 28, 0xf, 8, false) MUX_CFG(DA830, AXR1_4, 13, 0, 0xf, 1, false) MUX_CFG(DA830, AXR1_5, 13, 4, 0xf, 1, false) MUX_CFG(DA830, AXR1_6, 13, 8, 0xf, 1, false) MUX_CFG(DA830, AXR1_7, 13, 12, 0xf, 1, false) MUX_CFG(DA830, AXR1_8, 13, 16, 0xf, 1, false) MUX_CFG(DA830, AXR1_9, 13, 20, 0xf, 1, false) MUX_CFG(DA830, EMA_D_0, 13, 24, 0xf, 1, false) MUX_CFG(DA830, EMA_D_1, 13, 28, 0xf, 1, false) MUX_CFG(DA830, EQEP1B, 13, 0, 0xf, 2, false) MUX_CFG(DA830, EPWM2B, 13, 4, 0xf, 2, false) MUX_CFG(DA830, EPWM2A, 13, 8, 0xf, 2, false) MUX_CFG(DA830, EPWM1B, 13, 12, 0xf, 2, false) MUX_CFG(DA830, EPWM1A, 13, 16, 0xf, 2, false) MUX_CFG(DA830, MMCSD_DAT_0, 13, 24, 0xf, 2, false) MUX_CFG(DA830, MMCSD_DAT_1, 13, 28, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_0, 13, 24, 0xf, 4, false) MUX_CFG(DA830, UHPI_HD_1, 13, 28, 0xf, 4, false) MUX_CFG(DA830, GPIO4_4, 13, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO4_5, 13, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO4_6, 13, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO4_7, 13, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO4_8, 13, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO4_9, 13, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO0_0, 13, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO0_1, 13, 28, 0xf, 8, false) MUX_CFG(DA830, EMA_D_2, 14, 0, 0xf, 1, false) MUX_CFG(DA830, EMA_D_3, 14, 4, 0xf, 1, false) MUX_CFG(DA830, EMA_D_4, 14, 8, 0xf, 1, false) MUX_CFG(DA830, EMA_D_5, 14, 12, 0xf, 1, false) MUX_CFG(DA830, EMA_D_6, 14, 16, 0xf, 1, false) MUX_CFG(DA830, EMA_D_7, 14, 20, 0xf, 1, false) MUX_CFG(DA830, EMA_D_8, 14, 24, 0xf, 1, false) MUX_CFG(DA830, EMA_D_9, 14, 28, 0xf, 1, false) MUX_CFG(DA830, MMCSD_DAT_2, 14, 0, 0xf, 2, false) MUX_CFG(DA830, MMCSD_DAT_3, 14, 4, 0xf, 2, false) MUX_CFG(DA830, MMCSD_DAT_4, 14, 8, 0xf, 2, false) MUX_CFG(DA830, MMCSD_DAT_5, 14, 12, 0xf, 2, false) MUX_CFG(DA830, MMCSD_DAT_6, 14, 16, 0xf, 2, false) MUX_CFG(DA830, MMCSD_DAT_7, 14, 20, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_8, 14, 24, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_9, 14, 28, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_2, 14, 0, 0xf, 4, false) MUX_CFG(DA830, UHPI_HD_3, 14, 4, 0xf, 4, false) MUX_CFG(DA830, UHPI_HD_4, 14, 8, 0xf, 4, false) MUX_CFG(DA830, UHPI_HD_5, 14, 12, 0xf, 4, false) MUX_CFG(DA830, UHPI_HD_6, 14, 16, 0xf, 4, false) MUX_CFG(DA830, UHPI_HD_7, 14, 20, 0xf, 4, false) MUX_CFG(DA830, LCD_D_8, 14, 24, 0xf, 4, false) MUX_CFG(DA830, LCD_D_9, 14, 28, 0xf, 4, false) MUX_CFG(DA830, GPIO0_2, 14, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO0_3, 14, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO0_4, 14, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO0_5, 14, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO0_6, 14, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO0_7, 14, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO0_8, 14, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO0_9, 14, 28, 0xf, 8, false) MUX_CFG(DA830, EMA_D_10, 15, 0, 0xf, 1, false) MUX_CFG(DA830, EMA_D_11, 15, 4, 0xf, 1, false) MUX_CFG(DA830, EMA_D_12, 15, 8, 0xf, 1, false) MUX_CFG(DA830, EMA_D_13, 15, 12, 0xf, 1, false) MUX_CFG(DA830, EMA_D_14, 15, 16, 0xf, 1, false) MUX_CFG(DA830, EMA_D_15, 15, 20, 0xf, 1, false) MUX_CFG(DA830, EMA_A_0, 15, 24, 0xf, 1, false) MUX_CFG(DA830, EMA_A_1, 15, 28, 0xf, 1, false) MUX_CFG(DA830, UHPI_HD_10, 15, 0, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_11, 15, 4, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_12, 15, 8, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_13, 15, 12, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_14, 15, 16, 0xf, 2, false) MUX_CFG(DA830, UHPI_HD_15, 15, 20, 0xf, 2, false) MUX_CFG(DA830, LCD_D_7, 15, 24, 0xf, 2, false) MUX_CFG(DA830, MMCSD_CLK, 15, 28, 0xf, 2, false) MUX_CFG(DA830, LCD_D_10, 15, 0, 0xf, 4, false) MUX_CFG(DA830, LCD_D_11, 15, 4, 0xf, 4, false) MUX_CFG(DA830, LCD_D_12, 15, 8, 0xf, 4, false) MUX_CFG(DA830, LCD_D_13, 15, 12, 0xf, 4, false) MUX_CFG(DA830, LCD_D_14, 15, 16, 0xf, 4, false) MUX_CFG(DA830, LCD_D_15, 15, 20, 0xf, 4, false) MUX_CFG(DA830, UHPI_HCNTL0, 15, 28, 0xf, 4, false) MUX_CFG(DA830, GPIO0_10, 15, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO0_11, 15, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO0_12, 15, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO0_13, 15, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO0_14, 15, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO0_15, 15, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO1_0, 15, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO1_1, 15, 28, 0xf, 8, false) MUX_CFG(DA830, EMA_A_2, 16, 0, 0xf, 1, false) MUX_CFG(DA830, EMA_A_3, 16, 4, 0xf, 1, false) MUX_CFG(DA830, EMA_A_4, 16, 8, 0xf, 1, false) MUX_CFG(DA830, EMA_A_5, 16, 12, 0xf, 1, false) MUX_CFG(DA830, EMA_A_6, 16, 16, 0xf, 1, false) MUX_CFG(DA830, EMA_A_7, 16, 20, 0xf, 1, false) MUX_CFG(DA830, EMA_A_8, 16, 24, 0xf, 1, false) MUX_CFG(DA830, EMA_A_9, 16, 28, 0xf, 1, false) MUX_CFG(DA830, MMCSD_CMD, 16, 0, 0xf, 2, false) MUX_CFG(DA830, LCD_D_6, 16, 4, 0xf, 2, false) MUX_CFG(DA830, LCD_D_3, 16, 8, 0xf, 2, false) MUX_CFG(DA830, LCD_D_2, 16, 12, 0xf, 2, false) MUX_CFG(DA830, LCD_D_1, 16, 16, 0xf, 2, false) MUX_CFG(DA830, LCD_D_0, 16, 20, 0xf, 2, false) MUX_CFG(DA830, LCD_PCLK, 16, 24, 0xf, 2, false) MUX_CFG(DA830, LCD_HSYNC, 16, 28, 0xf, 2, false) MUX_CFG(DA830, UHPI_HCNTL1, 16, 0, 0xf, 4, false) MUX_CFG(DA830, GPIO1_2, 16, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO1_3, 16, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO1_4, 16, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO1_5, 16, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO1_6, 16, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO1_7, 16, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO1_8, 16, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO1_9, 16, 28, 0xf, 8, false) MUX_CFG(DA830, EMA_A_10, 17, 0, 0xf, 1, false) MUX_CFG(DA830, EMA_A_11, 17, 4, 0xf, 1, false) MUX_CFG(DA830, EMA_A_12, 17, 8, 0xf, 1, false) MUX_CFG(DA830, EMA_BA_1, 17, 12, 0xf, 1, false) MUX_CFG(DA830, EMA_BA_0, 17, 16, 0xf, 1, false) MUX_CFG(DA830, EMA_CLK, 17, 20, 0xf, 1, false) MUX_CFG(DA830, EMA_SDCKE, 17, 24, 0xf, 1, false) MUX_CFG(DA830, NEMA_CAS, 17, 28, 0xf, 1, false) MUX_CFG(DA830, LCD_VSYNC, 17, 0, 0xf, 2, false) MUX_CFG(DA830, NLCD_AC_ENB_CS, 17, 4, 0xf, 2, false) MUX_CFG(DA830, LCD_MCLK, 17, 8, 0xf, 2, false) MUX_CFG(DA830, LCD_D_5, 17, 12, 0xf, 2, false) MUX_CFG(DA830, LCD_D_4, 17, 16, 0xf, 2, false) MUX_CFG(DA830, OBSCLK, 17, 20, 0xf, 2, false) MUX_CFG(DA830, NEMA_CS_4, 17, 28, 0xf, 2, false) MUX_CFG(DA830, UHPI_HHWIL, 17, 12, 0xf, 4, false) MUX_CFG(DA830, AHCLKR2, 17, 20, 0xf, 4, false) MUX_CFG(DA830, GPIO1_10, 17, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO1_11, 17, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO1_12, 17, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO1_13, 17, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO1_14, 17, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO1_15, 17, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO2_0, 17, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO2_1, 17, 28, 0xf, 8, false) MUX_CFG(DA830, NEMA_RAS, 18, 0, 0xf, 1, false) MUX_CFG(DA830, NEMA_WE, 18, 4, 0xf, 1, false) MUX_CFG(DA830, NEMA_CS_0, 18, 8, 0xf, 1, false) MUX_CFG(DA830, NEMA_CS_2, 18, 12, 0xf, 1, false) MUX_CFG(DA830, NEMA_CS_3, 18, 16, 0xf, 1, false) MUX_CFG(DA830, NEMA_OE, 18, 20, 0xf, 1, false) MUX_CFG(DA830, NEMA_WE_DQM_1, 18, 24, 0xf, 1, false) MUX_CFG(DA830, NEMA_WE_DQM_0, 18, 28, 0xf, 1, false) MUX_CFG(DA830, NEMA_CS_5, 18, 0, 0xf, 2, false) MUX_CFG(DA830, UHPI_HRNW, 18, 4, 0xf, 2, false) MUX_CFG(DA830, NUHPI_HAS, 18, 8, 0xf, 2, false) MUX_CFG(DA830, NUHPI_HCS, 18, 12, 0xf, 2, false) MUX_CFG(DA830, NUHPI_HDS1, 18, 20, 0xf, 2, false) MUX_CFG(DA830, NUHPI_HDS2, 18, 24, 0xf, 2, false) MUX_CFG(DA830, NUHPI_HINT, 18, 28, 0xf, 2, false) MUX_CFG(DA830, AXR0_12, 18, 4, 0xf, 4, false) MUX_CFG(DA830, AMUTE2, 18, 16, 0xf, 4, false) MUX_CFG(DA830, AXR0_13, 18, 20, 0xf, 4, false) MUX_CFG(DA830, AXR0_14, 18, 24, 0xf, 4, false) MUX_CFG(DA830, AXR0_15, 18, 28, 0xf, 4, false) MUX_CFG(DA830, GPIO2_2, 18, 0, 0xf, 8, false) MUX_CFG(DA830, GPIO2_3, 18, 4, 0xf, 8, false) MUX_CFG(DA830, GPIO2_4, 18, 8, 0xf, 8, false) MUX_CFG(DA830, GPIO2_5, 18, 12, 0xf, 8, false) MUX_CFG(DA830, GPIO2_6, 18, 16, 0xf, 8, false) MUX_CFG(DA830, GPIO2_7, 18, 20, 0xf, 8, false) MUX_CFG(DA830, GPIO2_8, 18, 24, 0xf, 8, false) MUX_CFG(DA830, GPIO2_9, 18, 28, 0xf, 8, false) MUX_CFG(DA830, EMA_WAIT_0, 19, 0, 0xf, 1, false) MUX_CFG(DA830, NUHPI_HRDY, 19, 0, 0xf, 2, false) MUX_CFG(DA830, GPIO2_10, 19, 0, 0xf, 8, false) #endif }; const short da830_emif25_pins[] __initconst = { DA830_EMA_D_0, DA830_EMA_D_1, DA830_EMA_D_2, DA830_EMA_D_3, DA830_EMA_D_4, DA830_EMA_D_5, DA830_EMA_D_6, DA830_EMA_D_7, DA830_EMA_D_8, DA830_EMA_D_9, DA830_EMA_D_10, DA830_EMA_D_11, DA830_EMA_D_12, DA830_EMA_D_13, DA830_EMA_D_14, DA830_EMA_D_15, DA830_EMA_A_0, DA830_EMA_A_1, DA830_EMA_A_2, DA830_EMA_A_3, DA830_EMA_A_4, DA830_EMA_A_5, DA830_EMA_A_6, DA830_EMA_A_7, DA830_EMA_A_8, DA830_EMA_A_9, DA830_EMA_A_10, DA830_EMA_A_11, DA830_EMA_A_12, DA830_EMA_BA_0, DA830_EMA_BA_1, DA830_EMA_CLK, DA830_EMA_SDCKE, DA830_NEMA_CS_4, DA830_NEMA_CS_5, DA830_NEMA_WE, DA830_NEMA_CS_0, DA830_NEMA_CS_2, DA830_NEMA_CS_3, DA830_NEMA_OE, DA830_NEMA_WE_DQM_1, DA830_NEMA_WE_DQM_0, DA830_EMA_WAIT_0, -1 }; const short da830_spi0_pins[] __initconst = { DA830_SPI0_SOMI_0, DA830_SPI0_SIMO_0, DA830_SPI0_CLK, DA830_NSPI0_ENA, DA830_NSPI0_SCS_0, -1 }; const short da830_spi1_pins[] __initconst = { DA830_SPI1_SOMI_0, DA830_SPI1_SIMO_0, DA830_SPI1_CLK, DA830_NSPI1_ENA, DA830_NSPI1_SCS_0, -1 }; const short da830_mmc_sd_pins[] __initconst = { DA830_MMCSD_DAT_0, DA830_MMCSD_DAT_1, DA830_MMCSD_DAT_2, DA830_MMCSD_DAT_3, DA830_MMCSD_DAT_4, DA830_MMCSD_DAT_5, DA830_MMCSD_DAT_6, DA830_MMCSD_DAT_7, DA830_MMCSD_CLK, DA830_MMCSD_CMD, -1 }; const short da830_uart0_pins[] __initconst = { DA830_NUART0_CTS, DA830_NUART0_RTS, DA830_UART0_RXD, DA830_UART0_TXD, -1 }; const short da830_uart1_pins[] __initconst = { DA830_UART1_RXD, DA830_UART1_TXD, -1 }; const short da830_uart2_pins[] __initconst = { DA830_UART2_RXD, DA830_UART2_TXD, -1 }; const short da830_usb20_pins[] __initconst = { DA830_USB0_DRVVBUS, DA830_USB_REFCLKIN, -1 }; const short da830_usb11_pins[] __initconst = { DA830_USB_REFCLKIN, -1 }; const short da830_uhpi_pins[] __initconst = { DA830_UHPI_HD_0, DA830_UHPI_HD_1, DA830_UHPI_HD_2, DA830_UHPI_HD_3, DA830_UHPI_HD_4, DA830_UHPI_HD_5, DA830_UHPI_HD_6, DA830_UHPI_HD_7, DA830_UHPI_HD_8, DA830_UHPI_HD_9, DA830_UHPI_HD_10, DA830_UHPI_HD_11, DA830_UHPI_HD_12, DA830_UHPI_HD_13, DA830_UHPI_HD_14, DA830_UHPI_HD_15, DA830_UHPI_HCNTL0, DA830_UHPI_HCNTL1, DA830_UHPI_HHWIL, DA830_UHPI_HRNW, DA830_NUHPI_HAS, DA830_NUHPI_HCS, DA830_NUHPI_HDS1, DA830_NUHPI_HDS2, DA830_NUHPI_HINT, DA830_NUHPI_HRDY, -1 }; const short da830_cpgmac_pins[] __initconst = { DA830_RMII_TXD_0, DA830_RMII_TXD_1, DA830_RMII_TXEN, DA830_RMII_CRS_DV, DA830_RMII_RXD_0, DA830_RMII_RXD_1, DA830_RMII_RXER, DA830_MDIO_CLK, DA830_MDIO_D, -1 }; const short da830_emif3c_pins[] __initconst = { DA830_EMB_SDCKE, DA830_EMB_CLK_GLUE, DA830_EMB_CLK, DA830_NEMB_CS_0, DA830_NEMB_CAS, DA830_NEMB_RAS, DA830_NEMB_WE, DA830_EMB_BA_1, DA830_EMB_BA_0, DA830_EMB_A_0, DA830_EMB_A_1, DA830_EMB_A_2, DA830_EMB_A_3, DA830_EMB_A_4, DA830_EMB_A_5, DA830_EMB_A_6, DA830_EMB_A_7, DA830_EMB_A_8, DA830_EMB_A_9, DA830_EMB_A_10, DA830_EMB_A_11, DA830_EMB_A_12, DA830_NEMB_WE_DQM_3, DA830_NEMB_WE_DQM_2, DA830_EMB_D_0, DA830_EMB_D_1, DA830_EMB_D_2, DA830_EMB_D_3, DA830_EMB_D_4, DA830_EMB_D_5, DA830_EMB_D_6, DA830_EMB_D_7, DA830_EMB_D_8, DA830_EMB_D_9, DA830_EMB_D_10, DA830_EMB_D_11, DA830_EMB_D_12, DA830_EMB_D_13, DA830_EMB_D_14, DA830_EMB_D_15, DA830_EMB_D_16, DA830_EMB_D_17, DA830_EMB_D_18, DA830_EMB_D_19, DA830_EMB_D_20, DA830_EMB_D_21, DA830_EMB_D_22, DA830_EMB_D_23, DA830_EMB_D_24, DA830_EMB_D_25, DA830_EMB_D_26, DA830_EMB_D_27, DA830_EMB_D_28, DA830_EMB_D_29, DA830_EMB_D_30, DA830_EMB_D_31, DA830_NEMB_WE_DQM_1, DA830_NEMB_WE_DQM_0, -1 }; const short da830_mcasp0_pins[] __initconst = { DA830_AHCLKX0, DA830_ACLKX0, DA830_AFSX0, DA830_AHCLKR0, DA830_ACLKR0, DA830_AFSR0, DA830_AMUTE0, DA830_AXR0_0, DA830_AXR0_1, DA830_AXR0_2, DA830_AXR0_3, DA830_AXR0_4, DA830_AXR0_5, DA830_AXR0_6, DA830_AXR0_7, DA830_AXR0_8, DA830_AXR0_9, DA830_AXR0_10, DA830_AXR0_11, DA830_AXR0_12, DA830_AXR0_13, DA830_AXR0_14, DA830_AXR0_15, -1 }; const short da830_mcasp1_pins[] __initconst = { DA830_AHCLKX1, DA830_ACLKX1, DA830_AFSX1, DA830_AHCLKR1, DA830_ACLKR1, DA830_AFSR1, DA830_AMUTE1, DA830_AXR1_0, DA830_AXR1_1, DA830_AXR1_2, DA830_AXR1_3, DA830_AXR1_4, DA830_AXR1_5, DA830_AXR1_6, DA830_AXR1_7, DA830_AXR1_8, DA830_AXR1_9, DA830_AXR1_10, DA830_AXR1_11, -1 }; const short da830_mcasp2_pins[] __initconst = { DA830_AHCLKX2, DA830_ACLKX2, DA830_AFSX2, DA830_AHCLKR2, DA830_ACLKR2, DA830_AFSR2, DA830_AMUTE2, DA830_AXR2_0, DA830_AXR2_1, DA830_AXR2_2, DA830_AXR2_3, -1 }; const short da830_i2c0_pins[] __initconst = { DA830_I2C0_SDA, DA830_I2C0_SCL, -1 }; const short da830_i2c1_pins[] __initconst = { DA830_I2C1_SCL, DA830_I2C1_SDA, -1 }; const short da830_lcdcntl_pins[] __initconst = { DA830_LCD_D_0, DA830_LCD_D_1, DA830_LCD_D_2, DA830_LCD_D_3, DA830_LCD_D_4, DA830_LCD_D_5, DA830_LCD_D_6, DA830_LCD_D_7, DA830_LCD_D_8, DA830_LCD_D_9, DA830_LCD_D_10, DA830_LCD_D_11, DA830_LCD_D_12, DA830_LCD_D_13, DA830_LCD_D_14, DA830_LCD_D_15, DA830_LCD_PCLK, DA830_LCD_HSYNC, DA830_LCD_VSYNC, DA830_NLCD_AC_ENB_CS, DA830_LCD_MCLK, -1 }; const short da830_pwm_pins[] __initconst = { DA830_ECAP0_APWM0, DA830_ECAP1_APWM1, DA830_EPWM0B, DA830_EPWM0A, DA830_EPWMSYNCI, DA830_EPWMSYNC0, DA830_ECAP2_APWM2, DA830_EHRPWMGLUETZ, DA830_EPWM2B, DA830_EPWM2A, DA830_EPWM1B, DA830_EPWM1A, -1 }; const short da830_ecap0_pins[] __initconst = { DA830_ECAP0_APWM0, -1 }; const short da830_ecap1_pins[] __initconst = { DA830_ECAP1_APWM1, -1 }; const short da830_ecap2_pins[] __initconst = { DA830_ECAP2_APWM2, -1 }; const short da830_eqep0_pins[] __initconst = { DA830_EQEP0I, DA830_EQEP0S, DA830_EQEP0A, DA830_EQEP0B, -1 }; const short da830_eqep1_pins[] __initconst = { DA830_EQEP1I, DA830_EQEP1S, DA830_EQEP1A, DA830_EQEP1B, -1 }; /* FIQ are pri 0-1; otherwise 2-7, with 7 lowest priority */ static u8 da830_default_priorities[DA830_N_CP_INTC_IRQ] = { [IRQ_DA8XX_COMMTX] = 7, [IRQ_DA8XX_COMMRX] = 7, [IRQ_DA8XX_NINT] = 7, [IRQ_DA8XX_EVTOUT0] = 7, [IRQ_DA8XX_EVTOUT1] = 7, [IRQ_DA8XX_EVTOUT2] = 7, [IRQ_DA8XX_EVTOUT3] = 7, [IRQ_DA8XX_EVTOUT4] = 7, [IRQ_DA8XX_EVTOUT5] = 7, [IRQ_DA8XX_EVTOUT6] = 7, [IRQ_DA8XX_EVTOUT7] = 7, [IRQ_DA8XX_CCINT0] = 7, [IRQ_DA8XX_CCERRINT] = 7, [IRQ_DA8XX_TCERRINT0] = 7, [IRQ_DA8XX_AEMIFINT] = 7, [IRQ_DA8XX_I2CINT0] = 7, [IRQ_DA8XX_MMCSDINT0] = 7, [IRQ_DA8XX_MMCSDINT1] = 7, [IRQ_DA8XX_ALLINT0] = 7, [IRQ_DA8XX_RTC] = 7, [IRQ_DA8XX_SPINT0] = 7, [IRQ_DA8XX_TINT12_0] = 7, [IRQ_DA8XX_TINT34_0] = 7, [IRQ_DA8XX_TINT12_1] = 7, [IRQ_DA8XX_TINT34_1] = 7, [IRQ_DA8XX_UARTINT0] = 7, [IRQ_DA8XX_KEYMGRINT] = 7, [IRQ_DA830_MPUERR] = 7, [IRQ_DA8XX_CHIPINT0] = 7, [IRQ_DA8XX_CHIPINT1] = 7, [IRQ_DA8XX_CHIPINT2] = 7, [IRQ_DA8XX_CHIPINT3] = 7, [IRQ_DA8XX_TCERRINT1] = 7, [IRQ_DA8XX_C0_RX_THRESH_PULSE] = 7, [IRQ_DA8XX_C0_RX_PULSE] = 7, [IRQ_DA8XX_C0_TX_PULSE] = 7, [IRQ_DA8XX_C0_MISC_PULSE] = 7, [IRQ_DA8XX_C1_RX_THRESH_PULSE] = 7, [IRQ_DA8XX_C1_RX_PULSE] = 7, [IRQ_DA8XX_C1_TX_PULSE] = 7, [IRQ_DA8XX_C1_MISC_PULSE] = 7, [IRQ_DA8XX_MEMERR] = 7, [IRQ_DA8XX_GPIO0] = 7, [IRQ_DA8XX_GPIO1] = 7, [IRQ_DA8XX_GPIO2] = 7, [IRQ_DA8XX_GPIO3] = 7, [IRQ_DA8XX_GPIO4] = 7, [IRQ_DA8XX_GPIO5] = 7, [IRQ_DA8XX_GPIO6] = 7, [IRQ_DA8XX_GPIO7] = 7, [IRQ_DA8XX_GPIO8] = 7, [IRQ_DA8XX_I2CINT1] = 7, [IRQ_DA8XX_LCDINT] = 7, [IRQ_DA8XX_UARTINT1] = 7, [IRQ_DA8XX_MCASPINT] = 7, [IRQ_DA8XX_ALLINT1] = 7, [IRQ_DA8XX_SPINT1] = 7, [IRQ_DA8XX_UHPI_INT1] = 7, [IRQ_DA8XX_USB_INT] = 7, [IRQ_DA8XX_IRQN] = 7, [IRQ_DA8XX_RWAKEUP] = 7, [IRQ_DA8XX_UARTINT2] = 7, [IRQ_DA8XX_DFTSSINT] = 7, [IRQ_DA8XX_EHRPWM0] = 7, [IRQ_DA8XX_EHRPWM0TZ] = 7, [IRQ_DA8XX_EHRPWM1] = 7, [IRQ_DA8XX_EHRPWM1TZ] = 7, [IRQ_DA830_EHRPWM2] = 7, [IRQ_DA830_EHRPWM2TZ] = 7, [IRQ_DA8XX_ECAP0] = 7, [IRQ_DA8XX_ECAP1] = 7, [IRQ_DA8XX_ECAP2] = 7, [IRQ_DA830_EQEP0] = 7, [IRQ_DA830_EQEP1] = 7, [IRQ_DA830_T12CMPINT0_0] = 7, [IRQ_DA830_T12CMPINT1_0] = 7, [IRQ_DA830_T12CMPINT2_0] = 7, [IRQ_DA830_T12CMPINT3_0] = 7, [IRQ_DA830_T12CMPINT4_0] = 7, [IRQ_DA830_T12CMPINT5_0] = 7, [IRQ_DA830_T12CMPINT6_0] = 7, [IRQ_DA830_T12CMPINT7_0] = 7, [IRQ_DA830_T12CMPINT0_1] = 7, [IRQ_DA830_T12CMPINT1_1] = 7, [IRQ_DA830_T12CMPINT2_1] = 7, [IRQ_DA830_T12CMPINT3_1] = 7, [IRQ_DA830_T12CMPINT4_1] = 7, [IRQ_DA830_T12CMPINT5_1] = 7, [IRQ_DA830_T12CMPINT6_1] = 7, [IRQ_DA830_T12CMPINT7_1] = 7, [IRQ_DA8XX_ARMCLKSTOPREQ] = 7, }; static struct map_desc da830_io_desc[] = { { .virtual = IO_VIRT, .pfn = __phys_to_pfn(IO_PHYS), .length = IO_SIZE, .type = MT_DEVICE }, { .virtual = DA8XX_CP_INTC_VIRT, .pfn = __phys_to_pfn(DA8XX_CP_INTC_BASE), .length = DA8XX_CP_INTC_SIZE, .type = MT_DEVICE }, }; static u32 da830_psc_bases[] = { DA8XX_PSC0_BASE, DA8XX_PSC1_BASE }; /* Contents of JTAG ID register used to identify exact cpu type */ static struct davinci_id da830_ids[] = { { .variant = 0x0, .part_no = 0xb7df, .manufacturer = 0x017, /* 0x02f >> 1 */ .cpu_id = DAVINCI_CPU_ID_DA830, .name = "da830/omap-l137 rev1.0", }, { .variant = 0x8, .part_no = 0xb7df, .manufacturer = 0x017, .cpu_id = DAVINCI_CPU_ID_DA830, .name = "da830/omap-l137 rev1.1", }, { .variant = 0x9, .part_no = 0xb7df, .manufacturer = 0x017, .cpu_id = DAVINCI_CPU_ID_DA830, .name = "da830/omap-l137 rev2.0", }, }; static struct davinci_gpio_platform_data da830_gpio_platform_data = { .ngpio = 128, }; int __init da830_register_gpio(void) { return da8xx_register_gpio(&da830_gpio_platform_data); } static struct davinci_timer_instance da830_timer_instance[2] = { { .base = DA8XX_TIMER64P0_BASE, .bottom_irq = IRQ_DA8XX_TINT12_0, .top_irq = IRQ_DA8XX_TINT34_0, .cmp_off = DA830_CMP12_0, .cmp_irq = IRQ_DA830_T12CMPINT0_0, }, { .base = DA8XX_TIMER64P1_BASE, .bottom_irq = IRQ_DA8XX_TINT12_1, .top_irq = IRQ_DA8XX_TINT34_1, .cmp_off = DA830_CMP12_0, .cmp_irq = IRQ_DA830_T12CMPINT0_1, }, }; /* * T0_BOT: Timer 0, bottom : Used for clock_event & clocksource * T0_TOP: Timer 0, top : Used by DSP * T1_BOT, T1_TOP: Timer 1, bottom & top: Used for watchdog timer */ static struct davinci_timer_info da830_timer_info = { .timers = da830_timer_instance, .clockevent_id = T0_BOT, .clocksource_id = T0_BOT, }; static struct davinci_soc_info davinci_soc_info_da830 = { .io_desc = da830_io_desc, .io_desc_num = ARRAY_SIZE(da830_io_desc), .jtag_id_reg = DA8XX_SYSCFG0_BASE + DA8XX_JTAG_ID_REG, .ids = da830_ids, .ids_num = ARRAY_SIZE(da830_ids), .cpu_clks = da830_clks, .psc_bases = da830_psc_bases, .psc_bases_num = ARRAY_SIZE(da830_psc_bases), .pinmux_base = DA8XX_SYSCFG0_BASE + 0x120, .pinmux_pins = da830_pins, .pinmux_pins_num = ARRAY_SIZE(da830_pins), .intc_base = DA8XX_CP_INTC_BASE, .intc_type = DAVINCI_INTC_TYPE_CP_INTC, .intc_irq_prios = da830_default_priorities, .intc_irq_num = DA830_N_CP_INTC_IRQ, .timer_info = &da830_timer_info, .emac_pdata = &da8xx_emac_pdata, }; void __init da830_init(void) { davinci_common_init(&davinci_soc_info_da830); da8xx_syscfg0_base = ioremap(DA8XX_SYSCFG0_BASE, SZ_4K); WARN(!da8xx_syscfg0_base, "Unable to map syscfg0 module"); davinci_clk_init(davinci_soc_info_da830.cpu_clks); }
null
null
null
null
82,741
528
null
train_val
83ed75feba32e46f736fcce0d96a0445f29b96c2
162,372
krb5
0
https://github.com/krb5/krb5
2016-01-27 15:43:28-05:00
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* plus/tls/k5tls/none.c - Stub TLS module implementation */ /* * Copyright (C) 2014 by the Massachusetts Institute of Technology. * 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. * * 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 HOLDER 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. */ /* This dummy module is used if no TLS implemented is selected. */ #include "k5-int.h" #include "k5-utf8.h" #include "k5-tls.h" #ifdef TLS_IMPL_NONE krb5_error_code tls_k5tls_initvt(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable); krb5_error_code tls_k5tls_initvt(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable) { /* Leave all vtable functions nulled. */ return 0; } #endif /* TLS_IMPL_NONE */
null
null
null
null
73,680
20,191
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
185,186
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* ldmvsw.c: Sun4v LDOM Virtual Switch Driver. * * Copyright (C) 2016 Oracle. All rights reserved. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/delay.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/highmem.h> #include <linux/if_vlan.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/netdevice.h> #include <linux/slab.h> #include <linux/types.h> #if defined(CONFIG_IPV6) #include <linux/icmpv6.h> #endif #include <net/ip.h> #include <net/icmp.h> #include <net/route.h> #include <asm/vio.h> #include <asm/ldc.h> /* This driver makes use of the common code in sunvnet_common.c */ #include "sunvnet_common.h" /* Length of time before we decide the hardware is hung, * and dev->tx_timeout() should be called to fix the problem. */ #define VSW_TX_TIMEOUT (10 * HZ) /* Static HW Addr used for the network interfaces representing vsw ports */ static u8 vsw_port_hwaddr[ETH_ALEN] = {0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; #define DRV_MODULE_NAME "ldmvsw" #define DRV_MODULE_VERSION "1.1" #define DRV_MODULE_RELDATE "February 3, 2017" static char version[] = DRV_MODULE_NAME " " DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")"; MODULE_AUTHOR("Oracle"); MODULE_DESCRIPTION("Sun4v LDOM Virtual Switch Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_MODULE_VERSION); /* Ordered from largest major to lowest */ static struct vio_version vsw_versions[] = { { .major = 1, .minor = 8 }, { .major = 1, .minor = 7 }, { .major = 1, .minor = 6 }, { .major = 1, .minor = 0 }, }; static void vsw_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version)); } static u32 vsw_get_msglevel(struct net_device *dev) { struct vnet_port *port = netdev_priv(dev); return port->vp->msg_enable; } static void vsw_set_msglevel(struct net_device *dev, u32 value) { struct vnet_port *port = netdev_priv(dev); port->vp->msg_enable = value; } static const struct ethtool_ops vsw_ethtool_ops = { .get_drvinfo = vsw_get_drvinfo, .get_msglevel = vsw_get_msglevel, .set_msglevel = vsw_set_msglevel, .get_link = ethtool_op_get_link, }; static LIST_HEAD(vnet_list); static DEFINE_MUTEX(vnet_list_mutex); /* func arg to vnet_start_xmit_common() to get the proper tx port */ static struct vnet_port *vsw_tx_port_find(struct sk_buff *skb, struct net_device *dev) { struct vnet_port *port = netdev_priv(dev); return port; } static u16 vsw_select_queue(struct net_device *dev, struct sk_buff *skb, void *accel_priv, select_queue_fallback_t fallback) { struct vnet_port *port = netdev_priv(dev); if (!port) return 0; return port->q_index; } /* Wrappers to common functions */ static int vsw_start_xmit(struct sk_buff *skb, struct net_device *dev) { return sunvnet_start_xmit_common(skb, dev, vsw_tx_port_find); } static void vsw_set_rx_mode(struct net_device *dev) { struct vnet_port *port = netdev_priv(dev); return sunvnet_set_rx_mode_common(dev, port->vp); } #ifdef CONFIG_NET_POLL_CONTROLLER static void vsw_poll_controller(struct net_device *dev) { struct vnet_port *port = netdev_priv(dev); return sunvnet_poll_controller_common(dev, port->vp); } #endif static const struct net_device_ops vsw_ops = { .ndo_open = sunvnet_open_common, .ndo_stop = sunvnet_close_common, .ndo_set_rx_mode = vsw_set_rx_mode, .ndo_set_mac_address = sunvnet_set_mac_addr_common, .ndo_validate_addr = eth_validate_addr, .ndo_tx_timeout = sunvnet_tx_timeout_common, .ndo_start_xmit = vsw_start_xmit, .ndo_select_queue = vsw_select_queue, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = vsw_poll_controller, #endif }; static const char *local_mac_prop = "local-mac-address"; static const char *cfg_handle_prop = "cfg-handle"; static struct vnet *vsw_get_vnet(struct mdesc_handle *hp, u64 port_node, u64 *handle) { struct vnet *vp; struct vnet *iter; const u64 *local_mac = NULL; const u64 *cfghandle = NULL; u64 a; /* Get the parent virtual-network-switch macaddr and cfghandle */ mdesc_for_each_arc(a, hp, port_node, MDESC_ARC_TYPE_BACK) { u64 target = mdesc_arc_target(hp, a); const char *name; name = mdesc_get_property(hp, target, "name", NULL); if (!name || strcmp(name, "virtual-network-switch")) continue; local_mac = mdesc_get_property(hp, target, local_mac_prop, NULL); cfghandle = mdesc_get_property(hp, target, cfg_handle_prop, NULL); break; } if (!local_mac || !cfghandle) return ERR_PTR(-ENODEV); /* find or create associated vnet */ vp = NULL; mutex_lock(&vnet_list_mutex); list_for_each_entry(iter, &vnet_list, list) { if (iter->local_mac == *local_mac) { vp = iter; break; } } if (!vp) { vp = kzalloc(sizeof(*vp), GFP_KERNEL); if (unlikely(!vp)) { mutex_unlock(&vnet_list_mutex); return ERR_PTR(-ENOMEM); } spin_lock_init(&vp->lock); INIT_LIST_HEAD(&vp->port_list); INIT_LIST_HEAD(&vp->list); vp->local_mac = *local_mac; list_add(&vp->list, &vnet_list); } mutex_unlock(&vnet_list_mutex); *handle = (u64)*cfghandle; return vp; } static struct net_device *vsw_alloc_netdev(u8 hwaddr[], struct vio_dev *vdev, u64 handle, u64 port_id) { struct net_device *dev; struct vnet_port *port; int i; dev = alloc_etherdev_mqs(sizeof(*port), VNET_MAX_TXQS, 1); if (!dev) return ERR_PTR(-ENOMEM); dev->needed_headroom = VNET_PACKET_SKIP + 8; dev->needed_tailroom = 8; for (i = 0; i < ETH_ALEN; i++) { dev->dev_addr[i] = hwaddr[i]; dev->perm_addr[i] = dev->dev_addr[i]; } sprintf(dev->name, "vif%d.%d", (int)handle, (int)port_id); dev->netdev_ops = &vsw_ops; dev->ethtool_ops = &vsw_ethtool_ops; dev->watchdog_timeo = VSW_TX_TIMEOUT; dev->hw_features = NETIF_F_HW_CSUM | NETIF_F_SG; dev->features = dev->hw_features; /* MTU range: 68 - 65535 */ dev->min_mtu = ETH_MIN_MTU; dev->max_mtu = VNET_MAX_MTU; SET_NETDEV_DEV(dev, &vdev->dev); return dev; } static struct ldc_channel_config vsw_ldc_cfg = { .event = sunvnet_event_common, .mtu = 64, .mode = LDC_MODE_UNRELIABLE, }; static struct vio_driver_ops vsw_vio_ops = { .send_attr = sunvnet_send_attr_common, .handle_attr = sunvnet_handle_attr_common, .handshake_complete = sunvnet_handshake_complete_common, }; static const char *remote_macaddr_prop = "remote-mac-address"; static const char *id_prop = "id"; static int vsw_port_probe(struct vio_dev *vdev, const struct vio_device_id *id) { struct mdesc_handle *hp; struct vnet_port *port; unsigned long flags; struct vnet *vp; struct net_device *dev; const u64 *rmac; int len, i, err; const u64 *port_id; u64 handle; hp = mdesc_grab(); rmac = mdesc_get_property(hp, vdev->mp, remote_macaddr_prop, &len); err = -ENODEV; if (!rmac) { pr_err("Port lacks %s property\n", remote_macaddr_prop); mdesc_release(hp); return err; } port_id = mdesc_get_property(hp, vdev->mp, id_prop, NULL); err = -ENODEV; if (!port_id) { pr_err("Port lacks %s property\n", id_prop); mdesc_release(hp); return err; } /* Get (or create) the vnet associated with this port */ vp = vsw_get_vnet(hp, vdev->mp, &handle); if (unlikely(IS_ERR(vp))) { err = PTR_ERR(vp); pr_err("Failed to get vnet for vsw-port\n"); mdesc_release(hp); return err; } mdesc_release(hp); dev = vsw_alloc_netdev(vsw_port_hwaddr, vdev, handle, *port_id); if (IS_ERR(dev)) { err = PTR_ERR(dev); pr_err("Failed to alloc netdev for vsw-port\n"); return err; } port = netdev_priv(dev); INIT_LIST_HEAD(&port->list); for (i = 0; i < ETH_ALEN; i++) port->raddr[i] = (*rmac >> (5 - i) * 8) & 0xff; port->vp = vp; port->dev = dev; port->switch_port = 1; port->tso = false; /* no tso in vsw, misbehaves in bridge */ port->tsolen = 0; /* Mark the port as belonging to ldmvsw which directs the * the common code to use the net_device in the vnet_port * rather than the net_device in the vnet (which is used * by sunvnet). This bit is used by the VNET_PORT_TO_NET_DEVICE * macro. */ port->vsw = 1; err = vio_driver_init(&port->vio, vdev, VDEV_NETWORK, vsw_versions, ARRAY_SIZE(vsw_versions), &vsw_vio_ops, dev->name); if (err) goto err_out_free_dev; err = vio_ldc_alloc(&port->vio, &vsw_ldc_cfg, port); if (err) goto err_out_free_dev; dev_set_drvdata(&vdev->dev, port); netif_napi_add(dev, &port->napi, sunvnet_poll_common, NAPI_POLL_WEIGHT); spin_lock_irqsave(&vp->lock, flags); list_add_rcu(&port->list, &vp->port_list); spin_unlock_irqrestore(&vp->lock, flags); setup_timer(&port->clean_timer, sunvnet_clean_timer_expire_common, (unsigned long)port); err = register_netdev(dev); if (err) { pr_err("Cannot register net device, aborting\n"); goto err_out_del_timer; } spin_lock_irqsave(&vp->lock, flags); sunvnet_port_add_txq_common(port); spin_unlock_irqrestore(&vp->lock, flags); napi_enable(&port->napi); vio_port_up(&port->vio); netdev_info(dev, "LDOM vsw-port %pM\n", dev->dev_addr); pr_info("%s: PORT ( remote-mac %pM%s )\n", dev->name, port->raddr, " switch-port"); return 0; err_out_del_timer: del_timer_sync(&port->clean_timer); list_del_rcu(&port->list); synchronize_rcu(); netif_napi_del(&port->napi); dev_set_drvdata(&vdev->dev, NULL); vio_ldc_free(&port->vio); err_out_free_dev: free_netdev(dev); return err; } static int vsw_port_remove(struct vio_dev *vdev) { struct vnet_port *port = dev_get_drvdata(&vdev->dev); unsigned long flags; if (port) { del_timer_sync(&port->vio.timer); napi_disable(&port->napi); list_del_rcu(&port->list); synchronize_rcu(); del_timer_sync(&port->clean_timer); spin_lock_irqsave(&port->vp->lock, flags); sunvnet_port_rm_txq_common(port); spin_unlock_irqrestore(&port->vp->lock, flags); netif_napi_del(&port->napi); sunvnet_port_free_tx_bufs_common(port); vio_ldc_free(&port->vio); dev_set_drvdata(&vdev->dev, NULL); unregister_netdev(port->dev); free_netdev(port->dev); } return 0; } static void vsw_cleanup(void) { struct vnet *vp; /* just need to free up the vnet list */ mutex_lock(&vnet_list_mutex); while (!list_empty(&vnet_list)) { vp = list_first_entry(&vnet_list, struct vnet, list); list_del(&vp->list); /* vio_unregister_driver() should have cleaned up port_list */ if (!list_empty(&vp->port_list)) pr_err("Ports not removed by VIO subsystem!\n"); kfree(vp); } mutex_unlock(&vnet_list_mutex); } static const struct vio_device_id vsw_port_match[] = { { .type = "vsw-port", }, {}, }; MODULE_DEVICE_TABLE(vio, vsw_port_match); static struct vio_driver vsw_port_driver = { .id_table = vsw_port_match, .probe = vsw_port_probe, .remove = vsw_port_remove, .name = "vsw_port", }; static int __init vsw_init(void) { pr_info("%s\n", version); return vio_register_driver(&vsw_port_driver); } static void __exit vsw_exit(void) { vio_unregister_driver(&vsw_port_driver); vsw_cleanup(); } module_init(vsw_init); module_exit(vsw_exit);
null
null
null
null
93,533
2,510
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
155,567
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * 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 "config.h" #include "libavcodec/x86/fdct.h" #include "libavcodec/x86/xvididct.h" #include "libavcodec/x86/simple_idct.h" #if (CONFIG_PRORES_DECODER || CONFIG_PRORES_LGPL_DECODER) && ARCH_X86_64 && HAVE_X86ASM void ff_prores_idct_put_10_sse2(uint16_t *dst, int linesize, int16_t *block, int16_t *qmat); #define PR_WRAP(INSN) \ static void ff_prores_idct_put_10_##INSN##_wrap(int16_t *dst){ \ LOCAL_ALIGNED(16, int16_t, qmat, [64]); \ LOCAL_ALIGNED(16, int16_t, tmp, [64]); \ int i; \ \ for(i=0; i<64; i++){ \ qmat[i]=4; \ tmp[i]= dst[i]; \ } \ ff_prores_idct_put_10_##INSN (dst, 16, tmp, qmat); \ \ for(i=0; i<64; i++) { \ dst[i] -= 512; \ } \ } PR_WRAP(sse2) # if HAVE_AVX_EXTERNAL void ff_prores_idct_put_10_avx(uint16_t *dst, int linesize, int16_t *block, int16_t *qmat); PR_WRAP(avx) # endif #endif static const struct algo fdct_tab_arch[] = { #if HAVE_MMX_INLINE { "MMX", ff_fdct_mmx, FF_IDCT_PERM_NONE, AV_CPU_FLAG_MMX }, #endif #if HAVE_MMXEXT_INLINE { "MMXEXT", ff_fdct_mmxext, FF_IDCT_PERM_NONE, AV_CPU_FLAG_MMXEXT }, #endif #if HAVE_SSE2_INLINE { "SSE2", ff_fdct_sse2, FF_IDCT_PERM_NONE, AV_CPU_FLAG_SSE2 }, #endif { 0 } }; static const struct algo idct_tab_arch[] = { #if HAVE_MMX_EXTERNAL { "SIMPLE-MMX", ff_simple_idct_mmx, FF_IDCT_PERM_SIMPLE, AV_CPU_FLAG_MMX }, #endif #if CONFIG_MPEG4_DECODER && HAVE_X86ASM #if ARCH_X86_32 { "XVID-MMX", ff_xvid_idct_mmx, FF_IDCT_PERM_NONE, AV_CPU_FLAG_MMX, 1 }, { "XVID-MMXEXT", ff_xvid_idct_mmxext, FF_IDCT_PERM_NONE, AV_CPU_FLAG_MMXEXT, 1 }, #endif #if HAVE_SSE2_EXTERNAL { "XVID-SSE2", ff_xvid_idct_sse2, FF_IDCT_PERM_SSE2, AV_CPU_FLAG_SSE2, 1 }, #endif #endif /* CONFIG_MPEG4_DECODER && HAVE_X86ASM */ #if (CONFIG_PRORES_DECODER || CONFIG_PRORES_LGPL_DECODER) && ARCH_X86_64 && HAVE_X86ASM { "PR-SSE2", ff_prores_idct_put_10_sse2_wrap, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_SSE2, 1 }, # if HAVE_AVX_EXTERNAL { "PR-AVX", ff_prores_idct_put_10_avx_wrap, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_AVX, 1 }, # endif #endif #if HAVE_X86ASM #if ARCH_X86_64 #if HAVE_SSE2_EXTERNAL { "SIMPLE8-SSE2", ff_simple_idct8_sse2, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_SSE2}, { "SIMPLE10-SSE2", ff_simple_idct10_sse2, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_SSE2}, { "SIMPLE12-SSE2", ff_simple_idct12_sse2, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_SSE2, 1 }, #endif #if HAVE_AVX_EXTERNAL { "SIMPLE8-AVX", ff_simple_idct8_avx, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_AVX}, { "SIMPLE10-AVX", ff_simple_idct10_avx, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_AVX}, { "SIMPLE12-AVX", ff_simple_idct12_avx, FF_IDCT_PERM_TRANSPOSE, AV_CPU_FLAG_AVX, 1 }, #endif #endif #endif { 0 } }; static const uint8_t idct_simple_mmx_perm[64] = { 0x00, 0x08, 0x04, 0x09, 0x01, 0x0C, 0x05, 0x0D, 0x10, 0x18, 0x14, 0x19, 0x11, 0x1C, 0x15, 0x1D, 0x20, 0x28, 0x24, 0x29, 0x21, 0x2C, 0x25, 0x2D, 0x12, 0x1A, 0x16, 0x1B, 0x13, 0x1E, 0x17, 0x1F, 0x02, 0x0A, 0x06, 0x0B, 0x03, 0x0E, 0x07, 0x0F, 0x30, 0x38, 0x34, 0x39, 0x31, 0x3C, 0x35, 0x3D, 0x22, 0x2A, 0x26, 0x2B, 0x23, 0x2E, 0x27, 0x2F, 0x32, 0x3A, 0x36, 0x3B, 0x33, 0x3E, 0x37, 0x3F, }; static const uint8_t idct_sse2_row_perm[8] = { 0, 4, 1, 5, 2, 6, 3, 7 }; static int permute_x86(int16_t dst[64], const int16_t src[64], enum idct_permutation_type perm_type) { int i; switch (perm_type) { case FF_IDCT_PERM_SIMPLE: for (i = 0; i < 64; i++) dst[idct_simple_mmx_perm[i]] = src[i]; return 1; case FF_IDCT_PERM_SSE2: for (i = 0; i < 64; i++) dst[(i & 0x38) | idct_sse2_row_perm[i & 7]] = src[i]; return 1; } return 0; }
null
null
null
null
71,622
20,319
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
20,319
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 CONTENT_PUBLIC_BROWSER_URL_DATA_SOURCE_H_ #define CONTENT_PUBLIC_BROWSER_URL_DATA_SOURCE_H_ #include <string> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "content/common/content_export.h" #include "content/public/browser/resource_request_info.h" class GURL; namespace base { class RefCountedMemory; } namespace content { class BrowserContext; class ResourceContext; // A URLDataSource is an object that can answer requests for WebUI data // asynchronously. An implementation of URLDataSource should handle calls to // StartDataRequest() by starting its (implementation-specific) asynchronous // request for the data, then running the callback given in that method to // notify. class CONTENT_EXPORT URLDataSource { public: // Adds a URL data source to |browser_context|. static void Add(BrowserContext* browser_context, URLDataSource* source); virtual ~URLDataSource() {} // The name of this source. // E.g., for favicons, this could be "favicon", which results in paths for // specific resources like "favicon/34" getting sent to this source. For // sources where a scheme is used instead of the hostname as the unique // identifier, the suffix "://" must be added to the return value, eg. for a // URLDataSource which would display resources with URLs on the form // your-scheme://anything , GetSource() must return "your-scheme://". virtual std::string GetSource() const = 0; // Used by StartDataRequest so that the child class can return the data when // it's available. typedef base::Callback<void(scoped_refptr<base::RefCountedMemory>)> GotDataCallback; // Must be called on the task runner specified by TaskRunnerForRequestPath, // or the IO thread if TaskRunnerForRequestPath returns nullptr. // // Called by URLDataSource to request data at |path|. The string parameter is // the path of the request. The child class should run |callback| when the // data is available or if the request could not be satisfied. This can be // called either in this callback or asynchronously with the response. // |wc_getter| can be called on the UI thread to return the WebContents for // this request if it originates from a render frame. If it originated from a // worker or if the frame has destructed it will return null. virtual void StartDataRequest( const std::string& path, const ResourceRequestInfo::WebContentsGetter& wc_getter, const GotDataCallback& callback) = 0; // The following methods are all called on the IO thread. // Return the mimetype that should be sent with this response, or empty // string to specify no mime type. virtual std::string GetMimeType(const std::string& path) const = 0; // Returns the TaskRunner on which the delegate wishes to have // StartDataRequest called to handle the request for |path|. The default // implementation returns BrowserThread::UI. If the delegate does not care // which thread StartDataRequest is called on, this should return nullptr. // It may be beneficial to return nullptr for requests that are safe to handle // directly on the IO thread. This can improve performance by satisfying such // requests more rapidly when there is a large amount of UI thread contention. // Or the delegate can return a specific thread's TaskRunner if they wish. virtual scoped_refptr<base::SingleThreadTaskRunner> TaskRunnerForRequestPath( const std::string& path) const; // Returns true if the URLDataSource should replace an existing URLDataSource // with the same name that has already been registered. The default is true. // // WARNING: this is invoked on the IO thread. // // TODO: nuke this and convert all callers to not replace. virtual bool ShouldReplaceExistingSource() const; // Returns true if responses from this URLDataSource can be cached. virtual bool AllowCaching() const; // If you are overriding the following two methods, then you have a bug. // It is not acceptable to disable content-security-policy on chrome:// pages // to permit functionality excluded by CSP, such as inline script. // Instead, you must go back and change your WebUI page so that it is // compliant with the policy. This typically involves ensuring that all script // is delivered through the data manager backend. Do not disable CSP on your // page without first contacting the chrome security team. virtual bool ShouldAddContentSecurityPolicy() const; // For pre-existing code, enabling CSP with relaxed script-src attributes // may be marginally better than disabling CSP outright. // Do not override this method without first contacting the chrome security // team. // By default, "script-src chrome://resources 'self' 'unsafe-eval';" is added // to CSP. Override to change this. virtual std::string GetContentSecurityPolicyScriptSrc() const; // It is OK to override the following methods to a custom CSP directive // thereby slightly reducing the protection applied to the page. // By default, "object-src 'none';" is added to CSP. Override to change this. virtual std::string GetContentSecurityPolicyObjectSrc() const; // By default, "child-src 'none';" is added to CSP. Override to change this. virtual std::string GetContentSecurityPolicyChildSrc() const; // By default empty. Override to change this. virtual std::string GetContentSecurityPolicyStyleSrc() const; // By default empty. Override to change this. virtual std::string GetContentSecurityPolicyImgSrc() const; // By default, the "X-Frame-Options: DENY" header is sent. To stop this from // happening, return false. It is OK to return false as needed. virtual bool ShouldDenyXFrameOptions() const; // By default, only chrome: and chrome-devtools: requests are allowed. // Override in specific WebUI data sources to enable for additional schemes or // to implement fancier access control. Typically used in concert with // ContentBrowserClient::GetAdditionalWebUISchemes() to permit additional // WebUI scheme support for an embedder. virtual bool ShouldServiceRequest(const GURL& url, ResourceContext* resource_context, int render_process_id) const; // By default, Content-Type: header is not sent along with the response. // To start sending mime type returned by GetMimeType in HTTP headers, // return true. It is useful when tunneling response served from this data // source programmatically. Or when AppCache is enabled for this source as it // is for chrome-devtools. virtual bool ShouldServeMimeTypeAsContentTypeHeader() const; // This method is called when the request contains "Origin:" header. The value // of the header is passed in |origin| parameter. If the returned value is not // empty, it is used as a value for "Access-Control-Allow-Origin:" response // header, otherwise the header is not set. This method should return either // |origin|, or "*", or "none", or empty string. // Default implementation returns an empty string. virtual std::string GetAccessControlAllowOriginForOrigin( const std::string& origin) const; // Whether |path| is gzipped (and should be transmitted gzipped). virtual bool IsGzipped(const std::string& path) const; }; } // namespace content #endif // CONTENT_PUBLIC_BROWSER_URL_DATA_SOURCE_H_
null
null
null
null
17,182
20,832
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
185,827
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/********************************************************************** * Author: Cavium, Inc. * * Contact: [email protected] * Please include "LiquidIO" in the subject. * * Copyright (c) 2003-2016 Cavium, Inc. * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, Version 2, as * published by the Free Software Foundation. * * This file is distributed in the hope that it will be useful, but * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or * NONINFRINGEMENT. See the GNU General Public License for more details. ***********************************************************************/ #ifndef _LIQUIDIO_IMAGE_H_ #define _LIQUIDIO_IMAGE_H_ #define LIO_MAX_FW_TYPE_LEN (8) #define LIO_MAX_FW_FILENAME_LEN (256) #define LIO_FW_DIR "liquidio/" #define LIO_FW_BASE_NAME "lio_" #define LIO_FW_NAME_SUFFIX ".bin" #define LIO_FW_NAME_TYPE_NIC "nic" #define LIO_FW_NAME_TYPE_NONE "none" #define LIO_MAX_FIRMWARE_VERSION_LEN 16 #define LIO_MAX_BOOTCMD_LEN 1024 #define LIO_MAX_IMAGES 16 #define LIO_NIC_MAGIC 0x434E4943 /* "CNIC" */ struct octeon_firmware_desc { __be64 addr; __be32 len; __be32 crc32; /* crc32 of image */ }; /* Following the header is a list of 64-bit aligned binary images, * as described by the desc field. * Numeric fields are in network byte order. */ struct octeon_firmware_file_header { __be32 magic; char version[LIO_MAX_FIRMWARE_VERSION_LEN]; char bootcmd[LIO_MAX_BOOTCMD_LEN]; __be32 num_images; struct octeon_firmware_desc desc[LIO_MAX_IMAGES]; __be32 pad; __be32 crc32; /* header checksum */ }; #endif /* _LIQUIDIO_IMAGE_H_ */
null
null
null
null
94,174
2,812
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
265,380
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
#ifndef QEMU_NET_H #define QEMU_NET_H #include "qemu/queue.h" #include "qemu-common.h" #include "qapi/qmp/qdict.h" #include "qemu/option.h" #include "net/queue.h" #include "migration/vmstate.h" #include "qapi-types.h" #define MAC_FMT "%02X:%02X:%02X:%02X:%02X:%02X" #define MAC_ARG(x) ((uint8_t *)(x))[0], ((uint8_t *)(x))[1], \ ((uint8_t *)(x))[2], ((uint8_t *)(x))[3], \ ((uint8_t *)(x))[4], ((uint8_t *)(x))[5] #define MAX_QUEUE_NUM 1024 /* Maximum GSO packet size (64k) plus plenty of room for * the ethernet and virtio_net headers */ #define NET_BUFSIZE (4096 + 65536) struct MACAddr { uint8_t a[6]; }; /* qdev nic properties */ typedef struct NICPeers { NetClientState *ncs[MAX_QUEUE_NUM]; int32_t queues; } NICPeers; typedef struct NICConf { MACAddr macaddr; NICPeers peers; int32_t bootindex; } NICConf; #define DEFINE_NIC_PROPERTIES(_state, _conf) \ DEFINE_PROP_MACADDR("mac", _state, _conf.macaddr), \ DEFINE_PROP_VLAN("vlan", _state, _conf.peers), \ DEFINE_PROP_NETDEV("netdev", _state, _conf.peers) /* Net clients */ typedef void (NetPoll)(NetClientState *, bool enable); typedef int (NetCanReceive)(NetClientState *); typedef ssize_t (NetReceive)(NetClientState *, const uint8_t *, size_t); typedef ssize_t (NetReceiveIOV)(NetClientState *, const struct iovec *, int); typedef void (NetCleanup) (NetClientState *); typedef void (LinkStatusChanged)(NetClientState *); typedef void (NetClientDestructor)(NetClientState *); typedef RxFilterInfo *(QueryRxFilter)(NetClientState *); typedef bool (HasUfo)(NetClientState *); typedef bool (HasVnetHdr)(NetClientState *); typedef bool (HasVnetHdrLen)(NetClientState *, int); typedef void (UsingVnetHdr)(NetClientState *, bool); typedef void (SetOffload)(NetClientState *, int, int, int, int, int); typedef void (SetVnetHdrLen)(NetClientState *, int); typedef int (SetVnetLE)(NetClientState *, bool); typedef int (SetVnetBE)(NetClientState *, bool); typedef struct SocketReadState SocketReadState; typedef void (SocketReadStateFinalize)(SocketReadState *rs); typedef struct NetClientInfo { NetClientDriver type; size_t size; NetReceive *receive; NetReceive *receive_raw; NetReceiveIOV *receive_iov; NetCanReceive *can_receive; NetCleanup *cleanup; LinkStatusChanged *link_status_changed; QueryRxFilter *query_rx_filter; NetPoll *poll; HasUfo *has_ufo; HasVnetHdr *has_vnet_hdr; HasVnetHdrLen *has_vnet_hdr_len; UsingVnetHdr *using_vnet_hdr; SetOffload *set_offload; SetVnetHdrLen *set_vnet_hdr_len; SetVnetLE *set_vnet_le; SetVnetBE *set_vnet_be; } NetClientInfo; struct NetClientState { NetClientInfo *info; int link_down; QTAILQ_ENTRY(NetClientState) next; NetClientState *peer; NetQueue *incoming_queue; char *model; char *name; char info_str[256]; unsigned receive_disabled : 1; NetClientDestructor *destructor; unsigned int queue_index; unsigned rxfilter_notify_enabled:1; int vring_enable; QTAILQ_HEAD(NetFilterHead, NetFilterState) filters; }; typedef struct NICState { NetClientState *ncs; NICConf *conf; void *opaque; bool peer_deleted; } NICState; struct SocketReadState { int state; /* 0 = getting length, 1 = getting data */ uint32_t index; uint32_t packet_len; uint8_t buf[NET_BUFSIZE]; SocketReadStateFinalize *finalize; }; int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size); char *qemu_mac_strdup_printf(const uint8_t *macaddr); NetClientState *qemu_find_netdev(const char *id); int qemu_find_net_clients_except(const char *id, NetClientState **ncs, NetClientDriver type, int max); NetClientState *qemu_new_net_client(NetClientInfo *info, NetClientState *peer, const char *model, const char *name); NICState *qemu_new_nic(NetClientInfo *info, NICConf *conf, const char *model, const char *name, void *opaque); void qemu_del_nic(NICState *nic); NetClientState *qemu_get_subqueue(NICState *nic, int queue_index); NetClientState *qemu_get_queue(NICState *nic); NICState *qemu_get_nic(NetClientState *nc); void *qemu_get_nic_opaque(NetClientState *nc); void qemu_del_net_client(NetClientState *nc); typedef void (*qemu_nic_foreach)(NICState *nic, void *opaque); void qemu_foreach_nic(qemu_nic_foreach func, void *opaque); int qemu_can_send_packet(NetClientState *nc); ssize_t qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt); ssize_t qemu_sendv_packet_async(NetClientState *nc, const struct iovec *iov, int iovcnt, NetPacketSent *sent_cb); void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size); ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size); ssize_t qemu_send_packet_async(NetClientState *nc, const uint8_t *buf, int size, NetPacketSent *sent_cb); void qemu_purge_queued_packets(NetClientState *nc); void qemu_flush_queued_packets(NetClientState *nc); void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6]); bool qemu_has_ufo(NetClientState *nc); bool qemu_has_vnet_hdr(NetClientState *nc); bool qemu_has_vnet_hdr_len(NetClientState *nc, int len); void qemu_using_vnet_hdr(NetClientState *nc, bool enable); void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6, int ecn, int ufo); void qemu_set_vnet_hdr_len(NetClientState *nc, int len); int qemu_set_vnet_le(NetClientState *nc, bool is_le); int qemu_set_vnet_be(NetClientState *nc, bool is_be); void qemu_macaddr_default_if_unset(MACAddr *macaddr); int qemu_show_nic_models(const char *arg, const char *const *models); void qemu_check_nic_model(NICInfo *nd, const char *model); int qemu_find_nic_model(NICInfo *nd, const char * const *models, const char *default_model); ssize_t qemu_deliver_packet_iov(NetClientState *sender, unsigned flags, const struct iovec *iov, int iovcnt, void *opaque); void print_net_client(Monitor *mon, NetClientState *nc); void hmp_info_network(Monitor *mon, const QDict *qdict); void net_socket_rs_init(SocketReadState *rs, SocketReadStateFinalize *finalize); /* NIC info */ #define MAX_NICS 8 struct NICInfo { MACAddr macaddr; char *model; char *name; char *devaddr; NetClientState *netdev; int used; /* is this slot in nd_table[] being used? */ int instantiated; /* does this NICInfo correspond to an instantiated NIC? */ int nvectors; }; extern int nb_nics; extern NICInfo nd_table[MAX_NICS]; extern const char *host_net_devices[]; /* from net.c */ extern const char *legacy_tftp_prefix; extern const char *legacy_bootp_filename; int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp); int net_client_parse(QemuOptsList *opts_list, const char *str); int net_init_clients(void); void net_check_clients(void); void net_cleanup(void); void hmp_host_net_add(Monitor *mon, const QDict *qdict); void hmp_host_net_remove(Monitor *mon, const QDict *qdict); void netdev_add(QemuOpts *opts, Error **errp); void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp); int net_hub_id_for_client(NetClientState *nc, int *id); NetClientState *net_hub_port_find(int hub_id); #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup" #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown" #define DEFAULT_BRIDGE_HELPER CONFIG_QEMU_HELPERDIR "/qemu-bridge-helper" #define DEFAULT_BRIDGE_INTERFACE "br0" void qdev_set_nic_properties(DeviceState *dev, NICInfo *nd); #define POLYNOMIAL 0x04c11db6 unsigned compute_mcast_idx(const uint8_t *ep); #define vmstate_offset_macaddr(_state, _field) \ vmstate_offset_array(_state, _field.a, uint8_t, \ sizeof(typeof_field(_state, _field))) #define VMSTATE_MACADDR(_field, _state) { \ .name = (stringify(_field)), \ .size = sizeof(MACAddr), \ .info = &vmstate_info_buffer, \ .flags = VMS_BUFFER, \ .offset = vmstate_offset_macaddr(_state, _field), \ } #endif
null
null
null
null
123,504
42,005
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
207,000
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef __LINUX_PMIC_DA903X_H #define __LINUX_PMIC_DA903X_H /* Unified sub device IDs for DA9030/DA9034/DA9035 */ enum { DA9030_ID_LED_1, DA9030_ID_LED_2, DA9030_ID_LED_3, DA9030_ID_LED_4, DA9030_ID_LED_PC, DA9030_ID_VIBRA, DA9030_ID_WLED, DA9030_ID_BUCK1, DA9030_ID_BUCK2, DA9030_ID_LDO1, DA9030_ID_LDO2, DA9030_ID_LDO3, DA9030_ID_LDO4, DA9030_ID_LDO5, DA9030_ID_LDO6, DA9030_ID_LDO7, DA9030_ID_LDO8, DA9030_ID_LDO9, DA9030_ID_LDO10, DA9030_ID_LDO11, DA9030_ID_LDO12, DA9030_ID_LDO13, DA9030_ID_LDO14, DA9030_ID_LDO15, DA9030_ID_LDO16, DA9030_ID_LDO17, DA9030_ID_LDO18, DA9030_ID_LDO19, DA9030_ID_LDO_INT, /* LDO Internal */ DA9030_ID_BAT, /* battery charger */ DA9034_ID_LED_1, DA9034_ID_LED_2, DA9034_ID_VIBRA, DA9034_ID_WLED, DA9034_ID_TOUCH, DA9034_ID_BUCK1, DA9034_ID_BUCK2, DA9034_ID_LDO1, DA9034_ID_LDO2, DA9034_ID_LDO3, DA9034_ID_LDO4, DA9034_ID_LDO5, DA9034_ID_LDO6, DA9034_ID_LDO7, DA9034_ID_LDO8, DA9034_ID_LDO9, DA9034_ID_LDO10, DA9034_ID_LDO11, DA9034_ID_LDO12, DA9034_ID_LDO13, DA9034_ID_LDO14, DA9034_ID_LDO15, DA9035_ID_BUCK3, }; /* * DA9030/DA9034 LEDs sub-devices uses generic "struct led_info" * as the platform_data */ /* DA9030 flags for "struct led_info" */ #define DA9030_LED_RATE_ON (0 << 5) #define DA9030_LED_RATE_052S (1 << 5) #define DA9030_LED_DUTY_1_16 (0 << 3) #define DA9030_LED_DUTY_1_8 (1 << 3) #define DA9030_LED_DUTY_1_4 (2 << 3) #define DA9030_LED_DUTY_1_2 (3 << 3) #define DA9030_VIBRA_MODE_1P3V (0 << 1) #define DA9030_VIBRA_MODE_2P7V (1 << 1) #define DA9030_VIBRA_FREQ_1HZ (0 << 2) #define DA9030_VIBRA_FREQ_2HZ (1 << 2) #define DA9030_VIBRA_FREQ_4HZ (2 << 2) #define DA9030_VIBRA_FREQ_8HZ (3 << 2) #define DA9030_VIBRA_DUTY_ON (0 << 4) #define DA9030_VIBRA_DUTY_75P (1 << 4) #define DA9030_VIBRA_DUTY_50P (2 << 4) #define DA9030_VIBRA_DUTY_25P (3 << 4) /* DA9034 flags for "struct led_info" */ #define DA9034_LED_RAMP (1 << 7) /* DA9034 touch screen platform data */ struct da9034_touch_pdata { int interval_ms; /* sampling interval while pen down */ int x_inverted; int y_inverted; }; struct da9034_backlight_pdata { int output_current; /* output current of WLED, from 0-31 (in mA) */ }; /* DA9030 battery charger data */ struct power_supply_info; struct da9030_battery_info { /* battery parameters */ struct power_supply_info *battery_info; /* current and voltage to use for battery charging */ unsigned int charge_milliamp; unsigned int charge_millivolt; /* voltage thresholds (in millivolts) */ int vbat_low; int vbat_crit; int vbat_charge_start; int vbat_charge_stop; int vbat_charge_restart; /* battery nominal minimal and maximal voltages in millivolts */ int vcharge_min; int vcharge_max; /* Temperature thresholds. These are DA9030 register values "as is" and should be measured for each battery type */ int tbat_low; int tbat_high; int tbat_restart; /* battery monitor interval (seconds) */ unsigned int batmon_interval; /* platform callbacks for battery low and critical events */ void (*battery_low)(void); void (*battery_critical)(void); }; struct da903x_subdev_info { int id; const char *name; void *platform_data; }; struct da903x_platform_data { int num_subdevs; struct da903x_subdev_info *subdevs; }; /* bit definitions for DA9030 events */ #define DA9030_EVENT_ONKEY (1 << 0) #define DA9030_EVENT_PWREN (1 << 1) #define DA9030_EVENT_EXTON (1 << 2) #define DA9030_EVENT_CHDET (1 << 3) #define DA9030_EVENT_TBAT (1 << 4) #define DA9030_EVENT_VBATMON (1 << 5) #define DA9030_EVENT_VBATMON_TXON (1 << 6) #define DA9030_EVENT_CHIOVER (1 << 7) #define DA9030_EVENT_TCTO (1 << 8) #define DA9030_EVENT_CCTO (1 << 9) #define DA9030_EVENT_ADC_READY (1 << 10) #define DA9030_EVENT_VBUS_4P4 (1 << 11) #define DA9030_EVENT_VBUS_4P0 (1 << 12) #define DA9030_EVENT_SESS_VALID (1 << 13) #define DA9030_EVENT_SRP_DETECT (1 << 14) #define DA9030_EVENT_WATCHDOG (1 << 15) #define DA9030_EVENT_LDO15 (1 << 16) #define DA9030_EVENT_LDO16 (1 << 17) #define DA9030_EVENT_LDO17 (1 << 18) #define DA9030_EVENT_LDO18 (1 << 19) #define DA9030_EVENT_LDO19 (1 << 20) #define DA9030_EVENT_BUCK2 (1 << 21) /* bit definitions for DA9034 events */ #define DA9034_EVENT_ONKEY (1 << 0) #define DA9034_EVENT_EXTON (1 << 2) #define DA9034_EVENT_CHDET (1 << 3) #define DA9034_EVENT_TBAT (1 << 4) #define DA9034_EVENT_VBATMON (1 << 5) #define DA9034_EVENT_REV_IOVER (1 << 6) #define DA9034_EVENT_CH_IOVER (1 << 7) #define DA9034_EVENT_CH_TCTO (1 << 8) #define DA9034_EVENT_CH_CCTO (1 << 9) #define DA9034_EVENT_USB_DEV (1 << 10) #define DA9034_EVENT_OTGCP_IOVER (1 << 11) #define DA9034_EVENT_VBUS_4P55 (1 << 12) #define DA9034_EVENT_VBUS_3P8 (1 << 13) #define DA9034_EVENT_SESS_1P8 (1 << 14) #define DA9034_EVENT_SRP_READY (1 << 15) #define DA9034_EVENT_ADC_MAN (1 << 16) #define DA9034_EVENT_ADC_AUTO4 (1 << 17) #define DA9034_EVENT_ADC_AUTO5 (1 << 18) #define DA9034_EVENT_ADC_AUTO6 (1 << 19) #define DA9034_EVENT_PEN_DOWN (1 << 20) #define DA9034_EVENT_TSI_READY (1 << 21) #define DA9034_EVENT_UART_TX (1 << 22) #define DA9034_EVENT_UART_RX (1 << 23) #define DA9034_EVENT_HEADSET (1 << 25) #define DA9034_EVENT_HOOKSWITCH (1 << 26) #define DA9034_EVENT_WATCHDOG (1 << 27) extern int da903x_register_notifier(struct device *dev, struct notifier_block *nb, unsigned int events); extern int da903x_unregister_notifier(struct device *dev, struct notifier_block *nb, unsigned int events); /* Status Query Interface */ #define DA9030_STATUS_ONKEY (1 << 0) #define DA9030_STATUS_PWREN1 (1 << 1) #define DA9030_STATUS_EXTON (1 << 2) #define DA9030_STATUS_CHDET (1 << 3) #define DA9030_STATUS_TBAT (1 << 4) #define DA9030_STATUS_VBATMON (1 << 5) #define DA9030_STATUS_VBATMON_TXON (1 << 6) #define DA9030_STATUS_MCLKDET (1 << 7) #define DA9034_STATUS_ONKEY (1 << 0) #define DA9034_STATUS_EXTON (1 << 2) #define DA9034_STATUS_CHDET (1 << 3) #define DA9034_STATUS_TBAT (1 << 4) #define DA9034_STATUS_VBATMON (1 << 5) #define DA9034_STATUS_PEN_DOWN (1 << 6) #define DA9034_STATUS_MCLKDET (1 << 7) #define DA9034_STATUS_USB_DEV (1 << 8) #define DA9034_STATUS_HEADSET (1 << 9) #define DA9034_STATUS_HOOKSWITCH (1 << 10) #define DA9034_STATUS_REMCON (1 << 11) #define DA9034_STATUS_VBUS_VALID_4P55 (1 << 12) #define DA9034_STATUS_VBUS_VALID_3P8 (1 << 13) #define DA9034_STATUS_SESS_VALID_1P8 (1 << 14) #define DA9034_STATUS_SRP_READY (1 << 15) extern int da903x_query_status(struct device *dev, unsigned int status); /* NOTE: the functions below are not intended for use outside * of the DA903x sub-device drivers */ extern int da903x_write(struct device *dev, int reg, uint8_t val); extern int da903x_writes(struct device *dev, int reg, int len, uint8_t *val); extern int da903x_read(struct device *dev, int reg, uint8_t *val); extern int da903x_reads(struct device *dev, int reg, int len, uint8_t *val); extern int da903x_update(struct device *dev, int reg, uint8_t val, uint8_t mask); extern int da903x_set_bits(struct device *dev, int reg, uint8_t bit_mask); extern int da903x_clr_bits(struct device *dev, int reg, uint8_t bit_mask); #endif /* __LINUX_PMIC_DA903X_H */
null
null
null
null
115,347
1,105
8,9
train_val
ad103a1564365c95f4ee4f10261f9604f91f686a
1,105
Chrome
1
https://github.com/chromium/chromium
2012-11-15 07:27:55+00:00
bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { // TODO(brettw) this should be called only on the main thread! if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) * 4 >= std::numeric_limits<int32>::max()) return false; // Prevent overflow of signed 32-bit ints. format_ = format; width_ = width; height_ = height; return backend_->Init(this, format, width, height, init_to_zero); }
CVE-2012-5143
CWE-190
https://github.com/chromium/chromium/commit/ad103a1564365c95f4ee4f10261f9604f91f686a
Low
1,105
1,680
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
154,737
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * MPEG-4 Part 2 HW decode acceleration through NVDEC * * Copyright (c) 2017 Philip Langdale * * 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 "avcodec.h" #include "mpeg4video.h" #include "nvdec.h" #include "decode.h" static int nvdec_mpeg4_start_frame(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size) { Mpeg4DecContext *m = avctx->priv_data; MpegEncContext *s = &m->m; NVDECContext *ctx = avctx->internal->hwaccel_priv_data; CUVIDPICPARAMS *pp = &ctx->pic_params; CUVIDMPEG4PICPARAMS *ppc = &pp->CodecSpecific.mpeg4; FrameDecodeData *fdd; NVDECFrame *cf; AVFrame *cur_frame = s->current_picture.f; int ret, i; ret = ff_nvdec_start_frame(avctx, cur_frame); if (ret < 0) return ret; fdd = (FrameDecodeData*)cur_frame->private_ref->data; cf = (NVDECFrame*)fdd->hwaccel_priv; *pp = (CUVIDPICPARAMS) { .PicWidthInMbs = (cur_frame->width + 15) / 16, .FrameHeightInMbs = (cur_frame->height + 15) / 16, .CurrPicIdx = cf->idx, .intra_pic_flag = s->pict_type == AV_PICTURE_TYPE_I, .ref_pic_flag = s->pict_type == AV_PICTURE_TYPE_I || s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S, .CodecSpecific.mpeg4 = { .ForwardRefIdx = ff_nvdec_get_ref_idx(s->last_picture.f), .BackwardRefIdx = ff_nvdec_get_ref_idx(s->next_picture.f), .video_object_layer_width = s->width, .video_object_layer_height = s->height, .vop_time_increment_bitcount = m->time_increment_bits, .top_field_first = s->top_field_first, .resync_marker_disable = !m->resync_marker, .quant_type = s->mpeg_quant, .quarter_sample = s->quarter_sample, .short_video_header = avctx->codec->id == AV_CODEC_ID_H263, .divx_flags = s->divx_packed ? 5 : 0, .vop_coding_type = s->pict_type - AV_PICTURE_TYPE_I, .vop_coded = 1, .vop_rounding_type = s->no_rounding, .alternate_vertical_scan_flag = s->alternate_scan, .interlaced = !s->progressive_sequence, .vop_fcode_forward = s->f_code, .vop_fcode_backward = s->b_code, .trd = { s->pp_time, s->pp_field_time >> 1 }, .trb = { s->pb_time, s->pb_field_time >> 1 }, .gmc_enabled = s->pict_type == AV_PICTURE_TYPE_S && m->vol_sprite_usage == GMC_SPRITE, } }; for (i = 0; i < 64; ++i) { ppc->QuantMatrixIntra[i] = s->intra_matrix[i]; ppc->QuantMatrixInter[i] = s->inter_matrix[i]; } // We need to pass the full frame buffer and not just the slice return ff_nvdec_simple_decode_slice(avctx, buffer, size); } static int nvdec_mpeg4_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size) { return 0; } static int nvdec_mpeg4_frame_params(AVCodecContext *avctx, AVBufferRef *hw_frames_ctx) { // Each frame can at most have one P and one B reference return ff_nvdec_frame_params(avctx, hw_frames_ctx, 2); } const AVHWAccel ff_mpeg4_nvdec_hwaccel = { .name = "mpeg4_nvdec", .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_MPEG4, .pix_fmt = AV_PIX_FMT_CUDA, .start_frame = nvdec_mpeg4_start_frame, .end_frame = ff_nvdec_simple_end_frame, .decode_slice = nvdec_mpeg4_decode_slice, .frame_params = nvdec_mpeg4_frame_params, .init = ff_nvdec_decode_init, .uninit = ff_nvdec_decode_uninit, .priv_data_size = sizeof(NVDECContext), };
null
null
null
null
70,792
66,898
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
66,898
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 CHROME_BROWSER_SYNC_FILE_SYSTEM_DRIVE_BACKEND_CALLBACK_TRACKER_INTERNAL_H_ #define CHROME_BROWSER_SYNC_FILE_SYSTEM_DRIVE_BACKEND_CALLBACK_TRACKER_INTERNAL_H_ #include <memory> #include <utility> #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" namespace sync_file_system { namespace drive_backend { class CallbackTracker; namespace internal { class AbortHelper { public: explicit AbortHelper(CallbackTracker* tracker); ~AbortHelper(); base::WeakPtr<AbortHelper> AsWeakPtr(); static std::unique_ptr<AbortHelper> TakeOwnership( const base::WeakPtr<AbortHelper>& abort_helper); private: CallbackTracker* tracker_; // Not owned. base::WeakPtrFactory<AbortHelper> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(AbortHelper); }; template <typename> struct InvokeAndInvalidateHelper; template <typename... Args> struct InvokeAndInvalidateHelper<void(Args...)> { static void Run(const base::WeakPtr<AbortHelper>& abort_helper, const base::Callback<void(Args...)>& callback, Args... args) { std::unique_ptr<AbortHelper> deleter = AbortHelper::TakeOwnership(abort_helper); if (deleter) { callback.Run(std::forward<Args>(args)...); } } }; } // namespace internal } // namespace drive_backend } // namespace sync_file_system #endif // CHROME_BROWSER_SYNC_FILE_SYSTEM_DRIVE_BACKEND_CALLBACK_TRACKER_INTERNAL_H_
null
null
null
null
63,761
14,063
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
179,058
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (C) 2011 Texas Instruments Incorporated * Author: Mark Salter <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _ASM_C6X_SWAB_H #define _ASM_C6X_SWAB_H static inline __attribute_const__ __u16 __c6x_swab16(__u16 val) { asm("swap4 .l1 %0,%0\n" : "+a"(val)); return val; } static inline __attribute_const__ __u32 __c6x_swab32(__u32 val) { asm("swap4 .l1 %0,%0\n" "swap2 .l1 %0,%0\n" : "+a"(val)); return val; } static inline __attribute_const__ __u64 __c6x_swab64(__u64 val) { asm(" swap2 .s1 %p0,%P0\n" "|| swap2 .l1 %P0,%p0\n" " swap4 .l1 %p0,%p0\n" " swap4 .l1 %P0,%P0\n" : "+a"(val)); return val; } static inline __attribute_const__ __u32 __c6x_swahw32(__u32 val) { asm("swap2 .l1 %0,%0\n" : "+a"(val)); return val; } static inline __attribute_const__ __u32 __c6x_swahb32(__u32 val) { asm("swap4 .l1 %0,%0\n" : "+a"(val)); return val; } #define __arch_swab16 __c6x_swab16 #define __arch_swab32 __c6x_swab32 #define __arch_swab64 __c6x_swab64 #define __arch_swahw32 __c6x_swahw32 #define __arch_swahb32 __c6x_swahb32 #endif /* _ASM_C6X_SWAB_H */
null
null
null
null
87,405
14,044
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
14,044
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 "components/offline_pages/core/prefetch/get_operation_task.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "components/offline_pages/core/prefetch/prefetch_dispatcher.h" #include "components/offline_pages/core/prefetch/prefetch_network_request_factory.h" #include "components/offline_pages/core/prefetch/store/prefetch_store.h" #include "sql/connection.h" #include "sql/statement.h" #include "sql/transaction.h" namespace offline_pages { namespace { GetOperationTask::OperationResultList MakeError() { return nullptr; } bool UpdatePrefetchItemsForOperationSync(sql::Connection* db, const std::string& operation_name) { static const char kSql[] = "UPDATE prefetch_items SET" " state = ?," " get_operation_attempts = get_operation_attempts + 1" " WHERE state = ? AND operation_name = ?"; sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt(0, static_cast<int>(PrefetchItemState::SENT_GET_OPERATION)); statement.BindInt(1, static_cast<int>(PrefetchItemState::RECEIVED_GCM)); statement.BindString(2, operation_name); return statement.Run(); } std::unique_ptr<std::vector<std::string>> AvailableOperationsSync( sql::Connection* db) { static const char kSql[] = "SELECT DISTINCT operation_name FROM prefetch_items WHERE state = ?"; sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt(0, static_cast<int>(PrefetchItemState::RECEIVED_GCM)); auto operations = std::make_unique<std::vector<std::string>>(); while (statement.Step()) { operations->push_back(statement.ColumnString(0)); // operation_name } return operations; } GetOperationTask::OperationResultList SelectOperationsToFetch( sql::Connection* db) { if (!db) return MakeError(); sql::Transaction transaction(db); if (!transaction.Begin()) return MakeError(); auto operations = AvailableOperationsSync(db); if (!operations) return MakeError(); for (std::string operation : *operations) { if (!UpdatePrefetchItemsForOperationSync(db, operation)) return MakeError(); // Rollback. } if (!transaction.Commit()) return MakeError(); return operations; } } // namespace GetOperationTask::GetOperationTask( PrefetchStore* store, PrefetchNetworkRequestFactory* request_factory, const PrefetchRequestFinishedCallback& callback) : prefetch_store_(store), request_factory_(request_factory), callback_(callback), weak_factory_(this) {} GetOperationTask::~GetOperationTask() {} void GetOperationTask::Run() { prefetch_store_->Execute( base::BindOnce(&SelectOperationsToFetch), base::BindOnce(&GetOperationTask::StartGetOperationRequests, weak_factory_.GetWeakPtr())); } void GetOperationTask::StartGetOperationRequests( OperationResultList operation_names) { if (operation_names) { for (std::string& operation : *operation_names) { request_factory_->MakeGetOperationRequest(operation, callback_); } } TaskComplete(); } } // namespace offline_pages
null
null
null
null
10,907
39,188
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
39,188
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/modules/mediacapturefromelement/on_request_canvas_draw_listener.h" #include "third_party/skia/include/core/SkImage.h" namespace blink { OnRequestCanvasDrawListener::OnRequestCanvasDrawListener( std::unique_ptr<WebCanvasCaptureHandler> handler) : CanvasDrawListener(std::move(handler)) {} OnRequestCanvasDrawListener::~OnRequestCanvasDrawListener() = default; // static OnRequestCanvasDrawListener* OnRequestCanvasDrawListener::Create( std::unique_ptr<WebCanvasCaptureHandler> handler) { return new OnRequestCanvasDrawListener(std::move(handler)); } void OnRequestCanvasDrawListener::SendNewFrame( sk_sp<SkImage> image, base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider) { frame_capture_requested_ = false; CanvasDrawListener::SendNewFrame(image, context_provider); } } // namespace blink
null
null
null
null
36,051
27,692
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
27,692
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 2005 Google Inc. 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. // // Author: [email protected] (Eric Veach) #include "s2/s2cellid.h" #include <algorithm> #include <cfloat> #include <cstring> #include <iosfwd> #include <vector> #include <mutex> #include "base/format_macros.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "s2/r1interval.h" #include "s2/s2latlng.h" #ifdef _MSC_VER #pragma warning(disable : 4018) /* '<' : signed/unsigned mismatch */ #endif using S2::internal::kSwapMask; using S2::internal::kInvertMask; using S2::internal::kPosToIJ; using S2::internal::kPosToOrientation; using std::max; using std::min; using std::vector; // The following lookup tables are used to convert efficiently between an // (i,j) cell index and the corresponding position along the Hilbert curve. // "lookup_pos" maps 4 bits of "i", 4 bits of "j", and 2 bits representing the // orientation of the current cell into 8 bits representing the order in which // that subcell is visited by the Hilbert curve, plus 2 bits indicating the // new orientation of the Hilbert curve within that subcell. (Cell // orientations are represented as combination of kSwapMask and kInvertMask.) // // "lookup_ij" is an inverted table used for mapping in the opposite // direction. // // We also experimented with looking up 16 bits at a time (14 bits of position // plus 2 of orientation) but found that smaller lookup tables gave better // performance. (2KB fits easily in the primary cache.) // Values for these constants are *declared* in the *.h file. Even though // the declaration specifies a value for the constant, that declaration // is not a *definition* of storage for the value. Because the values are // supplied in the declaration, we don't need the values here. Failing to // define storage causes link errors for any code that tries to take the // address of one of these values. int const S2CellId::kFaceBits; int const S2CellId::kNumFaces; int const S2CellId::kMaxLevel; int const S2CellId::kPosBits; int const S2CellId::kMaxSize; static int const kLookupBits = 4; static uint16_t lookup_pos[1 << (2 * kLookupBits + 2)]; static uint16_t lookup_ij[1 << (2 * kLookupBits + 2)]; static void InitLookupCell(int level, int i, int j, int orig_orientation, int pos, int orientation) { if (level == kLookupBits) { int ij = (i << kLookupBits) + j; lookup_pos[(ij << 2) + orig_orientation] = (pos << 2) + orientation; lookup_ij[(pos << 2) + orig_orientation] = (ij << 2) + orientation; } else { level++; i <<= 1; j <<= 1; pos <<= 2; int const* r = kPosToIJ[orientation]; InitLookupCell(level, i + (r[0] >> 1), j + (r[0] & 1), orig_orientation, pos, orientation ^ kPosToOrientation[0]); InitLookupCell(level, i + (r[1] >> 1), j + (r[1] & 1), orig_orientation, pos + 1, orientation ^ kPosToOrientation[1]); InitLookupCell(level, i + (r[2] >> 1), j + (r[2] & 1), orig_orientation, pos + 2, orientation ^ kPosToOrientation[2]); InitLookupCell(level, i + (r[3] >> 1), j + (r[3] & 1), orig_orientation, pos + 3, orientation ^ kPosToOrientation[3]); } } static std::once_flag flag; inline static void MaybeInit() { std::call_once(flag, [] { InitLookupCell(0, 0, 0, 0, 0, 0); InitLookupCell(0, 0, 0, kSwapMask, 0, kSwapMask); InitLookupCell(0, 0, 0, kInvertMask, 0, kInvertMask); InitLookupCell(0, 0, 0, kSwapMask | kInvertMask, 0, kSwapMask | kInvertMask); }); } S2CellId S2CellId::advance(int64_t steps) const { if (steps == 0) return *this; // We clamp the number of steps if necessary to ensure that we do not // advance past the End() or before the Begin() of this level. Note that // min_steps and max_steps always fit in a signed 64-bit integer. int step_shift = 2 * (kMaxLevel - level()) + 1; if (steps < 0) { int64_t min_steps = -static_cast<int64_t>(id_ >> step_shift); if (steps < min_steps) steps = min_steps; } else { int64_t max_steps = (kWrapOffset + lsb() - id_) >> step_shift; if (steps > max_steps) steps = max_steps; } // If steps is negative, then shifting it left has undefined behavior. // Cast to uint64_t for a 2's complement answer. return S2CellId(id_ + (static_cast<uint64_t>(steps) << step_shift)); } int64_t S2CellId::distance_from_begin() const { const int step_shift = 2 * (kMaxLevel - level()) + 1; return id_ >> step_shift; } S2CellId S2CellId::advance_wrap(int64_t steps) const { DCHECK(is_valid()); if (steps == 0) return *this; int step_shift = 2 * (kMaxLevel - level()) + 1; if (steps < 0) { int64_t min_steps = -static_cast<int64_t>(id_ >> step_shift); if (steps < min_steps) { int64_t step_wrap = kWrapOffset >> step_shift; steps %= step_wrap; if (steps < min_steps) steps += step_wrap; } } else { // Unlike advance(), we don't want to return End(level). int64_t max_steps = (kWrapOffset - id_) >> step_shift; if (steps > max_steps) { int64_t step_wrap = kWrapOffset >> step_shift; steps %= step_wrap; if (steps > max_steps) steps -= step_wrap; } } return S2CellId(id_ + (static_cast<uint64_t>(steps) << step_shift)); } S2CellId S2CellId::maximum_tile(S2CellId const limit) const { S2CellId id = *this; S2CellId start = id.range_min(); if (start >= limit.range_min()) return limit; if (id.range_max() >= limit) { // The cell is too large. Shrink it. Note that when generating coverings // of S2CellId ranges, this loop usually executes only once. Also because // id.range_min() < limit.range_min(), we will always exit the loop by the // time we reach a leaf cell. do { id = id.child(0); } while (id.range_max() >= limit); return id; } // The cell may be too small. Grow it if necessary. Note that generally // this loop only iterates once. while (!id.is_face()) { S2CellId parent = id.parent(); if (parent.range_min() != start || parent.range_max() >= limit) break; id = parent; } return id; } int S2CellId::GetCommonAncestorLevel(S2CellId other) const { // Basically we find the first bit position at which the two S2CellIds // differ and convert that to a level. The max() below is necessary for the // case where one S2CellId is a descendant of the other. uint64_t bits = max(id() ^ other.id(), max(lsb(), other.lsb())); // Compute the position of the most significant bit, and then map // {0} -> 30, {1,2} -> 29, {3,4} -> 28, ... , {59,60} -> 0, {61,62,63} -> -1. return max(60 - Bits::FindMSBSetNonZero64(bits), -1) >> 1; } // Print the num_digits low order hex digits. static std::string HexFormatString(uint64_t val, size_t num_digits) { std::string result(num_digits, ' '); for (; num_digits--; val >>= 4) result[num_digits] = "0123456789abcdef"[val & 0xF]; return result; } std::string S2CellId::ToToken() const { // Simple implementation: print the id in hex without trailing zeros. // Using hex has the advantage that the tokens are case-insensitive, all // characters are alphanumeric, no characters require any special escaping // in queries for most indexing systems, and it's easy to compare cell // tokens against the feature ids of the corresponding features. // // Using base 64 would produce slightly shorter tokens, but for typical cell // sizes used during indexing (up to level 15 or so) the average savings // would be less than 2 bytes per cell which doesn't seem worth it. // "0" with trailing 0s stripped is the empty std::string, which is not a // reasonable token. Encode as "X". if (id_ == 0) return "X"; size_t const num_zero_digits = Bits::FindLSBSetNonZero64(id_) / 4; return HexFormatString(id_ >> (4 * num_zero_digits), 16 - num_zero_digits); } S2CellId S2CellId::FromToken(const char* token, size_t length) { if (length > 16) return S2CellId::None(); uint64_t id = 0; for (int i = 0, pos = 60; i < length; ++i, pos -= 4) { uint64_t d; if ('0' <= token[i] && token[i] <= '9') { d = token[i] - '0'; } else if ('a' <= token[i] && token[i] <= 'f') { d = token[i] - 'a' + 10; } else if ('A' <= token[i] && token[i] <= 'F') { d = token[i] - 'A' + 10; } else { return S2CellId::None(); } id |= d << pos; } return S2CellId(id); } S2CellId S2CellId::FromToken(std::string const& token) { return FromToken(token.data(), token.size()); } S2CellId S2CellId::FromFaceIJ(int face, int i, int j) { // Initialization if not done yet MaybeInit(); // Optimization notes: // - Non-overlapping bit fields can be combined with either "+" or "|". // Generally "+" seems to produce better code, but not always. // Note that this value gets shifted one bit to the left at the end // of the function. uint64_t n = static_cast<uint64_t>(face) << (kPosBits - 1); // Alternating faces have opposite Hilbert curve orientations; this // is necessary in order for all faces to have a right-handed // coordinate system. uint64_t bits = (face & kSwapMask); // Each iteration maps 4 bits of "i" and "j" into 8 bits of the Hilbert // curve position. The lookup table transforms a 10-bit key of the form // "iiiijjjjoo" to a 10-bit value of the form "ppppppppoo", where the // letters [ijpo] denote bits of "i", "j", Hilbert curve position, and // Hilbert curve orientation respectively. #define GET_BITS(k) \ do { \ int const mask = (1 << kLookupBits) - 1; \ bits += ((i >> (k * kLookupBits)) & mask) << (kLookupBits + 2); \ bits += ((j >> (k * kLookupBits)) & mask) << 2; \ bits = lookup_pos[bits]; \ n |= (bits >> 2) << (k * 2 * kLookupBits); \ bits &= (kSwapMask | kInvertMask); \ } while (0) GET_BITS(7); GET_BITS(6); GET_BITS(5); GET_BITS(4); GET_BITS(3); GET_BITS(2); GET_BITS(1); GET_BITS(0); #undef GET_BITS return S2CellId(n * 2 + 1); } S2CellId::S2CellId(S2Point const& p) { double u, v; int face = S2::XYZtoFaceUV(p, &u, &v); int i = S2::STtoIJ(S2::UVtoST(u)); int j = S2::STtoIJ(S2::UVtoST(v)); id_ = FromFaceIJ(face, i, j).id(); } S2CellId::S2CellId(S2LatLng const& ll) : S2CellId(ll.ToPoint()) {} int S2CellId::ToFaceIJOrientation(int* pi, int* pj, int* orientation) const { // Initialization if not done yet MaybeInit(); int i = 0, j = 0; int face = this->face(); int bits = (face & kSwapMask); // Each iteration maps 8 bits of the Hilbert curve position into // 4 bits of "i" and "j". The lookup table transforms a key of the // form "ppppppppoo" to a value of the form "iiiijjjjoo", where the // letters [ijpo] represents bits of "i", "j", the Hilbert curve // position, and the Hilbert curve orientation respectively. // // On the first iteration we need to be careful to clear out the bits // representing the cube face. #define GET_BITS(k) \ do { \ int const nbits = (k == 7) ? (kMaxLevel - 7 * kLookupBits) : kLookupBits; \ bits += (static_cast<int>(id_ >> (k * 2 * kLookupBits + 1)) & \ ((1 << (2 * nbits)) - 1)) \ << 2; \ bits = lookup_ij[bits]; \ i += (bits >> (kLookupBits + 2)) << (k * kLookupBits); \ j += ((bits >> 2) & ((1 << kLookupBits) - 1)) << (k * kLookupBits); \ bits &= (kSwapMask | kInvertMask); \ } while (0) GET_BITS(7); GET_BITS(6); GET_BITS(5); GET_BITS(4); GET_BITS(3); GET_BITS(2); GET_BITS(1); GET_BITS(0); #undef GET_BITS *pi = i; *pj = j; if (orientation != nullptr) { // The position of a non-leaf cell at level "n" consists of a prefix of // 2*n bits that identifies the cell, followed by a suffix of // 2*(kMaxLevel-n)+1 bits of the form 10*. If n==kMaxLevel, the suffix is // just "1" and has no effect. Otherwise, it consists of "10", followed // by (kMaxLevel-n-1) repetitions of "00", followed by "0". The "10" has // no effect, while each occurrence of "00" has the effect of reversing // the kSwapMask bit. DCHECK_EQ(0, kPosToOrientation[2]); DCHECK_EQ(kSwapMask, kPosToOrientation[0]); if (lsb() & static_cast<uint64_t>(0x1111111111111110)) { bits ^= kSwapMask; } *orientation = bits; } return face; } S2Point S2CellId::ToPointRaw() const { int si, ti; int face = GetCenterSiTi(&si, &ti); return S2::FaceSiTitoXYZ(face, si, ti); } S2LatLng S2CellId::ToLatLng() const { return S2LatLng(ToPointRaw()); } R2Point S2CellId::GetCenterST() const { int si, ti; GetCenterSiTi(&si, &ti); return R2Point(S2::SiTitoST(si), S2::SiTitoST(ti)); } R2Point S2CellId::GetCenterUV() const { int si, ti; GetCenterSiTi(&si, &ti); return R2Point(S2::STtoUV(S2::SiTitoST(si)), S2::STtoUV(S2::SiTitoST(ti))); } R2Rect S2CellId::IJLevelToBoundUV(int ij[2], int level) { R2Rect bound; int cell_size = GetSizeIJ(level); for (int d = 0; d < 2; ++d) { int ij_lo = ij[d] & -cell_size; int ij_hi = ij_lo + cell_size; bound[d][0] = S2::STtoUV(S2::IJtoSTMin(ij_lo)); bound[d][1] = S2::STtoUV(S2::IJtoSTMin(ij_hi)); } return bound; } R2Rect S2CellId::GetBoundST() const { double size = GetSizeST(); return R2Rect::FromCenterSize(GetCenterST(), R2Point(size, size)); } R2Rect S2CellId::GetBoundUV() const { int ij[2]; ToFaceIJOrientation(&ij[0], &ij[1], nullptr); return IJLevelToBoundUV(ij, level()); } // This is a helper function for ExpandedByDistanceUV(). // // Given an edge of the form (u,v0)-(u,v1), let max_v = max(abs(v0), abs(v1)). // This method returns a new u-coordinate u' such that the distance from the // line u=u' to the given edge (u,v0)-(u,v1) is exactly the given distance // (which is specified as the sine of the angle corresponding to the distance). static double ExpandEndpoint(double u, double max_v, double sin_dist) { // This is based on solving a spherical right triangle, similar to the // calculation in S2Cap::GetRectBound. double sin_u_shift = sin_dist * sqrt((1 + u * u + max_v * max_v) / (1 + u * u)); double cos_u_shift = sqrt(1 - sin_u_shift * sin_u_shift); // The following is an expansion of tan(atan(u) + asin(sin_u_shift)). return (cos_u_shift * u + sin_u_shift) / (cos_u_shift - sin_u_shift * u); } /* static */ R2Rect S2CellId::ExpandedByDistanceUV(R2Rect const& uv, S1Angle distance) { // Expand each of the four sides of the rectangle just enough to include all // points within the given distance of that side. (The rectangle may be // expanded by a different amount in (u,v)-space on each side.) double u0 = uv[0][0], u1 = uv[0][1], v0 = uv[1][0], v1 = uv[1][1]; double max_u = std::max(std::abs(u0), std::abs(u1)); double max_v = std::max(std::abs(v0), std::abs(v1)); double sin_dist = sin(distance); return R2Rect(R1Interval(ExpandEndpoint(u0, max_v, -sin_dist), ExpandEndpoint(u1, max_v, sin_dist)), R1Interval(ExpandEndpoint(v0, max_u, -sin_dist), ExpandEndpoint(v1, max_u, sin_dist))); } S2CellId S2CellId::FromFaceIJWrap(int face, int i, int j) { // Convert i and j to the coordinates of a leaf cell just beyond the // boundary of this face. This prevents 32-bit overflow in the case // of finding the neighbors of a face cell. i = max(-1, min(kMaxSize, i)); j = max(-1, min(kMaxSize, j)); // We want to wrap these coordinates onto the appropriate adjacent face. // The easiest way to do this is to convert the (i,j) coordinates to (x,y,z) // (which yields a point outside the normal face boundary), and then call // S2::XYZtoFaceUV() to project back onto the correct face. // // The code below converts (i,j) to (si,ti), and then (si,ti) to (u,v) using // the linear projection (u=2*s-1 and v=2*t-1). (The code further below // converts back using the inverse projection, s=0.5*(u+1) and t=0.5*(v+1). // Any projection would work here, so we use the simplest.) We also clamp // the (u,v) coordinates so that the point is barely outside the // [-1,1]x[-1,1] face rectangle, since otherwise the reprojection step // (which divides by the new z coordinate) might change the other // coordinates enough so that we end up in the wrong leaf cell. static const double kScale = 1.0 / kMaxSize; static const double kLimit = 1.0 + DBL_EPSILON; // The arithmetic below is designed to avoid 32-bit integer overflows. DCHECK_EQ(0, kMaxSize % 2); double u = max(-kLimit, min(kLimit, kScale * (2 * (i - kMaxSize / 2) + 1))); double v = max(-kLimit, min(kLimit, kScale * (2 * (j - kMaxSize / 2) + 1))); // Find the leaf cell coordinates on the adjacent face, and convert // them to a cell id at the appropriate level. face = S2::XYZtoFaceUV(S2::FaceUVtoXYZ(face, u, v), &u, &v); return FromFaceIJ(face, S2::STtoIJ(0.5 * (u + 1)), S2::STtoIJ(0.5 * (v + 1))); } inline S2CellId S2CellId::FromFaceIJSame(int face, int i, int j, bool same_face) { if (same_face) return S2CellId::FromFaceIJ(face, i, j); else return S2CellId::FromFaceIJWrap(face, i, j); } void S2CellId::GetEdgeNeighbors(S2CellId neighbors[4]) const { int i, j; int level = this->level(); int size = GetSizeIJ(level); int face = ToFaceIJOrientation(&i, &j, nullptr); // Edges 0, 1, 2, 3 are in the down, right, up, left directions. neighbors[0] = FromFaceIJSame(face, i, j - size, j - size >= 0).parent(level); neighbors[1] = FromFaceIJSame(face, i + size, j, i + size < kMaxSize).parent(level); neighbors[2] = FromFaceIJSame(face, i, j + size, j + size < kMaxSize).parent(level); neighbors[3] = FromFaceIJSame(face, i - size, j, i - size >= 0).parent(level); } void S2CellId::AppendVertexNeighbors(int level, vector<S2CellId>* output) const { // "level" must be strictly less than this cell's level so that we can // determine which vertex this cell is closest to. DCHECK_LT(level, this->level()); int i, j; int face = ToFaceIJOrientation(&i, &j, nullptr); // Determine the i- and j-offsets to the closest neighboring cell in each // direction. This involves looking at the next bit of "i" and "j" to // determine which quadrant of this->parent(level) this cell lies in. int halfsize = GetSizeIJ(level + 1); int size = halfsize << 1; bool isame, jsame; int ioffset, joffset; if (i & halfsize) { ioffset = size; isame = (i + size) < kMaxSize; } else { ioffset = -size; isame = (i - size) >= 0; } if (j & halfsize) { joffset = size; jsame = (j + size) < kMaxSize; } else { joffset = -size; jsame = (j - size) >= 0; } output->push_back(parent(level)); output->push_back(FromFaceIJSame(face, i + ioffset, j, isame).parent(level)); output->push_back(FromFaceIJSame(face, i, j + joffset, jsame).parent(level)); // If i- and j- edge neighbors are *both* on a different face, then this // vertex only has three neighbors (it is one of the 8 cube vertices). if (isame || jsame) { output->push_back( FromFaceIJSame(face, i + ioffset, j + joffset, isame && jsame) .parent(level)); } } void S2CellId::AppendAllNeighbors(int nbr_level, vector<S2CellId>* output) const { DCHECK_GE(nbr_level, level()); int i, j; int face = ToFaceIJOrientation(&i, &j, nullptr); // Find the coordinates of the lower left-hand leaf cell. We need to // normalize (i,j) to a known position within the cell because nbr_level // may be larger than this cell's level. int size = GetSizeIJ(); i &= -size; j &= -size; int nbr_size = GetSizeIJ(nbr_level); DCHECK_LE(nbr_size, size); // We compute the top-bottom, left-right, and diagonal neighbors in one // pass. The loop test is at the end of the loop to avoid 32-bit overflow. for (int k = -nbr_size;; k += nbr_size) { bool same_face; if (k < 0) { same_face = (j + k >= 0); } else if (k >= size) { same_face = (j + k < kMaxSize); } else { same_face = true; // Top and bottom neighbors. output->push_back(FromFaceIJSame(face, i + k, j - nbr_size, j - size >= 0) .parent(nbr_level)); output->push_back( FromFaceIJSame(face, i + k, j + size, j + size < kMaxSize) .parent(nbr_level)); } // Left, right, and diagonal neighbors. output->push_back( FromFaceIJSame(face, i - nbr_size, j + k, same_face && i - size >= 0) .parent(nbr_level)); output->push_back( FromFaceIJSame(face, i + size, j + k, same_face && i + size < kMaxSize) .parent(nbr_level)); if (k >= size) break; } } std::string S2CellId::ToString() const { if (!is_valid()) { return base::StringPrintf("Invalid: %016" PRIu64, id()); } std::string out = base::StringPrintf("%d/", face()); for (int current_level = 1; current_level <= level(); ++current_level) { // Avoid dependencies of SimpleItoA, and slowness of StringAppendF & // std::to_string. out += "0123"[child_position(current_level)]; } return out; } std::ostream& operator<<(std::ostream& os, S2CellId id) { return os << id.ToString(); }
null
null
null
null
24,555
7,966
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
7,966
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 NET_CERT_X509_UTIL_H_ #define NET_CERT_X509_UTIL_H_ #include <stdint.h> #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/strings/string_piece.h" #include "base/time/time.h" #include "net/base/hash_value.h" #include "net/base/net_export.h" #include "third_party/boringssl/src/include/openssl/base.h" #include "third_party/boringssl/src/include/openssl/pool.h" namespace crypto { class RSAPrivateKey; } namespace net { struct ParseCertificateOptions; class X509Certificate; namespace x509_util { // Supported digest algorithms for signing certificates. enum DigestAlgorithm { DIGEST_SHA256 }; // Generate a 'tls-server-end-point' channel binding based on the specified // certificate. Channel bindings are based on RFC 5929. NET_EXPORT_PRIVATE bool GetTLSServerEndPointChannelBinding( const X509Certificate& certificate, std::string* token); // Creates a public-private keypair and a self-signed certificate. // Subject, serial number and validity period are given as parameters. // The certificate is signed by the private key in |key|. The key length and // signature algorithm may be updated periodically to match best practices. // // |subject| is a distinguished name defined in RFC4514 with _only_ a CN // component, as in: // CN=Michael Wong // // SECURITY WARNING // // Using self-signed certificates has the following security risks: // 1. Encryption without authentication and thus vulnerable to // man-in-the-middle attacks. // 2. Self-signed certificates cannot be revoked. // // Use this certificate only after the above risks are acknowledged. NET_EXPORT bool CreateKeyAndSelfSignedCert( const std::string& subject, uint32_t serial_number, base::Time not_valid_before, base::Time not_valid_after, std::unique_ptr<crypto::RSAPrivateKey>* key, std::string* der_cert); // Creates a self-signed certificate from a provided key, using the specified // hash algorithm. NET_EXPORT bool CreateSelfSignedCert(EVP_PKEY* key, DigestAlgorithm alg, const std::string& subject, uint32_t serial_number, base::Time not_valid_before, base::Time not_valid_after, std::string* der_cert); // Returns a CRYPTO_BUFFER_POOL for deduplicating certificates. NET_EXPORT CRYPTO_BUFFER_POOL* GetBufferPool(); // Creates a CRYPTO_BUFFER in the same pool returned by GetBufferPool. NET_EXPORT bssl::UniquePtr<CRYPTO_BUFFER> CreateCryptoBuffer( const uint8_t* data, size_t length); // Creates a CRYPTO_BUFFER in the same pool returned by GetBufferPool. NET_EXPORT bssl::UniquePtr<CRYPTO_BUFFER> CreateCryptoBuffer( const base::StringPiece& data); // Overload with no definition, to disallow creating a CRYPTO_BUFFER from a // char* due to StringPiece implicit ctor. NET_EXPORT bssl::UniquePtr<CRYPTO_BUFFER> CreateCryptoBuffer( const char* invalid_data); // Increments the reference count of |buffer| and returns a UniquePtr owning // that reference. NET_EXPORT bssl::UniquePtr<CRYPTO_BUFFER> DupCryptoBuffer( CRYPTO_BUFFER* buffer); // Compares two CRYPTO_BUFFERs and returns true if they have the same contents. NET_EXPORT bool CryptoBufferEqual(const CRYPTO_BUFFER* a, const CRYPTO_BUFFER* b); // Returns a StringPiece pointing to the data in |buffer|. NET_EXPORT base::StringPiece CryptoBufferAsStringPiece( const CRYPTO_BUFFER* buffer); // Creates a new X509Certificate from the chain in |buffers|, which must have at // least one element. scoped_refptr<X509Certificate> CreateX509CertificateFromBuffers( STACK_OF(CRYPTO_BUFFER) * buffers); // Returns the default ParseCertificateOptions for the net stack. ParseCertificateOptions DefaultParseCertificateOptions(); // On success, returns true and updates |hash| to be the SHA-256 hash of the // subjectPublicKeyInfo of the certificate in |buffer|. If |buffer| is not a // valid certificate, returns false and |hash| is in an undefined state. NET_EXPORT bool CalculateSha256SpkiHash(const CRYPTO_BUFFER* buffer, HashValue* hash) WARN_UNUSED_RESULT; } // namespace x509_util } // namespace net #endif // NET_CERT_X509_UTIL_H_
null
null
null
null
4,829
4,180
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
169,175
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Copyright (c) 2008-2010, 2013 Dave Chinner * 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. * * This program is distributed in the hope that it would be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_shared.h" #include "xfs_format.h" #include "xfs_log_format.h" #include "xfs_trans_resv.h" #include "xfs_bit.h" #include "xfs_mount.h" #include "xfs_trans.h" #include "xfs_trans_priv.h" #include "xfs_error.h" #include "xfs_icreate_item.h" #include "xfs_log.h" kmem_zone_t *xfs_icreate_zone; /* inode create item zone */ static inline struct xfs_icreate_item *ICR_ITEM(struct xfs_log_item *lip) { return container_of(lip, struct xfs_icreate_item, ic_item); } /* * This returns the number of iovecs needed to log the given inode item. * * We only need one iovec for the icreate log structure. */ STATIC void xfs_icreate_item_size( struct xfs_log_item *lip, int *nvecs, int *nbytes) { *nvecs += 1; *nbytes += sizeof(struct xfs_icreate_log); } /* * This is called to fill in the vector of log iovecs for the * given inode create log item. */ STATIC void xfs_icreate_item_format( struct xfs_log_item *lip, struct xfs_log_vec *lv) { struct xfs_icreate_item *icp = ICR_ITEM(lip); struct xfs_log_iovec *vecp = NULL; xlog_copy_iovec(lv, &vecp, XLOG_REG_TYPE_ICREATE, &icp->ic_format, sizeof(struct xfs_icreate_log)); } /* Pinning has no meaning for the create item, so just return. */ STATIC void xfs_icreate_item_pin( struct xfs_log_item *lip) { } /* pinning has no meaning for the create item, so just return. */ STATIC void xfs_icreate_item_unpin( struct xfs_log_item *lip, int remove) { } STATIC void xfs_icreate_item_unlock( struct xfs_log_item *lip) { struct xfs_icreate_item *icp = ICR_ITEM(lip); if (icp->ic_item.li_flags & XFS_LI_ABORTED) kmem_zone_free(xfs_icreate_zone, icp); return; } /* * Because we have ordered buffers being tracked in the AIL for the inode * creation, we don't need the create item after this. Hence we can free * the log item and return -1 to tell the caller we're done with the item. */ STATIC xfs_lsn_t xfs_icreate_item_committed( struct xfs_log_item *lip, xfs_lsn_t lsn) { struct xfs_icreate_item *icp = ICR_ITEM(lip); kmem_zone_free(xfs_icreate_zone, icp); return (xfs_lsn_t)-1; } /* item can never get into the AIL */ STATIC uint xfs_icreate_item_push( struct xfs_log_item *lip, struct list_head *buffer_list) { ASSERT(0); return XFS_ITEM_SUCCESS; } /* Ordered buffers do the dependency tracking here, so this does nothing. */ STATIC void xfs_icreate_item_committing( struct xfs_log_item *lip, xfs_lsn_t lsn) { } /* * This is the ops vector shared by all buf log items. */ static const struct xfs_item_ops xfs_icreate_item_ops = { .iop_size = xfs_icreate_item_size, .iop_format = xfs_icreate_item_format, .iop_pin = xfs_icreate_item_pin, .iop_unpin = xfs_icreate_item_unpin, .iop_push = xfs_icreate_item_push, .iop_unlock = xfs_icreate_item_unlock, .iop_committed = xfs_icreate_item_committed, .iop_committing = xfs_icreate_item_committing, }; /* * Initialize the inode log item for a newly allocated (in-core) inode. * * Inode extents can only reside within an AG. Hence specify the starting * block for the inode chunk by offset within an AG as well as the * length of the allocated extent. * * This joins the item to the transaction and marks it dirty so * that we don't need a separate call to do this, nor does the * caller need to know anything about the icreate item. */ void xfs_icreate_log( struct xfs_trans *tp, xfs_agnumber_t agno, xfs_agblock_t agbno, unsigned int count, unsigned int inode_size, xfs_agblock_t length, unsigned int generation) { struct xfs_icreate_item *icp; icp = kmem_zone_zalloc(xfs_icreate_zone, KM_SLEEP); xfs_log_item_init(tp->t_mountp, &icp->ic_item, XFS_LI_ICREATE, &xfs_icreate_item_ops); icp->ic_format.icl_type = XFS_LI_ICREATE; icp->ic_format.icl_size = 1; /* single vector */ icp->ic_format.icl_ag = cpu_to_be32(agno); icp->ic_format.icl_agbno = cpu_to_be32(agbno); icp->ic_format.icl_count = cpu_to_be32(count); icp->ic_format.icl_isize = cpu_to_be32(inode_size); icp->ic_format.icl_length = cpu_to_be32(length); icp->ic_format.icl_gen = cpu_to_be32(generation); xfs_trans_add_item(tp, &icp->ic_item); tp->t_flags |= XFS_TRANS_DIRTY; icp->ic_item.li_desc->lid_flags |= XFS_LID_DIRTY; }
null
null
null
null
77,522
33,551
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
198,546
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* STV0900/0903 Multistandard Broadcast Frontend driver Copyright (C) Manu Abraham <[email protected]> Copyright (C) ST Microelectronics This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/dvb/frontend.h> #include "dvb_frontend.h" #include "stv6110x.h" /* for demodulator internal modes */ #include "stv090x_reg.h" #include "stv090x.h" #include "stv090x_priv.h" /* Max transfer size done by I2C transfer functions */ #define MAX_XFER_SIZE 64 static unsigned int verbose; module_param(verbose, int, 0644); /* internal params node */ struct stv090x_dev { /* pointer for internal params, one for each pair of demods */ struct stv090x_internal *internal; struct stv090x_dev *next_dev; }; /* first internal params */ static struct stv090x_dev *stv090x_first_dev; /* find chip by i2c adapter and i2c address */ static struct stv090x_dev *find_dev(struct i2c_adapter *i2c_adap, u8 i2c_addr) { struct stv090x_dev *temp_dev = stv090x_first_dev; /* Search of the last stv0900 chip or find it by i2c adapter and i2c address */ while ((temp_dev != NULL) && ((temp_dev->internal->i2c_adap != i2c_adap) || (temp_dev->internal->i2c_addr != i2c_addr))) { temp_dev = temp_dev->next_dev; } return temp_dev; } /* deallocating chip */ static void remove_dev(struct stv090x_internal *internal) { struct stv090x_dev *prev_dev = stv090x_first_dev; struct stv090x_dev *del_dev = find_dev(internal->i2c_adap, internal->i2c_addr); if (del_dev != NULL) { if (del_dev == stv090x_first_dev) { stv090x_first_dev = del_dev->next_dev; } else { while (prev_dev->next_dev != del_dev) prev_dev = prev_dev->next_dev; prev_dev->next_dev = del_dev->next_dev; } kfree(del_dev); } } /* allocating new chip */ static struct stv090x_dev *append_internal(struct stv090x_internal *internal) { struct stv090x_dev *new_dev; struct stv090x_dev *temp_dev; new_dev = kmalloc(sizeof(struct stv090x_dev), GFP_KERNEL); if (new_dev != NULL) { new_dev->internal = internal; new_dev->next_dev = NULL; /* append to list */ if (stv090x_first_dev == NULL) { stv090x_first_dev = new_dev; } else { temp_dev = stv090x_first_dev; while (temp_dev->next_dev != NULL) temp_dev = temp_dev->next_dev; temp_dev->next_dev = new_dev; } } return new_dev; } /* DVBS1 and DSS C/N Lookup table */ static const struct stv090x_tab stv090x_s1cn_tab[] = { { 0, 8917 }, /* 0.0dB */ { 5, 8801 }, /* 0.5dB */ { 10, 8667 }, /* 1.0dB */ { 15, 8522 }, /* 1.5dB */ { 20, 8355 }, /* 2.0dB */ { 25, 8175 }, /* 2.5dB */ { 30, 7979 }, /* 3.0dB */ { 35, 7763 }, /* 3.5dB */ { 40, 7530 }, /* 4.0dB */ { 45, 7282 }, /* 4.5dB */ { 50, 7026 }, /* 5.0dB */ { 55, 6781 }, /* 5.5dB */ { 60, 6514 }, /* 6.0dB */ { 65, 6241 }, /* 6.5dB */ { 70, 5965 }, /* 7.0dB */ { 75, 5690 }, /* 7.5dB */ { 80, 5424 }, /* 8.0dB */ { 85, 5161 }, /* 8.5dB */ { 90, 4902 }, /* 9.0dB */ { 95, 4654 }, /* 9.5dB */ { 100, 4417 }, /* 10.0dB */ { 105, 4186 }, /* 10.5dB */ { 110, 3968 }, /* 11.0dB */ { 115, 3757 }, /* 11.5dB */ { 120, 3558 }, /* 12.0dB */ { 125, 3366 }, /* 12.5dB */ { 130, 3185 }, /* 13.0dB */ { 135, 3012 }, /* 13.5dB */ { 140, 2850 }, /* 14.0dB */ { 145, 2698 }, /* 14.5dB */ { 150, 2550 }, /* 15.0dB */ { 160, 2283 }, /* 16.0dB */ { 170, 2042 }, /* 17.0dB */ { 180, 1827 }, /* 18.0dB */ { 190, 1636 }, /* 19.0dB */ { 200, 1466 }, /* 20.0dB */ { 210, 1315 }, /* 21.0dB */ { 220, 1181 }, /* 22.0dB */ { 230, 1064 }, /* 23.0dB */ { 240, 960 }, /* 24.0dB */ { 250, 869 }, /* 25.0dB */ { 260, 792 }, /* 26.0dB */ { 270, 724 }, /* 27.0dB */ { 280, 665 }, /* 28.0dB */ { 290, 616 }, /* 29.0dB */ { 300, 573 }, /* 30.0dB */ { 310, 537 }, /* 31.0dB */ { 320, 507 }, /* 32.0dB */ { 330, 483 }, /* 33.0dB */ { 400, 398 }, /* 40.0dB */ { 450, 381 }, /* 45.0dB */ { 500, 377 } /* 50.0dB */ }; /* DVBS2 C/N Lookup table */ static const struct stv090x_tab stv090x_s2cn_tab[] = { { -30, 13348 }, /* -3.0dB */ { -20, 12640 }, /* -2d.0B */ { -10, 11883 }, /* -1.0dB */ { 0, 11101 }, /* -0.0dB */ { 5, 10718 }, /* 0.5dB */ { 10, 10339 }, /* 1.0dB */ { 15, 9947 }, /* 1.5dB */ { 20, 9552 }, /* 2.0dB */ { 25, 9183 }, /* 2.5dB */ { 30, 8799 }, /* 3.0dB */ { 35, 8422 }, /* 3.5dB */ { 40, 8062 }, /* 4.0dB */ { 45, 7707 }, /* 4.5dB */ { 50, 7353 }, /* 5.0dB */ { 55, 7025 }, /* 5.5dB */ { 60, 6684 }, /* 6.0dB */ { 65, 6331 }, /* 6.5dB */ { 70, 6036 }, /* 7.0dB */ { 75, 5727 }, /* 7.5dB */ { 80, 5437 }, /* 8.0dB */ { 85, 5164 }, /* 8.5dB */ { 90, 4902 }, /* 9.0dB */ { 95, 4653 }, /* 9.5dB */ { 100, 4408 }, /* 10.0dB */ { 105, 4187 }, /* 10.5dB */ { 110, 3961 }, /* 11.0dB */ { 115, 3751 }, /* 11.5dB */ { 120, 3558 }, /* 12.0dB */ { 125, 3368 }, /* 12.5dB */ { 130, 3191 }, /* 13.0dB */ { 135, 3017 }, /* 13.5dB */ { 140, 2862 }, /* 14.0dB */ { 145, 2710 }, /* 14.5dB */ { 150, 2565 }, /* 15.0dB */ { 160, 2300 }, /* 16.0dB */ { 170, 2058 }, /* 17.0dB */ { 180, 1849 }, /* 18.0dB */ { 190, 1663 }, /* 19.0dB */ { 200, 1495 }, /* 20.0dB */ { 210, 1349 }, /* 21.0dB */ { 220, 1222 }, /* 22.0dB */ { 230, 1110 }, /* 23.0dB */ { 240, 1011 }, /* 24.0dB */ { 250, 925 }, /* 25.0dB */ { 260, 853 }, /* 26.0dB */ { 270, 789 }, /* 27.0dB */ { 280, 734 }, /* 28.0dB */ { 290, 690 }, /* 29.0dB */ { 300, 650 }, /* 30.0dB */ { 310, 619 }, /* 31.0dB */ { 320, 593 }, /* 32.0dB */ { 330, 571 }, /* 33.0dB */ { 400, 498 }, /* 40.0dB */ { 450, 484 }, /* 45.0dB */ { 500, 481 } /* 50.0dB */ }; /* RF level C/N lookup table */ static const struct stv090x_tab stv090x_rf_tab[] = { { -5, 0xcaa1 }, /* -5dBm */ { -10, 0xc229 }, /* -10dBm */ { -15, 0xbb08 }, /* -15dBm */ { -20, 0xb4bc }, /* -20dBm */ { -25, 0xad5a }, /* -25dBm */ { -30, 0xa298 }, /* -30dBm */ { -35, 0x98a8 }, /* -35dBm */ { -40, 0x8389 }, /* -40dBm */ { -45, 0x59be }, /* -45dBm */ { -50, 0x3a14 }, /* -50dBm */ { -55, 0x2d11 }, /* -55dBm */ { -60, 0x210d }, /* -60dBm */ { -65, 0xa14f }, /* -65dBm */ { -70, 0x07aa } /* -70dBm */ }; static struct stv090x_reg stv0900_initval[] = { { STV090x_OUTCFG, 0x00 }, { STV090x_MODECFG, 0xff }, { STV090x_AGCRF1CFG, 0x11 }, { STV090x_AGCRF2CFG, 0x13 }, { STV090x_TSGENERAL1X, 0x14 }, { STV090x_TSTTNR2, 0x21 }, { STV090x_TSTTNR4, 0x21 }, { STV090x_P2_DISTXCTL, 0x22 }, { STV090x_P2_F22TX, 0xc0 }, { STV090x_P2_F22RX, 0xc0 }, { STV090x_P2_DISRXCTL, 0x00 }, { STV090x_P2_DMDCFGMD, 0xF9 }, { STV090x_P2_DEMOD, 0x08 }, { STV090x_P2_DMDCFG3, 0xc4 }, { STV090x_P2_CARFREQ, 0xed }, { STV090x_P2_LDT, 0xd0 }, { STV090x_P2_LDT2, 0xb8 }, { STV090x_P2_TMGCFG, 0xd2 }, { STV090x_P2_TMGTHRISE, 0x20 }, { STV090x_P1_TMGCFG, 0xd2 }, { STV090x_P2_TMGTHFALL, 0x00 }, { STV090x_P2_FECSPY, 0x88 }, { STV090x_P2_FSPYDATA, 0x3a }, { STV090x_P2_FBERCPT4, 0x00 }, { STV090x_P2_FSPYBER, 0x10 }, { STV090x_P2_ERRCTRL1, 0x35 }, { STV090x_P2_ERRCTRL2, 0xc1 }, { STV090x_P2_CFRICFG, 0xf8 }, { STV090x_P2_NOSCFG, 0x1c }, { STV090x_P2_DMDTOM, 0x20 }, { STV090x_P2_CORRELMANT, 0x70 }, { STV090x_P2_CORRELABS, 0x88 }, { STV090x_P2_AGC2O, 0x5b }, { STV090x_P2_AGC2REF, 0x38 }, { STV090x_P2_CARCFG, 0xe4 }, { STV090x_P2_ACLC, 0x1A }, { STV090x_P2_BCLC, 0x09 }, { STV090x_P2_CARHDR, 0x08 }, { STV090x_P2_KREFTMG, 0xc1 }, { STV090x_P2_SFRUPRATIO, 0xf0 }, { STV090x_P2_SFRLOWRATIO, 0x70 }, { STV090x_P2_SFRSTEP, 0x58 }, { STV090x_P2_TMGCFG2, 0x01 }, { STV090x_P2_CAR2CFG, 0x26 }, { STV090x_P2_BCLC2S2Q, 0x86 }, { STV090x_P2_BCLC2S28, 0x86 }, { STV090x_P2_SMAPCOEF7, 0x77 }, { STV090x_P2_SMAPCOEF6, 0x85 }, { STV090x_P2_SMAPCOEF5, 0x77 }, { STV090x_P2_TSCFGL, 0x20 }, { STV090x_P2_DMDCFG2, 0x3b }, { STV090x_P2_MODCODLST0, 0xff }, { STV090x_P2_MODCODLST1, 0xff }, { STV090x_P2_MODCODLST2, 0xff }, { STV090x_P2_MODCODLST3, 0xff }, { STV090x_P2_MODCODLST4, 0xff }, { STV090x_P2_MODCODLST5, 0xff }, { STV090x_P2_MODCODLST6, 0xff }, { STV090x_P2_MODCODLST7, 0xcc }, { STV090x_P2_MODCODLST8, 0xcc }, { STV090x_P2_MODCODLST9, 0xcc }, { STV090x_P2_MODCODLSTA, 0xcc }, { STV090x_P2_MODCODLSTB, 0xcc }, { STV090x_P2_MODCODLSTC, 0xcc }, { STV090x_P2_MODCODLSTD, 0xcc }, { STV090x_P2_MODCODLSTE, 0xcc }, { STV090x_P2_MODCODLSTF, 0xcf }, { STV090x_P1_DISTXCTL, 0x22 }, { STV090x_P1_F22TX, 0xc0 }, { STV090x_P1_F22RX, 0xc0 }, { STV090x_P1_DISRXCTL, 0x00 }, { STV090x_P1_DMDCFGMD, 0xf9 }, { STV090x_P1_DEMOD, 0x08 }, { STV090x_P1_DMDCFG3, 0xc4 }, { STV090x_P1_DMDTOM, 0x20 }, { STV090x_P1_CARFREQ, 0xed }, { STV090x_P1_LDT, 0xd0 }, { STV090x_P1_LDT2, 0xb8 }, { STV090x_P1_TMGCFG, 0xd2 }, { STV090x_P1_TMGTHRISE, 0x20 }, { STV090x_P1_TMGTHFALL, 0x00 }, { STV090x_P1_SFRUPRATIO, 0xf0 }, { STV090x_P1_SFRLOWRATIO, 0x70 }, { STV090x_P1_TSCFGL, 0x20 }, { STV090x_P1_FECSPY, 0x88 }, { STV090x_P1_FSPYDATA, 0x3a }, { STV090x_P1_FBERCPT4, 0x00 }, { STV090x_P1_FSPYBER, 0x10 }, { STV090x_P1_ERRCTRL1, 0x35 }, { STV090x_P1_ERRCTRL2, 0xc1 }, { STV090x_P1_CFRICFG, 0xf8 }, { STV090x_P1_NOSCFG, 0x1c }, { STV090x_P1_CORRELMANT, 0x70 }, { STV090x_P1_CORRELABS, 0x88 }, { STV090x_P1_AGC2O, 0x5b }, { STV090x_P1_AGC2REF, 0x38 }, { STV090x_P1_CARCFG, 0xe4 }, { STV090x_P1_ACLC, 0x1A }, { STV090x_P1_BCLC, 0x09 }, { STV090x_P1_CARHDR, 0x08 }, { STV090x_P1_KREFTMG, 0xc1 }, { STV090x_P1_SFRSTEP, 0x58 }, { STV090x_P1_TMGCFG2, 0x01 }, { STV090x_P1_CAR2CFG, 0x26 }, { STV090x_P1_BCLC2S2Q, 0x86 }, { STV090x_P1_BCLC2S28, 0x86 }, { STV090x_P1_SMAPCOEF7, 0x77 }, { STV090x_P1_SMAPCOEF6, 0x85 }, { STV090x_P1_SMAPCOEF5, 0x77 }, { STV090x_P1_DMDCFG2, 0x3b }, { STV090x_P1_MODCODLST0, 0xff }, { STV090x_P1_MODCODLST1, 0xff }, { STV090x_P1_MODCODLST2, 0xff }, { STV090x_P1_MODCODLST3, 0xff }, { STV090x_P1_MODCODLST4, 0xff }, { STV090x_P1_MODCODLST5, 0xff }, { STV090x_P1_MODCODLST6, 0xff }, { STV090x_P1_MODCODLST7, 0xcc }, { STV090x_P1_MODCODLST8, 0xcc }, { STV090x_P1_MODCODLST9, 0xcc }, { STV090x_P1_MODCODLSTA, 0xcc }, { STV090x_P1_MODCODLSTB, 0xcc }, { STV090x_P1_MODCODLSTC, 0xcc }, { STV090x_P1_MODCODLSTD, 0xcc }, { STV090x_P1_MODCODLSTE, 0xcc }, { STV090x_P1_MODCODLSTF, 0xcf }, { STV090x_GENCFG, 0x1d }, { STV090x_NBITER_NF4, 0x37 }, { STV090x_NBITER_NF5, 0x29 }, { STV090x_NBITER_NF6, 0x37 }, { STV090x_NBITER_NF7, 0x33 }, { STV090x_NBITER_NF8, 0x31 }, { STV090x_NBITER_NF9, 0x2f }, { STV090x_NBITER_NF10, 0x39 }, { STV090x_NBITER_NF11, 0x3a }, { STV090x_NBITER_NF12, 0x29 }, { STV090x_NBITER_NF13, 0x37 }, { STV090x_NBITER_NF14, 0x33 }, { STV090x_NBITER_NF15, 0x2f }, { STV090x_NBITER_NF16, 0x39 }, { STV090x_NBITER_NF17, 0x3a }, { STV090x_NBITERNOERR, 0x04 }, { STV090x_GAINLLR_NF4, 0x0C }, { STV090x_GAINLLR_NF5, 0x0F }, { STV090x_GAINLLR_NF6, 0x11 }, { STV090x_GAINLLR_NF7, 0x14 }, { STV090x_GAINLLR_NF8, 0x17 }, { STV090x_GAINLLR_NF9, 0x19 }, { STV090x_GAINLLR_NF10, 0x20 }, { STV090x_GAINLLR_NF11, 0x21 }, { STV090x_GAINLLR_NF12, 0x0D }, { STV090x_GAINLLR_NF13, 0x0F }, { STV090x_GAINLLR_NF14, 0x13 }, { STV090x_GAINLLR_NF15, 0x1A }, { STV090x_GAINLLR_NF16, 0x1F }, { STV090x_GAINLLR_NF17, 0x21 }, { STV090x_RCCFGH, 0x20 }, { STV090x_P1_FECM, 0x01 }, /* disable DSS modes */ { STV090x_P2_FECM, 0x01 }, /* disable DSS modes */ { STV090x_P1_PRVIT, 0x2F }, /* disable PR 6/7 */ { STV090x_P2_PRVIT, 0x2F }, /* disable PR 6/7 */ }; static struct stv090x_reg stv0903_initval[] = { { STV090x_OUTCFG, 0x00 }, { STV090x_AGCRF1CFG, 0x11 }, { STV090x_STOPCLK1, 0x48 }, { STV090x_STOPCLK2, 0x14 }, { STV090x_TSTTNR1, 0x27 }, { STV090x_TSTTNR2, 0x21 }, { STV090x_P1_DISTXCTL, 0x22 }, { STV090x_P1_F22TX, 0xc0 }, { STV090x_P1_F22RX, 0xc0 }, { STV090x_P1_DISRXCTL, 0x00 }, { STV090x_P1_DMDCFGMD, 0xF9 }, { STV090x_P1_DEMOD, 0x08 }, { STV090x_P1_DMDCFG3, 0xc4 }, { STV090x_P1_CARFREQ, 0xed }, { STV090x_P1_TNRCFG2, 0x82 }, { STV090x_P1_LDT, 0xd0 }, { STV090x_P1_LDT2, 0xb8 }, { STV090x_P1_TMGCFG, 0xd2 }, { STV090x_P1_TMGTHRISE, 0x20 }, { STV090x_P1_TMGTHFALL, 0x00 }, { STV090x_P1_SFRUPRATIO, 0xf0 }, { STV090x_P1_SFRLOWRATIO, 0x70 }, { STV090x_P1_TSCFGL, 0x20 }, { STV090x_P1_FECSPY, 0x88 }, { STV090x_P1_FSPYDATA, 0x3a }, { STV090x_P1_FBERCPT4, 0x00 }, { STV090x_P1_FSPYBER, 0x10 }, { STV090x_P1_ERRCTRL1, 0x35 }, { STV090x_P1_ERRCTRL2, 0xc1 }, { STV090x_P1_CFRICFG, 0xf8 }, { STV090x_P1_NOSCFG, 0x1c }, { STV090x_P1_DMDTOM, 0x20 }, { STV090x_P1_CORRELMANT, 0x70 }, { STV090x_P1_CORRELABS, 0x88 }, { STV090x_P1_AGC2O, 0x5b }, { STV090x_P1_AGC2REF, 0x38 }, { STV090x_P1_CARCFG, 0xe4 }, { STV090x_P1_ACLC, 0x1A }, { STV090x_P1_BCLC, 0x09 }, { STV090x_P1_CARHDR, 0x08 }, { STV090x_P1_KREFTMG, 0xc1 }, { STV090x_P1_SFRSTEP, 0x58 }, { STV090x_P1_TMGCFG2, 0x01 }, { STV090x_P1_CAR2CFG, 0x26 }, { STV090x_P1_BCLC2S2Q, 0x86 }, { STV090x_P1_BCLC2S28, 0x86 }, { STV090x_P1_SMAPCOEF7, 0x77 }, { STV090x_P1_SMAPCOEF6, 0x85 }, { STV090x_P1_SMAPCOEF5, 0x77 }, { STV090x_P1_DMDCFG2, 0x3b }, { STV090x_P1_MODCODLST0, 0xff }, { STV090x_P1_MODCODLST1, 0xff }, { STV090x_P1_MODCODLST2, 0xff }, { STV090x_P1_MODCODLST3, 0xff }, { STV090x_P1_MODCODLST4, 0xff }, { STV090x_P1_MODCODLST5, 0xff }, { STV090x_P1_MODCODLST6, 0xff }, { STV090x_P1_MODCODLST7, 0xcc }, { STV090x_P1_MODCODLST8, 0xcc }, { STV090x_P1_MODCODLST9, 0xcc }, { STV090x_P1_MODCODLSTA, 0xcc }, { STV090x_P1_MODCODLSTB, 0xcc }, { STV090x_P1_MODCODLSTC, 0xcc }, { STV090x_P1_MODCODLSTD, 0xcc }, { STV090x_P1_MODCODLSTE, 0xcc }, { STV090x_P1_MODCODLSTF, 0xcf }, { STV090x_GENCFG, 0x1c }, { STV090x_NBITER_NF4, 0x37 }, { STV090x_NBITER_NF5, 0x29 }, { STV090x_NBITER_NF6, 0x37 }, { STV090x_NBITER_NF7, 0x33 }, { STV090x_NBITER_NF8, 0x31 }, { STV090x_NBITER_NF9, 0x2f }, { STV090x_NBITER_NF10, 0x39 }, { STV090x_NBITER_NF11, 0x3a }, { STV090x_NBITER_NF12, 0x29 }, { STV090x_NBITER_NF13, 0x37 }, { STV090x_NBITER_NF14, 0x33 }, { STV090x_NBITER_NF15, 0x2f }, { STV090x_NBITER_NF16, 0x39 }, { STV090x_NBITER_NF17, 0x3a }, { STV090x_NBITERNOERR, 0x04 }, { STV090x_GAINLLR_NF4, 0x0C }, { STV090x_GAINLLR_NF5, 0x0F }, { STV090x_GAINLLR_NF6, 0x11 }, { STV090x_GAINLLR_NF7, 0x14 }, { STV090x_GAINLLR_NF8, 0x17 }, { STV090x_GAINLLR_NF9, 0x19 }, { STV090x_GAINLLR_NF10, 0x20 }, { STV090x_GAINLLR_NF11, 0x21 }, { STV090x_GAINLLR_NF12, 0x0D }, { STV090x_GAINLLR_NF13, 0x0F }, { STV090x_GAINLLR_NF14, 0x13 }, { STV090x_GAINLLR_NF15, 0x1A }, { STV090x_GAINLLR_NF16, 0x1F }, { STV090x_GAINLLR_NF17, 0x21 }, { STV090x_RCCFGH, 0x20 }, { STV090x_P1_FECM, 0x01 }, /*disable the DSS mode */ { STV090x_P1_PRVIT, 0x2f } /*disable puncture rate 6/7*/ }; static struct stv090x_reg stv0900_cut20_val[] = { { STV090x_P2_DMDCFG3, 0xe8 }, { STV090x_P2_DMDCFG4, 0x10 }, { STV090x_P2_CARFREQ, 0x38 }, { STV090x_P2_CARHDR, 0x20 }, { STV090x_P2_KREFTMG, 0x5a }, { STV090x_P2_SMAPCOEF7, 0x06 }, { STV090x_P2_SMAPCOEF6, 0x00 }, { STV090x_P2_SMAPCOEF5, 0x04 }, { STV090x_P2_NOSCFG, 0x0c }, { STV090x_P1_DMDCFG3, 0xe8 }, { STV090x_P1_DMDCFG4, 0x10 }, { STV090x_P1_CARFREQ, 0x38 }, { STV090x_P1_CARHDR, 0x20 }, { STV090x_P1_KREFTMG, 0x5a }, { STV090x_P1_SMAPCOEF7, 0x06 }, { STV090x_P1_SMAPCOEF6, 0x00 }, { STV090x_P1_SMAPCOEF5, 0x04 }, { STV090x_P1_NOSCFG, 0x0c }, { STV090x_GAINLLR_NF4, 0x21 }, { STV090x_GAINLLR_NF5, 0x21 }, { STV090x_GAINLLR_NF6, 0x20 }, { STV090x_GAINLLR_NF7, 0x1F }, { STV090x_GAINLLR_NF8, 0x1E }, { STV090x_GAINLLR_NF9, 0x1E }, { STV090x_GAINLLR_NF10, 0x1D }, { STV090x_GAINLLR_NF11, 0x1B }, { STV090x_GAINLLR_NF12, 0x20 }, { STV090x_GAINLLR_NF13, 0x20 }, { STV090x_GAINLLR_NF14, 0x20 }, { STV090x_GAINLLR_NF15, 0x20 }, { STV090x_GAINLLR_NF16, 0x20 }, { STV090x_GAINLLR_NF17, 0x21 }, }; static struct stv090x_reg stv0903_cut20_val[] = { { STV090x_P1_DMDCFG3, 0xe8 }, { STV090x_P1_DMDCFG4, 0x10 }, { STV090x_P1_CARFREQ, 0x38 }, { STV090x_P1_CARHDR, 0x20 }, { STV090x_P1_KREFTMG, 0x5a }, { STV090x_P1_SMAPCOEF7, 0x06 }, { STV090x_P1_SMAPCOEF6, 0x00 }, { STV090x_P1_SMAPCOEF5, 0x04 }, { STV090x_P1_NOSCFG, 0x0c }, { STV090x_GAINLLR_NF4, 0x21 }, { STV090x_GAINLLR_NF5, 0x21 }, { STV090x_GAINLLR_NF6, 0x20 }, { STV090x_GAINLLR_NF7, 0x1F }, { STV090x_GAINLLR_NF8, 0x1E }, { STV090x_GAINLLR_NF9, 0x1E }, { STV090x_GAINLLR_NF10, 0x1D }, { STV090x_GAINLLR_NF11, 0x1B }, { STV090x_GAINLLR_NF12, 0x20 }, { STV090x_GAINLLR_NF13, 0x20 }, { STV090x_GAINLLR_NF14, 0x20 }, { STV090x_GAINLLR_NF15, 0x20 }, { STV090x_GAINLLR_NF16, 0x20 }, { STV090x_GAINLLR_NF17, 0x21 } }; /* Cut 2.0 Long Frame Tracking CR loop */ static struct stv090x_long_frame_crloop stv090x_s2_crl_cut20[] = { /* MODCOD 2MPon 2MPoff 5MPon 5MPoff 10MPon 10MPoff 20MPon 20MPoff 30MPon 30MPoff */ { STV090x_QPSK_12, 0x1f, 0x3f, 0x1e, 0x3f, 0x3d, 0x1f, 0x3d, 0x3e, 0x3d, 0x1e }, { STV090x_QPSK_35, 0x2f, 0x3f, 0x2e, 0x2f, 0x3d, 0x0f, 0x0e, 0x2e, 0x3d, 0x0e }, { STV090x_QPSK_23, 0x2f, 0x3f, 0x2e, 0x2f, 0x0e, 0x0f, 0x0e, 0x1e, 0x3d, 0x3d }, { STV090x_QPSK_34, 0x3f, 0x3f, 0x3e, 0x1f, 0x0e, 0x3e, 0x0e, 0x1e, 0x3d, 0x3d }, { STV090x_QPSK_45, 0x3f, 0x3f, 0x3e, 0x1f, 0x0e, 0x3e, 0x0e, 0x1e, 0x3d, 0x3d }, { STV090x_QPSK_56, 0x3f, 0x3f, 0x3e, 0x1f, 0x0e, 0x3e, 0x0e, 0x1e, 0x3d, 0x3d }, { STV090x_QPSK_89, 0x3f, 0x3f, 0x3e, 0x1f, 0x1e, 0x3e, 0x0e, 0x1e, 0x3d, 0x3d }, { STV090x_QPSK_910, 0x3f, 0x3f, 0x3e, 0x1f, 0x1e, 0x3e, 0x0e, 0x1e, 0x3d, 0x3d }, { STV090x_8PSK_35, 0x3c, 0x3e, 0x1c, 0x2e, 0x0c, 0x1e, 0x2b, 0x2d, 0x1b, 0x1d }, { STV090x_8PSK_23, 0x1d, 0x3e, 0x3c, 0x2e, 0x2c, 0x1e, 0x0c, 0x2d, 0x2b, 0x1d }, { STV090x_8PSK_34, 0x0e, 0x3e, 0x3d, 0x2e, 0x0d, 0x1e, 0x2c, 0x2d, 0x0c, 0x1d }, { STV090x_8PSK_56, 0x2e, 0x3e, 0x1e, 0x2e, 0x2d, 0x1e, 0x3c, 0x2d, 0x2c, 0x1d }, { STV090x_8PSK_89, 0x3e, 0x3e, 0x1e, 0x2e, 0x3d, 0x1e, 0x0d, 0x2d, 0x3c, 0x1d }, { STV090x_8PSK_910, 0x3e, 0x3e, 0x1e, 0x2e, 0x3d, 0x1e, 0x1d, 0x2d, 0x0d, 0x1d } }; /* Cut 3.0 Long Frame Tracking CR loop */ static struct stv090x_long_frame_crloop stv090x_s2_crl_cut30[] = { /* MODCOD 2MPon 2MPoff 5MPon 5MPoff 10MPon 10MPoff 20MPon 20MPoff 30MPon 30MPoff */ { STV090x_QPSK_12, 0x3c, 0x2c, 0x0c, 0x2c, 0x1b, 0x2c, 0x1b, 0x1c, 0x0b, 0x3b }, { STV090x_QPSK_35, 0x0d, 0x0d, 0x0c, 0x0d, 0x1b, 0x3c, 0x1b, 0x1c, 0x0b, 0x3b }, { STV090x_QPSK_23, 0x1d, 0x0d, 0x0c, 0x1d, 0x2b, 0x3c, 0x1b, 0x1c, 0x0b, 0x3b }, { STV090x_QPSK_34, 0x1d, 0x1d, 0x0c, 0x1d, 0x2b, 0x3c, 0x1b, 0x1c, 0x0b, 0x3b }, { STV090x_QPSK_45, 0x2d, 0x1d, 0x1c, 0x1d, 0x2b, 0x3c, 0x2b, 0x0c, 0x1b, 0x3b }, { STV090x_QPSK_56, 0x2d, 0x1d, 0x1c, 0x1d, 0x2b, 0x3c, 0x2b, 0x0c, 0x1b, 0x3b }, { STV090x_QPSK_89, 0x3d, 0x2d, 0x1c, 0x1d, 0x3b, 0x3c, 0x2b, 0x0c, 0x1b, 0x3b }, { STV090x_QPSK_910, 0x3d, 0x2d, 0x1c, 0x1d, 0x3b, 0x3c, 0x2b, 0x0c, 0x1b, 0x3b }, { STV090x_8PSK_35, 0x39, 0x29, 0x39, 0x19, 0x19, 0x19, 0x19, 0x19, 0x09, 0x19 }, { STV090x_8PSK_23, 0x2a, 0x39, 0x1a, 0x0a, 0x39, 0x0a, 0x29, 0x39, 0x29, 0x0a }, { STV090x_8PSK_34, 0x2b, 0x3a, 0x1b, 0x1b, 0x3a, 0x1b, 0x1a, 0x0b, 0x1a, 0x3a }, { STV090x_8PSK_56, 0x0c, 0x1b, 0x3b, 0x3b, 0x1b, 0x3b, 0x3a, 0x3b, 0x3a, 0x1b }, { STV090x_8PSK_89, 0x0d, 0x3c, 0x2c, 0x2c, 0x2b, 0x0c, 0x0b, 0x3b, 0x0b, 0x1b }, { STV090x_8PSK_910, 0x0d, 0x0d, 0x2c, 0x3c, 0x3b, 0x1c, 0x0b, 0x3b, 0x0b, 0x1b } }; /* Cut 2.0 Long Frame Tracking CR Loop */ static struct stv090x_long_frame_crloop stv090x_s2_apsk_crl_cut20[] = { /* MODCOD 2MPon 2MPoff 5MPon 5MPoff 10MPon 10MPoff 20MPon 20MPoff 30MPon 30MPoff */ { STV090x_16APSK_23, 0x0c, 0x0c, 0x0c, 0x0c, 0x1d, 0x0c, 0x3c, 0x0c, 0x2c, 0x0c }, { STV090x_16APSK_34, 0x0c, 0x0c, 0x0c, 0x0c, 0x0e, 0x0c, 0x2d, 0x0c, 0x1d, 0x0c }, { STV090x_16APSK_45, 0x0c, 0x0c, 0x0c, 0x0c, 0x1e, 0x0c, 0x3d, 0x0c, 0x2d, 0x0c }, { STV090x_16APSK_56, 0x0c, 0x0c, 0x0c, 0x0c, 0x1e, 0x0c, 0x3d, 0x0c, 0x2d, 0x0c }, { STV090x_16APSK_89, 0x0c, 0x0c, 0x0c, 0x0c, 0x2e, 0x0c, 0x0e, 0x0c, 0x3d, 0x0c }, { STV090x_16APSK_910, 0x0c, 0x0c, 0x0c, 0x0c, 0x2e, 0x0c, 0x0e, 0x0c, 0x3d, 0x0c }, { STV090x_32APSK_34, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c }, { STV090x_32APSK_45, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c }, { STV090x_32APSK_56, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c }, { STV090x_32APSK_89, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c }, { STV090x_32APSK_910, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c } }; /* Cut 3.0 Long Frame Tracking CR Loop */ static struct stv090x_long_frame_crloop stv090x_s2_apsk_crl_cut30[] = { /* MODCOD 2MPon 2MPoff 5MPon 5MPoff 10MPon 10MPoff 20MPon 20MPoff 30MPon 30MPoff */ { STV090x_16APSK_23, 0x0a, 0x0a, 0x0a, 0x0a, 0x1a, 0x0a, 0x3a, 0x0a, 0x2a, 0x0a }, { STV090x_16APSK_34, 0x0a, 0x0a, 0x0a, 0x0a, 0x0b, 0x0a, 0x3b, 0x0a, 0x1b, 0x0a }, { STV090x_16APSK_45, 0x0a, 0x0a, 0x0a, 0x0a, 0x1b, 0x0a, 0x3b, 0x0a, 0x2b, 0x0a }, { STV090x_16APSK_56, 0x0a, 0x0a, 0x0a, 0x0a, 0x1b, 0x0a, 0x3b, 0x0a, 0x2b, 0x0a }, { STV090x_16APSK_89, 0x0a, 0x0a, 0x0a, 0x0a, 0x2b, 0x0a, 0x0c, 0x0a, 0x3b, 0x0a }, { STV090x_16APSK_910, 0x0a, 0x0a, 0x0a, 0x0a, 0x2b, 0x0a, 0x0c, 0x0a, 0x3b, 0x0a }, { STV090x_32APSK_34, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a }, { STV090x_32APSK_45, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a }, { STV090x_32APSK_56, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a }, { STV090x_32APSK_89, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a }, { STV090x_32APSK_910, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a } }; static struct stv090x_long_frame_crloop stv090x_s2_lowqpsk_crl_cut20[] = { /* MODCOD 2MPon 2MPoff 5MPon 5MPoff 10MPon 10MPoff 20MPon 20MPoff 30MPon 30MPoff */ { STV090x_QPSK_14, 0x0f, 0x3f, 0x0e, 0x3f, 0x2d, 0x2f, 0x2d, 0x1f, 0x3d, 0x3e }, { STV090x_QPSK_13, 0x0f, 0x3f, 0x0e, 0x3f, 0x2d, 0x2f, 0x3d, 0x0f, 0x3d, 0x2e }, { STV090x_QPSK_25, 0x1f, 0x3f, 0x1e, 0x3f, 0x3d, 0x1f, 0x3d, 0x3e, 0x3d, 0x2e } }; static struct stv090x_long_frame_crloop stv090x_s2_lowqpsk_crl_cut30[] = { /* MODCOD 2MPon 2MPoff 5MPon 5MPoff 10MPon 10MPoff 20MPon 20MPoff 30MPon 30MPoff */ { STV090x_QPSK_14, 0x0c, 0x3c, 0x0b, 0x3c, 0x2a, 0x2c, 0x2a, 0x1c, 0x3a, 0x3b }, { STV090x_QPSK_13, 0x0c, 0x3c, 0x0b, 0x3c, 0x2a, 0x2c, 0x3a, 0x0c, 0x3a, 0x2b }, { STV090x_QPSK_25, 0x1c, 0x3c, 0x1b, 0x3c, 0x3a, 0x1c, 0x3a, 0x3b, 0x3a, 0x2b } }; /* Cut 2.0 Short Frame Tracking CR Loop */ static struct stv090x_short_frame_crloop stv090x_s2_short_crl_cut20[] = { /* MODCOD 2M 5M 10M 20M 30M */ { STV090x_QPSK, 0x2f, 0x2e, 0x0e, 0x0e, 0x3d }, { STV090x_8PSK, 0x3e, 0x0e, 0x2d, 0x0d, 0x3c }, { STV090x_16APSK, 0x1e, 0x1e, 0x1e, 0x3d, 0x2d }, { STV090x_32APSK, 0x1e, 0x1e, 0x1e, 0x3d, 0x2d } }; /* Cut 3.0 Short Frame Tracking CR Loop */ static struct stv090x_short_frame_crloop stv090x_s2_short_crl_cut30[] = { /* MODCOD 2M 5M 10M 20M 30M */ { STV090x_QPSK, 0x2C, 0x2B, 0x0B, 0x0B, 0x3A }, { STV090x_8PSK, 0x3B, 0x0B, 0x2A, 0x0A, 0x39 }, { STV090x_16APSK, 0x1B, 0x1B, 0x1B, 0x3A, 0x2A }, { STV090x_32APSK, 0x1B, 0x1B, 0x1B, 0x3A, 0x2A } }; static inline s32 comp2(s32 __x, s32 __width) { if (__width == 32) return __x; else return (__x >= (1 << (__width - 1))) ? (__x - (1 << __width)) : __x; } static int stv090x_read_reg(struct stv090x_state *state, unsigned int reg) { const struct stv090x_config *config = state->config; int ret; u8 b0[] = { reg >> 8, reg & 0xff }; u8 buf; struct i2c_msg msg[] = { { .addr = config->address, .flags = 0, .buf = b0, .len = 2 }, { .addr = config->address, .flags = I2C_M_RD, .buf = &buf, .len = 1 } }; ret = i2c_transfer(state->i2c, msg, 2); if (ret != 2) { if (ret != -ERESTARTSYS) dprintk(FE_ERROR, 1, "Read error, Reg=[0x%02x], Status=%d", reg, ret); return ret < 0 ? ret : -EREMOTEIO; } if (unlikely(*state->verbose >= FE_DEBUGREG)) dprintk(FE_ERROR, 1, "Reg=[0x%02x], data=%02x", reg, buf); return (unsigned int) buf; } static int stv090x_write_regs(struct stv090x_state *state, unsigned int reg, u8 *data, u32 count) { const struct stv090x_config *config = state->config; int ret; u8 buf[MAX_XFER_SIZE]; struct i2c_msg i2c_msg = { .addr = config->address, .flags = 0, .buf = buf, .len = 2 + count }; if (2 + count > sizeof(buf)) { printk(KERN_WARNING "%s: i2c wr reg=%04x: len=%d is too big!\n", KBUILD_MODNAME, reg, count); return -EINVAL; } buf[0] = reg >> 8; buf[1] = reg & 0xff; memcpy(&buf[2], data, count); dprintk(FE_DEBUGREG, 1, "%s [0x%04x]: %*ph", __func__, reg, count, data); ret = i2c_transfer(state->i2c, &i2c_msg, 1); if (ret != 1) { if (ret != -ERESTARTSYS) dprintk(FE_ERROR, 1, "Reg=[0x%04x], Data=[0x%02x ...], Count=%u, Status=%d", reg, data[0], count, ret); return ret < 0 ? ret : -EREMOTEIO; } return 0; } static int stv090x_write_reg(struct stv090x_state *state, unsigned int reg, u8 data) { return stv090x_write_regs(state, reg, &data, 1); } static int stv090x_i2c_gate_ctrl(struct stv090x_state *state, int enable) { u32 reg; /* * NOTE! A lock is used as a FSM to control the state in which * access is serialized between two tuners on the same demod. * This has nothing to do with a lock to protect a critical section * which may in some other cases be confused with protecting I/O * access to the demodulator gate. * In case of any error, the lock is unlocked and exit within the * relevant operations themselves. */ if (enable) { if (state->config->tuner_i2c_lock) state->config->tuner_i2c_lock(&state->frontend, 1); else mutex_lock(&state->internal->tuner_lock); } reg = STV090x_READ_DEMOD(state, I2CRPT); if (enable) { dprintk(FE_DEBUG, 1, "Enable Gate"); STV090x_SETFIELD_Px(reg, I2CT_ON_FIELD, 1); if (STV090x_WRITE_DEMOD(state, I2CRPT, reg) < 0) goto err; } else { dprintk(FE_DEBUG, 1, "Disable Gate"); STV090x_SETFIELD_Px(reg, I2CT_ON_FIELD, 0); if ((STV090x_WRITE_DEMOD(state, I2CRPT, reg)) < 0) goto err; } if (!enable) { if (state->config->tuner_i2c_lock) state->config->tuner_i2c_lock(&state->frontend, 0); else mutex_unlock(&state->internal->tuner_lock); } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); if (state->config->tuner_i2c_lock) state->config->tuner_i2c_lock(&state->frontend, 0); else mutex_unlock(&state->internal->tuner_lock); return -1; } static void stv090x_get_lock_tmg(struct stv090x_state *state) { switch (state->algo) { case STV090x_BLIND_SEARCH: dprintk(FE_DEBUG, 1, "Blind Search"); if (state->srate <= 1500000) { /*10Msps< SR <=15Msps*/ state->DemodTimeout = 1500; state->FecTimeout = 400; } else if (state->srate <= 5000000) { /*10Msps< SR <=15Msps*/ state->DemodTimeout = 1000; state->FecTimeout = 300; } else { /*SR >20Msps*/ state->DemodTimeout = 700; state->FecTimeout = 100; } break; case STV090x_COLD_SEARCH: case STV090x_WARM_SEARCH: default: dprintk(FE_DEBUG, 1, "Normal Search"); if (state->srate <= 1000000) { /*SR <=1Msps*/ state->DemodTimeout = 4500; state->FecTimeout = 1700; } else if (state->srate <= 2000000) { /*1Msps < SR <= 2Msps */ state->DemodTimeout = 2500; state->FecTimeout = 1100; } else if (state->srate <= 5000000) { /*2Msps < SR <= 5Msps */ state->DemodTimeout = 1000; state->FecTimeout = 550; } else if (state->srate <= 10000000) { /*5Msps < SR <= 10Msps */ state->DemodTimeout = 700; state->FecTimeout = 250; } else if (state->srate <= 20000000) { /*10Msps < SR <= 20Msps */ state->DemodTimeout = 400; state->FecTimeout = 130; } else { /*SR >20Msps*/ state->DemodTimeout = 300; state->FecTimeout = 100; } break; } if (state->algo == STV090x_WARM_SEARCH) state->DemodTimeout /= 2; } static int stv090x_set_srate(struct stv090x_state *state, u32 srate) { u32 sym; if (srate > 60000000) { sym = (srate << 4); /* SR * 2^16 / master_clk */ sym /= (state->internal->mclk >> 12); } else if (srate > 6000000) { sym = (srate << 6); sym /= (state->internal->mclk >> 10); } else { sym = (srate << 9); sym /= (state->internal->mclk >> 7); } if (STV090x_WRITE_DEMOD(state, SFRINIT1, (sym >> 8) & 0x7f) < 0) /* MSB */ goto err; if (STV090x_WRITE_DEMOD(state, SFRINIT0, (sym & 0xff)) < 0) /* LSB */ goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_set_max_srate(struct stv090x_state *state, u32 clk, u32 srate) { u32 sym; srate = 105 * (srate / 100); if (srate > 60000000) { sym = (srate << 4); /* SR * 2^16 / master_clk */ sym /= (state->internal->mclk >> 12); } else if (srate > 6000000) { sym = (srate << 6); sym /= (state->internal->mclk >> 10); } else { sym = (srate << 9); sym /= (state->internal->mclk >> 7); } if (sym < 0x7fff) { if (STV090x_WRITE_DEMOD(state, SFRUP1, (sym >> 8) & 0x7f) < 0) /* MSB */ goto err; if (STV090x_WRITE_DEMOD(state, SFRUP0, sym & 0xff) < 0) /* LSB */ goto err; } else { if (STV090x_WRITE_DEMOD(state, SFRUP1, 0x7f) < 0) /* MSB */ goto err; if (STV090x_WRITE_DEMOD(state, SFRUP0, 0xff) < 0) /* LSB */ goto err; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_set_min_srate(struct stv090x_state *state, u32 clk, u32 srate) { u32 sym; srate = 95 * (srate / 100); if (srate > 60000000) { sym = (srate << 4); /* SR * 2^16 / master_clk */ sym /= (state->internal->mclk >> 12); } else if (srate > 6000000) { sym = (srate << 6); sym /= (state->internal->mclk >> 10); } else { sym = (srate << 9); sym /= (state->internal->mclk >> 7); } if (STV090x_WRITE_DEMOD(state, SFRLOW1, ((sym >> 8) & 0x7f)) < 0) /* MSB */ goto err; if (STV090x_WRITE_DEMOD(state, SFRLOW0, (sym & 0xff)) < 0) /* LSB */ goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static u32 stv090x_car_width(u32 srate, enum stv090x_rolloff rolloff) { u32 ro; switch (rolloff) { case STV090x_RO_20: ro = 20; break; case STV090x_RO_25: ro = 25; break; case STV090x_RO_35: default: ro = 35; break; } return srate + (srate * ro) / 100; } static int stv090x_set_vit_thacq(struct stv090x_state *state) { if (STV090x_WRITE_DEMOD(state, VTH12, 0x96) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH23, 0x64) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH34, 0x36) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH56, 0x23) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH67, 0x1e) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH78, 0x19) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_set_vit_thtracq(struct stv090x_state *state) { if (STV090x_WRITE_DEMOD(state, VTH12, 0xd0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH23, 0x7d) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH34, 0x53) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH56, 0x2f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH67, 0x24) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VTH78, 0x1f) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_set_viterbi(struct stv090x_state *state) { switch (state->search_mode) { case STV090x_SEARCH_AUTO: if (STV090x_WRITE_DEMOD(state, FECM, 0x10) < 0) /* DVB-S and DVB-S2 */ goto err; if (STV090x_WRITE_DEMOD(state, PRVIT, 0x3f) < 0) /* all puncture rate */ goto err; break; case STV090x_SEARCH_DVBS1: if (STV090x_WRITE_DEMOD(state, FECM, 0x00) < 0) /* disable DSS */ goto err; switch (state->fec) { case STV090x_PR12: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x01) < 0) goto err; break; case STV090x_PR23: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x02) < 0) goto err; break; case STV090x_PR34: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x04) < 0) goto err; break; case STV090x_PR56: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x08) < 0) goto err; break; case STV090x_PR78: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x20) < 0) goto err; break; default: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x2f) < 0) /* all */ goto err; break; } break; case STV090x_SEARCH_DSS: if (STV090x_WRITE_DEMOD(state, FECM, 0x80) < 0) goto err; switch (state->fec) { case STV090x_PR12: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x01) < 0) goto err; break; case STV090x_PR23: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x02) < 0) goto err; break; case STV090x_PR67: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x10) < 0) goto err; break; default: if (STV090x_WRITE_DEMOD(state, PRVIT, 0x13) < 0) /* 1/2, 2/3, 6/7 */ goto err; break; } break; default: break; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_stop_modcod(struct stv090x_state *state) { if (STV090x_WRITE_DEMOD(state, MODCODLST0, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST1, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST2, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST3, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST4, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST5, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST6, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST7, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST8, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST9, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTA, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTB, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTC, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTD, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTE, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTF, 0xff) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_activate_modcod(struct stv090x_state *state) { if (STV090x_WRITE_DEMOD(state, MODCODLST0, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST1, 0xfc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST2, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST3, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST4, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST5, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST6, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST7, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST8, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST9, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTA, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTB, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTC, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTD, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTE, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTF, 0xcf) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_activate_modcod_single(struct stv090x_state *state) { if (STV090x_WRITE_DEMOD(state, MODCODLST0, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST1, 0xf0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST2, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST3, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST4, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST5, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST6, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST7, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST8, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST9, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTA, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTB, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTC, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTD, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTE, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTF, 0x0f) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_vitclk_ctl(struct stv090x_state *state, int enable) { u32 reg; switch (state->demod) { case STV090x_DEMODULATOR_0: mutex_lock(&state->internal->demod_lock); reg = stv090x_read_reg(state, STV090x_STOPCLK2); STV090x_SETFIELD(reg, STOP_CLKVIT1_FIELD, enable); if (stv090x_write_reg(state, STV090x_STOPCLK2, reg) < 0) goto err; mutex_unlock(&state->internal->demod_lock); break; case STV090x_DEMODULATOR_1: mutex_lock(&state->internal->demod_lock); reg = stv090x_read_reg(state, STV090x_STOPCLK2); STV090x_SETFIELD(reg, STOP_CLKVIT2_FIELD, enable); if (stv090x_write_reg(state, STV090x_STOPCLK2, reg) < 0) goto err; mutex_unlock(&state->internal->demod_lock); break; default: dprintk(FE_ERROR, 1, "Wrong demodulator!"); break; } return 0; err: mutex_unlock(&state->internal->demod_lock); dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_dvbs_track_crl(struct stv090x_state *state) { if (state->internal->dev_ver >= 0x30) { /* Set ACLC BCLC optimised value vs SR */ if (state->srate >= 15000000) { if (STV090x_WRITE_DEMOD(state, ACLC, 0x2b) < 0) goto err; if (STV090x_WRITE_DEMOD(state, BCLC, 0x1a) < 0) goto err; } else if ((state->srate >= 7000000) && (15000000 > state->srate)) { if (STV090x_WRITE_DEMOD(state, ACLC, 0x0c) < 0) goto err; if (STV090x_WRITE_DEMOD(state, BCLC, 0x1b) < 0) goto err; } else if (state->srate < 7000000) { if (STV090x_WRITE_DEMOD(state, ACLC, 0x2c) < 0) goto err; if (STV090x_WRITE_DEMOD(state, BCLC, 0x1c) < 0) goto err; } } else { /* Cut 2.0 */ if (STV090x_WRITE_DEMOD(state, ACLC, 0x1a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, BCLC, 0x09) < 0) goto err; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_delivery_search(struct stv090x_state *state) { u32 reg; switch (state->search_mode) { case STV090x_SEARCH_DVBS1: case STV090x_SEARCH_DSS: reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, DVBS1_ENABLE_FIELD, 1); STV090x_SETFIELD_Px(reg, DVBS2_ENABLE_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; /* Activate Viterbi decoder in legacy search, * do not use FRESVIT1, might impact VITERBI2 */ if (stv090x_vitclk_ctl(state, 0) < 0) goto err; if (stv090x_dvbs_track_crl(state) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CAR2CFG, 0x22) < 0) /* disable DVB-S2 */ goto err; if (stv090x_set_vit_thacq(state) < 0) goto err; if (stv090x_set_viterbi(state) < 0) goto err; break; case STV090x_SEARCH_DVBS2: reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, DVBS1_ENABLE_FIELD, 0); STV090x_SETFIELD_Px(reg, DVBS2_ENABLE_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, DVBS1_ENABLE_FIELD, 1); STV090x_SETFIELD_Px(reg, DVBS2_ENABLE_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; if (stv090x_vitclk_ctl(state, 1) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ACLC, 0x1a) < 0) /* stop DVB-S CR loop */ goto err; if (STV090x_WRITE_DEMOD(state, BCLC, 0x09) < 0) goto err; if (state->internal->dev_ver <= 0x20) { /* enable S2 carrier loop */ if (STV090x_WRITE_DEMOD(state, CAR2CFG, 0x26) < 0) goto err; } else { /* > Cut 3: Stop carrier 3 */ if (STV090x_WRITE_DEMOD(state, CAR2CFG, 0x66) < 0) goto err; } if (state->demod_mode != STV090x_SINGLE) { /* Cut 2: enable link during search */ if (stv090x_activate_modcod(state) < 0) goto err; } else { /* Single demodulator * Authorize SHORT and LONG frames, * QPSK, 8PSK, 16APSK and 32APSK */ if (stv090x_activate_modcod_single(state) < 0) goto err; } if (stv090x_set_vit_thtracq(state) < 0) goto err; break; case STV090x_SEARCH_AUTO: default: /* enable DVB-S2 and DVB-S2 in Auto MODE */ reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, DVBS1_ENABLE_FIELD, 0); STV090x_SETFIELD_Px(reg, DVBS2_ENABLE_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, DVBS1_ENABLE_FIELD, 1); STV090x_SETFIELD_Px(reg, DVBS2_ENABLE_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; if (stv090x_vitclk_ctl(state, 0) < 0) goto err; if (stv090x_dvbs_track_crl(state) < 0) goto err; if (state->internal->dev_ver <= 0x20) { /* enable S2 carrier loop */ if (STV090x_WRITE_DEMOD(state, CAR2CFG, 0x26) < 0) goto err; } else { /* > Cut 3: Stop carrier 3 */ if (STV090x_WRITE_DEMOD(state, CAR2CFG, 0x66) < 0) goto err; } if (state->demod_mode != STV090x_SINGLE) { /* Cut 2: enable link during search */ if (stv090x_activate_modcod(state) < 0) goto err; } else { /* Single demodulator * Authorize SHORT and LONG frames, * QPSK, 8PSK, 16APSK and 32APSK */ if (stv090x_activate_modcod_single(state) < 0) goto err; } if (stv090x_set_vit_thacq(state) < 0) goto err; if (stv090x_set_viterbi(state) < 0) goto err; break; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_start_search(struct stv090x_state *state) { u32 reg, freq_abs; s16 freq; /* Reset demodulator */ reg = STV090x_READ_DEMOD(state, DMDISTATE); STV090x_SETFIELD_Px(reg, I2C_DEMOD_MODE_FIELD, 0x1f); if (STV090x_WRITE_DEMOD(state, DMDISTATE, reg) < 0) goto err; if (state->internal->dev_ver <= 0x20) { if (state->srate <= 5000000) { if (STV090x_WRITE_DEMOD(state, CARCFG, 0x44) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRUP1, 0x0f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRUP0, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRLOW1, 0xf0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRLOW0, 0x00) < 0) goto err; /*enlarge the timing bandwidth for Low SR*/ if (STV090x_WRITE_DEMOD(state, RTCS2, 0x68) < 0) goto err; } else { /* If the symbol rate is >5 Msps Set The carrier search up and low to auto mode */ if (STV090x_WRITE_DEMOD(state, CARCFG, 0xc4) < 0) goto err; /*reduce the timing bandwidth for high SR*/ if (STV090x_WRITE_DEMOD(state, RTCS2, 0x44) < 0) goto err; } } else { /* >= Cut 3 */ if (state->srate <= 5000000) { /* enlarge the timing bandwidth for Low SR */ STV090x_WRITE_DEMOD(state, RTCS2, 0x68); } else { /* reduce timing bandwidth for high SR */ STV090x_WRITE_DEMOD(state, RTCS2, 0x44); } /* Set CFR min and max to manual mode */ STV090x_WRITE_DEMOD(state, CARCFG, 0x46); if (state->algo == STV090x_WARM_SEARCH) { /* WARM Start * CFR min = -1MHz, * CFR max = +1MHz */ freq_abs = 1000 << 16; freq_abs /= (state->internal->mclk / 1000); freq = (s16) freq_abs; } else { /* COLD Start * CFR min =- (SearchRange / 2 + 600KHz) * CFR max = +(SearchRange / 2 + 600KHz) * (600KHz for the tuner step size) */ freq_abs = (state->search_range / 2000) + 600; freq_abs = freq_abs << 16; freq_abs /= (state->internal->mclk / 1000); freq = (s16) freq_abs; } if (STV090x_WRITE_DEMOD(state, CFRUP1, MSB(freq)) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRUP0, LSB(freq)) < 0) goto err; freq *= -1; if (STV090x_WRITE_DEMOD(state, CFRLOW1, MSB(freq)) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRLOW0, LSB(freq)) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, CFRINIT1, 0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, 0) < 0) goto err; if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, EQUALCFG, 0x41) < 0) goto err; if (STV090x_WRITE_DEMOD(state, FFECFG, 0x41) < 0) goto err; if ((state->search_mode == STV090x_SEARCH_DVBS1) || (state->search_mode == STV090x_SEARCH_DSS) || (state->search_mode == STV090x_SEARCH_AUTO)) { if (STV090x_WRITE_DEMOD(state, VITSCALE, 0x82) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VAVSRVIT, 0x00) < 0) goto err; } } if (STV090x_WRITE_DEMOD(state, SFRSTEP, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHRISE, 0xe0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHFALL, 0xc0) < 0) goto err; reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, SCAN_ENABLE_FIELD, 0); STV090x_SETFIELD_Px(reg, CFR_AUTOSCAN_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; reg = STV090x_READ_DEMOD(state, DMDCFG2); STV090x_SETFIELD_Px(reg, S1S2_SEQUENTIAL_FIELD, 0x0); if (STV090x_WRITE_DEMOD(state, DMDCFG2, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, RTC, 0x88) < 0) goto err; if (state->internal->dev_ver >= 0x20) { /*Frequency offset detector setting*/ if (state->srate < 2000000) { if (state->internal->dev_ver <= 0x20) { /* Cut 2 */ if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x39) < 0) goto err; } else { /* Cut 3 */ if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x89) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, CARHDR, 0x40) < 0) goto err; } else if (state->srate < 10000000) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x4c) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CARHDR, 0x20) < 0) goto err; } else { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x4b) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CARHDR, 0x20) < 0) goto err; } } else { if (state->srate < 10000000) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0xef) < 0) goto err; } else { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0xed) < 0) goto err; } } switch (state->algo) { case STV090x_WARM_SEARCH: /* The symbol rate and the exact * carrier Frequency are known */ if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x18) < 0) goto err; break; case STV090x_COLD_SEARCH: /* The symbol rate is known */ if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x15) < 0) goto err; break; default: break; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_get_agc2_min_level(struct stv090x_state *state) { u32 agc2_min = 0xffff, agc2 = 0, freq_init, freq_step, reg; s32 i, j, steps, dir; if (STV090x_WRITE_DEMOD(state, AGC2REF, 0x38) < 0) goto err; reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, SCAN_ENABLE_FIELD, 0); STV090x_SETFIELD_Px(reg, CFR_AUTOSCAN_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRUP1, 0x83) < 0) /* SR = 65 Msps Max */ goto err; if (STV090x_WRITE_DEMOD(state, SFRUP0, 0xc0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRLOW1, 0x82) < 0) /* SR= 400 ksps Min */ goto err; if (STV090x_WRITE_DEMOD(state, SFRLOW0, 0xa0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDTOM, 0x00) < 0) /* stop acq @ coarse carrier state */ goto err; if (stv090x_set_srate(state, 1000000) < 0) goto err; steps = state->search_range / 1000000; if (steps <= 0) steps = 1; dir = 1; freq_step = (1000000 * 256) / (state->internal->mclk / 256); freq_init = 0; for (i = 0; i < steps; i++) { if (dir > 0) freq_init = freq_init + (freq_step * i); else freq_init = freq_init - (freq_step * i); dir *= -1; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x5c) < 0) /* Demod RESET */ goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT1, (freq_init >> 8) & 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, freq_init & 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x58) < 0) /* Demod RESET */ goto err; msleep(10); agc2 = 0; for (j = 0; j < 10; j++) { agc2 += (STV090x_READ_DEMOD(state, AGC2I1) << 8) | STV090x_READ_DEMOD(state, AGC2I0); } agc2 /= 10; if (agc2 < agc2_min) agc2_min = agc2; } return agc2_min; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static u32 stv090x_get_srate(struct stv090x_state *state, u32 clk) { u8 r3, r2, r1, r0; s32 srate, int_1, int_2, tmp_1, tmp_2; r3 = STV090x_READ_DEMOD(state, SFR3); r2 = STV090x_READ_DEMOD(state, SFR2); r1 = STV090x_READ_DEMOD(state, SFR1); r0 = STV090x_READ_DEMOD(state, SFR0); srate = ((r3 << 24) | (r2 << 16) | (r1 << 8) | r0); int_1 = clk >> 16; int_2 = srate >> 16; tmp_1 = clk % 0x10000; tmp_2 = srate % 0x10000; srate = (int_1 * int_2) + ((int_1 * tmp_2) >> 16) + ((int_2 * tmp_1) >> 16); return srate; } static u32 stv090x_srate_srch_coarse(struct stv090x_state *state) { struct dvb_frontend *fe = &state->frontend; int tmg_lock = 0, i; s32 tmg_cpt = 0, dir = 1, steps, cur_step = 0, freq; u32 srate_coarse = 0, agc2 = 0, car_step = 1200, reg; u32 agc2th; if (state->internal->dev_ver >= 0x30) agc2th = 0x2e00; else agc2th = 0x1f00; reg = STV090x_READ_DEMOD(state, DMDISTATE); STV090x_SETFIELD_Px(reg, I2C_DEMOD_MODE_FIELD, 0x1f); /* Demod RESET */ if (STV090x_WRITE_DEMOD(state, DMDISTATE, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGCFG, 0x12) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGCFG2, 0xc0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHRISE, 0xf0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHFALL, 0xe0) < 0) goto err; reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, SCAN_ENABLE_FIELD, 1); STV090x_SETFIELD_Px(reg, CFR_AUTOSCAN_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRUP1, 0x83) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRUP0, 0xc0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRLOW1, 0x82) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRLOW0, 0xa0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDTOM, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, AGC2REF, 0x50) < 0) goto err; if (state->internal->dev_ver >= 0x30) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x99) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRSTEP, 0x98) < 0) goto err; } else if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x6a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRSTEP, 0x95) < 0) goto err; } if (state->srate <= 2000000) car_step = 1000; else if (state->srate <= 5000000) car_step = 2000; else if (state->srate <= 12000000) car_step = 3000; else car_step = 5000; steps = -1 + ((state->search_range / 1000) / car_step); steps /= 2; steps = (2 * steps) + 1; if (steps < 0) steps = 1; else if (steps > 10) { steps = 11; car_step = (state->search_range / 1000) / 10; } cur_step = 0; dir = 1; freq = state->frequency; while ((!tmg_lock) && (cur_step < steps)) { if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x5f) < 0) /* Demod RESET */ goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT1, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRINIT1, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRINIT0, 0x00) < 0) goto err; /* trigger acquisition */ if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x40) < 0) goto err; msleep(50); for (i = 0; i < 10; i++) { reg = STV090x_READ_DEMOD(state, DSTATUS); if (STV090x_GETFIELD_Px(reg, TMGLOCK_QUALITY_FIELD) >= 2) tmg_cpt++; agc2 += (STV090x_READ_DEMOD(state, AGC2I1) << 8) | STV090x_READ_DEMOD(state, AGC2I0); } agc2 /= 10; srate_coarse = stv090x_get_srate(state, state->internal->mclk); cur_step++; dir *= -1; if ((tmg_cpt >= 5) && (agc2 < agc2th) && (srate_coarse < 50000000) && (srate_coarse > 850000)) tmg_lock = 1; else if (cur_step < steps) { if (dir > 0) freq += cur_step * car_step; else freq -= cur_step * car_step; /* Setup tuner */ if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_set_frequency) { if (state->config->tuner_set_frequency(fe, freq) < 0) goto err_gateoff; } if (state->config->tuner_set_bandwidth) { if (state->config->tuner_set_bandwidth(fe, state->tuner_bw) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; msleep(50); if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_get_status) { if (state->config->tuner_get_status(fe, &reg) < 0) goto err_gateoff; } if (reg) dprintk(FE_DEBUG, 1, "Tuner phase locked"); else dprintk(FE_DEBUG, 1, "Tuner unlocked"); if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; } } if (!tmg_lock) srate_coarse = 0; else srate_coarse = stv090x_get_srate(state, state->internal->mclk); return srate_coarse; err_gateoff: stv090x_i2c_gate_ctrl(state, 0); err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static u32 stv090x_srate_srch_fine(struct stv090x_state *state) { u32 srate_coarse, freq_coarse, sym, reg; srate_coarse = stv090x_get_srate(state, state->internal->mclk); freq_coarse = STV090x_READ_DEMOD(state, CFR2) << 8; freq_coarse |= STV090x_READ_DEMOD(state, CFR1); sym = 13 * (srate_coarse / 10); /* SFRUP = SFR + 30% */ if (sym < state->srate) srate_coarse = 0; else { if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1f) < 0) /* Demod RESET */ goto err; if (STV090x_WRITE_DEMOD(state, TMGCFG2, 0xc1) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHRISE, 0x20) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHFALL, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGCFG, 0xd2) < 0) goto err; reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, CFR_AUTOSCAN_FIELD, 0x00); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, AGC2REF, 0x38) < 0) goto err; if (state->internal->dev_ver >= 0x30) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x79) < 0) goto err; } else if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x49) < 0) goto err; } if (srate_coarse > 3000000) { sym = 13 * (srate_coarse / 10); /* SFRUP = SFR + 30% */ sym = (sym / 1000) * 65536; sym /= (state->internal->mclk / 1000); if (STV090x_WRITE_DEMOD(state, SFRUP1, (sym >> 8) & 0x7f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRUP0, sym & 0xff) < 0) goto err; sym = 10 * (srate_coarse / 13); /* SFRLOW = SFR - 30% */ sym = (sym / 1000) * 65536; sym /= (state->internal->mclk / 1000); if (STV090x_WRITE_DEMOD(state, SFRLOW1, (sym >> 8) & 0x7f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRLOW0, sym & 0xff) < 0) goto err; sym = (srate_coarse / 1000) * 65536; sym /= (state->internal->mclk / 1000); if (STV090x_WRITE_DEMOD(state, SFRINIT1, (sym >> 8) & 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRINIT0, sym & 0xff) < 0) goto err; } else { sym = 13 * (srate_coarse / 10); /* SFRUP = SFR + 30% */ sym = (sym / 100) * 65536; sym /= (state->internal->mclk / 100); if (STV090x_WRITE_DEMOD(state, SFRUP1, (sym >> 8) & 0x7f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRUP0, sym & 0xff) < 0) goto err; sym = 10 * (srate_coarse / 14); /* SFRLOW = SFR - 30% */ sym = (sym / 100) * 65536; sym /= (state->internal->mclk / 100); if (STV090x_WRITE_DEMOD(state, SFRLOW1, (sym >> 8) & 0x7f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRLOW0, sym & 0xff) < 0) goto err; sym = (srate_coarse / 100) * 65536; sym /= (state->internal->mclk / 100); if (STV090x_WRITE_DEMOD(state, SFRINIT1, (sym >> 8) & 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, SFRINIT0, sym & 0xff) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, DMDTOM, 0x20) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT1, (freq_coarse >> 8) & 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, freq_coarse & 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x15) < 0) /* trigger acquisition */ goto err; } return srate_coarse; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_get_dmdlock(struct stv090x_state *state, s32 timeout) { s32 timer = 0, lock = 0; u32 reg; u8 stat; while ((timer < timeout) && (!lock)) { reg = STV090x_READ_DEMOD(state, DMDSTATE); stat = STV090x_GETFIELD_Px(reg, HEADER_MODE_FIELD); switch (stat) { case 0: /* searching */ case 1: /* first PLH detected */ default: dprintk(FE_DEBUG, 1, "Demodulator searching .."); lock = 0; break; case 2: /* DVB-S2 mode */ case 3: /* DVB-S1/legacy mode */ reg = STV090x_READ_DEMOD(state, DSTATUS); lock = STV090x_GETFIELD_Px(reg, LOCK_DEFINITIF_FIELD); break; } if (!lock) msleep(10); else dprintk(FE_DEBUG, 1, "Demodulator acquired LOCK"); timer += 10; } return lock; } static int stv090x_blind_search(struct stv090x_state *state) { u32 agc2, reg, srate_coarse; s32 cpt_fail, agc2_ovflw, i; u8 k_ref, k_max, k_min; int coarse_fail = 0; int lock; k_max = 110; k_min = 10; agc2 = stv090x_get_agc2_min_level(state); if (agc2 > STV090x_SEARCH_AGC2_TH(state->internal->dev_ver)) { lock = 0; } else { if (state->internal->dev_ver <= 0x20) { if (STV090x_WRITE_DEMOD(state, CARCFG, 0xc4) < 0) goto err; } else { /* > Cut 3 */ if (STV090x_WRITE_DEMOD(state, CARCFG, 0x06) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, RTCS2, 0x44) < 0) goto err; if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, EQUALCFG, 0x41) < 0) goto err; if (STV090x_WRITE_DEMOD(state, FFECFG, 0x41) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VITSCALE, 0x82) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VAVSRVIT, 0x00) < 0) /* set viterbi hysteresis */ goto err; } k_ref = k_max; do { if (STV090x_WRITE_DEMOD(state, KREFTMG, k_ref) < 0) goto err; if (stv090x_srate_srch_coarse(state) != 0) { srate_coarse = stv090x_srate_srch_fine(state); if (srate_coarse != 0) { stv090x_get_lock_tmg(state); lock = stv090x_get_dmdlock(state, state->DemodTimeout); } else { lock = 0; } } else { cpt_fail = 0; agc2_ovflw = 0; for (i = 0; i < 10; i++) { agc2 += (STV090x_READ_DEMOD(state, AGC2I1) << 8) | STV090x_READ_DEMOD(state, AGC2I0); if (agc2 >= 0xff00) agc2_ovflw++; reg = STV090x_READ_DEMOD(state, DSTATUS2); if ((STV090x_GETFIELD_Px(reg, CFR_OVERFLOW_FIELD) == 0x01) && (STV090x_GETFIELD_Px(reg, DEMOD_DELOCK_FIELD) == 0x01)) cpt_fail++; } if ((cpt_fail > 7) || (agc2_ovflw > 7)) coarse_fail = 1; lock = 0; } k_ref -= 20; } while ((k_ref >= k_min) && (!lock) && (!coarse_fail)); } return lock; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_chk_tmg(struct stv090x_state *state) { u32 reg; s32 tmg_cpt = 0, i; u8 freq, tmg_thh, tmg_thl; int tmg_lock = 0; freq = STV090x_READ_DEMOD(state, CARFREQ); tmg_thh = STV090x_READ_DEMOD(state, TMGTHRISE); tmg_thl = STV090x_READ_DEMOD(state, TMGTHFALL); if (STV090x_WRITE_DEMOD(state, TMGTHRISE, 0x20) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHFALL, 0x00) < 0) goto err; reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, CFR_AUTOSCAN_FIELD, 0x00); /* stop carrier offset search */ if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, RTC, 0x80) < 0) goto err; if (STV090x_WRITE_DEMOD(state, RTCS2, 0x40) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT1, 0x00) < 0) /* set car ofset to 0 */ goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, AGC2REF, 0x65) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x18) < 0) /* trigger acquisition */ goto err; msleep(10); for (i = 0; i < 10; i++) { reg = STV090x_READ_DEMOD(state, DSTATUS); if (STV090x_GETFIELD_Px(reg, TMGLOCK_QUALITY_FIELD) >= 2) tmg_cpt++; msleep(1); } if (tmg_cpt >= 3) tmg_lock = 1; if (STV090x_WRITE_DEMOD(state, AGC2REF, 0x38) < 0) goto err; if (STV090x_WRITE_DEMOD(state, RTC, 0x88) < 0) /* DVB-S1 timing */ goto err; if (STV090x_WRITE_DEMOD(state, RTCS2, 0x68) < 0) /* DVB-S2 timing */ goto err; if (STV090x_WRITE_DEMOD(state, CARFREQ, freq) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHRISE, tmg_thh) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGTHFALL, tmg_thl) < 0) goto err; return tmg_lock; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_get_coldlock(struct stv090x_state *state, s32 timeout_dmd) { struct dvb_frontend *fe = &state->frontend; u32 reg; s32 car_step, steps, cur_step, dir, freq, timeout_lock; int lock; if (state->srate >= 10000000) timeout_lock = timeout_dmd / 3; else timeout_lock = timeout_dmd / 2; lock = stv090x_get_dmdlock(state, timeout_lock); /* cold start wait */ if (lock) return lock; if (state->srate >= 10000000) { if (stv090x_chk_tmg(state)) { if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x15) < 0) goto err; return stv090x_get_dmdlock(state, timeout_dmd); } return 0; } if (state->srate <= 4000000) car_step = 1000; else if (state->srate <= 7000000) car_step = 2000; else if (state->srate <= 10000000) car_step = 3000; else car_step = 5000; steps = (state->search_range / 1000) / car_step; steps /= 2; steps = 2 * (steps + 1); if (steps < 0) steps = 2; else if (steps > 12) steps = 12; cur_step = 1; dir = 1; freq = state->frequency; state->tuner_bw = stv090x_car_width(state->srate, state->rolloff) + state->srate; while ((cur_step <= steps) && (!lock)) { if (dir > 0) freq += cur_step * car_step; else freq -= cur_step * car_step; /* Setup tuner */ if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_set_frequency) { if (state->config->tuner_set_frequency(fe, freq) < 0) goto err_gateoff; } if (state->config->tuner_set_bandwidth) { if (state->config->tuner_set_bandwidth(fe, state->tuner_bw) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; msleep(50); if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_get_status) { if (state->config->tuner_get_status(fe, &reg) < 0) goto err_gateoff; } if (reg) dprintk(FE_DEBUG, 1, "Tuner phase locked"); else dprintk(FE_DEBUG, 1, "Tuner unlocked"); if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1c); if (STV090x_WRITE_DEMOD(state, CFRINIT1, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, 0x00) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x15) < 0) goto err; lock = stv090x_get_dmdlock(state, (timeout_dmd / 3)); dir *= -1; cur_step++; } return lock; err_gateoff: stv090x_i2c_gate_ctrl(state, 0); err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_get_loop_params(struct stv090x_state *state, s32 *freq_inc, s32 *timeout_sw, s32 *steps) { s32 timeout, inc, steps_max, srate, car_max; srate = state->srate; car_max = state->search_range / 1000; car_max += car_max / 10; car_max = 65536 * (car_max / 2); car_max /= (state->internal->mclk / 1000); if (car_max > 0x4000) car_max = 0x4000 ; /* maxcarrier should be<= +-1/4 Mclk */ inc = srate; inc /= state->internal->mclk / 1000; inc *= 256; inc *= 256; inc /= 1000; switch (state->search_mode) { case STV090x_SEARCH_DVBS1: case STV090x_SEARCH_DSS: inc *= 3; /* freq step = 3% of srate */ timeout = 20; break; case STV090x_SEARCH_DVBS2: inc *= 4; timeout = 25; break; case STV090x_SEARCH_AUTO: default: inc *= 3; timeout = 25; break; } inc /= 100; if ((inc > car_max) || (inc < 0)) inc = car_max / 2; /* increment <= 1/8 Mclk */ timeout *= 27500; /* 27.5 Msps reference */ if (srate > 0) timeout /= (srate / 1000); if ((timeout > 100) || (timeout < 0)) timeout = 100; steps_max = (car_max / inc) + 1; /* min steps = 3 */ if ((steps_max > 100) || (steps_max < 0)) { steps_max = 100; /* max steps <= 100 */ inc = car_max / steps_max; } *freq_inc = inc; *timeout_sw = timeout; *steps = steps_max; return 0; } static int stv090x_chk_signal(struct stv090x_state *state) { s32 offst_car, agc2, car_max; int no_signal; offst_car = STV090x_READ_DEMOD(state, CFR2) << 8; offst_car |= STV090x_READ_DEMOD(state, CFR1); offst_car = comp2(offst_car, 16); agc2 = STV090x_READ_DEMOD(state, AGC2I1) << 8; agc2 |= STV090x_READ_DEMOD(state, AGC2I0); car_max = state->search_range / 1000; car_max += (car_max / 10); /* 10% margin */ car_max = (65536 * car_max / 2); car_max /= state->internal->mclk / 1000; if (car_max > 0x4000) car_max = 0x4000; if ((agc2 > 0x2000) || (offst_car > 2 * car_max) || (offst_car < -2 * car_max)) { no_signal = 1; dprintk(FE_DEBUG, 1, "No Signal"); } else { no_signal = 0; dprintk(FE_DEBUG, 1, "Found Signal"); } return no_signal; } static int stv090x_search_car_loop(struct stv090x_state *state, s32 inc, s32 timeout, int zigzag, s32 steps_max) { int no_signal, lock = 0; s32 cpt_step = 0, offst_freq, car_max; u32 reg; car_max = state->search_range / 1000; car_max += (car_max / 10); car_max = (65536 * car_max / 2); car_max /= (state->internal->mclk / 1000); if (car_max > 0x4000) car_max = 0x4000; if (zigzag) offst_freq = 0; else offst_freq = -car_max + inc; do { if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1c) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT1, ((offst_freq / 256) & 0xff)) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, offst_freq & 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x18) < 0) goto err; reg = STV090x_READ_DEMOD(state, PDELCTRL1); STV090x_SETFIELD_Px(reg, ALGOSWRST_FIELD, 0x1); /* stop DVB-S2 packet delin */ if (STV090x_WRITE_DEMOD(state, PDELCTRL1, reg) < 0) goto err; if (zigzag) { if (offst_freq >= 0) offst_freq = -offst_freq - 2 * inc; else offst_freq = -offst_freq; } else { offst_freq += 2 * inc; } cpt_step++; lock = stv090x_get_dmdlock(state, timeout); no_signal = stv090x_chk_signal(state); } while ((!lock) && (!no_signal) && ((offst_freq - inc) < car_max) && ((offst_freq + inc) > -car_max) && (cpt_step < steps_max)); reg = STV090x_READ_DEMOD(state, PDELCTRL1); STV090x_SETFIELD_Px(reg, ALGOSWRST_FIELD, 0); if (STV090x_WRITE_DEMOD(state, PDELCTRL1, reg) < 0) goto err; return lock; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_sw_algo(struct stv090x_state *state) { int no_signal, zigzag, lock = 0; u32 reg; s32 dvbs2_fly_wheel; s32 inc, timeout_step, trials, steps_max; /* get params */ stv090x_get_loop_params(state, &inc, &timeout_step, &steps_max); switch (state->search_mode) { case STV090x_SEARCH_DVBS1: case STV090x_SEARCH_DSS: /* accelerate the frequency detector */ if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x3B) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, DMDCFGMD, 0x49) < 0) goto err; zigzag = 0; break; case STV090x_SEARCH_DVBS2: if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, CORRELABS, 0x79) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, DMDCFGMD, 0x89) < 0) goto err; zigzag = 1; break; case STV090x_SEARCH_AUTO: default: /* accelerate the frequency detector */ if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x3b) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CORRELABS, 0x79) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, DMDCFGMD, 0xc9) < 0) goto err; zigzag = 0; break; } trials = 0; do { lock = stv090x_search_car_loop(state, inc, timeout_step, zigzag, steps_max); no_signal = stv090x_chk_signal(state); trials++; /*run the SW search 2 times maximum*/ if (lock || no_signal || (trials == 2)) { /*Check if the demod is not losing lock in DVBS2*/ if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x49) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CORRELABS, 0x9e) < 0) goto err; } reg = STV090x_READ_DEMOD(state, DMDSTATE); if ((lock) && (STV090x_GETFIELD_Px(reg, HEADER_MODE_FIELD) == STV090x_DVBS2)) { /*Check if the demod is not losing lock in DVBS2*/ msleep(timeout_step); reg = STV090x_READ_DEMOD(state, DMDFLYW); dvbs2_fly_wheel = STV090x_GETFIELD_Px(reg, FLYWHEEL_CPT_FIELD); if (dvbs2_fly_wheel < 0xd) { /*if correct frames is decrementing */ msleep(timeout_step); reg = STV090x_READ_DEMOD(state, DMDFLYW); dvbs2_fly_wheel = STV090x_GETFIELD_Px(reg, FLYWHEEL_CPT_FIELD); } if (dvbs2_fly_wheel < 0xd) { /*FALSE lock, The demod is losing lock */ lock = 0; if (trials < 2) { if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, CORRELABS, 0x79) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, DMDCFGMD, 0x89) < 0) goto err; } } } } } while ((!lock) && (trials < 2) && (!no_signal)); return lock; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static enum stv090x_delsys stv090x_get_std(struct stv090x_state *state) { u32 reg; enum stv090x_delsys delsys; reg = STV090x_READ_DEMOD(state, DMDSTATE); if (STV090x_GETFIELD_Px(reg, HEADER_MODE_FIELD) == 2) delsys = STV090x_DVBS2; else if (STV090x_GETFIELD_Px(reg, HEADER_MODE_FIELD) == 3) { reg = STV090x_READ_DEMOD(state, FECM); if (STV090x_GETFIELD_Px(reg, DSS_DVB_FIELD) == 1) delsys = STV090x_DSS; else delsys = STV090x_DVBS1; } else { delsys = STV090x_ERROR; } return delsys; } /* in Hz */ static s32 stv090x_get_car_freq(struct stv090x_state *state, u32 mclk) { s32 derot, int_1, int_2, tmp_1, tmp_2; derot = STV090x_READ_DEMOD(state, CFR2) << 16; derot |= STV090x_READ_DEMOD(state, CFR1) << 8; derot |= STV090x_READ_DEMOD(state, CFR0); derot = comp2(derot, 24); int_1 = mclk >> 12; int_2 = derot >> 12; /* carrier_frequency = MasterClock * Reg / 2^24 */ tmp_1 = mclk % 0x1000; tmp_2 = derot % 0x1000; derot = (int_1 * int_2) + ((int_1 * tmp_2) >> 12) + ((int_2 * tmp_1) >> 12); return derot; } static int stv090x_get_viterbi(struct stv090x_state *state) { u32 reg, rate; reg = STV090x_READ_DEMOD(state, VITCURPUN); rate = STV090x_GETFIELD_Px(reg, VIT_CURPUN_FIELD); switch (rate) { case 13: state->fec = STV090x_PR12; break; case 18: state->fec = STV090x_PR23; break; case 21: state->fec = STV090x_PR34; break; case 24: state->fec = STV090x_PR56; break; case 25: state->fec = STV090x_PR67; break; case 26: state->fec = STV090x_PR78; break; default: state->fec = STV090x_PRERR; break; } return 0; } static enum stv090x_signal_state stv090x_get_sig_params(struct stv090x_state *state) { struct dvb_frontend *fe = &state->frontend; u8 tmg; u32 reg; s32 i = 0, offst_freq; msleep(5); if (state->algo == STV090x_BLIND_SEARCH) { tmg = STV090x_READ_DEMOD(state, TMGREG2); STV090x_WRITE_DEMOD(state, SFRSTEP, 0x5c); while ((i <= 50) && (tmg != 0) && (tmg != 0xff)) { tmg = STV090x_READ_DEMOD(state, TMGREG2); msleep(5); i += 5; } } state->delsys = stv090x_get_std(state); if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_get_frequency) { if (state->config->tuner_get_frequency(fe, &state->frequency) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; offst_freq = stv090x_get_car_freq(state, state->internal->mclk) / 1000; state->frequency += offst_freq; if (stv090x_get_viterbi(state) < 0) goto err; reg = STV090x_READ_DEMOD(state, DMDMODCOD); state->modcod = STV090x_GETFIELD_Px(reg, DEMOD_MODCOD_FIELD); state->pilots = STV090x_GETFIELD_Px(reg, DEMOD_TYPE_FIELD) & 0x01; state->frame_len = STV090x_GETFIELD_Px(reg, DEMOD_TYPE_FIELD) >> 1; reg = STV090x_READ_DEMOD(state, TMGOBS); state->rolloff = STV090x_GETFIELD_Px(reg, ROLLOFF_STATUS_FIELD); reg = STV090x_READ_DEMOD(state, FECM); state->inversion = STV090x_GETFIELD_Px(reg, IQINV_FIELD); if ((state->algo == STV090x_BLIND_SEARCH) || (state->srate < 10000000)) { if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_get_frequency) { if (state->config->tuner_get_frequency(fe, &state->frequency) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; if (abs(offst_freq) <= ((state->search_range / 2000) + 500)) return STV090x_RANGEOK; else if (abs(offst_freq) <= (stv090x_car_width(state->srate, state->rolloff) / 2000)) return STV090x_RANGEOK; } else { if (abs(offst_freq) <= ((state->search_range / 2000) + 500)) return STV090x_RANGEOK; } return STV090x_OUTOFRANGE; err_gateoff: stv090x_i2c_gate_ctrl(state, 0); err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static u32 stv090x_get_tmgoffst(struct stv090x_state *state, u32 srate) { s32 offst_tmg; offst_tmg = STV090x_READ_DEMOD(state, TMGREG2) << 16; offst_tmg |= STV090x_READ_DEMOD(state, TMGREG1) << 8; offst_tmg |= STV090x_READ_DEMOD(state, TMGREG0); offst_tmg = comp2(offst_tmg, 24); /* 2's complement */ if (!offst_tmg) offst_tmg = 1; offst_tmg = ((s32) srate * 10) / ((s32) 0x1000000 / offst_tmg); offst_tmg /= 320; return offst_tmg; } static u8 stv090x_optimize_carloop(struct stv090x_state *state, enum stv090x_modcod modcod, s32 pilots) { u8 aclc = 0x29; s32 i; struct stv090x_long_frame_crloop *car_loop, *car_loop_qpsk_low, *car_loop_apsk_low; if (state->internal->dev_ver == 0x20) { car_loop = stv090x_s2_crl_cut20; car_loop_qpsk_low = stv090x_s2_lowqpsk_crl_cut20; car_loop_apsk_low = stv090x_s2_apsk_crl_cut20; } else { /* >= Cut 3 */ car_loop = stv090x_s2_crl_cut30; car_loop_qpsk_low = stv090x_s2_lowqpsk_crl_cut30; car_loop_apsk_low = stv090x_s2_apsk_crl_cut30; } if (modcod < STV090x_QPSK_12) { i = 0; while ((i < 3) && (modcod != car_loop_qpsk_low[i].modcod)) i++; if (i >= 3) i = 2; } else { i = 0; while ((i < 14) && (modcod != car_loop[i].modcod)) i++; if (i >= 14) { i = 0; while ((i < 11) && (modcod != car_loop_apsk_low[i].modcod)) i++; if (i >= 11) i = 10; } } if (modcod <= STV090x_QPSK_25) { if (pilots) { if (state->srate <= 3000000) aclc = car_loop_qpsk_low[i].crl_pilots_on_2; else if (state->srate <= 7000000) aclc = car_loop_qpsk_low[i].crl_pilots_on_5; else if (state->srate <= 15000000) aclc = car_loop_qpsk_low[i].crl_pilots_on_10; else if (state->srate <= 25000000) aclc = car_loop_qpsk_low[i].crl_pilots_on_20; else aclc = car_loop_qpsk_low[i].crl_pilots_on_30; } else { if (state->srate <= 3000000) aclc = car_loop_qpsk_low[i].crl_pilots_off_2; else if (state->srate <= 7000000) aclc = car_loop_qpsk_low[i].crl_pilots_off_5; else if (state->srate <= 15000000) aclc = car_loop_qpsk_low[i].crl_pilots_off_10; else if (state->srate <= 25000000) aclc = car_loop_qpsk_low[i].crl_pilots_off_20; else aclc = car_loop_qpsk_low[i].crl_pilots_off_30; } } else if (modcod <= STV090x_8PSK_910) { if (pilots) { if (state->srate <= 3000000) aclc = car_loop[i].crl_pilots_on_2; else if (state->srate <= 7000000) aclc = car_loop[i].crl_pilots_on_5; else if (state->srate <= 15000000) aclc = car_loop[i].crl_pilots_on_10; else if (state->srate <= 25000000) aclc = car_loop[i].crl_pilots_on_20; else aclc = car_loop[i].crl_pilots_on_30; } else { if (state->srate <= 3000000) aclc = car_loop[i].crl_pilots_off_2; else if (state->srate <= 7000000) aclc = car_loop[i].crl_pilots_off_5; else if (state->srate <= 15000000) aclc = car_loop[i].crl_pilots_off_10; else if (state->srate <= 25000000) aclc = car_loop[i].crl_pilots_off_20; else aclc = car_loop[i].crl_pilots_off_30; } } else { /* 16APSK and 32APSK */ /* * This should never happen in practice, except if * something is really wrong at the car_loop table. */ if (i >= 11) i = 10; if (state->srate <= 3000000) aclc = car_loop_apsk_low[i].crl_pilots_on_2; else if (state->srate <= 7000000) aclc = car_loop_apsk_low[i].crl_pilots_on_5; else if (state->srate <= 15000000) aclc = car_loop_apsk_low[i].crl_pilots_on_10; else if (state->srate <= 25000000) aclc = car_loop_apsk_low[i].crl_pilots_on_20; else aclc = car_loop_apsk_low[i].crl_pilots_on_30; } return aclc; } static u8 stv090x_optimize_carloop_short(struct stv090x_state *state) { struct stv090x_short_frame_crloop *short_crl = NULL; s32 index = 0; u8 aclc = 0x0b; switch (state->modulation) { case STV090x_QPSK: default: index = 0; break; case STV090x_8PSK: index = 1; break; case STV090x_16APSK: index = 2; break; case STV090x_32APSK: index = 3; break; } if (state->internal->dev_ver >= 0x30) { /* Cut 3.0 and up */ short_crl = stv090x_s2_short_crl_cut30; } else { /* Cut 2.0 and up: we don't support cuts older than 2.0 */ short_crl = stv090x_s2_short_crl_cut20; } if (state->srate <= 3000000) aclc = short_crl[index].crl_2; else if (state->srate <= 7000000) aclc = short_crl[index].crl_5; else if (state->srate <= 15000000) aclc = short_crl[index].crl_10; else if (state->srate <= 25000000) aclc = short_crl[index].crl_20; else aclc = short_crl[index].crl_30; return aclc; } static int stv090x_optimize_track(struct stv090x_state *state) { struct dvb_frontend *fe = &state->frontend; enum stv090x_modcod modcod; s32 srate, pilots, aclc, f_1, f_0, i = 0, blind_tune = 0; u32 reg; srate = stv090x_get_srate(state, state->internal->mclk); srate += stv090x_get_tmgoffst(state, srate); switch (state->delsys) { case STV090x_DVBS1: case STV090x_DSS: if (state->search_mode == STV090x_SEARCH_AUTO) { reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, DVBS1_ENABLE_FIELD, 1); STV090x_SETFIELD_Px(reg, DVBS2_ENABLE_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; } reg = STV090x_READ_DEMOD(state, DEMOD); STV090x_SETFIELD_Px(reg, ROLLOFF_CONTROL_FIELD, state->rolloff); STV090x_SETFIELD_Px(reg, MANUAL_SXROLLOFF_FIELD, 0x01); if (STV090x_WRITE_DEMOD(state, DEMOD, reg) < 0) goto err; if (state->internal->dev_ver >= 0x30) { if (stv090x_get_viterbi(state) < 0) goto err; if (state->fec == STV090x_PR12) { if (STV090x_WRITE_DEMOD(state, GAUSSR0, 0x98) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CCIR0, 0x18) < 0) goto err; } else { if (STV090x_WRITE_DEMOD(state, GAUSSR0, 0x18) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CCIR0, 0x18) < 0) goto err; } } if (STV090x_WRITE_DEMOD(state, ERRCTRL1, 0x75) < 0) goto err; break; case STV090x_DVBS2: reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, DVBS1_ENABLE_FIELD, 0); STV090x_SETFIELD_Px(reg, DVBS2_ENABLE_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; if (state->internal->dev_ver >= 0x30) { if (STV090x_WRITE_DEMOD(state, ACLC, 0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, BCLC, 0) < 0) goto err; } if (state->frame_len == STV090x_LONG_FRAME) { reg = STV090x_READ_DEMOD(state, DMDMODCOD); modcod = STV090x_GETFIELD_Px(reg, DEMOD_MODCOD_FIELD); pilots = STV090x_GETFIELD_Px(reg, DEMOD_TYPE_FIELD) & 0x01; aclc = stv090x_optimize_carloop(state, modcod, pilots); if (modcod <= STV090x_QPSK_910) { STV090x_WRITE_DEMOD(state, ACLC2S2Q, aclc); } else if (modcod <= STV090x_8PSK_910) { if (STV090x_WRITE_DEMOD(state, ACLC2S2Q, 0x2a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ACLC2S28, aclc) < 0) goto err; } if ((state->demod_mode == STV090x_SINGLE) && (modcod > STV090x_8PSK_910)) { if (modcod <= STV090x_16APSK_910) { if (STV090x_WRITE_DEMOD(state, ACLC2S2Q, 0x2a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ACLC2S216A, aclc) < 0) goto err; } else { if (STV090x_WRITE_DEMOD(state, ACLC2S2Q, 0x2a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ACLC2S232A, aclc) < 0) goto err; } } } else { /*Carrier loop setting for short frame*/ aclc = stv090x_optimize_carloop_short(state); if (state->modulation == STV090x_QPSK) { if (STV090x_WRITE_DEMOD(state, ACLC2S2Q, aclc) < 0) goto err; } else if (state->modulation == STV090x_8PSK) { if (STV090x_WRITE_DEMOD(state, ACLC2S2Q, 0x2a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ACLC2S28, aclc) < 0) goto err; } else if (state->modulation == STV090x_16APSK) { if (STV090x_WRITE_DEMOD(state, ACLC2S2Q, 0x2a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ACLC2S216A, aclc) < 0) goto err; } else if (state->modulation == STV090x_32APSK) { if (STV090x_WRITE_DEMOD(state, ACLC2S2Q, 0x2a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ACLC2S232A, aclc) < 0) goto err; } } STV090x_WRITE_DEMOD(state, ERRCTRL1, 0x67); /* PER */ break; case STV090x_ERROR: default: reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, DVBS1_ENABLE_FIELD, 1); STV090x_SETFIELD_Px(reg, DVBS2_ENABLE_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; break; } f_1 = STV090x_READ_DEMOD(state, CFR2); f_0 = STV090x_READ_DEMOD(state, CFR1); reg = STV090x_READ_DEMOD(state, TMGOBS); if (state->algo == STV090x_BLIND_SEARCH) { STV090x_WRITE_DEMOD(state, SFRSTEP, 0x00); reg = STV090x_READ_DEMOD(state, DMDCFGMD); STV090x_SETFIELD_Px(reg, SCAN_ENABLE_FIELD, 0x00); STV090x_SETFIELD_Px(reg, CFR_AUTOSCAN_FIELD, 0x00); if (STV090x_WRITE_DEMOD(state, DMDCFGMD, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGCFG2, 0xc1) < 0) goto err; if (stv090x_set_srate(state, srate) < 0) goto err; blind_tune = 1; if (stv090x_dvbs_track_crl(state) < 0) goto err; } if (state->internal->dev_ver >= 0x20) { if ((state->search_mode == STV090x_SEARCH_DVBS1) || (state->search_mode == STV090x_SEARCH_DSS) || (state->search_mode == STV090x_SEARCH_AUTO)) { if (STV090x_WRITE_DEMOD(state, VAVSRVIT, 0x0a) < 0) goto err; if (STV090x_WRITE_DEMOD(state, VITSCALE, 0x00) < 0) goto err; } } if (STV090x_WRITE_DEMOD(state, AGC2REF, 0x38) < 0) goto err; /* AUTO tracking MODE */ if (STV090x_WRITE_DEMOD(state, SFRUP1, 0x80) < 0) goto err; /* AUTO tracking MODE */ if (STV090x_WRITE_DEMOD(state, SFRLOW1, 0x80) < 0) goto err; if ((state->internal->dev_ver >= 0x20) || (blind_tune == 1) || (state->srate < 10000000)) { /* update initial carrier freq with the found freq offset */ if (STV090x_WRITE_DEMOD(state, CFRINIT1, f_1) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, f_0) < 0) goto err; state->tuner_bw = stv090x_car_width(srate, state->rolloff) + 10000000; if ((state->internal->dev_ver >= 0x20) || (blind_tune == 1)) { if (state->algo != STV090x_WARM_SEARCH) { if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_set_bandwidth) { if (state->config->tuner_set_bandwidth(fe, state->tuner_bw) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; } } if ((state->algo == STV090x_BLIND_SEARCH) || (state->srate < 10000000)) msleep(50); /* blind search: wait 50ms for SR stabilization */ else msleep(5); stv090x_get_lock_tmg(state); if (!(stv090x_get_dmdlock(state, (state->DemodTimeout / 2)))) { if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT1, f_1) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, f_0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x18) < 0) goto err; i = 0; while ((!(stv090x_get_dmdlock(state, (state->DemodTimeout / 2)))) && (i <= 2)) { if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x1f) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT1, f_1) < 0) goto err; if (STV090x_WRITE_DEMOD(state, CFRINIT0, f_0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x18) < 0) goto err; i++; } } } if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, CARFREQ, 0x49) < 0) goto err; } if ((state->delsys == STV090x_DVBS1) || (state->delsys == STV090x_DSS)) stv090x_set_vit_thtracq(state); return 0; err_gateoff: stv090x_i2c_gate_ctrl(state, 0); err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_get_feclock(struct stv090x_state *state, s32 timeout) { s32 timer = 0, lock = 0, stat; u32 reg; while ((timer < timeout) && (!lock)) { reg = STV090x_READ_DEMOD(state, DMDSTATE); stat = STV090x_GETFIELD_Px(reg, HEADER_MODE_FIELD); switch (stat) { case 0: /* searching */ case 1: /* first PLH detected */ default: lock = 0; break; case 2: /* DVB-S2 mode */ reg = STV090x_READ_DEMOD(state, PDELSTATUS1); lock = STV090x_GETFIELD_Px(reg, PKTDELIN_LOCK_FIELD); break; case 3: /* DVB-S1/legacy mode */ reg = STV090x_READ_DEMOD(state, VSTATUSVIT); lock = STV090x_GETFIELD_Px(reg, LOCKEDVIT_FIELD); break; } if (!lock) { msleep(10); timer += 10; } } return lock; } static int stv090x_get_lock(struct stv090x_state *state, s32 timeout_dmd, s32 timeout_fec) { u32 reg; s32 timer = 0; int lock; lock = stv090x_get_dmdlock(state, timeout_dmd); if (lock) lock = stv090x_get_feclock(state, timeout_fec); if (lock) { lock = 0; while ((timer < timeout_fec) && (!lock)) { reg = STV090x_READ_DEMOD(state, TSSTATUS); lock = STV090x_GETFIELD_Px(reg, TSFIFO_LINEOK_FIELD); msleep(1); timer++; } } return lock; } static int stv090x_set_s2rolloff(struct stv090x_state *state) { u32 reg; if (state->internal->dev_ver <= 0x20) { /* rolloff to auto mode if DVBS2 */ reg = STV090x_READ_DEMOD(state, DEMOD); STV090x_SETFIELD_Px(reg, MANUAL_SXROLLOFF_FIELD, 0x00); if (STV090x_WRITE_DEMOD(state, DEMOD, reg) < 0) goto err; } else { /* DVB-S2 rolloff to auto mode if DVBS2 */ reg = STV090x_READ_DEMOD(state, DEMOD); STV090x_SETFIELD_Px(reg, MANUAL_S2ROLLOFF_FIELD, 0x00); if (STV090x_WRITE_DEMOD(state, DEMOD, reg) < 0) goto err; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static enum stv090x_signal_state stv090x_algo(struct stv090x_state *state) { struct dvb_frontend *fe = &state->frontend; enum stv090x_signal_state signal_state = STV090x_NOCARRIER; u32 reg; s32 agc1_power, power_iq = 0, i; int lock = 0, low_sr = 0; reg = STV090x_READ_DEMOD(state, TSCFGH); STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 1); /* Stop path 1 stream merger */ if (STV090x_WRITE_DEMOD(state, TSCFGH, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, DMDISTATE, 0x5c) < 0) /* Demod stop */ goto err; if (state->internal->dev_ver >= 0x20) { if (state->srate > 5000000) { if (STV090x_WRITE_DEMOD(state, CORRELABS, 0x9e) < 0) goto err; } else { if (STV090x_WRITE_DEMOD(state, CORRELABS, 0x82) < 0) goto err; } } stv090x_get_lock_tmg(state); if (state->algo == STV090x_BLIND_SEARCH) { state->tuner_bw = 2 * 36000000; /* wide bw for unknown srate */ if (STV090x_WRITE_DEMOD(state, TMGCFG2, 0xc0) < 0) /* wider srate scan */ goto err; if (STV090x_WRITE_DEMOD(state, CORRELMANT, 0x70) < 0) goto err; if (stv090x_set_srate(state, 1000000) < 0) /* initial srate = 1Msps */ goto err; } else { /* known srate */ if (STV090x_WRITE_DEMOD(state, DMDTOM, 0x20) < 0) goto err; if (STV090x_WRITE_DEMOD(state, TMGCFG, 0xd2) < 0) goto err; if (state->srate < 2000000) { /* SR < 2MSPS */ if (STV090x_WRITE_DEMOD(state, CORRELMANT, 0x63) < 0) goto err; } else { /* SR >= 2Msps */ if (STV090x_WRITE_DEMOD(state, CORRELMANT, 0x70) < 0) goto err; } if (STV090x_WRITE_DEMOD(state, AGC2REF, 0x38) < 0) goto err; if (state->internal->dev_ver >= 0x20) { if (STV090x_WRITE_DEMOD(state, KREFTMG, 0x5a) < 0) goto err; if (state->algo == STV090x_COLD_SEARCH) state->tuner_bw = (15 * (stv090x_car_width(state->srate, state->rolloff) + 10000000)) / 10; else if (state->algo == STV090x_WARM_SEARCH) state->tuner_bw = stv090x_car_width(state->srate, state->rolloff) + 10000000; } /* if cold start or warm (Symbolrate is known) * use a Narrow symbol rate scan range */ if (STV090x_WRITE_DEMOD(state, TMGCFG2, 0xc1) < 0) /* narrow srate scan */ goto err; if (stv090x_set_srate(state, state->srate) < 0) goto err; if (stv090x_set_max_srate(state, state->internal->mclk, state->srate) < 0) goto err; if (stv090x_set_min_srate(state, state->internal->mclk, state->srate) < 0) goto err; if (state->srate >= 10000000) low_sr = 0; else low_sr = 1; } /* Setup tuner */ if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_set_bbgain) { reg = state->config->tuner_bbgain; if (reg == 0) reg = 10; /* default: 10dB */ if (state->config->tuner_set_bbgain(fe, reg) < 0) goto err_gateoff; } if (state->config->tuner_set_frequency) { if (state->config->tuner_set_frequency(fe, state->frequency) < 0) goto err_gateoff; } if (state->config->tuner_set_bandwidth) { if (state->config->tuner_set_bandwidth(fe, state->tuner_bw) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; msleep(50); if (state->config->tuner_get_status) { if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_get_status(fe, &reg) < 0) goto err_gateoff; if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; if (reg) dprintk(FE_DEBUG, 1, "Tuner phase locked"); else { dprintk(FE_DEBUG, 1, "Tuner unlocked"); return STV090x_NOCARRIER; } } msleep(10); agc1_power = MAKEWORD16(STV090x_READ_DEMOD(state, AGCIQIN1), STV090x_READ_DEMOD(state, AGCIQIN0)); if (agc1_power == 0) { /* If AGC1 integrator value is 0 * then read POWERI, POWERQ */ for (i = 0; i < 5; i++) { power_iq += (STV090x_READ_DEMOD(state, POWERI) + STV090x_READ_DEMOD(state, POWERQ)) >> 1; } power_iq /= 5; } if ((agc1_power == 0) && (power_iq < STV090x_IQPOWER_THRESHOLD)) { dprintk(FE_ERROR, 1, "No Signal: POWER_IQ=0x%02x", power_iq); lock = 0; signal_state = STV090x_NOAGC1; } else { reg = STV090x_READ_DEMOD(state, DEMOD); STV090x_SETFIELD_Px(reg, SPECINV_CONTROL_FIELD, state->inversion); if (state->internal->dev_ver <= 0x20) { /* rolloff to auto mode if DVBS2 */ STV090x_SETFIELD_Px(reg, MANUAL_SXROLLOFF_FIELD, 1); } else { /* DVB-S2 rolloff to auto mode if DVBS2 */ STV090x_SETFIELD_Px(reg, MANUAL_S2ROLLOFF_FIELD, 1); } if (STV090x_WRITE_DEMOD(state, DEMOD, reg) < 0) goto err; if (stv090x_delivery_search(state) < 0) goto err; if (state->algo != STV090x_BLIND_SEARCH) { if (stv090x_start_search(state) < 0) goto err; } } if (signal_state == STV090x_NOAGC1) return signal_state; if (state->algo == STV090x_BLIND_SEARCH) lock = stv090x_blind_search(state); else if (state->algo == STV090x_COLD_SEARCH) lock = stv090x_get_coldlock(state, state->DemodTimeout); else if (state->algo == STV090x_WARM_SEARCH) lock = stv090x_get_dmdlock(state, state->DemodTimeout); if ((!lock) && (state->algo == STV090x_COLD_SEARCH)) { if (!low_sr) { if (stv090x_chk_tmg(state)) lock = stv090x_sw_algo(state); } } if (lock) signal_state = stv090x_get_sig_params(state); if ((lock) && (signal_state == STV090x_RANGEOK)) { /* signal within Range */ stv090x_optimize_track(state); if (state->internal->dev_ver >= 0x20) { /* >= Cut 2.0 :release TS reset after * demod lock and optimized Tracking */ reg = STV090x_READ_DEMOD(state, TSCFGH); STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 0); /* release merger reset */ if (STV090x_WRITE_DEMOD(state, TSCFGH, reg) < 0) goto err; msleep(3); STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 1); /* merger reset */ if (STV090x_WRITE_DEMOD(state, TSCFGH, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 0); /* release merger reset */ if (STV090x_WRITE_DEMOD(state, TSCFGH, reg) < 0) goto err; } lock = stv090x_get_lock(state, state->FecTimeout, state->FecTimeout); if (lock) { if (state->delsys == STV090x_DVBS2) { stv090x_set_s2rolloff(state); reg = STV090x_READ_DEMOD(state, PDELCTRL2); STV090x_SETFIELD_Px(reg, RESET_UPKO_COUNT, 1); if (STV090x_WRITE_DEMOD(state, PDELCTRL2, reg) < 0) goto err; /* Reset DVBS2 packet delinator error counter */ reg = STV090x_READ_DEMOD(state, PDELCTRL2); STV090x_SETFIELD_Px(reg, RESET_UPKO_COUNT, 0); if (STV090x_WRITE_DEMOD(state, PDELCTRL2, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ERRCTRL1, 0x67) < 0) /* PER */ goto err; } else { if (STV090x_WRITE_DEMOD(state, ERRCTRL1, 0x75) < 0) goto err; } /* Reset the Total packet counter */ if (STV090x_WRITE_DEMOD(state, FBERCPT4, 0x00) < 0) goto err; /* Reset the packet Error counter2 */ if (STV090x_WRITE_DEMOD(state, ERRCTRL2, 0xc1) < 0) goto err; } else { signal_state = STV090x_NODATA; stv090x_chk_signal(state); } } return signal_state; err_gateoff: stv090x_i2c_gate_ctrl(state, 0); err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_set_mis(struct stv090x_state *state, int mis) { u32 reg; if (mis < 0 || mis > 255) { dprintk(FE_DEBUG, 1, "Disable MIS filtering"); reg = STV090x_READ_DEMOD(state, PDELCTRL1); STV090x_SETFIELD_Px(reg, FILTER_EN_FIELD, 0x00); if (STV090x_WRITE_DEMOD(state, PDELCTRL1, reg) < 0) goto err; } else { dprintk(FE_DEBUG, 1, "Enable MIS filtering - %d", mis); reg = STV090x_READ_DEMOD(state, PDELCTRL1); STV090x_SETFIELD_Px(reg, FILTER_EN_FIELD, 0x01); if (STV090x_WRITE_DEMOD(state, PDELCTRL1, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ISIENTRY, mis) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ISIBITENA, 0xff) < 0) goto err; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static enum dvbfe_search stv090x_search(struct dvb_frontend *fe) { struct stv090x_state *state = fe->demodulator_priv; struct dtv_frontend_properties *props = &fe->dtv_property_cache; if (props->frequency == 0) return DVBFE_ALGO_SEARCH_INVALID; switch (props->delivery_system) { case SYS_DSS: state->delsys = STV090x_DSS; break; case SYS_DVBS: state->delsys = STV090x_DVBS1; break; case SYS_DVBS2: state->delsys = STV090x_DVBS2; break; default: return DVBFE_ALGO_SEARCH_INVALID; } state->frequency = props->frequency; state->srate = props->symbol_rate; state->search_mode = STV090x_SEARCH_AUTO; state->algo = STV090x_COLD_SEARCH; state->fec = STV090x_PRERR; if (state->srate > 10000000) { dprintk(FE_DEBUG, 1, "Search range: 10 MHz"); state->search_range = 10000000; } else { dprintk(FE_DEBUG, 1, "Search range: 5 MHz"); state->search_range = 5000000; } stv090x_set_mis(state, props->stream_id); if (stv090x_algo(state) == STV090x_RANGEOK) { dprintk(FE_DEBUG, 1, "Search success!"); return DVBFE_ALGO_SEARCH_SUCCESS; } else { dprintk(FE_DEBUG, 1, "Search failed!"); return DVBFE_ALGO_SEARCH_FAILED; } return DVBFE_ALGO_SEARCH_ERROR; } static int stv090x_read_status(struct dvb_frontend *fe, enum fe_status *status) { struct stv090x_state *state = fe->demodulator_priv; u32 reg, dstatus; u8 search_state; *status = 0; dstatus = STV090x_READ_DEMOD(state, DSTATUS); if (STV090x_GETFIELD_Px(dstatus, CAR_LOCK_FIELD)) *status |= FE_HAS_SIGNAL | FE_HAS_CARRIER; reg = STV090x_READ_DEMOD(state, DMDSTATE); search_state = STV090x_GETFIELD_Px(reg, HEADER_MODE_FIELD); switch (search_state) { case 0: /* searching */ case 1: /* first PLH detected */ default: dprintk(FE_DEBUG, 1, "Status: Unlocked (Searching ..)"); break; case 2: /* DVB-S2 mode */ dprintk(FE_DEBUG, 1, "Delivery system: DVB-S2"); if (STV090x_GETFIELD_Px(dstatus, LOCK_DEFINITIF_FIELD)) { reg = STV090x_READ_DEMOD(state, PDELSTATUS1); if (STV090x_GETFIELD_Px(reg, PKTDELIN_LOCK_FIELD)) { *status |= FE_HAS_VITERBI; reg = STV090x_READ_DEMOD(state, TSSTATUS); if (STV090x_GETFIELD_Px(reg, TSFIFO_LINEOK_FIELD)) *status |= FE_HAS_SYNC | FE_HAS_LOCK; } } break; case 3: /* DVB-S1/legacy mode */ dprintk(FE_DEBUG, 1, "Delivery system: DVB-S"); if (STV090x_GETFIELD_Px(dstatus, LOCK_DEFINITIF_FIELD)) { reg = STV090x_READ_DEMOD(state, VSTATUSVIT); if (STV090x_GETFIELD_Px(reg, LOCKEDVIT_FIELD)) { *status |= FE_HAS_VITERBI; reg = STV090x_READ_DEMOD(state, TSSTATUS); if (STV090x_GETFIELD_Px(reg, TSFIFO_LINEOK_FIELD)) *status |= FE_HAS_SYNC | FE_HAS_LOCK; } } break; } return 0; } static int stv090x_read_per(struct dvb_frontend *fe, u32 *per) { struct stv090x_state *state = fe->demodulator_priv; s32 count_4, count_3, count_2, count_1, count_0, count; u32 reg, h, m, l; enum fe_status status; stv090x_read_status(fe, &status); if (!(status & FE_HAS_LOCK)) { *per = 1 << 23; /* Max PER */ } else { /* Counter 2 */ reg = STV090x_READ_DEMOD(state, ERRCNT22); h = STV090x_GETFIELD_Px(reg, ERR_CNT2_FIELD); reg = STV090x_READ_DEMOD(state, ERRCNT21); m = STV090x_GETFIELD_Px(reg, ERR_CNT21_FIELD); reg = STV090x_READ_DEMOD(state, ERRCNT20); l = STV090x_GETFIELD_Px(reg, ERR_CNT20_FIELD); *per = ((h << 16) | (m << 8) | l); count_4 = STV090x_READ_DEMOD(state, FBERCPT4); count_3 = STV090x_READ_DEMOD(state, FBERCPT3); count_2 = STV090x_READ_DEMOD(state, FBERCPT2); count_1 = STV090x_READ_DEMOD(state, FBERCPT1); count_0 = STV090x_READ_DEMOD(state, FBERCPT0); if ((!count_4) && (!count_3)) { count = (count_2 & 0xff) << 16; count |= (count_1 & 0xff) << 8; count |= count_0 & 0xff; } else { count = 1 << 24; } if (count == 0) *per = 1; } if (STV090x_WRITE_DEMOD(state, FBERCPT4, 0) < 0) goto err; if (STV090x_WRITE_DEMOD(state, ERRCTRL2, 0xc1) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_table_lookup(const struct stv090x_tab *tab, int max, int val) { int res = 0; int min = 0, med; if ((val >= tab[min].read && val < tab[max].read) || (val >= tab[max].read && val < tab[min].read)) { while ((max - min) > 1) { med = (max + min) / 2; if ((val >= tab[min].read && val < tab[med].read) || (val >= tab[med].read && val < tab[min].read)) max = med; else min = med; } res = ((val - tab[min].read) * (tab[max].real - tab[min].real) / (tab[max].read - tab[min].read)) + tab[min].real; } else { if (tab[min].read < tab[max].read) { if (val < tab[min].read) res = tab[min].real; else if (val >= tab[max].read) res = tab[max].real; } else { if (val >= tab[min].read) res = tab[min].real; else if (val < tab[max].read) res = tab[max].real; } } return res; } static int stv090x_read_signal_strength(struct dvb_frontend *fe, u16 *strength) { struct stv090x_state *state = fe->demodulator_priv; u32 reg; s32 agc_0, agc_1, agc; s32 str; reg = STV090x_READ_DEMOD(state, AGCIQIN1); agc_1 = STV090x_GETFIELD_Px(reg, AGCIQ_VALUE_FIELD); reg = STV090x_READ_DEMOD(state, AGCIQIN0); agc_0 = STV090x_GETFIELD_Px(reg, AGCIQ_VALUE_FIELD); agc = MAKEWORD16(agc_1, agc_0); str = stv090x_table_lookup(stv090x_rf_tab, ARRAY_SIZE(stv090x_rf_tab) - 1, agc); if (agc > stv090x_rf_tab[0].read) str = 0; else if (agc < stv090x_rf_tab[ARRAY_SIZE(stv090x_rf_tab) - 1].read) str = -100; *strength = (str + 100) * 0xFFFF / 100; return 0; } static int stv090x_read_cnr(struct dvb_frontend *fe, u16 *cnr) { struct stv090x_state *state = fe->demodulator_priv; u32 reg_0, reg_1, reg, i; s32 val_0, val_1, val = 0; u8 lock_f; s32 div; u32 last; switch (state->delsys) { case STV090x_DVBS2: reg = STV090x_READ_DEMOD(state, DSTATUS); lock_f = STV090x_GETFIELD_Px(reg, LOCK_DEFINITIF_FIELD); if (lock_f) { msleep(5); for (i = 0; i < 16; i++) { reg_1 = STV090x_READ_DEMOD(state, NNOSPLHT1); val_1 = STV090x_GETFIELD_Px(reg_1, NOSPLHT_NORMED_FIELD); reg_0 = STV090x_READ_DEMOD(state, NNOSPLHT0); val_0 = STV090x_GETFIELD_Px(reg_0, NOSPLHT_NORMED_FIELD); val += MAKEWORD16(val_1, val_0); msleep(1); } val /= 16; last = ARRAY_SIZE(stv090x_s2cn_tab) - 1; div = stv090x_s2cn_tab[last].real - stv090x_s2cn_tab[3].real; val = stv090x_table_lookup(stv090x_s2cn_tab, last, val); if (val < 0) val = 0; *cnr = val * 0xFFFF / div; } break; case STV090x_DVBS1: case STV090x_DSS: reg = STV090x_READ_DEMOD(state, DSTATUS); lock_f = STV090x_GETFIELD_Px(reg, LOCK_DEFINITIF_FIELD); if (lock_f) { msleep(5); for (i = 0; i < 16; i++) { reg_1 = STV090x_READ_DEMOD(state, NOSDATAT1); val_1 = STV090x_GETFIELD_Px(reg_1, NOSDATAT_UNNORMED_FIELD); reg_0 = STV090x_READ_DEMOD(state, NOSDATAT0); val_0 = STV090x_GETFIELD_Px(reg_0, NOSDATAT_UNNORMED_FIELD); val += MAKEWORD16(val_1, val_0); msleep(1); } val /= 16; last = ARRAY_SIZE(stv090x_s1cn_tab) - 1; div = stv090x_s1cn_tab[last].real - stv090x_s1cn_tab[0].real; val = stv090x_table_lookup(stv090x_s1cn_tab, last, val); *cnr = val * 0xFFFF / div; } break; default: break; } return 0; } static int stv090x_set_tone(struct dvb_frontend *fe, enum fe_sec_tone_mode tone) { struct stv090x_state *state = fe->demodulator_priv; u32 reg; reg = STV090x_READ_DEMOD(state, DISTXCTL); switch (tone) { case SEC_TONE_ON: STV090x_SETFIELD_Px(reg, DISTX_MODE_FIELD, 0); STV090x_SETFIELD_Px(reg, DISEQC_RESET_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, DISEQC_RESET_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; break; case SEC_TONE_OFF: STV090x_SETFIELD_Px(reg, DISTX_MODE_FIELD, 0); STV090x_SETFIELD_Px(reg, DISEQC_RESET_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; break; default: return -EINVAL; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static enum dvbfe_algo stv090x_frontend_algo(struct dvb_frontend *fe) { return DVBFE_ALGO_CUSTOM; } static int stv090x_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *cmd) { struct stv090x_state *state = fe->demodulator_priv; u32 reg, idle = 0, fifo_full = 1; int i; reg = STV090x_READ_DEMOD(state, DISTXCTL); STV090x_SETFIELD_Px(reg, DISTX_MODE_FIELD, (state->config->diseqc_envelope_mode) ? 4 : 2); STV090x_SETFIELD_Px(reg, DISEQC_RESET_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, DISEQC_RESET_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, DIS_PRECHARGE_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; for (i = 0; i < cmd->msg_len; i++) { while (fifo_full) { reg = STV090x_READ_DEMOD(state, DISTXSTATUS); fifo_full = STV090x_GETFIELD_Px(reg, FIFO_FULL_FIELD); } if (STV090x_WRITE_DEMOD(state, DISTXDATA, cmd->msg[i]) < 0) goto err; } reg = STV090x_READ_DEMOD(state, DISTXCTL); STV090x_SETFIELD_Px(reg, DIS_PRECHARGE_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; i = 0; while ((!idle) && (i < 10)) { reg = STV090x_READ_DEMOD(state, DISTXSTATUS); idle = STV090x_GETFIELD_Px(reg, TX_IDLE_FIELD); msleep(10); i++; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_send_diseqc_burst(struct dvb_frontend *fe, enum fe_sec_mini_cmd burst) { struct stv090x_state *state = fe->demodulator_priv; u32 reg, idle = 0, fifo_full = 1; u8 mode, value; int i; reg = STV090x_READ_DEMOD(state, DISTXCTL); if (burst == SEC_MINI_A) { mode = (state->config->diseqc_envelope_mode) ? 5 : 3; value = 0x00; } else { mode = (state->config->diseqc_envelope_mode) ? 4 : 2; value = 0xFF; } STV090x_SETFIELD_Px(reg, DISTX_MODE_FIELD, mode); STV090x_SETFIELD_Px(reg, DISEQC_RESET_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, DISEQC_RESET_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, DIS_PRECHARGE_FIELD, 1); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; while (fifo_full) { reg = STV090x_READ_DEMOD(state, DISTXSTATUS); fifo_full = STV090x_GETFIELD_Px(reg, FIFO_FULL_FIELD); } if (STV090x_WRITE_DEMOD(state, DISTXDATA, value) < 0) goto err; reg = STV090x_READ_DEMOD(state, DISTXCTL); STV090x_SETFIELD_Px(reg, DIS_PRECHARGE_FIELD, 0); if (STV090x_WRITE_DEMOD(state, DISTXCTL, reg) < 0) goto err; i = 0; while ((!idle) && (i < 10)) { reg = STV090x_READ_DEMOD(state, DISTXSTATUS); idle = STV090x_GETFIELD_Px(reg, TX_IDLE_FIELD); msleep(10); i++; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_recv_slave_reply(struct dvb_frontend *fe, struct dvb_diseqc_slave_reply *reply) { struct stv090x_state *state = fe->demodulator_priv; u32 reg = 0, i = 0, rx_end = 0; while ((rx_end != 1) && (i < 10)) { msleep(10); i++; reg = STV090x_READ_DEMOD(state, DISRX_ST0); rx_end = STV090x_GETFIELD_Px(reg, RX_END_FIELD); } if (rx_end) { reply->msg_len = STV090x_GETFIELD_Px(reg, FIFO_BYTENBR_FIELD); for (i = 0; i < reply->msg_len; i++) reply->msg[i] = STV090x_READ_DEMOD(state, DISRXDATA); } return 0; } static int stv090x_sleep(struct dvb_frontend *fe) { struct stv090x_state *state = fe->demodulator_priv; u32 reg; u8 full_standby = 0; if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (state->config->tuner_sleep) { if (state->config->tuner_sleep(fe) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; dprintk(FE_DEBUG, 1, "Set %s(%d) to sleep", state->device == STV0900 ? "STV0900" : "STV0903", state->demod); mutex_lock(&state->internal->demod_lock); switch (state->demod) { case STV090x_DEMODULATOR_0: /* power off ADC 1 */ reg = stv090x_read_reg(state, STV090x_TSTTNR1); STV090x_SETFIELD(reg, ADC1_PON_FIELD, 0); if (stv090x_write_reg(state, STV090x_TSTTNR1, reg) < 0) goto err_unlock; /* power off DiSEqC 1 */ reg = stv090x_read_reg(state, STV090x_TSTTNR2); STV090x_SETFIELD(reg, DISEQC1_PON_FIELD, 0); if (stv090x_write_reg(state, STV090x_TSTTNR2, reg) < 0) goto err_unlock; /* check whether path 2 is already sleeping, that is when ADC2 is off */ reg = stv090x_read_reg(state, STV090x_TSTTNR3); if (STV090x_GETFIELD(reg, ADC2_PON_FIELD) == 0) full_standby = 1; /* stop clocks */ reg = stv090x_read_reg(state, STV090x_STOPCLK1); /* packet delineator 1 clock */ STV090x_SETFIELD(reg, STOP_CLKPKDT1_FIELD, 1); /* ADC 1 clock */ STV090x_SETFIELD(reg, STOP_CLKADCI1_FIELD, 1); /* FEC clock is shared between the two paths, only stop it when full standby is possible */ if (full_standby) STV090x_SETFIELD(reg, STOP_CLKFEC_FIELD, 1); if (stv090x_write_reg(state, STV090x_STOPCLK1, reg) < 0) goto err_unlock; reg = stv090x_read_reg(state, STV090x_STOPCLK2); /* sampling 1 clock */ STV090x_SETFIELD(reg, STOP_CLKSAMP1_FIELD, 1); /* viterbi 1 clock */ STV090x_SETFIELD(reg, STOP_CLKVIT1_FIELD, 1); /* TS clock is shared between the two paths, only stop it when full standby is possible */ if (full_standby) STV090x_SETFIELD(reg, STOP_CLKTS_FIELD, 1); if (stv090x_write_reg(state, STV090x_STOPCLK2, reg) < 0) goto err_unlock; break; case STV090x_DEMODULATOR_1: /* power off ADC 2 */ reg = stv090x_read_reg(state, STV090x_TSTTNR3); STV090x_SETFIELD(reg, ADC2_PON_FIELD, 0); if (stv090x_write_reg(state, STV090x_TSTTNR3, reg) < 0) goto err_unlock; /* power off DiSEqC 2 */ reg = stv090x_read_reg(state, STV090x_TSTTNR4); STV090x_SETFIELD(reg, DISEQC2_PON_FIELD, 0); if (stv090x_write_reg(state, STV090x_TSTTNR4, reg) < 0) goto err_unlock; /* check whether path 1 is already sleeping, that is when ADC1 is off */ reg = stv090x_read_reg(state, STV090x_TSTTNR1); if (STV090x_GETFIELD(reg, ADC1_PON_FIELD) == 0) full_standby = 1; /* stop clocks */ reg = stv090x_read_reg(state, STV090x_STOPCLK1); /* packet delineator 2 clock */ STV090x_SETFIELD(reg, STOP_CLKPKDT2_FIELD, 1); /* ADC 2 clock */ STV090x_SETFIELD(reg, STOP_CLKADCI2_FIELD, 1); /* FEC clock is shared between the two paths, only stop it when full standby is possible */ if (full_standby) STV090x_SETFIELD(reg, STOP_CLKFEC_FIELD, 1); if (stv090x_write_reg(state, STV090x_STOPCLK1, reg) < 0) goto err_unlock; reg = stv090x_read_reg(state, STV090x_STOPCLK2); /* sampling 2 clock */ STV090x_SETFIELD(reg, STOP_CLKSAMP2_FIELD, 1); /* viterbi 2 clock */ STV090x_SETFIELD(reg, STOP_CLKVIT2_FIELD, 1); /* TS clock is shared between the two paths, only stop it when full standby is possible */ if (full_standby) STV090x_SETFIELD(reg, STOP_CLKTS_FIELD, 1); if (stv090x_write_reg(state, STV090x_STOPCLK2, reg) < 0) goto err_unlock; break; default: dprintk(FE_ERROR, 1, "Wrong demodulator!"); break; } if (full_standby) { /* general power off */ reg = stv090x_read_reg(state, STV090x_SYNTCTRL); STV090x_SETFIELD(reg, STANDBY_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_SYNTCTRL, reg) < 0) goto err_unlock; } mutex_unlock(&state->internal->demod_lock); return 0; err_gateoff: stv090x_i2c_gate_ctrl(state, 0); goto err; err_unlock: mutex_unlock(&state->internal->demod_lock); err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_wakeup(struct dvb_frontend *fe) { struct stv090x_state *state = fe->demodulator_priv; u32 reg; dprintk(FE_DEBUG, 1, "Wake %s(%d) from standby", state->device == STV0900 ? "STV0900" : "STV0903", state->demod); mutex_lock(&state->internal->demod_lock); /* general power on */ reg = stv090x_read_reg(state, STV090x_SYNTCTRL); STV090x_SETFIELD(reg, STANDBY_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_SYNTCTRL, reg) < 0) goto err; switch (state->demod) { case STV090x_DEMODULATOR_0: /* power on ADC 1 */ reg = stv090x_read_reg(state, STV090x_TSTTNR1); STV090x_SETFIELD(reg, ADC1_PON_FIELD, 1); if (stv090x_write_reg(state, STV090x_TSTTNR1, reg) < 0) goto err; /* power on DiSEqC 1 */ reg = stv090x_read_reg(state, STV090x_TSTTNR2); STV090x_SETFIELD(reg, DISEQC1_PON_FIELD, 1); if (stv090x_write_reg(state, STV090x_TSTTNR2, reg) < 0) goto err; /* activate clocks */ reg = stv090x_read_reg(state, STV090x_STOPCLK1); /* packet delineator 1 clock */ STV090x_SETFIELD(reg, STOP_CLKPKDT1_FIELD, 0); /* ADC 1 clock */ STV090x_SETFIELD(reg, STOP_CLKADCI1_FIELD, 0); /* FEC clock */ STV090x_SETFIELD(reg, STOP_CLKFEC_FIELD, 0); if (stv090x_write_reg(state, STV090x_STOPCLK1, reg) < 0) goto err; reg = stv090x_read_reg(state, STV090x_STOPCLK2); /* sampling 1 clock */ STV090x_SETFIELD(reg, STOP_CLKSAMP1_FIELD, 0); /* viterbi 1 clock */ STV090x_SETFIELD(reg, STOP_CLKVIT1_FIELD, 0); /* TS clock */ STV090x_SETFIELD(reg, STOP_CLKTS_FIELD, 0); if (stv090x_write_reg(state, STV090x_STOPCLK2, reg) < 0) goto err; break; case STV090x_DEMODULATOR_1: /* power on ADC 2 */ reg = stv090x_read_reg(state, STV090x_TSTTNR3); STV090x_SETFIELD(reg, ADC2_PON_FIELD, 1); if (stv090x_write_reg(state, STV090x_TSTTNR3, reg) < 0) goto err; /* power on DiSEqC 2 */ reg = stv090x_read_reg(state, STV090x_TSTTNR4); STV090x_SETFIELD(reg, DISEQC2_PON_FIELD, 1); if (stv090x_write_reg(state, STV090x_TSTTNR4, reg) < 0) goto err; /* activate clocks */ reg = stv090x_read_reg(state, STV090x_STOPCLK1); /* packet delineator 2 clock */ STV090x_SETFIELD(reg, STOP_CLKPKDT2_FIELD, 0); /* ADC 2 clock */ STV090x_SETFIELD(reg, STOP_CLKADCI2_FIELD, 0); /* FEC clock */ STV090x_SETFIELD(reg, STOP_CLKFEC_FIELD, 0); if (stv090x_write_reg(state, STV090x_STOPCLK1, reg) < 0) goto err; reg = stv090x_read_reg(state, STV090x_STOPCLK2); /* sampling 2 clock */ STV090x_SETFIELD(reg, STOP_CLKSAMP2_FIELD, 0); /* viterbi 2 clock */ STV090x_SETFIELD(reg, STOP_CLKVIT2_FIELD, 0); /* TS clock */ STV090x_SETFIELD(reg, STOP_CLKTS_FIELD, 0); if (stv090x_write_reg(state, STV090x_STOPCLK2, reg) < 0) goto err; break; default: dprintk(FE_ERROR, 1, "Wrong demodulator!"); break; } mutex_unlock(&state->internal->demod_lock); return 0; err: mutex_unlock(&state->internal->demod_lock); dprintk(FE_ERROR, 1, "I/O error"); return -1; } static void stv090x_release(struct dvb_frontend *fe) { struct stv090x_state *state = fe->demodulator_priv; state->internal->num_used--; if (state->internal->num_used <= 0) { dprintk(FE_ERROR, 1, "Actually removing"); remove_dev(state->internal); kfree(state->internal); } kfree(state); } static int stv090x_ldpc_mode(struct stv090x_state *state, enum stv090x_mode ldpc_mode) { u32 reg = 0; reg = stv090x_read_reg(state, STV090x_GENCFG); switch (ldpc_mode) { case STV090x_DUAL: default: if ((state->demod_mode != STV090x_DUAL) || (STV090x_GETFIELD(reg, DDEMOD_FIELD) != 1)) { /* set LDPC to dual mode */ if (stv090x_write_reg(state, STV090x_GENCFG, 0x1d) < 0) goto err; state->demod_mode = STV090x_DUAL; reg = stv090x_read_reg(state, STV090x_TSTRES0); STV090x_SETFIELD(reg, FRESFEC_FIELD, 0x1); if (stv090x_write_reg(state, STV090x_TSTRES0, reg) < 0) goto err; STV090x_SETFIELD(reg, FRESFEC_FIELD, 0x0); if (stv090x_write_reg(state, STV090x_TSTRES0, reg) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST0, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST1, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST2, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST3, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST4, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST5, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST6, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST7, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST8, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLST9, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTA, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTB, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTC, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTD, 0xcc) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTE, 0xff) < 0) goto err; if (STV090x_WRITE_DEMOD(state, MODCODLSTF, 0xcf) < 0) goto err; } break; case STV090x_SINGLE: if (stv090x_stop_modcod(state) < 0) goto err; if (stv090x_activate_modcod_single(state) < 0) goto err; if (state->demod == STV090x_DEMODULATOR_1) { if (stv090x_write_reg(state, STV090x_GENCFG, 0x06) < 0) /* path 2 */ goto err; } else { if (stv090x_write_reg(state, STV090x_GENCFG, 0x04) < 0) /* path 1 */ goto err; } reg = stv090x_read_reg(state, STV090x_TSTRES0); STV090x_SETFIELD(reg, FRESFEC_FIELD, 0x1); if (stv090x_write_reg(state, STV090x_TSTRES0, reg) < 0) goto err; STV090x_SETFIELD(reg, FRESFEC_FIELD, 0x0); if (stv090x_write_reg(state, STV090x_TSTRES0, reg) < 0) goto err; reg = STV090x_READ_DEMOD(state, PDELCTRL1); STV090x_SETFIELD_Px(reg, ALGOSWRST_FIELD, 0x01); if (STV090x_WRITE_DEMOD(state, PDELCTRL1, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, ALGOSWRST_FIELD, 0x00); if (STV090x_WRITE_DEMOD(state, PDELCTRL1, reg) < 0) goto err; break; } return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } /* return (Hz), clk in Hz*/ static u32 stv090x_get_mclk(struct stv090x_state *state) { const struct stv090x_config *config = state->config; u32 div, reg; u8 ratio; div = stv090x_read_reg(state, STV090x_NCOARSE); reg = stv090x_read_reg(state, STV090x_SYNTCTRL); ratio = STV090x_GETFIELD(reg, SELX1RATIO_FIELD) ? 4 : 6; return (div + 1) * config->xtal / ratio; /* kHz */ } static int stv090x_set_mclk(struct stv090x_state *state, u32 mclk, u32 clk) { const struct stv090x_config *config = state->config; u32 reg, div, clk_sel; reg = stv090x_read_reg(state, STV090x_SYNTCTRL); clk_sel = ((STV090x_GETFIELD(reg, SELX1RATIO_FIELD) == 1) ? 4 : 6); div = ((clk_sel * mclk) / config->xtal) - 1; reg = stv090x_read_reg(state, STV090x_NCOARSE); STV090x_SETFIELD(reg, M_DIV_FIELD, div); if (stv090x_write_reg(state, STV090x_NCOARSE, reg) < 0) goto err; state->internal->mclk = stv090x_get_mclk(state); /*Set the DiseqC frequency to 22KHz */ div = state->internal->mclk / 704000; if (STV090x_WRITE_DEMOD(state, F22TX, div) < 0) goto err; if (STV090x_WRITE_DEMOD(state, F22RX, div) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv0900_set_tspath(struct stv090x_state *state) { u32 reg; if (state->internal->dev_ver >= 0x20) { switch (state->config->ts1_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: switch (state->config->ts2_mode) { case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: default: stv090x_write_reg(state, STV090x_TSGENERAL, 0x00); break; case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: if (stv090x_write_reg(state, STV090x_TSGENERAL, 0x06) < 0) /* Mux'd stream mode */ goto err; reg = stv090x_read_reg(state, STV090x_P1_TSCFGM); STV090x_SETFIELD_Px(reg, TSFIFO_MANSPEED_FIELD, 3); if (stv090x_write_reg(state, STV090x_P1_TSCFGM, reg) < 0) goto err; reg = stv090x_read_reg(state, STV090x_P2_TSCFGM); STV090x_SETFIELD_Px(reg, TSFIFO_MANSPEED_FIELD, 3); if (stv090x_write_reg(state, STV090x_P2_TSCFGM, reg) < 0) goto err; if (stv090x_write_reg(state, STV090x_P1_TSSPEED, 0x14) < 0) goto err; if (stv090x_write_reg(state, STV090x_P2_TSSPEED, 0x28) < 0) goto err; break; } break; case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: default: switch (state->config->ts2_mode) { case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: default: if (stv090x_write_reg(state, STV090x_TSGENERAL, 0x0c) < 0) goto err; break; case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: if (stv090x_write_reg(state, STV090x_TSGENERAL, 0x0a) < 0) goto err; break; } break; } } else { switch (state->config->ts1_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: switch (state->config->ts2_mode) { case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: default: stv090x_write_reg(state, STV090x_TSGENERAL1X, 0x10); break; case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: stv090x_write_reg(state, STV090x_TSGENERAL1X, 0x16); reg = stv090x_read_reg(state, STV090x_P1_TSCFGM); STV090x_SETFIELD_Px(reg, TSFIFO_MANSPEED_FIELD, 3); if (stv090x_write_reg(state, STV090x_P1_TSCFGM, reg) < 0) goto err; reg = stv090x_read_reg(state, STV090x_P1_TSCFGM); STV090x_SETFIELD_Px(reg, TSFIFO_MANSPEED_FIELD, 0); if (stv090x_write_reg(state, STV090x_P1_TSCFGM, reg) < 0) goto err; if (stv090x_write_reg(state, STV090x_P1_TSSPEED, 0x14) < 0) goto err; if (stv090x_write_reg(state, STV090x_P2_TSSPEED, 0x28) < 0) goto err; break; } break; case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: default: switch (state->config->ts2_mode) { case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: default: stv090x_write_reg(state, STV090x_TSGENERAL1X, 0x14); break; case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: stv090x_write_reg(state, STV090x_TSGENERAL1X, 0x12); break; } break; } } switch (state->config->ts1_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_TEIUPDATE_FIELD, state->config->ts1_tei); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x00); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_DVBCI: reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_TEIUPDATE_FIELD, state->config->ts1_tei); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x00); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_SERIAL_PUNCTURED: reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_TEIUPDATE_FIELD, state->config->ts1_tei); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x01); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_SERIAL_CONTINUOUS: reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_TEIUPDATE_FIELD, state->config->ts1_tei); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x01); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; break; default: break; } switch (state->config->ts2_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: reg = stv090x_read_reg(state, STV090x_P2_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_TEIUPDATE_FIELD, state->config->ts2_tei); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x00); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P2_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_DVBCI: reg = stv090x_read_reg(state, STV090x_P2_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_TEIUPDATE_FIELD, state->config->ts2_tei); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x00); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P2_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_SERIAL_PUNCTURED: reg = stv090x_read_reg(state, STV090x_P2_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_TEIUPDATE_FIELD, state->config->ts2_tei); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x01); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P2_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_SERIAL_CONTINUOUS: reg = stv090x_read_reg(state, STV090x_P2_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_TEIUPDATE_FIELD, state->config->ts2_tei); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x01); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P2_TSCFGH, reg) < 0) goto err; break; default: break; } if (state->config->ts1_clk > 0) { u32 speed; switch (state->config->ts1_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: default: speed = state->internal->mclk / (state->config->ts1_clk / 4); if (speed < 0x08) speed = 0x08; if (speed > 0xFF) speed = 0xFF; break; case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: speed = state->internal->mclk / (state->config->ts1_clk / 32); if (speed < 0x20) speed = 0x20; if (speed > 0xFF) speed = 0xFF; break; } reg = stv090x_read_reg(state, STV090x_P1_TSCFGM); STV090x_SETFIELD_Px(reg, TSFIFO_MANSPEED_FIELD, 3); if (stv090x_write_reg(state, STV090x_P1_TSCFGM, reg) < 0) goto err; if (stv090x_write_reg(state, STV090x_P1_TSSPEED, speed) < 0) goto err; } if (state->config->ts2_clk > 0) { u32 speed; switch (state->config->ts2_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: default: speed = state->internal->mclk / (state->config->ts2_clk / 4); if (speed < 0x08) speed = 0x08; if (speed > 0xFF) speed = 0xFF; break; case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: speed = state->internal->mclk / (state->config->ts2_clk / 32); if (speed < 0x20) speed = 0x20; if (speed > 0xFF) speed = 0xFF; break; } reg = stv090x_read_reg(state, STV090x_P2_TSCFGM); STV090x_SETFIELD_Px(reg, TSFIFO_MANSPEED_FIELD, 3); if (stv090x_write_reg(state, STV090x_P2_TSCFGM, reg) < 0) goto err; if (stv090x_write_reg(state, STV090x_P2_TSSPEED, speed) < 0) goto err; } reg = stv090x_read_reg(state, STV090x_P2_TSCFGH); STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P2_TSCFGH, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P2_TSCFGH, reg) < 0) goto err; reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv0903_set_tspath(struct stv090x_state *state) { u32 reg; if (state->internal->dev_ver >= 0x20) { switch (state->config->ts1_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: stv090x_write_reg(state, STV090x_TSGENERAL, 0x00); break; case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: default: stv090x_write_reg(state, STV090x_TSGENERAL, 0x0c); break; } } else { switch (state->config->ts1_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: stv090x_write_reg(state, STV090x_TSGENERAL1X, 0x10); break; case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: default: stv090x_write_reg(state, STV090x_TSGENERAL1X, 0x14); break; } } switch (state->config->ts1_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x00); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_DVBCI: reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x00); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_SERIAL_PUNCTURED: reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x01); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; break; case STV090x_TSMODE_SERIAL_CONTINUOUS: reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, TSFIFO_SERIAL_FIELD, 0x01); STV090x_SETFIELD_Px(reg, TSFIFO_DVBCI_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; break; default: break; } if (state->config->ts1_clk > 0) { u32 speed; switch (state->config->ts1_mode) { case STV090x_TSMODE_PARALLEL_PUNCTURED: case STV090x_TSMODE_DVBCI: default: speed = state->internal->mclk / (state->config->ts1_clk / 4); if (speed < 0x08) speed = 0x08; if (speed > 0xFF) speed = 0xFF; break; case STV090x_TSMODE_SERIAL_PUNCTURED: case STV090x_TSMODE_SERIAL_CONTINUOUS: speed = state->internal->mclk / (state->config->ts1_clk / 32); if (speed < 0x20) speed = 0x20; if (speed > 0xFF) speed = 0xFF; break; } reg = stv090x_read_reg(state, STV090x_P1_TSCFGM); STV090x_SETFIELD_Px(reg, TSFIFO_MANSPEED_FIELD, 3); if (stv090x_write_reg(state, STV090x_P1_TSCFGM, reg) < 0) goto err; if (stv090x_write_reg(state, STV090x_P1_TSSPEED, speed) < 0) goto err; } reg = stv090x_read_reg(state, STV090x_P1_TSCFGH); STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 0x01); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; STV090x_SETFIELD_Px(reg, RST_HWARE_FIELD, 0x00); if (stv090x_write_reg(state, STV090x_P1_TSCFGH, reg) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_init(struct dvb_frontend *fe) { struct stv090x_state *state = fe->demodulator_priv; const struct stv090x_config *config = state->config; u32 reg; if (state->internal->mclk == 0) { /* call tuner init to configure the tuner's clock output divider directly before setting up the master clock of the stv090x. */ if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (config->tuner_init) { if (config->tuner_init(fe) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; stv090x_set_mclk(state, 135000000, config->xtal); /* 135 Mhz */ msleep(5); if (stv090x_write_reg(state, STV090x_SYNTCTRL, 0x20 | config->clk_mode) < 0) goto err; stv090x_get_mclk(state); } if (stv090x_wakeup(fe) < 0) { dprintk(FE_ERROR, 1, "Error waking device"); goto err; } if (stv090x_ldpc_mode(state, state->demod_mode) < 0) goto err; reg = STV090x_READ_DEMOD(state, TNRCFG2); STV090x_SETFIELD_Px(reg, TUN_IQSWAP_FIELD, state->inversion); if (STV090x_WRITE_DEMOD(state, TNRCFG2, reg) < 0) goto err; reg = STV090x_READ_DEMOD(state, DEMOD); STV090x_SETFIELD_Px(reg, ROLLOFF_CONTROL_FIELD, state->rolloff); if (STV090x_WRITE_DEMOD(state, DEMOD, reg) < 0) goto err; if (stv090x_i2c_gate_ctrl(state, 1) < 0) goto err; if (config->tuner_set_mode) { if (config->tuner_set_mode(fe, TUNER_WAKE) < 0) goto err_gateoff; } if (config->tuner_init) { if (config->tuner_init(fe) < 0) goto err_gateoff; } if (stv090x_i2c_gate_ctrl(state, 0) < 0) goto err; if (state->device == STV0900) { if (stv0900_set_tspath(state) < 0) goto err; } else { if (stv0903_set_tspath(state) < 0) goto err; } return 0; err_gateoff: stv090x_i2c_gate_ctrl(state, 0); err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_setup(struct dvb_frontend *fe) { struct stv090x_state *state = fe->demodulator_priv; const struct stv090x_config *config = state->config; const struct stv090x_reg *stv090x_initval = NULL; const struct stv090x_reg *stv090x_cut20_val = NULL; unsigned long t1_size = 0, t2_size = 0; u32 reg = 0; int i; if (state->device == STV0900) { dprintk(FE_DEBUG, 1, "Initializing STV0900"); stv090x_initval = stv0900_initval; t1_size = ARRAY_SIZE(stv0900_initval); stv090x_cut20_val = stv0900_cut20_val; t2_size = ARRAY_SIZE(stv0900_cut20_val); } else if (state->device == STV0903) { dprintk(FE_DEBUG, 1, "Initializing STV0903"); stv090x_initval = stv0903_initval; t1_size = ARRAY_SIZE(stv0903_initval); stv090x_cut20_val = stv0903_cut20_val; t2_size = ARRAY_SIZE(stv0903_cut20_val); } /* STV090x init */ /* Stop Demod */ if (stv090x_write_reg(state, STV090x_P1_DMDISTATE, 0x5c) < 0) goto err; if (state->device == STV0900) if (stv090x_write_reg(state, STV090x_P2_DMDISTATE, 0x5c) < 0) goto err; msleep(5); /* Set No Tuner Mode */ if (stv090x_write_reg(state, STV090x_P1_TNRCFG, 0x6c) < 0) goto err; if (state->device == STV0900) if (stv090x_write_reg(state, STV090x_P2_TNRCFG, 0x6c) < 0) goto err; /* I2C repeater OFF */ STV090x_SETFIELD_Px(reg, ENARPT_LEVEL_FIELD, config->repeater_level); if (stv090x_write_reg(state, STV090x_P1_I2CRPT, reg) < 0) goto err; if (state->device == STV0900) if (stv090x_write_reg(state, STV090x_P2_I2CRPT, reg) < 0) goto err; if (stv090x_write_reg(state, STV090x_NCOARSE, 0x13) < 0) /* set PLL divider */ goto err; msleep(5); if (stv090x_write_reg(state, STV090x_I2CCFG, 0x08) < 0) /* 1/41 oversampling */ goto err; if (stv090x_write_reg(state, STV090x_SYNTCTRL, 0x20 | config->clk_mode) < 0) /* enable PLL */ goto err; msleep(5); /* write initval */ dprintk(FE_DEBUG, 1, "Setting up initial values"); for (i = 0; i < t1_size; i++) { if (stv090x_write_reg(state, stv090x_initval[i].addr, stv090x_initval[i].data) < 0) goto err; } state->internal->dev_ver = stv090x_read_reg(state, STV090x_MID); if (state->internal->dev_ver >= 0x20) { if (stv090x_write_reg(state, STV090x_TSGENERAL, 0x0c) < 0) goto err; /* write cut20_val*/ dprintk(FE_DEBUG, 1, "Setting up Cut 2.0 initial values"); for (i = 0; i < t2_size; i++) { if (stv090x_write_reg(state, stv090x_cut20_val[i].addr, stv090x_cut20_val[i].data) < 0) goto err; } } else if (state->internal->dev_ver < 0x20) { dprintk(FE_ERROR, 1, "ERROR: Unsupported Cut: 0x%02x!", state->internal->dev_ver); goto err; } else if (state->internal->dev_ver > 0x30) { /* we shouldn't bail out from here */ dprintk(FE_ERROR, 1, "INFO: Cut: 0x%02x probably incomplete support!", state->internal->dev_ver); } /* ADC1 range */ reg = stv090x_read_reg(state, STV090x_TSTTNR1); STV090x_SETFIELD(reg, ADC1_INMODE_FIELD, (config->adc1_range == STV090x_ADC_1Vpp) ? 0 : 1); if (stv090x_write_reg(state, STV090x_TSTTNR1, reg) < 0) goto err; /* ADC2 range */ reg = stv090x_read_reg(state, STV090x_TSTTNR3); STV090x_SETFIELD(reg, ADC2_INMODE_FIELD, (config->adc2_range == STV090x_ADC_1Vpp) ? 0 : 1); if (stv090x_write_reg(state, STV090x_TSTTNR3, reg) < 0) goto err; if (stv090x_write_reg(state, STV090x_TSTRES0, 0x80) < 0) goto err; if (stv090x_write_reg(state, STV090x_TSTRES0, 0x00) < 0) goto err; return 0; err: dprintk(FE_ERROR, 1, "I/O error"); return -1; } static int stv090x_set_gpio(struct dvb_frontend *fe, u8 gpio, u8 dir, u8 value, u8 xor_value) { struct stv090x_state *state = fe->demodulator_priv; u8 reg = 0; STV090x_SETFIELD(reg, GPIOx_OPD_FIELD, dir); STV090x_SETFIELD(reg, GPIOx_CONFIG_FIELD, value); STV090x_SETFIELD(reg, GPIOx_XOR_FIELD, xor_value); return stv090x_write_reg(state, STV090x_GPIOxCFG(gpio), reg); } static const struct dvb_frontend_ops stv090x_ops = { .delsys = { SYS_DVBS, SYS_DVBS2, SYS_DSS }, .info = { .name = "STV090x Multistandard", .frequency_min = 950000, .frequency_max = 2150000, .frequency_stepsize = 0, .frequency_tolerance = 0, .symbol_rate_min = 1000000, .symbol_rate_max = 45000000, .caps = FE_CAN_INVERSION_AUTO | FE_CAN_FEC_AUTO | FE_CAN_QPSK | FE_CAN_2G_MODULATION }, .release = stv090x_release, .init = stv090x_init, .sleep = stv090x_sleep, .get_frontend_algo = stv090x_frontend_algo, .diseqc_send_master_cmd = stv090x_send_diseqc_msg, .diseqc_send_burst = stv090x_send_diseqc_burst, .diseqc_recv_slave_reply = stv090x_recv_slave_reply, .set_tone = stv090x_set_tone, .search = stv090x_search, .read_status = stv090x_read_status, .read_ber = stv090x_read_per, .read_signal_strength = stv090x_read_signal_strength, .read_snr = stv090x_read_cnr, }; struct dvb_frontend *stv090x_attach(struct stv090x_config *config, struct i2c_adapter *i2c, enum stv090x_demodulator demod) { struct stv090x_state *state = NULL; struct stv090x_dev *temp_int; state = kzalloc(sizeof (struct stv090x_state), GFP_KERNEL); if (state == NULL) goto error; state->verbose = &verbose; state->config = config; state->i2c = i2c; state->frontend.ops = stv090x_ops; state->frontend.demodulator_priv = state; state->demod = demod; state->demod_mode = config->demod_mode; /* Single or Dual mode */ state->device = config->device; state->rolloff = STV090x_RO_35; /* default */ temp_int = find_dev(state->i2c, state->config->address); if ((temp_int != NULL) && (state->demod_mode == STV090x_DUAL)) { state->internal = temp_int->internal; state->internal->num_used++; dprintk(FE_INFO, 1, "Found Internal Structure!"); } else { state->internal = kmalloc(sizeof(struct stv090x_internal), GFP_KERNEL); if (!state->internal) goto error; temp_int = append_internal(state->internal); if (!temp_int) { kfree(state->internal); goto error; } state->internal->num_used = 1; state->internal->mclk = 0; state->internal->dev_ver = 0; state->internal->i2c_adap = state->i2c; state->internal->i2c_addr = state->config->address; dprintk(FE_INFO, 1, "Create New Internal Structure!"); mutex_init(&state->internal->demod_lock); mutex_init(&state->internal->tuner_lock); if (stv090x_setup(&state->frontend) < 0) { dprintk(FE_ERROR, 1, "Error setting up device"); goto err_remove; } } if (state->internal->dev_ver >= 0x30) state->frontend.ops.info.caps |= FE_CAN_MULTISTREAM; /* workaround for stuck DiSEqC output */ if (config->diseqc_envelope_mode) stv090x_send_diseqc_burst(&state->frontend, SEC_MINI_A); config->set_gpio = stv090x_set_gpio; dprintk(FE_ERROR, 1, "Attaching %s demodulator(%d) Cut=0x%02x", state->device == STV0900 ? "STV0900" : "STV0903", demod, state->internal->dev_ver); return &state->frontend; err_remove: remove_dev(state->internal); kfree(state->internal); error: kfree(state); return NULL; } EXPORT_SYMBOL(stv090x_attach); MODULE_PARM_DESC(verbose, "Set Verbosity level"); MODULE_AUTHOR("Manu Abraham"); MODULE_DESCRIPTION("STV090x Multi-Std Broadcast frontend"); MODULE_LICENSE("GPL");
null
null
null
null
106,893
264
4,48
train_val
87c48fa3b4630905f98268dde838ee43626a060c
165,259
linux
1
https://github.com/torvalds/linux
2011-07-21 21:25:58-07:00
static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return -ENOMEM; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; } err = skb_append_datato_frags(sk,skb, getfrag, from, (length - transhdrlen)); if (!err) { struct frag_hdr fhdr; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); return 0; } /* There is not enough support do UPD LSO, * so follow normal path */ kfree_skb(skb); return err; }
CVE-2011-2699
null
https://github.com/torvalds/linux/commit/87c48fa3b4630905f98268dde838ee43626a060c
Low
3,153
1,739
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
166,734
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * net/sched/act_meta_mark.c IFE skb->mark metadata module * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * copyright Jamal Hadi Salim (2015) * */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/skbuff.h> #include <linux/rtnetlink.h> #include <linux/module.h> #include <linux/init.h> #include <net/netlink.h> #include <net/pkt_sched.h> #include <uapi/linux/tc_act/tc_ife.h> #include <net/tc_act/tc_ife.h> #include <linux/rtnetlink.h> static int skbmark_encode(struct sk_buff *skb, void *skbdata, struct tcf_meta_info *e) { u32 ifemark = skb->mark; return ife_encode_meta_u32(ifemark, skbdata, e); } static int skbmark_decode(struct sk_buff *skb, void *data, u16 len) { u32 ifemark = *(u32 *)data; skb->mark = ntohl(ifemark); return 0; } static int skbmark_check(struct sk_buff *skb, struct tcf_meta_info *e) { return ife_check_meta_u32(skb->mark, e); } static struct tcf_meta_ops ife_skbmark_ops = { .metaid = IFE_META_SKBMARK, .metatype = NLA_U32, .name = "skbmark", .synopsis = "skb mark 32 bit metadata", .check_presence = skbmark_check, .encode = skbmark_encode, .decode = skbmark_decode, .get = ife_get_meta_u32, .alloc = ife_alloc_meta_u32, .release = ife_release_meta_gen, .validate = ife_validate_meta_u32, .owner = THIS_MODULE, }; static int __init ifemark_init_module(void) { return register_ife_op(&ife_skbmark_ops); } static void __exit ifemark_cleanup_module(void) { unregister_ife_op(&ife_skbmark_ops); } module_init(ifemark_init_module); module_exit(ifemark_cleanup_module); MODULE_AUTHOR("Jamal Hadi Salim(2015)"); MODULE_DESCRIPTION("Inter-FE skb mark metadata module"); MODULE_LICENSE("GPL"); MODULE_ALIAS_IFE_META(IFE_META_SKBMARK);
null
null
null
null
75,082
42,929
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
42,929
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 "base/test/test_discardable_memory_allocator.h" #include <cstdint> #include <cstring> #include "base/logging.h" #include "base/memory/discardable_memory.h" #include "base/memory/ptr_util.h" namespace base { namespace { class DiscardableMemoryImpl : public DiscardableMemory { public: explicit DiscardableMemoryImpl(size_t size) : data_(new uint8_t[size]), size_(size) {} // Overridden from DiscardableMemory: bool Lock() override { DCHECK(!is_locked_); is_locked_ = true; return false; } void Unlock() override { DCHECK(is_locked_); is_locked_ = false; // Force eviction to catch clients not correctly checking the return value // of Lock(). memset(data_.get(), 0, size_); } void* data() const override { DCHECK(is_locked_); return data_.get(); } trace_event::MemoryAllocatorDump* CreateMemoryAllocatorDump( const char* name, trace_event::ProcessMemoryDump* pmd) const override { return nullptr; } private: bool is_locked_ = true; std::unique_ptr<uint8_t[]> data_; size_t size_; }; } // namespace std::unique_ptr<DiscardableMemory> TestDiscardableMemoryAllocator::AllocateLockedDiscardableMemory(size_t size) { return std::make_unique<DiscardableMemoryImpl>(size); } } // namespace base
null
null
null
null
39,792
20,983
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
20,983
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. #include <tuple> #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "content/common/frame_messages.h" #include "content/public/test/render_view_test.h" #include "content/renderer/render_frame_impl.h" #include "content/renderer/render_view_impl.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_size.h" #include "third_party/blink/public/web/web_view.h" // Tests for the external select popup menu (Mac specific). namespace content { namespace { const char* const kSelectID = "mySelect"; const char* const kEmptySelectID = "myEmptySelect"; } // namespace class ExternalPopupMenuTest : public RenderViewTest { public: ExternalPopupMenuTest() {} RenderViewImpl* view() { return static_cast<RenderViewImpl*>(view_); } RenderFrameImpl* frame() { return view()->GetMainRenderFrame(); } void SetUp() override { RenderViewTest::SetUp(); // We need to set this explictly as RenderMain is not run. blink::WebView::SetUseExternalPopupMenus(true); std::string html = "<select id='mySelect' onchange='selectChanged(this)'>" " <option>zero</option>" " <option selected='1'>one</option>" " <option>two</option>" "</select>" "<select id='myEmptySelect'>" "</select>"; if (ShouldRemoveSelectOnChange()) { html += "<script>" " function selectChanged(select) {" " select.parentNode.removeChild(select);" " }" "</script>"; } // Load the test page. LoadHTML(html.c_str()); // Set a minimum size and give focus so simulated events work. view()->GetWidget()->GetWebWidget()->Resize(blink::WebSize(500, 500)); view()->GetWidget()->GetWebWidget()->SetFocus(true); } int GetSelectedIndex() { base::string16 script(base::ASCIIToUTF16(kSelectID)); script.append(base::ASCIIToUTF16(".selectedIndex")); int selected_index = -1; ExecuteJavaScriptAndReturnIntValue(script, &selected_index); return selected_index; } protected: virtual bool ShouldRemoveSelectOnChange() const { return false; } DISALLOW_COPY_AND_ASSIGN(ExternalPopupMenuTest); }; // Normal case: test showing a select popup, canceling/selecting an item. TEST_F(ExternalPopupMenuTest, NormalCase) { IPC::TestSink& sink = render_thread_->sink(); // Click the text field once. EXPECT_TRUE(SimulateElementClick(kSelectID)); // We should have sent a message to the browser to show the popup menu. const IPC::Message* message = sink.GetUniqueMessageMatching(FrameHostMsg_ShowPopup::ID); ASSERT_TRUE(message != NULL); std::tuple<FrameHostMsg_ShowPopup_Params> param; FrameHostMsg_ShowPopup::Read(message, &param); ASSERT_EQ(3U, std::get<0>(param).popup_items.size()); EXPECT_EQ(1, std::get<0>(param).selected_item); // Simulate the user canceling the popup; the index should not have changed. frame()->OnSelectPopupMenuItem(-1); EXPECT_EQ(1, GetSelectedIndex()); // Show the pop-up again and this time make a selection. EXPECT_TRUE(SimulateElementClick(kSelectID)); frame()->OnSelectPopupMenuItem(0); EXPECT_EQ(0, GetSelectedIndex()); // Show the pop-up again and make another selection. sink.ClearMessages(); EXPECT_TRUE(SimulateElementClick(kSelectID)); message = sink.GetUniqueMessageMatching(FrameHostMsg_ShowPopup::ID); ASSERT_TRUE(message != NULL); FrameHostMsg_ShowPopup::Read(message, &param); ASSERT_EQ(3U, std::get<0>(param).popup_items.size()); EXPECT_EQ(0, std::get<0>(param).selected_item); } // Page shows popup, then navigates away while popup showing, then select. TEST_F(ExternalPopupMenuTest, ShowPopupThenNavigate) { // Click the text field once. EXPECT_TRUE(SimulateElementClick(kSelectID)); // Now we navigate to another pager. LoadHTML("<blink>Awesome page!</blink>"); // Now the user selects something, we should not crash. frame()->OnSelectPopupMenuItem(-1); } // An empty select should not cause a crash when clicked. // http://crbug.com/63774 TEST_F(ExternalPopupMenuTest, EmptySelect) { EXPECT_TRUE(SimulateElementClick(kEmptySelectID)); } class ExternalPopupMenuRemoveTest : public ExternalPopupMenuTest { public: ExternalPopupMenuRemoveTest() {} protected: bool ShouldRemoveSelectOnChange() const override { return true; } }; // Tests that nothing bad happen when the page removes the select when it // changes. (http://crbug.com/61997) TEST_F(ExternalPopupMenuRemoveTest, RemoveOnChange) { // Click the text field once to show the popup. EXPECT_TRUE(SimulateElementClick(kSelectID)); // Select something, it causes the select to be removed from the page. frame()->OnSelectPopupMenuItem(0); // Just to check the soundness of the test, call SimulateElementClick again. // It should return false as the select has been removed. EXPECT_FALSE(SimulateElementClick(kSelectID)); } class ExternalPopupMenuDisplayNoneTest : public ExternalPopupMenuTest { public: ExternalPopupMenuDisplayNoneTest() {} void SetUp() override { RenderViewTest::SetUp(); // We need to set this explictly as RenderMain is not run. blink::WebView::SetUseExternalPopupMenus(true); std::string html = "<select id='mySelect'>" " <option value='zero'>zero</option>" " <optgroup label='hide' style='display: none'>" " <option value='one'>one</option>" " </optgroup>" " <option value='two'>two</option>" " <option value='three'>three</option>" " <option value='four'>four</option>" " <option value='five'>five</option>" "</select>"; // Load the test page. LoadHTML(html.c_str()); // Set a minimum size and give focus so simulated events work. view()->GetWidget()->GetWebWidget()->Resize(blink::WebSize(500, 500)); view()->GetWidget()->GetWebWidget()->SetFocus(true); } }; TEST_F(ExternalPopupMenuDisplayNoneTest, SelectItem) { IPC::TestSink& sink = render_thread_->sink(); // Click the text field once to show the popup. EXPECT_TRUE(SimulateElementClick(kSelectID)); // Read the message sent to browser to show the popup menu. const IPC::Message* message = sink.GetUniqueMessageMatching(FrameHostMsg_ShowPopup::ID); ASSERT_TRUE(message != NULL); std::tuple<FrameHostMsg_ShowPopup_Params> param; FrameHostMsg_ShowPopup::Read(message, &param); // Number of items should match item count minus the number // of "display: none" items. ASSERT_EQ(5U, std::get<0>(param).popup_items.size()); // Select index 1 item. This should select item with index 2, // skipping the item with 'display: none' frame()->OnSelectPopupMenuItem(1); EXPECT_EQ(2, GetSelectedIndex()); } } // namespace content
null
null
null
null
17,846
1,721
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
154,778
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * Interplay MVE Video Decoder * Copyright (C) 2003 The FFmpeg project * * 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 */ /** * @file * Interplay MVE Video Decoder by Mike Melanson ([email protected]) * For more information about the Interplay MVE format, visit: * http://www.pcisys.net/~melanson/codecs/interplay-mve.txt * This code is written in such a way that the identifiers match up * with the encoding descriptions in the document. * * This decoder presently only supports a PAL8 output colorspace. * * An Interplay video frame consists of 2 parts: The decoding map and * the video data. A demuxer must load these 2 parts together in a single * buffer before sending it through the stream to this decoder. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libavutil/intreadwrite.h" #define BITSTREAM_READER_LE #include "avcodec.h" #include "bytestream.h" #include "get_bits.h" #include "hpeldsp.h" #include "internal.h" #define PALETTE_COUNT 256 typedef struct IpvideoContext { AVCodecContext *avctx; HpelDSPContext hdsp; AVFrame *second_last_frame; AVFrame *last_frame; /* For format 0x10 */ AVFrame *cur_decode_frame; AVFrame *prev_decode_frame; const unsigned char *decoding_map; int decoding_map_size; const unsigned char *skip_map; int skip_map_size; int is_16bpp; GetByteContext stream_ptr, mv_ptr; unsigned char *pixel_ptr; int line_inc; int stride; int upper_motion_limit_offset; uint32_t pal[256]; } IpvideoContext; static int copy_from(IpvideoContext *s, AVFrame *src, AVFrame *dst, int delta_x, int delta_y) { int current_offset = s->pixel_ptr - dst->data[0]; int motion_offset = current_offset + delta_y * dst->linesize[0] + delta_x * (1 + s->is_16bpp); if (motion_offset < 0) { av_log(s->avctx, AV_LOG_ERROR, "motion offset < 0 (%d)\n", motion_offset); return AVERROR_INVALIDDATA; } else if (motion_offset > s->upper_motion_limit_offset) { av_log(s->avctx, AV_LOG_ERROR, "motion offset above limit (%d >= %d)\n", motion_offset, s->upper_motion_limit_offset); return AVERROR_INVALIDDATA; } if (!src->data[0]) { av_log(s->avctx, AV_LOG_ERROR, "Invalid decode type, corrupted header?\n"); return AVERROR(EINVAL); } s->hdsp.put_pixels_tab[!s->is_16bpp][0](s->pixel_ptr, src->data[0] + motion_offset, dst->linesize[0], 8); return 0; } static int ipvideo_decode_block_opcode_0x0(IpvideoContext *s, AVFrame *frame) { return copy_from(s, s->last_frame, frame, 0, 0); } static int ipvideo_decode_block_opcode_0x1(IpvideoContext *s, AVFrame *frame) { return copy_from(s, s->second_last_frame, frame, 0, 0); } static int ipvideo_decode_block_opcode_0x2(IpvideoContext *s, AVFrame *frame) { unsigned char B; int x, y; /* copy block from 2 frames ago using a motion vector; need 1 more byte */ if (!s->is_16bpp) { B = bytestream2_get_byte(&s->stream_ptr); } else { B = bytestream2_get_byte(&s->mv_ptr); } if (B < 56) { x = 8 + (B % 7); y = B / 7; } else { x = -14 + ((B - 56) % 29); y = 8 + ((B - 56) / 29); } ff_tlog(s->avctx, "motion byte = %d, (x, y) = (%d, %d)\n", B, x, y); return copy_from(s, s->second_last_frame, frame, x, y); } static int ipvideo_decode_block_opcode_0x3(IpvideoContext *s, AVFrame *frame) { unsigned char B; int x, y; /* copy 8x8 block from current frame from an up/left block */ /* need 1 more byte for motion */ if (!s->is_16bpp) { B = bytestream2_get_byte(&s->stream_ptr); } else { B = bytestream2_get_byte(&s->mv_ptr); } if (B < 56) { x = -(8 + (B % 7)); y = -(B / 7); } else { x = -(-14 + ((B - 56) % 29)); y = -( 8 + ((B - 56) / 29)); } ff_tlog(s->avctx, "motion byte = %d, (x, y) = (%d, %d)\n", B, x, y); return copy_from(s, frame, frame, x, y); } static int ipvideo_decode_block_opcode_0x4(IpvideoContext *s, AVFrame *frame) { int x, y; unsigned char B, BL, BH; /* copy a block from the previous frame; need 1 more byte */ if (!s->is_16bpp) { B = bytestream2_get_byte(&s->stream_ptr); } else { B = bytestream2_get_byte(&s->mv_ptr); } BL = B & 0x0F; BH = (B >> 4) & 0x0F; x = -8 + BL; y = -8 + BH; ff_tlog(s->avctx, "motion byte = %d, (x, y) = (%d, %d)\n", B, x, y); return copy_from(s, s->last_frame, frame, x, y); } static int ipvideo_decode_block_opcode_0x5(IpvideoContext *s, AVFrame *frame) { signed char x, y; /* copy a block from the previous frame using an expanded range; * need 2 more bytes */ x = bytestream2_get_byte(&s->stream_ptr); y = bytestream2_get_byte(&s->stream_ptr); ff_tlog(s->avctx, "motion bytes = %d, %d\n", x, y); return copy_from(s, s->last_frame, frame, x, y); } static int ipvideo_decode_block_opcode_0x6(IpvideoContext *s, AVFrame *frame) { /* mystery opcode? skip multiple blocks? */ av_log(s->avctx, AV_LOG_ERROR, "Help! Mystery opcode 0x6 seen\n"); /* report success */ return 0; } static int ipvideo_decode_block_opcode_0x7(IpvideoContext *s, AVFrame *frame) { int x, y; unsigned char P[2]; unsigned int flags; if (bytestream2_get_bytes_left(&s->stream_ptr) < 4) { av_log(s->avctx, AV_LOG_ERROR, "too little data for opcode 0x7\n"); return AVERROR_INVALIDDATA; } /* 2-color encoding */ P[0] = bytestream2_get_byte(&s->stream_ptr); P[1] = bytestream2_get_byte(&s->stream_ptr); if (P[0] <= P[1]) { /* need 8 more bytes from the stream */ for (y = 0; y < 8; y++) { flags = bytestream2_get_byte(&s->stream_ptr) | 0x100; for (; flags != 1; flags >>= 1) *s->pixel_ptr++ = P[flags & 1]; s->pixel_ptr += s->line_inc; } } else { /* need 2 more bytes from the stream */ flags = bytestream2_get_le16(&s->stream_ptr); for (y = 0; y < 8; y += 2) { for (x = 0; x < 8; x += 2, flags >>= 1) { s->pixel_ptr[x ] = s->pixel_ptr[x + 1 ] = s->pixel_ptr[x + s->stride] = s->pixel_ptr[x + 1 + s->stride] = P[flags & 1]; } s->pixel_ptr += s->stride * 2; } } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0x8(IpvideoContext *s, AVFrame *frame) { int x, y; unsigned char P[4]; unsigned int flags = 0; if (bytestream2_get_bytes_left(&s->stream_ptr) < 12) { av_log(s->avctx, AV_LOG_ERROR, "too little data for opcode 0x8\n"); return AVERROR_INVALIDDATA; } /* 2-color encoding for each 4x4 quadrant, or 2-color encoding on * either top and bottom or left and right halves */ P[0] = bytestream2_get_byte(&s->stream_ptr); P[1] = bytestream2_get_byte(&s->stream_ptr); if (P[0] <= P[1]) { for (y = 0; y < 16; y++) { // new values for each 4x4 block if (!(y & 3)) { if (y) { P[0] = bytestream2_get_byte(&s->stream_ptr); P[1] = bytestream2_get_byte(&s->stream_ptr); } flags = bytestream2_get_le16(&s->stream_ptr); } for (x = 0; x < 4; x++, flags >>= 1) *s->pixel_ptr++ = P[flags & 1]; s->pixel_ptr += s->stride - 4; // switch to right half if (y == 7) s->pixel_ptr -= 8 * s->stride - 4; } } else { flags = bytestream2_get_le32(&s->stream_ptr); P[2] = bytestream2_get_byte(&s->stream_ptr); P[3] = bytestream2_get_byte(&s->stream_ptr); if (P[2] <= P[3]) { /* vertical split; left & right halves are 2-color encoded */ for (y = 0; y < 16; y++) { for (x = 0; x < 4; x++, flags >>= 1) *s->pixel_ptr++ = P[flags & 1]; s->pixel_ptr += s->stride - 4; // switch to right half if (y == 7) { s->pixel_ptr -= 8 * s->stride - 4; P[0] = P[2]; P[1] = P[3]; flags = bytestream2_get_le32(&s->stream_ptr); } } } else { /* horizontal split; top & bottom halves are 2-color encoded */ for (y = 0; y < 8; y++) { if (y == 4) { P[0] = P[2]; P[1] = P[3]; flags = bytestream2_get_le32(&s->stream_ptr); } for (x = 0; x < 8; x++, flags >>= 1) *s->pixel_ptr++ = P[flags & 1]; s->pixel_ptr += s->line_inc; } } } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0x9(IpvideoContext *s, AVFrame *frame) { int x, y; unsigned char P[4]; if (bytestream2_get_bytes_left(&s->stream_ptr) < 8) { av_log(s->avctx, AV_LOG_ERROR, "too little data for opcode 0x9\n"); return AVERROR_INVALIDDATA; } /* 4-color encoding */ bytestream2_get_buffer(&s->stream_ptr, P, 4); if (P[0] <= P[1]) { if (P[2] <= P[3]) { /* 1 of 4 colors for each pixel, need 16 more bytes */ for (y = 0; y < 8; y++) { /* get the next set of 8 2-bit flags */ int flags = bytestream2_get_le16(&s->stream_ptr); for (x = 0; x < 8; x++, flags >>= 2) *s->pixel_ptr++ = P[flags & 0x03]; s->pixel_ptr += s->line_inc; } } else { uint32_t flags; /* 1 of 4 colors for each 2x2 block, need 4 more bytes */ flags = bytestream2_get_le32(&s->stream_ptr); for (y = 0; y < 8; y += 2) { for (x = 0; x < 8; x += 2, flags >>= 2) { s->pixel_ptr[x ] = s->pixel_ptr[x + 1 ] = s->pixel_ptr[x + s->stride] = s->pixel_ptr[x + 1 + s->stride] = P[flags & 0x03]; } s->pixel_ptr += s->stride * 2; } } } else { uint64_t flags; /* 1 of 4 colors for each 2x1 or 1x2 block, need 8 more bytes */ flags = bytestream2_get_le64(&s->stream_ptr); if (P[2] <= P[3]) { for (y = 0; y < 8; y++) { for (x = 0; x < 8; x += 2, flags >>= 2) { s->pixel_ptr[x ] = s->pixel_ptr[x + 1] = P[flags & 0x03]; } s->pixel_ptr += s->stride; } } else { for (y = 0; y < 8; y += 2) { for (x = 0; x < 8; x++, flags >>= 2) { s->pixel_ptr[x ] = s->pixel_ptr[x + s->stride] = P[flags & 0x03]; } s->pixel_ptr += s->stride * 2; } } } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xA(IpvideoContext *s, AVFrame *frame) { int x, y; unsigned char P[8]; int flags = 0; if (bytestream2_get_bytes_left(&s->stream_ptr) < 16) { av_log(s->avctx, AV_LOG_ERROR, "too little data for opcode 0xA\n"); return AVERROR_INVALIDDATA; } bytestream2_get_buffer(&s->stream_ptr, P, 4); /* 4-color encoding for each 4x4 quadrant, or 4-color encoding on * either top and bottom or left and right halves */ if (P[0] <= P[1]) { /* 4-color encoding for each quadrant; need 32 bytes */ for (y = 0; y < 16; y++) { // new values for each 4x4 block if (!(y & 3)) { if (y) bytestream2_get_buffer(&s->stream_ptr, P, 4); flags = bytestream2_get_le32(&s->stream_ptr); } for (x = 0; x < 4; x++, flags >>= 2) *s->pixel_ptr++ = P[flags & 0x03]; s->pixel_ptr += s->stride - 4; // switch to right half if (y == 7) s->pixel_ptr -= 8 * s->stride - 4; } } else { // vertical split? int vert; uint64_t flags = bytestream2_get_le64(&s->stream_ptr); bytestream2_get_buffer(&s->stream_ptr, P + 4, 4); vert = P[4] <= P[5]; /* 4-color encoding for either left and right or top and bottom * halves */ for (y = 0; y < 16; y++) { for (x = 0; x < 4; x++, flags >>= 2) *s->pixel_ptr++ = P[flags & 0x03]; if (vert) { s->pixel_ptr += s->stride - 4; // switch to right half if (y == 7) s->pixel_ptr -= 8 * s->stride - 4; } else if (y & 1) s->pixel_ptr += s->line_inc; // load values for second half if (y == 7) { memcpy(P, P + 4, 4); flags = bytestream2_get_le64(&s->stream_ptr); } } } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xB(IpvideoContext *s, AVFrame *frame) { int y; /* 64-color encoding (each pixel in block is a different color) */ for (y = 0; y < 8; y++) { bytestream2_get_buffer(&s->stream_ptr, s->pixel_ptr, 8); s->pixel_ptr += s->stride; } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xC(IpvideoContext *s, AVFrame *frame) { int x, y; /* 16-color block encoding: each 2x2 block is a different color */ for (y = 0; y < 8; y += 2) { for (x = 0; x < 8; x += 2) { s->pixel_ptr[x ] = s->pixel_ptr[x + 1 ] = s->pixel_ptr[x + s->stride] = s->pixel_ptr[x + 1 + s->stride] = bytestream2_get_byte(&s->stream_ptr); } s->pixel_ptr += s->stride * 2; } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xD(IpvideoContext *s, AVFrame *frame) { int y; unsigned char P[2]; if (bytestream2_get_bytes_left(&s->stream_ptr) < 4) { av_log(s->avctx, AV_LOG_ERROR, "too little data for opcode 0xD\n"); return AVERROR_INVALIDDATA; } /* 4-color block encoding: each 4x4 block is a different color */ for (y = 0; y < 8; y++) { if (!(y & 3)) { P[0] = bytestream2_get_byte(&s->stream_ptr); P[1] = bytestream2_get_byte(&s->stream_ptr); } memset(s->pixel_ptr, P[0], 4); memset(s->pixel_ptr + 4, P[1], 4); s->pixel_ptr += s->stride; } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xE(IpvideoContext *s, AVFrame *frame) { int y; unsigned char pix; /* 1-color encoding: the whole block is 1 solid color */ pix = bytestream2_get_byte(&s->stream_ptr); for (y = 0; y < 8; y++) { memset(s->pixel_ptr, pix, 8); s->pixel_ptr += s->stride; } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xF(IpvideoContext *s, AVFrame *frame) { int x, y; unsigned char sample[2]; /* dithered encoding */ sample[0] = bytestream2_get_byte(&s->stream_ptr); sample[1] = bytestream2_get_byte(&s->stream_ptr); for (y = 0; y < 8; y++) { for (x = 0; x < 8; x += 2) { *s->pixel_ptr++ = sample[ y & 1 ]; *s->pixel_ptr++ = sample[!(y & 1)]; } s->pixel_ptr += s->line_inc; } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0x6_16(IpvideoContext *s, AVFrame *frame) { signed char x, y; /* copy a block from the second last frame using an expanded range */ x = bytestream2_get_byte(&s->stream_ptr); y = bytestream2_get_byte(&s->stream_ptr); ff_tlog(s->avctx, "motion bytes = %d, %d\n", x, y); return copy_from(s, s->second_last_frame, frame, x, y); } static int ipvideo_decode_block_opcode_0x7_16(IpvideoContext *s, AVFrame *frame) { int x, y; uint16_t P[2]; unsigned int flags; uint16_t *pixel_ptr = (uint16_t*)s->pixel_ptr; /* 2-color encoding */ P[0] = bytestream2_get_le16(&s->stream_ptr); P[1] = bytestream2_get_le16(&s->stream_ptr); if (!(P[0] & 0x8000)) { for (y = 0; y < 8; y++) { flags = bytestream2_get_byte(&s->stream_ptr) | 0x100; for (; flags != 1; flags >>= 1) *pixel_ptr++ = P[flags & 1]; pixel_ptr += s->line_inc; } } else { flags = bytestream2_get_le16(&s->stream_ptr); for (y = 0; y < 8; y += 2) { for (x = 0; x < 8; x += 2, flags >>= 1) { pixel_ptr[x ] = pixel_ptr[x + 1 ] = pixel_ptr[x + s->stride] = pixel_ptr[x + 1 + s->stride] = P[flags & 1]; } pixel_ptr += s->stride * 2; } } return 0; } static int ipvideo_decode_block_opcode_0x8_16(IpvideoContext *s, AVFrame *frame) { int x, y; uint16_t P[4]; unsigned int flags = 0; uint16_t *pixel_ptr = (uint16_t*)s->pixel_ptr; /* 2-color encoding for each 4x4 quadrant, or 2-color encoding on * either top and bottom or left and right halves */ P[0] = bytestream2_get_le16(&s->stream_ptr); P[1] = bytestream2_get_le16(&s->stream_ptr); if (!(P[0] & 0x8000)) { for (y = 0; y < 16; y++) { // new values for each 4x4 block if (!(y & 3)) { if (y) { P[0] = bytestream2_get_le16(&s->stream_ptr); P[1] = bytestream2_get_le16(&s->stream_ptr); } flags = bytestream2_get_le16(&s->stream_ptr); } for (x = 0; x < 4; x++, flags >>= 1) *pixel_ptr++ = P[flags & 1]; pixel_ptr += s->stride - 4; // switch to right half if (y == 7) pixel_ptr -= 8 * s->stride - 4; } } else { flags = bytestream2_get_le32(&s->stream_ptr); P[2] = bytestream2_get_le16(&s->stream_ptr); P[3] = bytestream2_get_le16(&s->stream_ptr); if (!(P[2] & 0x8000)) { /* vertical split; left & right halves are 2-color encoded */ for (y = 0; y < 16; y++) { for (x = 0; x < 4; x++, flags >>= 1) *pixel_ptr++ = P[flags & 1]; pixel_ptr += s->stride - 4; // switch to right half if (y == 7) { pixel_ptr -= 8 * s->stride - 4; P[0] = P[2]; P[1] = P[3]; flags = bytestream2_get_le32(&s->stream_ptr); } } } else { /* horizontal split; top & bottom halves are 2-color encoded */ for (y = 0; y < 8; y++) { if (y == 4) { P[0] = P[2]; P[1] = P[3]; flags = bytestream2_get_le32(&s->stream_ptr); } for (x = 0; x < 8; x++, flags >>= 1) *pixel_ptr++ = P[flags & 1]; pixel_ptr += s->line_inc; } } } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0x9_16(IpvideoContext *s, AVFrame *frame) { int x, y; uint16_t P[4]; uint16_t *pixel_ptr = (uint16_t*)s->pixel_ptr; /* 4-color encoding */ for (x = 0; x < 4; x++) P[x] = bytestream2_get_le16(&s->stream_ptr); if (!(P[0] & 0x8000)) { if (!(P[2] & 0x8000)) { /* 1 of 4 colors for each pixel */ for (y = 0; y < 8; y++) { /* get the next set of 8 2-bit flags */ int flags = bytestream2_get_le16(&s->stream_ptr); for (x = 0; x < 8; x++, flags >>= 2) *pixel_ptr++ = P[flags & 0x03]; pixel_ptr += s->line_inc; } } else { uint32_t flags; /* 1 of 4 colors for each 2x2 block */ flags = bytestream2_get_le32(&s->stream_ptr); for (y = 0; y < 8; y += 2) { for (x = 0; x < 8; x += 2, flags >>= 2) { pixel_ptr[x ] = pixel_ptr[x + 1 ] = pixel_ptr[x + s->stride] = pixel_ptr[x + 1 + s->stride] = P[flags & 0x03]; } pixel_ptr += s->stride * 2; } } } else { uint64_t flags; /* 1 of 4 colors for each 2x1 or 1x2 block */ flags = bytestream2_get_le64(&s->stream_ptr); if (!(P[2] & 0x8000)) { for (y = 0; y < 8; y++) { for (x = 0; x < 8; x += 2, flags >>= 2) { pixel_ptr[x ] = pixel_ptr[x + 1] = P[flags & 0x03]; } pixel_ptr += s->stride; } } else { for (y = 0; y < 8; y += 2) { for (x = 0; x < 8; x++, flags >>= 2) { pixel_ptr[x ] = pixel_ptr[x + s->stride] = P[flags & 0x03]; } pixel_ptr += s->stride * 2; } } } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xA_16(IpvideoContext *s, AVFrame *frame) { int x, y; uint16_t P[8]; int flags = 0; uint16_t *pixel_ptr = (uint16_t*)s->pixel_ptr; for (x = 0; x < 4; x++) P[x] = bytestream2_get_le16(&s->stream_ptr); /* 4-color encoding for each 4x4 quadrant, or 4-color encoding on * either top and bottom or left and right halves */ if (!(P[0] & 0x8000)) { /* 4-color encoding for each quadrant */ for (y = 0; y < 16; y++) { // new values for each 4x4 block if (!(y & 3)) { if (y) for (x = 0; x < 4; x++) P[x] = bytestream2_get_le16(&s->stream_ptr); flags = bytestream2_get_le32(&s->stream_ptr); } for (x = 0; x < 4; x++, flags >>= 2) *pixel_ptr++ = P[flags & 0x03]; pixel_ptr += s->stride - 4; // switch to right half if (y == 7) pixel_ptr -= 8 * s->stride - 4; } } else { // vertical split? int vert; uint64_t flags = bytestream2_get_le64(&s->stream_ptr); for (x = 4; x < 8; x++) P[x] = bytestream2_get_le16(&s->stream_ptr); vert = !(P[4] & 0x8000); /* 4-color encoding for either left and right or top and bottom * halves */ for (y = 0; y < 16; y++) { for (x = 0; x < 4; x++, flags >>= 2) *pixel_ptr++ = P[flags & 0x03]; if (vert) { pixel_ptr += s->stride - 4; // switch to right half if (y == 7) pixel_ptr -= 8 * s->stride - 4; } else if (y & 1) pixel_ptr += s->line_inc; // load values for second half if (y == 7) { memcpy(P, P + 4, 8); flags = bytestream2_get_le64(&s->stream_ptr); } } } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xB_16(IpvideoContext *s, AVFrame *frame) { int x, y; uint16_t *pixel_ptr = (uint16_t*)s->pixel_ptr; /* 64-color encoding (each pixel in block is a different color) */ for (y = 0; y < 8; y++) { for (x = 0; x < 8; x++) pixel_ptr[x] = bytestream2_get_le16(&s->stream_ptr); pixel_ptr += s->stride; } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xC_16(IpvideoContext *s, AVFrame *frame) { int x, y; uint16_t *pixel_ptr = (uint16_t*)s->pixel_ptr; /* 16-color block encoding: each 2x2 block is a different color */ for (y = 0; y < 8; y += 2) { for (x = 0; x < 8; x += 2) { pixel_ptr[x ] = pixel_ptr[x + 1 ] = pixel_ptr[x + s->stride] = pixel_ptr[x + 1 + s->stride] = bytestream2_get_le16(&s->stream_ptr); } pixel_ptr += s->stride * 2; } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xD_16(IpvideoContext *s, AVFrame *frame) { int x, y; uint16_t P[2]; uint16_t *pixel_ptr = (uint16_t*)s->pixel_ptr; /* 4-color block encoding: each 4x4 block is a different color */ for (y = 0; y < 8; y++) { if (!(y & 3)) { P[0] = bytestream2_get_le16(&s->stream_ptr); P[1] = bytestream2_get_le16(&s->stream_ptr); } for (x = 0; x < 8; x++) pixel_ptr[x] = P[x >> 2]; pixel_ptr += s->stride; } /* report success */ return 0; } static int ipvideo_decode_block_opcode_0xE_16(IpvideoContext *s, AVFrame *frame) { int x, y; uint16_t pix; uint16_t *pixel_ptr = (uint16_t*)s->pixel_ptr; /* 1-color encoding: the whole block is 1 solid color */ pix = bytestream2_get_le16(&s->stream_ptr); for (y = 0; y < 8; y++) { for (x = 0; x < 8; x++) pixel_ptr[x] = pix; pixel_ptr += s->stride; } /* report success */ return 0; } static int (* const ipvideo_decode_block[])(IpvideoContext *s, AVFrame *frame) = { ipvideo_decode_block_opcode_0x0, ipvideo_decode_block_opcode_0x1, ipvideo_decode_block_opcode_0x2, ipvideo_decode_block_opcode_0x3, ipvideo_decode_block_opcode_0x4, ipvideo_decode_block_opcode_0x5, ipvideo_decode_block_opcode_0x6, ipvideo_decode_block_opcode_0x7, ipvideo_decode_block_opcode_0x8, ipvideo_decode_block_opcode_0x9, ipvideo_decode_block_opcode_0xA, ipvideo_decode_block_opcode_0xB, ipvideo_decode_block_opcode_0xC, ipvideo_decode_block_opcode_0xD, ipvideo_decode_block_opcode_0xE, ipvideo_decode_block_opcode_0xF, }; static int (* const ipvideo_decode_block16[])(IpvideoContext *s, AVFrame *frame) = { ipvideo_decode_block_opcode_0x0, ipvideo_decode_block_opcode_0x1, ipvideo_decode_block_opcode_0x2, ipvideo_decode_block_opcode_0x3, ipvideo_decode_block_opcode_0x4, ipvideo_decode_block_opcode_0x5, ipvideo_decode_block_opcode_0x6_16, ipvideo_decode_block_opcode_0x7_16, ipvideo_decode_block_opcode_0x8_16, ipvideo_decode_block_opcode_0x9_16, ipvideo_decode_block_opcode_0xA_16, ipvideo_decode_block_opcode_0xB_16, ipvideo_decode_block_opcode_0xC_16, ipvideo_decode_block_opcode_0xD_16, ipvideo_decode_block_opcode_0xE_16, ipvideo_decode_block_opcode_0x1, }; static void ipvideo_format_06_firstpass(IpvideoContext *s, AVFrame *frame, int16_t opcode) { int line; if (!opcode) { for (line = 0; line < 8; ++line) { bytestream2_get_buffer(&s->stream_ptr, s->pixel_ptr, 8); s->pixel_ptr += s->stride; } } else { /* Don't try to copy second_last_frame data on the first frames */ if (s->avctx->frame_number > 2) copy_from(s, s->second_last_frame, frame, 0, 0); } } static void ipvideo_format_06_secondpass(IpvideoContext *s, AVFrame *frame, int16_t opcode) { int off_x, off_y; if (opcode < 0) { off_x = ((uint16_t)opcode - 0xC000) % frame->linesize[0]; off_y = ((uint16_t)opcode - 0xC000) / frame->linesize[0]; copy_from(s, s->last_frame, frame, off_x, off_y); } else if (opcode > 0) { off_x = ((uint16_t)opcode - 0x4000) % frame->linesize[0]; off_y = ((uint16_t)opcode - 0x4000) / frame->linesize[0]; copy_from(s, frame, frame, off_x, off_y); } } static void (* const ipvideo_format_06_passes[])(IpvideoContext *s, AVFrame *frame, int16_t op) = { ipvideo_format_06_firstpass, ipvideo_format_06_secondpass, }; static void ipvideo_decode_format_06_opcodes(IpvideoContext *s, AVFrame *frame) { int pass, x, y; int16_t opcode; GetByteContext decoding_map_ptr; /* this is PAL8, so make the palette available */ memcpy(frame->data[1], s->pal, AVPALETTE_SIZE); s->stride = frame->linesize[0]; s->line_inc = s->stride - 8; s->upper_motion_limit_offset = (s->avctx->height - 8) * frame->linesize[0] + (s->avctx->width - 8) * (1 + s->is_16bpp); bytestream2_init(&decoding_map_ptr, s->decoding_map, s->decoding_map_size); for (pass = 0; pass < 2; ++pass) { bytestream2_seek(&decoding_map_ptr, 0, SEEK_SET); for (y = 0; y < s->avctx->height; y += 8) { for (x = 0; x < s->avctx->width; x += 8) { opcode = bytestream2_get_le16(&decoding_map_ptr); ff_tlog(s->avctx, " block @ (%3d, %3d): opcode 0x%X, data ptr offset %d\n", x, y, opcode, bytestream2_tell(&s->stream_ptr)); s->pixel_ptr = frame->data[0] + x + y * frame->linesize[0]; ipvideo_format_06_passes[pass](s, frame, opcode); } } } if (bytestream2_get_bytes_left(&s->stream_ptr) > 1) { av_log(s->avctx, AV_LOG_DEBUG, "decode finished with %d bytes left over\n", bytestream2_get_bytes_left(&s->stream_ptr)); } } static void ipvideo_format_10_firstpass(IpvideoContext *s, AVFrame *frame, int16_t opcode) { int line; if (!opcode) { for (line = 0; line < 8; ++line) { bytestream2_get_buffer(&s->stream_ptr, s->pixel_ptr, 8); s->pixel_ptr += s->stride; } } } static void ipvideo_format_10_secondpass(IpvideoContext *s, AVFrame *frame, int16_t opcode) { int off_x, off_y; if (opcode < 0) { off_x = ((uint16_t)opcode - 0xC000) % s->cur_decode_frame->linesize[0]; off_y = ((uint16_t)opcode - 0xC000) / s->cur_decode_frame->linesize[0]; copy_from(s, s->prev_decode_frame, s->cur_decode_frame, off_x, off_y); } else if (opcode > 0) { off_x = ((uint16_t)opcode - 0x4000) % s->cur_decode_frame->linesize[0]; off_y = ((uint16_t)opcode - 0x4000) / s->cur_decode_frame->linesize[0]; copy_from(s, s->cur_decode_frame, s->cur_decode_frame, off_x, off_y); } } static void (* const ipvideo_format_10_passes[])(IpvideoContext *s, AVFrame *frame, int16_t op) = { ipvideo_format_10_firstpass, ipvideo_format_10_secondpass, }; static void ipvideo_decode_format_10_opcodes(IpvideoContext *s, AVFrame *frame) { int pass, x, y, changed_block; int16_t opcode, skip; GetByteContext decoding_map_ptr; GetByteContext skip_map_ptr; bytestream2_skip(&s->stream_ptr, 14); /* data starts 14 bytes in */ /* this is PAL8, so make the palette available */ memcpy(frame->data[1], s->pal, AVPALETTE_SIZE); s->stride = frame->linesize[0]; s->line_inc = s->stride - 8; s->upper_motion_limit_offset = (s->avctx->height - 8) * frame->linesize[0] + (s->avctx->width - 8) * (1 + s->is_16bpp); bytestream2_init(&decoding_map_ptr, s->decoding_map, s->decoding_map_size); bytestream2_init(&skip_map_ptr, s->skip_map, s->skip_map_size); for (pass = 0; pass < 2; ++pass) { bytestream2_seek(&decoding_map_ptr, 0, SEEK_SET); bytestream2_seek(&skip_map_ptr, 0, SEEK_SET); skip = bytestream2_get_le16(&skip_map_ptr); for (y = 0; y < s->avctx->height; y += 8) { for (x = 0; x < s->avctx->width; x += 8) { s->pixel_ptr = s->cur_decode_frame->data[0] + x + y * s->cur_decode_frame->linesize[0]; while (skip <= 0) { if (skip != -0x8000 && skip) { opcode = bytestream2_get_le16(&decoding_map_ptr); ipvideo_format_10_passes[pass](s, frame, opcode); break; } if (bytestream2_get_bytes_left(&skip_map_ptr) < 2) return; skip = bytestream2_get_le16(&skip_map_ptr); } skip *= 2; } } } bytestream2_seek(&skip_map_ptr, 0, SEEK_SET); skip = bytestream2_get_le16(&skip_map_ptr); for (y = 0; y < s->avctx->height; y += 8) { for (x = 0; x < s->avctx->width; x += 8) { changed_block = 0; s->pixel_ptr = frame->data[0] + x + y*frame->linesize[0]; while (skip <= 0) { if (skip != -0x8000 && skip) { changed_block = 1; break; } if (bytestream2_get_bytes_left(&skip_map_ptr) < 2) return; skip = bytestream2_get_le16(&skip_map_ptr); } if (changed_block) { copy_from(s, s->cur_decode_frame, frame, 0, 0); } else { /* Don't try to copy last_frame data on the first frame */ if (s->avctx->frame_number) copy_from(s, s->last_frame, frame, 0, 0); } skip *= 2; } } FFSWAP(AVFrame*, s->prev_decode_frame, s->cur_decode_frame); if (bytestream2_get_bytes_left(&s->stream_ptr) > 1) { av_log(s->avctx, AV_LOG_DEBUG, "decode finished with %d bytes left over\n", bytestream2_get_bytes_left(&s->stream_ptr)); } } static void ipvideo_decode_format_11_opcodes(IpvideoContext *s, AVFrame *frame) { int x, y; unsigned char opcode; int ret; GetBitContext gb; bytestream2_skip(&s->stream_ptr, 14); /* data starts 14 bytes in */ if (!s->is_16bpp) { /* this is PAL8, so make the palette available */ memcpy(frame->data[1], s->pal, AVPALETTE_SIZE); s->stride = frame->linesize[0]; } else { s->stride = frame->linesize[0] >> 1; s->mv_ptr = s->stream_ptr; bytestream2_skip(&s->mv_ptr, bytestream2_get_le16(&s->stream_ptr)); } s->line_inc = s->stride - 8; s->upper_motion_limit_offset = (s->avctx->height - 8) * frame->linesize[0] + (s->avctx->width - 8) * (1 + s->is_16bpp); init_get_bits(&gb, s->decoding_map, s->decoding_map_size * 8); for (y = 0; y < s->avctx->height; y += 8) { for (x = 0; x < s->avctx->width; x += 8) { if (get_bits_left(&gb) < 4) return; opcode = get_bits(&gb, 4); ff_tlog(s->avctx, " block @ (%3d, %3d): encoding 0x%X, data ptr offset %d\n", x, y, opcode, bytestream2_tell(&s->stream_ptr)); if (!s->is_16bpp) { s->pixel_ptr = frame->data[0] + x + y*frame->linesize[0]; ret = ipvideo_decode_block[opcode](s, frame); } else { s->pixel_ptr = frame->data[0] + x*2 + y*frame->linesize[0]; ret = ipvideo_decode_block16[opcode](s, frame); } if (ret != 0) { av_log(s->avctx, AV_LOG_ERROR, "decode problem on frame %d, @ block (%d, %d)\n", s->avctx->frame_number, x, y); return; } } } if (bytestream2_get_bytes_left(&s->stream_ptr) > 1) { av_log(s->avctx, AV_LOG_DEBUG, "decode finished with %d bytes left over\n", bytestream2_get_bytes_left(&s->stream_ptr)); } } static av_cold int ipvideo_decode_init(AVCodecContext *avctx) { IpvideoContext *s = avctx->priv_data; int ret; s->avctx = avctx; s->is_16bpp = avctx->bits_per_coded_sample == 16; avctx->pix_fmt = s->is_16bpp ? AV_PIX_FMT_RGB555 : AV_PIX_FMT_PAL8; ff_hpeldsp_init(&s->hdsp, avctx->flags); s->last_frame = av_frame_alloc(); s->second_last_frame = av_frame_alloc(); s->cur_decode_frame = av_frame_alloc(); s->prev_decode_frame = av_frame_alloc(); if (!s->last_frame || !s->second_last_frame || !s->cur_decode_frame || !s->prev_decode_frame) { ret = AVERROR(ENOMEM); goto error; } s->cur_decode_frame->width = avctx->width; s->prev_decode_frame->width = avctx->width; s->cur_decode_frame->height = avctx->height; s->prev_decode_frame->height = avctx->height; s->cur_decode_frame->format = avctx->pix_fmt; s->prev_decode_frame->format = avctx->pix_fmt; ret = ff_get_buffer(avctx, s->cur_decode_frame, 0); if (ret < 0) goto error; ret = ff_get_buffer(avctx, s->prev_decode_frame, 0); if (ret < 0) goto error; return 0; error: av_frame_free(&s->last_frame); av_frame_free(&s->second_last_frame); av_frame_free(&s->cur_decode_frame); av_frame_free(&s->prev_decode_frame); return ret; } static int ipvideo_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; IpvideoContext *s = avctx->priv_data; AVFrame *frame = data; int ret; int send_buffer; int frame_format; int video_data_size; if (av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, NULL)) { av_frame_unref(s->last_frame); av_frame_unref(s->second_last_frame); av_frame_unref(s->cur_decode_frame); av_frame_unref(s->prev_decode_frame); } if (!s->cur_decode_frame->data[0]) { ret = ff_get_buffer(avctx, s->cur_decode_frame, 0); if (ret < 0) return ret; ret = ff_get_buffer(avctx, s->prev_decode_frame, 0); if (ret < 0) { av_frame_unref(s->cur_decode_frame); return ret; } } if (buf_size < 8) return AVERROR_INVALIDDATA; frame_format = AV_RL8(buf); send_buffer = AV_RL8(buf + 1); video_data_size = AV_RL16(buf + 2); s->decoding_map_size = AV_RL16(buf + 4); s->skip_map_size = AV_RL16(buf + 6); switch(frame_format) { case 0x06: if (s->decoding_map_size) { av_log(avctx, AV_LOG_ERROR, "Decoding map for format 0x06\n"); return AVERROR_INVALIDDATA; } if (s->skip_map_size) { av_log(avctx, AV_LOG_ERROR, "Skip map for format 0x06\n"); return AVERROR_INVALIDDATA; } if (s->is_16bpp) { av_log(avctx, AV_LOG_ERROR, "Video format 0x06 does not support 16bpp movies\n"); return AVERROR_INVALIDDATA; } /* Decoding map for 0x06 frame format is at the top of pixeldata */ s->decoding_map_size = ((s->avctx->width / 8) * (s->avctx->height / 8)) * 2; s->decoding_map = buf + 8 + 14; /* 14 bits of op data */ video_data_size -= s->decoding_map_size + 14; if (video_data_size <= 0) return AVERROR_INVALIDDATA; if (buf_size < 8 + s->decoding_map_size + 14 + video_data_size) return AVERROR_INVALIDDATA; bytestream2_init(&s->stream_ptr, buf + 8 + s->decoding_map_size + 14, video_data_size); break; case 0x10: if (! s->decoding_map_size) { av_log(avctx, AV_LOG_ERROR, "Empty decoding map for format 0x10\n"); return AVERROR_INVALIDDATA; } if (! s->skip_map_size) { av_log(avctx, AV_LOG_ERROR, "Empty skip map for format 0x10\n"); return AVERROR_INVALIDDATA; } if (s->is_16bpp) { av_log(avctx, AV_LOG_ERROR, "Video format 0x10 does not support 16bpp movies\n"); return AVERROR_INVALIDDATA; } if (buf_size < 8 + video_data_size + s->decoding_map_size + s->skip_map_size) return AVERROR_INVALIDDATA; bytestream2_init(&s->stream_ptr, buf + 8, video_data_size); s->decoding_map = buf + 8 + video_data_size; s->skip_map = buf + 8 + video_data_size + s->decoding_map_size; break; case 0x11: if (! s->decoding_map_size) { av_log(avctx, AV_LOG_ERROR, "Empty decoding map for format 0x11\n"); return AVERROR_INVALIDDATA; } if (s->skip_map_size) { av_log(avctx, AV_LOG_ERROR, "Skip map for format 0x11\n"); return AVERROR_INVALIDDATA; } if (buf_size < 8 + video_data_size + s->decoding_map_size) return AVERROR_INVALIDDATA; bytestream2_init(&s->stream_ptr, buf + 8, video_data_size); s->decoding_map = buf + 8 + video_data_size; break; default: av_log(avctx, AV_LOG_ERROR, "Frame type 0x%02X unsupported\n", frame_format); } /* ensure we can't overread the packet */ if (buf_size < 8 + s->decoding_map_size + video_data_size + s->skip_map_size) { av_log(avctx, AV_LOG_ERROR, "Invalid IP packet size\n"); return AVERROR_INVALIDDATA; } if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0) return ret; if (!s->is_16bpp) { int size; const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &size); if (pal && size == AVPALETTE_SIZE) { frame->palette_has_changed = 1; memcpy(s->pal, pal, AVPALETTE_SIZE); } else if (pal) { av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size); } } switch(frame_format) { case 0x06: ipvideo_decode_format_06_opcodes(s, frame); break; case 0x10: ipvideo_decode_format_10_opcodes(s, frame); break; case 0x11: ipvideo_decode_format_11_opcodes(s, frame); break; } *got_frame = send_buffer; /* shuffle frames */ av_frame_unref(s->second_last_frame); FFSWAP(AVFrame*, s->second_last_frame, s->last_frame); if ((ret = av_frame_ref(s->last_frame, frame)) < 0) return ret; /* report that the buffer was completely consumed */ return buf_size; } static av_cold int ipvideo_decode_end(AVCodecContext *avctx) { IpvideoContext *s = avctx->priv_data; av_frame_free(&s->last_frame); av_frame_free(&s->second_last_frame); av_frame_free(&s->cur_decode_frame); av_frame_free(&s->prev_decode_frame); return 0; } AVCodec ff_interplay_video_decoder = { .name = "interplayvideo", .long_name = NULL_IF_CONFIG_SMALL("Interplay MVE video"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_INTERPLAY_VIDEO, .priv_data_size = sizeof(IpvideoContext), .init = ipvideo_decode_init, .close = ipvideo_decode_end, .decode = ipvideo_decode_frame, .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_PARAM_CHANGE, };
null
null
null
null
70,833
35,684
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
35,684
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2009 Igalia S.L. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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. */ #include "third_party/blink/renderer/core/editing/commands/editor_command.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_editing_command_type.h" #include "third_party/blink/renderer/bindings/core/v8/exception_state.h" #include "third_party/blink/renderer/core/css/css_property_value_set.h" #include "third_party/blink/renderer/core/css_property_names.h" #include "third_party/blink/renderer/core/css_value_keywords.h" #include "third_party/blink/renderer/core/dom/events/event.h" #include "third_party/blink/renderer/core/dom/tag_collection.h" #include "third_party/blink/renderer/core/editing/commands/clipboard_commands.h" #include "third_party/blink/renderer/core/editing/commands/create_link_command.h" #include "third_party/blink/renderer/core/editing/commands/editing_commands_utilities.h" #include "third_party/blink/renderer/core/editing/commands/editor_command_names.h" #include "third_party/blink/renderer/core/editing/commands/format_block_command.h" #include "third_party/blink/renderer/core/editing/commands/indent_outdent_command.h" #include "third_party/blink/renderer/core/editing/commands/insert_commands.h" #include "third_party/blink/renderer/core/editing/commands/move_commands.h" #include "third_party/blink/renderer/core/editing/commands/remove_format_command.h" #include "third_party/blink/renderer/core/editing/commands/style_commands.h" #include "third_party/blink/renderer/core/editing/commands/typing_command.h" #include "third_party/blink/renderer/core/editing/commands/unlink_command.h" #include "third_party/blink/renderer/core/editing/editing_tri_state.h" #include "third_party/blink/renderer/core/editing/editing_utilities.h" #include "third_party/blink/renderer/core/editing/editor.h" #include "third_party/blink/renderer/core/editing/ephemeral_range.h" #include "third_party/blink/renderer/core/editing/frame_selection.h" #include "third_party/blink/renderer/core/editing/iterators/text_iterator.h" #include "third_party/blink/renderer/core/editing/selection_modifier.h" #include "third_party/blink/renderer/core/editing/selection_template.h" #include "third_party/blink/renderer/core/editing/set_selection_options.h" #include "third_party/blink/renderer/core/editing/spellcheck/spell_checker.h" #include "third_party/blink/renderer/core/editing/visible_position.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/html_names.h" #include "third_party/blink/renderer/core/input/event_handler.h" #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/platform/histogram.h" #include "third_party/blink/renderer/platform/kill_ring.h" #include "third_party/blink/renderer/platform/scroll/scrollbar.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" #include <iterator> namespace blink { using namespace HTMLNames; namespace { struct CommandNameEntry { const char* name; WebEditingCommandType type; }; const CommandNameEntry kCommandNameEntries[] = { #define V(name) {#name, WebEditingCommandType::k##name}, FOR_EACH_BLINK_EDITING_COMMAND_NAME(V) #undef V }; // Handles all commands except WebEditingCommandType::Invalid. static_assert( arraysize(kCommandNameEntries) + 1 == static_cast<size_t>(WebEditingCommandType::kNumberOfCommandTypes), "must handle all valid WebEditingCommandType"); WebEditingCommandType WebEditingCommandTypeFromCommandName( const String& command_name) { const CommandNameEntry* result = std::lower_bound( std::begin(kCommandNameEntries), std::end(kCommandNameEntries), command_name, [](const CommandNameEntry& entry, const String& needle) { return CodePointCompareIgnoringASCIICase(needle, entry.name) > 0; }); if (result != std::end(kCommandNameEntries) && CodePointCompareIgnoringASCIICase(command_name, result->name) == 0) return result->type; return WebEditingCommandType::kInvalid; } // |frame| is only used for |InsertNewline| due to how |executeInsertNewline()| // works. InputEvent::InputType InputTypeFromCommandType( WebEditingCommandType command_type, LocalFrame& frame) { // We only handle InputType on spec for 'beforeinput'. // http://w3c.github.io/editing/input-events.html using CommandType = WebEditingCommandType; using InputType = InputEvent::InputType; // |executeInsertNewline()| could do two things but we have no other ways to // predict. if (command_type == CommandType::kInsertNewline) return frame.GetEditor().CanEditRichly() ? InputType::kInsertParagraph : InputType::kInsertLineBreak; switch (command_type) { // Insertion. case CommandType::kInsertBacktab: case CommandType::kInsertText: return InputType::kInsertText; case CommandType::kInsertLineBreak: return InputType::kInsertLineBreak; case CommandType::kInsertParagraph: case CommandType::kInsertNewlineInQuotedContent: return InputType::kInsertParagraph; case CommandType::kInsertHorizontalRule: return InputType::kInsertHorizontalRule; case CommandType::kInsertOrderedList: return InputType::kInsertOrderedList; case CommandType::kInsertUnorderedList: return InputType::kInsertUnorderedList; // Deletion. case CommandType::kDelete: case CommandType::kDeleteBackward: case CommandType::kDeleteBackwardByDecomposingPreviousCharacter: return InputType::kDeleteContentBackward; case CommandType::kDeleteForward: return InputType::kDeleteContentForward; case CommandType::kDeleteToBeginningOfLine: return InputType::kDeleteSoftLineBackward; case CommandType::kDeleteToEndOfLine: return InputType::kDeleteSoftLineForward; case CommandType::kDeleteWordBackward: return InputType::kDeleteWordBackward; case CommandType::kDeleteWordForward: return InputType::kDeleteWordForward; case CommandType::kDeleteToBeginningOfParagraph: return InputType::kDeleteHardLineBackward; case CommandType::kDeleteToEndOfParagraph: return InputType::kDeleteHardLineForward; // TODO(chongz): Find appreciate InputType for following commands. case CommandType::kDeleteToMark: return InputType::kNone; // Command. case CommandType::kUndo: return InputType::kHistoryUndo; case CommandType::kRedo: return InputType::kHistoryRedo; // Cut and Paste will be handled in |Editor::dispatchCPPEvent()|. // Styling. case CommandType::kBold: case CommandType::kToggleBold: return InputType::kFormatBold; case CommandType::kItalic: case CommandType::kToggleItalic: return InputType::kFormatItalic; case CommandType::kUnderline: case CommandType::kToggleUnderline: return InputType::kFormatUnderline; case CommandType::kStrikethrough: return InputType::kFormatStrikeThrough; case CommandType::kSuperscript: return InputType::kFormatSuperscript; case CommandType::kSubscript: return InputType::kFormatSubscript; default: return InputType::kNone; } } StaticRangeVector* RangesFromCurrentSelectionOrExtendCaret( const LocalFrame& frame, SelectionModifyDirection direction, TextGranularity granularity) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); SelectionModifier selection_modifier( frame, frame.Selection().GetSelectionInDOMTree()); selection_modifier.SetSelectionIsDirectional( frame.Selection().IsDirectional()); if (selection_modifier.Selection().IsCaret()) selection_modifier.Modify(SelectionModifyAlteration::kExtend, direction, granularity); StaticRangeVector* ranges = new StaticRangeVector; // We only supports single selections. if (selection_modifier.Selection().IsNone()) return ranges; ranges->push_back(StaticRange::Create( FirstEphemeralRangeOf(selection_modifier.Selection()))); return ranges; } EphemeralRange ComputeRangeForTranspose(LocalFrame& frame) { const VisibleSelection& selection = frame.Selection().ComputeVisibleSelectionInDOMTree(); if (!selection.IsCaret()) return EphemeralRange(); // Make a selection that goes back one character and forward two characters. const VisiblePosition& caret = selection.VisibleStart(); const VisiblePosition& next = IsEndOfParagraph(caret) ? caret : NextPositionOf(caret); const VisiblePosition& previous = PreviousPositionOf(next); if (next.DeepEquivalent() == previous.DeepEquivalent()) return EphemeralRange(); const VisiblePosition& previous_of_previous = PreviousPositionOf(previous); if (!InSameParagraph(next, previous_of_previous)) return EphemeralRange(); return MakeRange(previous_of_previous, next); } } // anonymous namespace class EditorInternalCommand { public: WebEditingCommandType command_type; bool (*execute)(LocalFrame&, Event*, EditorCommandSource, const String&); bool (*is_supported_from_dom)(LocalFrame*); bool (*is_enabled)(LocalFrame&, Event*, EditorCommandSource); EditingTriState (*state)(LocalFrame&, Event*); String (*value)(const EditorInternalCommand&, LocalFrame&, Event*); bool is_text_insertion; bool (*can_execute)(LocalFrame&, EditorCommandSource); }; static const bool kNotTextInsertion = false; static const bool kIsTextInsertion = true; static bool ExecuteApplyParagraphStyle(LocalFrame& frame, EditorCommandSource source, InputEvent::InputType input_type, CSSPropertyID property_id, const String& property_value) { MutableCSSPropertyValueSet* style = MutableCSSPropertyValueSet::Create(kHTMLQuirksMode); style->SetProperty(property_id, property_value, /* important */ false, frame.GetDocument()->GetSecureContextMode()); // FIXME: We don't call shouldApplyStyle when the source is DOM; is there a // good reason for that? switch (source) { case EditorCommandSource::kMenuOrKeyBinding: frame.GetEditor().ApplyParagraphStyleToSelection(style, input_type); return true; case EditorCommandSource::kDOM: frame.GetEditor().ApplyParagraphStyle(style, input_type); return true; } NOTREACHED(); return false; } bool ExpandSelectionToGranularity(LocalFrame& frame, TextGranularity granularity) { const VisibleSelection& selection = CreateVisibleSelectionWithGranularity( SelectionInDOMTree::Builder() .SetBaseAndExtent( frame.Selection().ComputeVisibleSelectionInDOMTree().Base(), frame.Selection().ComputeVisibleSelectionInDOMTree().Extent()) .Build(), granularity); const EphemeralRange new_range = selection.ToNormalizedEphemeralRange(); if (new_range.IsNull()) return false; if (new_range.IsCollapsed()) return false; frame.Selection().SetSelection( SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build(), SetSelectionOptions::Builder().SetShouldCloseTyping(true).Build()); return true; } static bool HasChildTags(Element& element, const QualifiedName& tag_name) { return !element.getElementsByTagName(tag_name.LocalName())->IsEmpty(); } static EditingTriState SelectionListState(const FrameSelection& selection, const QualifiedName& tag_name) { if (selection.ComputeVisibleSelectionInDOMTreeDeprecated().IsCaret()) { if (EnclosingElementWithTag( selection.ComputeVisibleSelectionInDOMTreeDeprecated().Start(), tag_name)) return EditingTriState::kTrue; } else if (selection.ComputeVisibleSelectionInDOMTreeDeprecated().IsRange()) { Element* start_element = EnclosingElementWithTag( selection.ComputeVisibleSelectionInDOMTreeDeprecated().Start(), tag_name); Element* end_element = EnclosingElementWithTag( selection.ComputeVisibleSelectionInDOMTreeDeprecated().End(), tag_name); if (start_element && end_element && start_element == end_element) { // If the selected list has the different type of list as child, return // |FalseTriState|. // See http://crbug.com/385374 if (HasChildTags(*start_element, tag_name.Matches(ulTag) ? olTag : ulTag)) return EditingTriState::kFalse; return EditingTriState::kTrue; } } return EditingTriState::kFalse; } static EphemeralRange UnionEphemeralRanges(const EphemeralRange& range1, const EphemeralRange& range2) { const Position start_position = range1.StartPosition().CompareTo(range2.StartPosition()) <= 0 ? range1.StartPosition() : range2.StartPosition(); const Position end_position = range1.EndPosition().CompareTo(range2.EndPosition()) <= 0 ? range1.EndPosition() : range2.EndPosition(); return EphemeralRange(start_position, end_position); } // Execute command functions static bool CanSmartCopyOrDelete(LocalFrame& frame) { return frame.GetEditor().SmartInsertDeleteEnabled() && frame.Selection().Granularity() == TextGranularity::kWord; } static bool ExecuteCreateLink(LocalFrame& frame, Event*, EditorCommandSource, const String& value) { if (value.IsEmpty()) return false; DCHECK(frame.GetDocument()); return CreateLinkCommand::Create(*frame.GetDocument(), value)->Apply(); } static bool ExecuteDefaultParagraphSeparator(LocalFrame& frame, Event*, EditorCommandSource, const String& value) { if (DeprecatedEqualIgnoringCase(value, "div")) { frame.GetEditor().SetDefaultParagraphSeparator( EditorParagraphSeparator::kIsDiv); return true; } if (DeprecatedEqualIgnoringCase(value, "p")) { frame.GetEditor().SetDefaultParagraphSeparator( EditorParagraphSeparator::kIsP); } return true; } static void PerformDelete(LocalFrame& frame) { if (!frame.GetEditor().CanDelete()) return; // TODO(editing-dev): The use of UpdateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. // |SelectedRange| requires clean layout for visible selection normalization. frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); frame.GetEditor().AddToKillRing(frame.GetEditor().SelectedRange()); // TODO(chongz): |Editor::performDelete()| has no direction. // https://github.com/w3c/editing/issues/130 frame.GetEditor().DeleteSelectionWithSmartDelete( CanSmartCopyOrDelete(frame) ? DeleteMode::kSmart : DeleteMode::kSimple, InputEvent::InputType::kDeleteContentBackward); // clear the "start new kill ring sequence" setting, because it was set to // true when the selection was updated by deleting the range frame.GetEditor().SetStartNewKillRingSequence(false); } static bool ExecuteDelete(LocalFrame& frame, Event*, EditorCommandSource source, const String&) { switch (source) { case EditorCommandSource::kMenuOrKeyBinding: { // Doesn't modify the text if the current selection isn't a range. PerformDelete(frame); return true; } case EditorCommandSource::kDOM: // If the current selection is a caret, delete the preceding character. IE // performs forwardDelete, but we currently side with Firefox. Doesn't // scroll to make the selection visible, or modify the kill ring (this // time, siding with IE, not Firefox). DCHECK(frame.GetDocument()); TypingCommand::DeleteKeyPressed( *frame.GetDocument(), frame.Selection().Granularity() == TextGranularity::kWord ? TypingCommand::kSmartDelete : 0); return true; } NOTREACHED(); return false; } static bool DeleteWithDirection(LocalFrame& frame, DeleteDirection direction, TextGranularity granularity, bool kill_ring, bool is_typing_action) { Editor& editor = frame.GetEditor(); if (!editor.CanEdit()) return false; EditingState editing_state; if (frame.Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() .IsRange()) { if (is_typing_action) { DCHECK(frame.GetDocument()); TypingCommand::DeleteKeyPressed( *frame.GetDocument(), CanSmartCopyOrDelete(frame) ? TypingCommand::kSmartDelete : 0, granularity); editor.RevealSelectionAfterEditingOperation(); } else { if (kill_ring) editor.AddToKillRing(editor.SelectedRange()); editor.DeleteSelectionWithSmartDelete( CanSmartCopyOrDelete(frame) ? DeleteMode::kSmart : DeleteMode::kSimple, DeletionInputTypeFromTextGranularity(direction, granularity)); // Implicitly calls revealSelectionAfterEditingOperation(). } } else { TypingCommand::Options options = 0; if (CanSmartCopyOrDelete(frame)) options |= TypingCommand::kSmartDelete; if (kill_ring) options |= TypingCommand::kKillRing; switch (direction) { case DeleteDirection::kForward: DCHECK(frame.GetDocument()); TypingCommand::ForwardDeleteKeyPressed( *frame.GetDocument(), &editing_state, options, granularity); if (editing_state.IsAborted()) return false; break; case DeleteDirection::kBackward: DCHECK(frame.GetDocument()); TypingCommand::DeleteKeyPressed(*frame.GetDocument(), options, granularity); break; } editor.RevealSelectionAfterEditingOperation(); } // FIXME: We should to move this down into deleteKeyPressed. // clear the "start new kill ring sequence" setting, because it was set to // true when the selection was updated by deleting the range if (kill_ring) editor.SetStartNewKillRingSequence(false); return true; } static bool ExecuteDeleteBackward(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DeleteWithDirection(frame, DeleteDirection::kBackward, TextGranularity::kCharacter, false, true); return true; } static bool ExecuteDeleteBackwardByDecomposingPreviousCharacter( LocalFrame& frame, Event*, EditorCommandSource, const String&) { DLOG(ERROR) << "DeleteBackwardByDecomposingPreviousCharacter is not " "implemented, doing DeleteBackward instead"; DeleteWithDirection(frame, DeleteDirection::kBackward, TextGranularity::kCharacter, false, true); return true; } static bool ExecuteDeleteForward(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DeleteWithDirection(frame, DeleteDirection::kForward, TextGranularity::kCharacter, false, true); return true; } static bool ExecuteDeleteToBeginningOfLine(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DeleteWithDirection(frame, DeleteDirection::kBackward, TextGranularity::kLineBoundary, true, false); return true; } static bool ExecuteDeleteToBeginningOfParagraph(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DeleteWithDirection(frame, DeleteDirection::kBackward, TextGranularity::kParagraphBoundary, true, false); return true; } static bool ExecuteDeleteToEndOfLine(LocalFrame& frame, Event*, EditorCommandSource, const String&) { // Despite its name, this command should delete the newline at the end of a // paragraph if you are at the end of a paragraph (like // DeleteToEndOfParagraph). DeleteWithDirection(frame, DeleteDirection::kForward, TextGranularity::kLineBoundary, true, false); return true; } static bool ExecuteDeleteToEndOfParagraph(LocalFrame& frame, Event*, EditorCommandSource, const String&) { // Despite its name, this command should delete the newline at the end of // a paragraph if you are at the end of a paragraph. DeleteWithDirection(frame, DeleteDirection::kForward, TextGranularity::kParagraphBoundary, true, false); return true; } static bool ExecuteDeleteToMark(LocalFrame& frame, Event*, EditorCommandSource, const String&) { const EphemeralRange mark = frame.GetEditor().Mark().ToNormalizedEphemeralRange(); if (mark.IsNotNull()) { frame.Selection().SetSelection( SelectionInDOMTree::Builder() .SetBaseAndExtent( UnionEphemeralRanges(mark, frame.GetEditor().SelectedRange())) .Build(), SetSelectionOptions::Builder().SetShouldCloseTyping(true).Build()); } PerformDelete(frame); // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); frame.GetEditor().SetMark(); return true; } static bool ExecuteDeleteWordBackward(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DeleteWithDirection(frame, DeleteDirection::kBackward, TextGranularity::kWord, true, false); return true; } static bool ExecuteDeleteWordForward(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DeleteWithDirection(frame, DeleteDirection::kForward, TextGranularity::kWord, true, false); return true; } static bool ExecuteFindString(LocalFrame& frame, Event*, EditorCommandSource, const String& value) { return Editor::FindString(frame, value, kCaseInsensitive | kWrapAround); } static bool ExecuteFormatBlock(LocalFrame& frame, Event*, EditorCommandSource, const String& value) { String tag_name = value.DeprecatedLower(); if (tag_name[0] == '<' && tag_name[tag_name.length() - 1] == '>') tag_name = tag_name.Substring(1, tag_name.length() - 2); AtomicString local_name, prefix; if (!Document::ParseQualifiedName(AtomicString(tag_name), prefix, local_name, IGNORE_EXCEPTION_FOR_TESTING)) return false; QualifiedName qualified_tag_name(prefix, local_name, xhtmlNamespaceURI); DCHECK(frame.GetDocument()); FormatBlockCommand* command = FormatBlockCommand::Create(*frame.GetDocument(), qualified_tag_name); command->Apply(); return command->DidApply(); } static bool ExecuteForwardDelete(LocalFrame& frame, Event*, EditorCommandSource source, const String&) { EditingState editing_state; switch (source) { case EditorCommandSource::kMenuOrKeyBinding: DeleteWithDirection(frame, DeleteDirection::kForward, TextGranularity::kCharacter, false, true); return true; case EditorCommandSource::kDOM: // Doesn't scroll to make the selection visible, or modify the kill ring. // ForwardDelete is not implemented in IE or Firefox, so this behavior is // only needed for backward compatibility with ourselves, and for // consistency with Delete. DCHECK(frame.GetDocument()); TypingCommand::ForwardDeleteKeyPressed(*frame.GetDocument(), &editing_state); if (editing_state.IsAborted()) return false; return true; } NOTREACHED(); return false; } static bool ExecuteIgnoreSpelling(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.GetSpellChecker().IgnoreSpelling(); return true; } static bool ExecuteIndent(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DCHECK(frame.GetDocument()); return IndentOutdentCommand::Create(*frame.GetDocument(), IndentOutdentCommand::kIndent) ->Apply(); } static bool ExecuteJustifyCenter(LocalFrame& frame, Event*, EditorCommandSource source, const String&) { return ExecuteApplyParagraphStyle(frame, source, InputEvent::InputType::kFormatJustifyCenter, CSSPropertyTextAlign, "center"); } static bool ExecuteJustifyFull(LocalFrame& frame, Event*, EditorCommandSource source, const String&) { return ExecuteApplyParagraphStyle(frame, source, InputEvent::InputType::kFormatJustifyFull, CSSPropertyTextAlign, "justify"); } static bool ExecuteJustifyLeft(LocalFrame& frame, Event*, EditorCommandSource source, const String&) { return ExecuteApplyParagraphStyle(frame, source, InputEvent::InputType::kFormatJustifyLeft, CSSPropertyTextAlign, "left"); } static bool ExecuteJustifyRight(LocalFrame& frame, Event*, EditorCommandSource source, const String&) { return ExecuteApplyParagraphStyle(frame, source, InputEvent::InputType::kFormatJustifyRight, CSSPropertyTextAlign, "right"); } static bool ExecuteOutdent(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DCHECK(frame.GetDocument()); return IndentOutdentCommand::Create(*frame.GetDocument(), IndentOutdentCommand::kOutdent) ->Apply(); } static bool ExecuteToggleOverwrite(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.GetEditor().ToggleOverwriteModeEnabled(); return true; } static bool ExecutePrint(LocalFrame& frame, Event*, EditorCommandSource, const String&) { Page* page = frame.GetPage(); if (!page) return false; return page->GetChromeClient().Print(&frame); } static bool ExecuteRedo(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.GetEditor().Redo(); return true; } static bool ExecuteRemoveFormat(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DCHECK(frame.GetDocument()); RemoveFormatCommand::Create(*frame.GetDocument())->Apply(); return true; } static bool ExecuteScrollPageBackward(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return frame.GetEventHandler().BubblingScroll(kScrollBlockDirectionBackward, kScrollByPage); } static bool ExecuteScrollPageForward(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return frame.GetEventHandler().BubblingScroll(kScrollBlockDirectionForward, kScrollByPage); } static bool ExecuteScrollLineUp(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return frame.GetEventHandler().BubblingScroll(kScrollUpIgnoringWritingMode, kScrollByLine); } static bool ExecuteScrollLineDown(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return frame.GetEventHandler().BubblingScroll(kScrollDownIgnoringWritingMode, kScrollByLine); } static bool ExecuteScrollToBeginningOfDocument(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return frame.GetEventHandler().BubblingScroll(kScrollBlockDirectionBackward, kScrollByDocument); } static bool ExecuteScrollToEndOfDocument(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return frame.GetEventHandler().BubblingScroll(kScrollBlockDirectionForward, kScrollByDocument); } static bool ExecuteSelectAll(LocalFrame& frame, Event*, EditorCommandSource source, const String&) { const SetSelectionBy set_selection_by = source == EditorCommandSource::kMenuOrKeyBinding ? SetSelectionBy::kUser : SetSelectionBy::kSystem; frame.Selection().SelectAll(set_selection_by); return true; } static bool ExecuteSelectLine(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return ExpandSelectionToGranularity(frame, TextGranularity::kLine); } static bool ExecuteSelectParagraph(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return ExpandSelectionToGranularity(frame, TextGranularity::kParagraph); } static bool ExecuteSelectSentence(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return ExpandSelectionToGranularity(frame, TextGranularity::kSentence); } static bool ExecuteSelectToMark(LocalFrame& frame, Event*, EditorCommandSource, const String&) { const EphemeralRange mark = frame.GetEditor().Mark().ToNormalizedEphemeralRange(); EphemeralRange selection = frame.GetEditor().SelectedRange(); if (mark.IsNull() || selection.IsNull()) return false; frame.Selection().SetSelection( SelectionInDOMTree::Builder() .SetBaseAndExtent(UnionEphemeralRanges(mark, selection)) .Build(), SetSelectionOptions::Builder().SetShouldCloseTyping(true).Build()); return true; } static bool ExecuteSelectWord(LocalFrame& frame, Event*, EditorCommandSource, const String&) { return ExpandSelectionToGranularity(frame, TextGranularity::kWord); } static bool ExecuteSetMark(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.GetEditor().SetMark(); return true; } static bool ExecuteSwapWithMark(LocalFrame& frame, Event*, EditorCommandSource, const String&) { const VisibleSelection mark(frame.GetEditor().Mark()); const VisibleSelection& selection = frame.Selection().ComputeVisibleSelectionInDOMTreeDeprecated(); const bool mark_is_directional = frame.GetEditor().MarkIsDirectional(); if (mark.IsNone() || selection.IsNone()) return false; frame.GetEditor().SetMark(); frame.Selection().SetSelection(mark.AsSelection(), SetSelectionOptions::Builder() .SetIsDirectional(mark_is_directional) .Build()); return true; } static bool ExecuteTranspose(LocalFrame& frame, Event*, EditorCommandSource, const String&) { Editor& editor = frame.GetEditor(); if (!editor.CanEdit()) return false; Document* const document = frame.GetDocument(); // TODO(editing-dev): The use of UpdateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. document->UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& range = ComputeRangeForTranspose(frame); if (range.IsNull()) return false; // Transpose the two characters. const String& text = PlainText(range); if (text.length() != 2) return false; const String& transposed = text.Right(1) + text.Left(1); if (DispatchBeforeInputInsertText( EventTargetNodeForDocument(document), transposed, InputEvent::InputType::kInsertTranspose, new StaticRangeVector(1, StaticRange::Create(range))) != DispatchEventResult::kNotCanceled) return false; // 'beforeinput' event handler may destroy document-> if (frame.GetDocument() != document) return false; // TODO(editing-dev): The use of UpdateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. document->UpdateStyleAndLayoutIgnorePendingStylesheets(); // 'beforeinput' event handler may change selection, we need to re-calculate // range. const EphemeralRange& new_range = ComputeRangeForTranspose(frame); if (new_range.IsNull()) return false; const String& new_text = PlainText(new_range); if (new_text.length() != 2) return false; const String& new_transposed = new_text.Right(1) + new_text.Left(1); const SelectionInDOMTree& new_selection = SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build(); // Select the two characters. if (CreateVisibleSelection(new_selection) != frame.Selection().ComputeVisibleSelectionInDOMTree()) frame.Selection().SetSelectionAndEndTyping(new_selection); // Insert the transposed characters. editor.ReplaceSelectionWithText(new_transposed, false, false, InputEvent::InputType::kInsertTranspose); return true; } static bool ExecuteUndo(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.GetEditor().Undo(); return true; } static bool ExecuteUnlink(LocalFrame& frame, Event*, EditorCommandSource, const String&) { DCHECK(frame.GetDocument()); return UnlinkCommand::Create(*frame.GetDocument())->Apply(); } static bool ExecuteUnselect(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.Selection().Clear(); return true; } static bool ExecuteYank(LocalFrame& frame, Event*, EditorCommandSource, const String&) { const String& yank_string = frame.GetEditor().GetKillRing().Yank(); if (DispatchBeforeInputInsertText( EventTargetNodeForDocument(frame.GetDocument()), yank_string, InputEvent::InputType::kInsertFromYank) != DispatchEventResult::kNotCanceled) return true; // 'beforeinput' event handler may destroy document. if (frame.GetDocument()->GetFrame() != &frame) return false; // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. see http://crbug.com/590369 for more details. frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); frame.GetEditor().InsertTextWithoutSendingTextEvent( yank_string, false, nullptr, InputEvent::InputType::kInsertFromYank); frame.GetEditor().GetKillRing().SetToYankedState(); return true; } static bool ExecuteYankAndSelect(LocalFrame& frame, Event*, EditorCommandSource, const String&) { const String& yank_string = frame.GetEditor().GetKillRing().Yank(); if (DispatchBeforeInputInsertText( EventTargetNodeForDocument(frame.GetDocument()), yank_string, InputEvent::InputType::kInsertFromYank) != DispatchEventResult::kNotCanceled) return true; // 'beforeinput' event handler may destroy document. if (frame.GetDocument()->GetFrame() != &frame) return false; // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. see http://crbug.com/590369 for more details. frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); frame.GetEditor().InsertTextWithoutSendingTextEvent( frame.GetEditor().GetKillRing().Yank(), true, nullptr, InputEvent::InputType::kInsertFromYank); frame.GetEditor().GetKillRing().SetToYankedState(); return true; } // Supported functions static bool Supported(LocalFrame*) { return true; } static bool SupportedFromMenuOrKeyBinding(LocalFrame*) { return false; } // Enabled functions static bool Enabled(LocalFrame&, Event*, EditorCommandSource) { return true; } static bool EnabledVisibleSelection(LocalFrame& frame, Event* event, EditorCommandSource source) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); if (source == EditorCommandSource::kMenuOrKeyBinding && !frame.Selection().SelectionHasFocus()) return false; // The term "visible" here includes a caret in editable text or a range in any // text. const VisibleSelection& selection = CreateVisibleSelection(frame.GetEditor().SelectionForCommand(event)); return (selection.IsCaret() && selection.IsContentEditable()) || selection.IsRange(); } static bool EnabledVisibleSelectionAndMark(LocalFrame& frame, Event* event, EditorCommandSource source) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); if (source == EditorCommandSource::kMenuOrKeyBinding && !frame.Selection().SelectionHasFocus()) return false; const VisibleSelection& selection = CreateVisibleSelection(frame.GetEditor().SelectionForCommand(event)); return ((selection.IsCaret() && selection.IsContentEditable()) || selection.IsRange()) && !frame.GetEditor().Mark().IsNone(); } static bool EnableCaretInEditableText(LocalFrame& frame, Event* event, EditorCommandSource source) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); if (source == EditorCommandSource::kMenuOrKeyBinding && !frame.Selection().SelectionHasFocus()) return false; const VisibleSelection& selection = CreateVisibleSelection(frame.GetEditor().SelectionForCommand(event)); return selection.IsCaret() && selection.IsContentEditable(); } static bool EnabledInEditableText(LocalFrame& frame, Event* event, EditorCommandSource source) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); if (source == EditorCommandSource::kMenuOrKeyBinding && !frame.Selection().SelectionHasFocus()) return false; const SelectionInDOMTree selection = frame.GetEditor().SelectionForCommand(event); return RootEditableElementOf( CreateVisiblePosition(selection.Base()).DeepEquivalent()); } static bool EnabledDelete(LocalFrame& frame, Event* event, EditorCommandSource source) { switch (source) { case EditorCommandSource::kMenuOrKeyBinding: return frame.Selection().SelectionHasFocus() && frame.GetEditor().CanDelete(); case EditorCommandSource::kDOM: // "Delete" from DOM is like delete/backspace keypress, affects selected // range if non-empty, otherwise removes a character return EnabledInEditableText(frame, event, source); } NOTREACHED(); return false; } static bool EnabledInRichlyEditableText(LocalFrame& frame, Event*, EditorCommandSource source) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); if (source == EditorCommandSource::kMenuOrKeyBinding && !frame.Selection().SelectionHasFocus()) return false; const VisibleSelection& selection = frame.Selection().ComputeVisibleSelectionInDOMTree(); return !selection.IsNone() && IsRichlyEditablePosition(selection.Base()) && selection.RootEditableElement(); } static bool EnabledRangeInEditableText(LocalFrame& frame, Event*, EditorCommandSource source) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); if (source == EditorCommandSource::kMenuOrKeyBinding && !frame.Selection().SelectionHasFocus()) return false; return frame.Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() .IsRange() && frame.Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() .IsContentEditable(); } static bool EnabledRangeInRichlyEditableText(LocalFrame& frame, Event*, EditorCommandSource source) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); if (source == EditorCommandSource::kMenuOrKeyBinding && !frame.Selection().SelectionHasFocus()) return false; const VisibleSelection& selection = frame.Selection().ComputeVisibleSelectionInDOMTree(); return selection.IsRange() && IsRichlyEditablePosition(selection.Base()); } static bool EnabledRedo(LocalFrame& frame, Event*, EditorCommandSource) { return frame.GetEditor().CanRedo(); } static bool EnabledUndo(LocalFrame& frame, Event*, EditorCommandSource) { return frame.GetEditor().CanUndo(); } static bool EnabledUnselect(LocalFrame& frame, Event* event, EditorCommandSource) { frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); // The term "visible" here includes a caret in editable text or a range in any // text. const VisibleSelection& selection = CreateVisibleSelection(frame.GetEditor().SelectionForCommand(event)); return (selection.IsCaret() && selection.IsContentEditable()) || selection.IsRange(); } static bool EnabledSelectAll(LocalFrame& frame, Event*, EditorCommandSource source) { // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. frame.GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); const VisibleSelection& selection = frame.Selection().ComputeVisibleSelectionInDOMTree(); if (selection.IsNone()) return true; // Hidden selection appears as no selection to users, in which case user- // triggered SelectAll should be enabled and act as if there is no selection. if (source == EditorCommandSource::kMenuOrKeyBinding && frame.Selection().IsHidden()) return true; if (Node* root = HighestEditableRoot(selection.Start())) { if (!root->hasChildren()) return false; // TODO(amaralp): Return false if already fully selected. } // TODO(amaralp): Address user-select handling. return true; } // State functions static EditingTriState StateNone(LocalFrame&, Event*) { return EditingTriState::kFalse; } EditingTriState StateOrderedList(LocalFrame& frame, Event*) { return SelectionListState(frame.Selection(), olTag); } static EditingTriState StateUnorderedList(LocalFrame& frame, Event*) { return SelectionListState(frame.Selection(), ulTag); } static EditingTriState StateJustifyCenter(LocalFrame& frame, Event*) { return StyleCommands::StateStyle(frame, CSSPropertyTextAlign, "center"); } static EditingTriState StateJustifyFull(LocalFrame& frame, Event*) { return StyleCommands::StateStyle(frame, CSSPropertyTextAlign, "justify"); } static EditingTriState StateJustifyLeft(LocalFrame& frame, Event*) { return StyleCommands::StateStyle(frame, CSSPropertyTextAlign, "left"); } static EditingTriState StateJustifyRight(LocalFrame& frame, Event*) { return StyleCommands::StateStyle(frame, CSSPropertyTextAlign, "right"); } // Value functions static String ValueStateOrNull(const EditorInternalCommand& self, LocalFrame& frame, Event* triggering_event) { if (self.state == StateNone) return String(); return self.state(frame, triggering_event) == EditingTriState::kTrue ? "true" : "false"; } // The command has no value. // https://w3c.github.io/editing/execCommand.html#querycommandvalue() // > ... or has no value, return the empty string. static String ValueEmpty(const EditorInternalCommand&, LocalFrame&, Event*) { return g_empty_string; } static String ValueDefaultParagraphSeparator(const EditorInternalCommand&, LocalFrame& frame, Event*) { switch (frame.GetEditor().DefaultParagraphSeparator()) { case EditorParagraphSeparator::kIsDiv: return divTag.LocalName(); case EditorParagraphSeparator::kIsP: return pTag.LocalName(); } NOTREACHED(); return String(); } static String ValueFormatBlock(const EditorInternalCommand&, LocalFrame& frame, Event*) { const VisibleSelection& selection = frame.Selection().ComputeVisibleSelectionInDOMTreeDeprecated(); if (selection.IsNone() || !selection.IsValidFor(*(frame.GetDocument())) || !selection.IsContentEditable()) return ""; Element* format_block_element = FormatBlockCommand::ElementForFormatBlockCommand( FirstEphemeralRangeOf(selection)); if (!format_block_element) return ""; return format_block_element->localName(); } // CanExectue functions static bool CanNotExecuteWhenDisabled(LocalFrame&, EditorCommandSource) { return false; } // Map of functions static const EditorInternalCommand* InternalCommand( const String& command_name) { static const EditorInternalCommand kEditorCommands[] = { // Lists all commands in blink::WebEditingCommandType. // Must be ordered by |commandType| for index lookup. // Covered by unit tests in EditingCommandTest.cpp {WebEditingCommandType::kAlignJustified, ExecuteJustifyFull, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kAlignLeft, ExecuteJustifyLeft, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kAlignRight, ExecuteJustifyRight, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kBackColor, StyleCommands::ExecuteBackColor, Supported, EnabledInRichlyEditableText, StateNone, StyleCommands::ValueBackColor, kNotTextInsertion, CanNotExecuteWhenDisabled}, // FIXME: remove BackwardDelete when Safari for Windows stops using it. {WebEditingCommandType::kBackwardDelete, ExecuteDeleteBackward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kBold, StyleCommands::ExecuteToggleBold, Supported, EnabledInRichlyEditableText, StyleCommands::StateBold, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kCopy, ClipboardCommands::ExecuteCopy, Supported, ClipboardCommands::EnabledCopy, StateNone, ValueStateOrNull, kNotTextInsertion, ClipboardCommands::CanWriteClipboard}, {WebEditingCommandType::kCreateLink, ExecuteCreateLink, Supported, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kCut, ClipboardCommands::ExecuteCut, Supported, ClipboardCommands::EnabledCut, StateNone, ValueStateOrNull, kNotTextInsertion, ClipboardCommands::CanWriteClipboard}, {WebEditingCommandType::kDefaultParagraphSeparator, ExecuteDefaultParagraphSeparator, Supported, Enabled, StateNone, ValueDefaultParagraphSeparator, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDelete, ExecuteDelete, Supported, EnabledDelete, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteBackward, ExecuteDeleteBackward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteBackwardByDecomposingPreviousCharacter, ExecuteDeleteBackwardByDecomposingPreviousCharacter, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteForward, ExecuteDeleteForward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteToBeginningOfLine, ExecuteDeleteToBeginningOfLine, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteToBeginningOfParagraph, ExecuteDeleteToBeginningOfParagraph, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteToEndOfLine, ExecuteDeleteToEndOfLine, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteToEndOfParagraph, ExecuteDeleteToEndOfParagraph, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteToMark, ExecuteDeleteToMark, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteWordBackward, ExecuteDeleteWordBackward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kDeleteWordForward, ExecuteDeleteWordForward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kFindString, ExecuteFindString, Supported, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kFontName, StyleCommands::ExecuteFontName, Supported, EnabledInRichlyEditableText, StateNone, StyleCommands::ValueFontName, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kFontSize, StyleCommands::ExecuteFontSize, Supported, EnabledInRichlyEditableText, StateNone, StyleCommands::ValueFontSize, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kFontSizeDelta, StyleCommands::ExecuteFontSizeDelta, Supported, EnabledInRichlyEditableText, StateNone, StyleCommands::ValueFontSizeDelta, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kForeColor, StyleCommands::ExecuteForeColor, Supported, EnabledInRichlyEditableText, StateNone, StyleCommands::ValueForeColor, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kFormatBlock, ExecuteFormatBlock, Supported, EnabledInRichlyEditableText, StateNone, ValueFormatBlock, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kForwardDelete, ExecuteForwardDelete, Supported, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kHiliteColor, StyleCommands::ExecuteBackColor, Supported, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kIgnoreSpelling, ExecuteIgnoreSpelling, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kIndent, ExecuteIndent, Supported, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertBacktab, InsertCommands::ExecuteInsertBacktab, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kIsTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertHTML, InsertCommands::ExecuteInsertHTML, Supported, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertHorizontalRule, InsertCommands::ExecuteInsertHorizontalRule, Supported, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertImage, InsertCommands::ExecuteInsertImage, Supported, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertLineBreak, InsertCommands::ExecuteInsertLineBreak, Supported, EnabledInEditableText, StateNone, ValueStateOrNull, kIsTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertNewline, InsertCommands::ExecuteInsertNewline, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kIsTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertNewlineInQuotedContent, InsertCommands::ExecuteInsertNewlineInQuotedContent, Supported, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertOrderedList, InsertCommands::ExecuteInsertOrderedList, Supported, EnabledInRichlyEditableText, StateOrderedList, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertParagraph, InsertCommands::ExecuteInsertParagraph, Supported, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertTab, InsertCommands::ExecuteInsertTab, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kIsTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertText, InsertCommands::ExecuteInsertText, Supported, EnabledInEditableText, StateNone, ValueStateOrNull, kIsTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kInsertUnorderedList, InsertCommands::ExecuteInsertUnorderedList, Supported, EnabledInRichlyEditableText, StateUnorderedList, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kItalic, StyleCommands::ExecuteToggleItalic, Supported, EnabledInRichlyEditableText, StyleCommands::StateItalic, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kJustifyCenter, ExecuteJustifyCenter, Supported, EnabledInRichlyEditableText, StateJustifyCenter, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kJustifyFull, ExecuteJustifyFull, Supported, EnabledInRichlyEditableText, StateJustifyFull, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kJustifyLeft, ExecuteJustifyLeft, Supported, EnabledInRichlyEditableText, StateJustifyLeft, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kJustifyNone, ExecuteJustifyLeft, Supported, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kJustifyRight, ExecuteJustifyRight, Supported, EnabledInRichlyEditableText, StateJustifyRight, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMakeTextWritingDirectionLeftToRight, StyleCommands::ExecuteMakeTextWritingDirectionLeftToRight, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StyleCommands::StateTextWritingDirectionLeftToRight, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMakeTextWritingDirectionNatural, StyleCommands::ExecuteMakeTextWritingDirectionNatural, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StyleCommands::StateTextWritingDirectionNatural, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMakeTextWritingDirectionRightToLeft, StyleCommands::ExecuteMakeTextWritingDirectionRightToLeft, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StyleCommands::StateTextWritingDirectionRightToLeft, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveBackward, MoveCommands::ExecuteMoveBackward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveBackwardAndModifySelection, MoveCommands::ExecuteMoveBackwardAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveDown, MoveCommands::ExecuteMoveDown, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveDownAndModifySelection, MoveCommands::ExecuteMoveDownAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveForward, MoveCommands::ExecuteMoveForward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveForwardAndModifySelection, MoveCommands::ExecuteMoveForwardAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveLeft, MoveCommands::ExecuteMoveLeft, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveLeftAndModifySelection, MoveCommands::ExecuteMoveLeftAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMovePageDown, MoveCommands::ExecuteMovePageDown, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMovePageDownAndModifySelection, MoveCommands::ExecuteMovePageDownAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMovePageUp, MoveCommands::ExecuteMovePageUp, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMovePageUpAndModifySelection, MoveCommands::ExecuteMovePageUpAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveParagraphBackward, MoveCommands::ExecuteMoveParagraphBackward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveParagraphBackwardAndModifySelection, MoveCommands::ExecuteMoveParagraphBackwardAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveParagraphForward, MoveCommands::ExecuteMoveParagraphForward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveParagraphForwardAndModifySelection, MoveCommands::ExecuteMoveParagraphForwardAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveRight, MoveCommands::ExecuteMoveRight, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveRightAndModifySelection, MoveCommands::ExecuteMoveRightAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToBeginningOfDocument, MoveCommands::ExecuteMoveToBeginningOfDocument, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToBeginningOfDocumentAndModifySelection, MoveCommands::ExecuteMoveToBeginningOfDocumentAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToBeginningOfLine, MoveCommands::ExecuteMoveToBeginningOfLine, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToBeginningOfLineAndModifySelection, MoveCommands::ExecuteMoveToBeginningOfLineAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToBeginningOfParagraph, MoveCommands::ExecuteMoveToBeginningOfParagraph, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToBeginningOfParagraphAndModifySelection, MoveCommands::ExecuteMoveToBeginningOfParagraphAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToBeginningOfSentence, MoveCommands::ExecuteMoveToBeginningOfSentence, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToBeginningOfSentenceAndModifySelection, MoveCommands::ExecuteMoveToBeginningOfSentenceAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToEndOfDocument, MoveCommands::ExecuteMoveToEndOfDocument, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToEndOfDocumentAndModifySelection, MoveCommands::ExecuteMoveToEndOfDocumentAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToEndOfLine, MoveCommands::ExecuteMoveToEndOfLine, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToEndOfLineAndModifySelection, MoveCommands::ExecuteMoveToEndOfLineAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToEndOfParagraph, MoveCommands::ExecuteMoveToEndOfParagraph, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToEndOfParagraphAndModifySelection, MoveCommands::ExecuteMoveToEndOfParagraphAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToEndOfSentence, MoveCommands::ExecuteMoveToEndOfSentence, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToEndOfSentenceAndModifySelection, MoveCommands::ExecuteMoveToEndOfSentenceAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToLeftEndOfLine, MoveCommands::ExecuteMoveToLeftEndOfLine, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToLeftEndOfLineAndModifySelection, MoveCommands::ExecuteMoveToLeftEndOfLineAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToRightEndOfLine, MoveCommands::ExecuteMoveToRightEndOfLine, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveToRightEndOfLineAndModifySelection, MoveCommands::ExecuteMoveToRightEndOfLineAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveUp, MoveCommands::ExecuteMoveUp, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveUpAndModifySelection, MoveCommands::ExecuteMoveUpAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveWordBackward, MoveCommands::ExecuteMoveWordBackward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveWordBackwardAndModifySelection, MoveCommands::ExecuteMoveWordBackwardAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveWordForward, MoveCommands::ExecuteMoveWordForward, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveWordForwardAndModifySelection, MoveCommands::ExecuteMoveWordForwardAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveWordLeft, MoveCommands::ExecuteMoveWordLeft, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveWordLeftAndModifySelection, MoveCommands::ExecuteMoveWordLeftAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveWordRight, MoveCommands::ExecuteMoveWordRight, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kMoveWordRightAndModifySelection, MoveCommands::ExecuteMoveWordRightAndModifySelection, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kOutdent, ExecuteOutdent, Supported, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kOverWrite, ExecuteToggleOverwrite, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kPaste, ClipboardCommands::ExecutePaste, ClipboardCommands::PasteSupported, ClipboardCommands::EnabledPaste, StateNone, ValueStateOrNull, kNotTextInsertion, ClipboardCommands::CanReadClipboard}, {WebEditingCommandType::kPasteAndMatchStyle, ClipboardCommands::ExecutePasteAndMatchStyle, Supported, ClipboardCommands::EnabledPaste, StateNone, ValueStateOrNull, kNotTextInsertion, ClipboardCommands::CanReadClipboard}, {WebEditingCommandType::kPasteGlobalSelection, ClipboardCommands::ExecutePasteGlobalSelection, SupportedFromMenuOrKeyBinding, ClipboardCommands::EnabledPaste, StateNone, ValueStateOrNull, kNotTextInsertion, ClipboardCommands::CanReadClipboard}, {WebEditingCommandType::kPrint, ExecutePrint, Supported, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kRedo, ExecuteRedo, Supported, EnabledRedo, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kRemoveFormat, ExecuteRemoveFormat, Supported, EnabledRangeInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kScrollPageBackward, ExecuteScrollPageBackward, SupportedFromMenuOrKeyBinding, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kScrollPageForward, ExecuteScrollPageForward, SupportedFromMenuOrKeyBinding, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kScrollLineUp, ExecuteScrollLineUp, SupportedFromMenuOrKeyBinding, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kScrollLineDown, ExecuteScrollLineDown, SupportedFromMenuOrKeyBinding, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kScrollToBeginningOfDocument, ExecuteScrollToBeginningOfDocument, SupportedFromMenuOrKeyBinding, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kScrollToEndOfDocument, ExecuteScrollToEndOfDocument, SupportedFromMenuOrKeyBinding, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSelectAll, ExecuteSelectAll, Supported, EnabledSelectAll, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSelectLine, ExecuteSelectLine, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSelectParagraph, ExecuteSelectParagraph, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSelectSentence, ExecuteSelectSentence, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSelectToMark, ExecuteSelectToMark, SupportedFromMenuOrKeyBinding, EnabledVisibleSelectionAndMark, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSelectWord, ExecuteSelectWord, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSetMark, ExecuteSetMark, SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kStrikethrough, StyleCommands::ExecuteStrikethrough, Supported, EnabledInRichlyEditableText, StyleCommands::StateStrikethrough, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kStyleWithCSS, StyleCommands::ExecuteStyleWithCSS, Supported, Enabled, StyleCommands::StateStyleWithCSS, ValueEmpty, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSubscript, StyleCommands::ExecuteSubscript, Supported, EnabledInRichlyEditableText, StyleCommands::StateSubscript, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSuperscript, StyleCommands::ExecuteSuperscript, Supported, EnabledInRichlyEditableText, StyleCommands::StateSuperscript, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kSwapWithMark, ExecuteSwapWithMark, SupportedFromMenuOrKeyBinding, EnabledVisibleSelectionAndMark, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kToggleBold, StyleCommands::ExecuteToggleBold, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StyleCommands::StateBold, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kToggleItalic, StyleCommands::ExecuteToggleItalic, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StyleCommands::StateItalic, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kToggleUnderline, StyleCommands::ExecuteUnderline, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StyleCommands::StateUnderline, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kTranspose, ExecuteTranspose, Supported, EnableCaretInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kUnderline, StyleCommands::ExecuteUnderline, Supported, EnabledInRichlyEditableText, StyleCommands::StateUnderline, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kUndo, ExecuteUndo, Supported, EnabledUndo, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kUnlink, ExecuteUnlink, Supported, EnabledRangeInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kUnscript, StyleCommands::ExecuteUnscript, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kUnselect, ExecuteUnselect, Supported, EnabledUnselect, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kUseCSS, StyleCommands::ExecuteUseCSS, Supported, Enabled, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kYank, ExecuteYank, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kYankAndSelect, ExecuteYankAndSelect, SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, {WebEditingCommandType::kAlignCenter, ExecuteJustifyCenter, SupportedFromMenuOrKeyBinding, EnabledInRichlyEditableText, StateNone, ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled}, }; // Handles all commands except WebEditingCommandType::Invalid. static_assert( arraysize(kEditorCommands) + 1 == static_cast<size_t>(WebEditingCommandType::kNumberOfCommandTypes), "must handle all valid WebEditingCommandType"); WebEditingCommandType command_type = WebEditingCommandTypeFromCommandName(command_name); if (command_type == WebEditingCommandType::kInvalid) return nullptr; int command_index = static_cast<int>(command_type) - 1; DCHECK(command_index >= 0 && command_index < static_cast<int>(arraysize(kEditorCommands))); return &kEditorCommands[command_index]; } EditorCommand Editor::CreateCommand(const String& command_name) const { return EditorCommand(InternalCommand(command_name), EditorCommandSource::kMenuOrKeyBinding, frame_); } EditorCommand Editor::CreateCommand(const String& command_name, EditorCommandSource source) const { return EditorCommand(InternalCommand(command_name), source, frame_); } bool Editor::ExecuteCommand(const String& command_name) { // Specially handling commands that Editor::execCommand does not directly // support. DCHECK(GetFrame().GetDocument()->IsActive()); if (command_name == "DeleteToEndOfParagraph") { if (!DeleteWithDirection(GetFrame(), DeleteDirection::kForward, TextGranularity::kParagraphBoundary, true, false)) { DeleteWithDirection(GetFrame(), DeleteDirection::kForward, TextGranularity::kCharacter, true, false); } return true; } if (command_name == "DeleteBackward") return CreateCommand(AtomicString("BackwardDelete")).Execute(); if (command_name == "DeleteForward") return CreateCommand(AtomicString("ForwardDelete")).Execute(); if (command_name == "AdvanceToNextMisspelling") { // TODO(editing-dev): Use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. see http://crbug.com/590369 for more details. GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); // We need to pass false here or else the currently selected word will never // be skipped. GetSpellChecker().AdvanceToNextMisspelling(false); return true; } if (command_name == "ToggleSpellPanel") { // TODO(editing-dev): Use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. // see http://crbug.com/590369 for more details. GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); GetSpellChecker().ShowSpellingGuessPanel(); return true; } return CreateCommand(command_name).Execute(); } bool Editor::ExecuteCommand(const String& command_name, const String& value) { // moveToBeginningOfDocument and moveToEndfDocument are only handled by WebKit // for editable nodes. DCHECK(GetFrame().GetDocument()->IsActive()); if (!CanEdit() && command_name == "moveToBeginningOfDocument") return GetFrame().GetEventHandler().BubblingScroll( kScrollUpIgnoringWritingMode, kScrollByDocument); if (!CanEdit() && command_name == "moveToEndOfDocument") return GetFrame().GetEventHandler().BubblingScroll( kScrollDownIgnoringWritingMode, kScrollByDocument); if (command_name == "ToggleSpellPanel") { // TODO(editing-dev): Use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. see http://crbug.com/590369 for more details. GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); GetSpellChecker().ShowSpellingGuessPanel(); return true; } return CreateCommand(command_name).Execute(value); } bool Editor::IsCommandEnabled(const String& command_name) const { return CreateCommand(command_name).IsEnabled(); } EditorCommand::EditorCommand() : command_(nullptr), source_(EditorCommandSource::kMenuOrKeyBinding) {} EditorCommand::EditorCommand(const EditorInternalCommand* command, EditorCommandSource source, LocalFrame* frame) : command_(command), source_(source), frame_(command ? frame : nullptr) { // Use separate assertions so we can tell which bad thing happened. if (!command) DCHECK(!frame_); else DCHECK(frame_); } LocalFrame& EditorCommand::GetFrame() const { DCHECK(frame_); return *frame_; } bool EditorCommand::Execute(const String& parameter, Event* triggering_event) const { if (!CanExecute(triggering_event)) return false; if (source_ == EditorCommandSource::kMenuOrKeyBinding) { InputEvent::InputType input_type = InputTypeFromCommandType(command_->command_type, *frame_); if (input_type != InputEvent::InputType::kNone) { if (DispatchBeforeInputEditorCommand( EventTargetNodeForDocument(frame_->GetDocument()), input_type, GetTargetRanges()) != DispatchEventResult::kNotCanceled) return true; // 'beforeinput' event handler may destroy target frame. if (frame_->GetDocument()->GetFrame() != frame_) return false; } } GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); DEFINE_STATIC_LOCAL(SparseHistogram, command_histogram, ("WebCore.Editing.Commands")); command_histogram.Sample(static_cast<int>(command_->command_type)); return command_->execute(*frame_, triggering_event, source_, parameter); } bool EditorCommand::Execute(Event* triggering_event) const { return Execute(String(), triggering_event); } bool EditorCommand::CanExecute(Event* triggering_event) const { if (IsEnabled(triggering_event)) return true; return IsSupported() && frame_ && command_->can_execute(*frame_, source_); } bool EditorCommand::IsSupported() const { if (!command_) return false; switch (source_) { case EditorCommandSource::kMenuOrKeyBinding: return true; case EditorCommandSource::kDOM: return command_->is_supported_from_dom(frame_.Get()); } NOTREACHED(); return false; } bool EditorCommand::IsEnabled(Event* triggering_event) const { if (!IsSupported() || !frame_) return false; return command_->is_enabled(*frame_, triggering_event, source_); } EditingTriState EditorCommand::GetState(Event* triggering_event) const { if (!IsSupported() || !frame_) return EditingTriState::kFalse; return command_->state(*frame_, triggering_event); } String EditorCommand::Value(Event* triggering_event) const { if (!IsSupported() || !frame_) return String(); return command_->value(*command_, *frame_, triggering_event); } bool EditorCommand::IsTextInsertion() const { return command_ && command_->is_text_insertion; } int EditorCommand::IdForHistogram() const { return IsSupported() ? static_cast<int>(command_->command_type) : 0; } const StaticRangeVector* EditorCommand::GetTargetRanges() const { const Node* target = EventTargetNodeForDocument(frame_->GetDocument()); if (!IsSupported() || !frame_ || !target || !HasRichlyEditableStyle(*target)) return nullptr; switch (command_->command_type) { case WebEditingCommandType::kDelete: case WebEditingCommandType::kDeleteBackward: return RangesFromCurrentSelectionOrExtendCaret( *frame_, SelectionModifyDirection::kBackward, TextGranularity::kCharacter); case WebEditingCommandType::kDeleteForward: return RangesFromCurrentSelectionOrExtendCaret( *frame_, SelectionModifyDirection::kForward, TextGranularity::kCharacter); case WebEditingCommandType::kDeleteToBeginningOfLine: return RangesFromCurrentSelectionOrExtendCaret( *frame_, SelectionModifyDirection::kBackward, TextGranularity::kLine); case WebEditingCommandType::kDeleteToBeginningOfParagraph: return RangesFromCurrentSelectionOrExtendCaret( *frame_, SelectionModifyDirection::kBackward, TextGranularity::kParagraph); case WebEditingCommandType::kDeleteToEndOfLine: return RangesFromCurrentSelectionOrExtendCaret( *frame_, SelectionModifyDirection::kForward, TextGranularity::kLine); case WebEditingCommandType::kDeleteToEndOfParagraph: return RangesFromCurrentSelectionOrExtendCaret( *frame_, SelectionModifyDirection::kForward, TextGranularity::kParagraph); case WebEditingCommandType::kDeleteWordBackward: return RangesFromCurrentSelectionOrExtendCaret( *frame_, SelectionModifyDirection::kBackward, TextGranularity::kWord); case WebEditingCommandType::kDeleteWordForward: return RangesFromCurrentSelectionOrExtendCaret( *frame_, SelectionModifyDirection::kForward, TextGranularity::kWord); default: return TargetRangesForInputEvent(*target); } } } // namespace blink
null
null
null
null
32,547
27,299
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
192,294
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * addi_apci_1516.c * Copyright (C) 2004,2005 ADDI-DATA GmbH for the source code of this module. * Project manager: Eric Stolz * * ADDI-DATA GmbH * Dieselstrasse 3 * D-77833 Ottersweier * Tel: +19(0)7223/9493-0 * Fax: +49(0)7223/9493-92 * http://www.addi-data.com * [email protected] * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * 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 "../comedi_pci.h" #include "addi_watchdog.h" /* * PCI bar 1 I/O Register map - Digital input/output */ #define APCI1516_DI_REG 0x00 #define APCI1516_DO_REG 0x04 /* * PCI bar 2 I/O Register map - Watchdog (APCI-1516 and APCI-2016) */ #define APCI1516_WDOG_REG 0x00 enum apci1516_boardid { BOARD_APCI1016, BOARD_APCI1516, BOARD_APCI2016, }; struct apci1516_boardinfo { const char *name; int di_nchan; int do_nchan; int has_wdog; }; static const struct apci1516_boardinfo apci1516_boardtypes[] = { [BOARD_APCI1016] = { .name = "apci1016", .di_nchan = 16, }, [BOARD_APCI1516] = { .name = "apci1516", .di_nchan = 8, .do_nchan = 8, .has_wdog = 1, }, [BOARD_APCI2016] = { .name = "apci2016", .do_nchan = 16, .has_wdog = 1, }, }; struct apci1516_private { unsigned long wdog_iobase; }; static int apci1516_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { data[1] = inw(dev->iobase + APCI1516_DI_REG); return insn->n; } static int apci1516_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { s->state = inw(dev->iobase + APCI1516_DO_REG); if (comedi_dio_update_state(s, data)) outw(s->state, dev->iobase + APCI1516_DO_REG); data[1] = s->state; return insn->n; } static int apci1516_reset(struct comedi_device *dev) { const struct apci1516_boardinfo *board = dev->board_ptr; struct apci1516_private *devpriv = dev->private; if (!board->has_wdog) return 0; outw(0x0, dev->iobase + APCI1516_DO_REG); addi_watchdog_reset(devpriv->wdog_iobase); return 0; } static int apci1516_auto_attach(struct comedi_device *dev, unsigned long context) { struct pci_dev *pcidev = comedi_to_pci_dev(dev); const struct apci1516_boardinfo *board = NULL; struct apci1516_private *devpriv; struct comedi_subdevice *s; int ret; if (context < ARRAY_SIZE(apci1516_boardtypes)) board = &apci1516_boardtypes[context]; if (!board) return -ENODEV; dev->board_ptr = board; dev->board_name = board->name; devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv)); if (!devpriv) return -ENOMEM; ret = comedi_pci_enable(dev); if (ret) return ret; dev->iobase = pci_resource_start(pcidev, 1); devpriv->wdog_iobase = pci_resource_start(pcidev, 2); ret = comedi_alloc_subdevices(dev, 3); if (ret) return ret; /* Initialize the digital input subdevice */ s = &dev->subdevices[0]; if (board->di_nchan) { s->type = COMEDI_SUBD_DI; s->subdev_flags = SDF_READABLE; s->n_chan = board->di_nchan; s->maxdata = 1; s->range_table = &range_digital; s->insn_bits = apci1516_di_insn_bits; } else { s->type = COMEDI_SUBD_UNUSED; } /* Initialize the digital output subdevice */ s = &dev->subdevices[1]; if (board->do_nchan) { s->type = COMEDI_SUBD_DO; s->subdev_flags = SDF_WRITABLE; s->n_chan = board->do_nchan; s->maxdata = 1; s->range_table = &range_digital; s->insn_bits = apci1516_do_insn_bits; } else { s->type = COMEDI_SUBD_UNUSED; } /* Initialize the watchdog subdevice */ s = &dev->subdevices[2]; if (board->has_wdog) { ret = addi_watchdog_init(s, devpriv->wdog_iobase); if (ret) return ret; } else { s->type = COMEDI_SUBD_UNUSED; } apci1516_reset(dev); return 0; } static void apci1516_detach(struct comedi_device *dev) { if (dev->iobase) apci1516_reset(dev); comedi_pci_detach(dev); } static struct comedi_driver apci1516_driver = { .driver_name = "addi_apci_1516", .module = THIS_MODULE, .auto_attach = apci1516_auto_attach, .detach = apci1516_detach, }; static int apci1516_pci_probe(struct pci_dev *dev, const struct pci_device_id *id) { return comedi_pci_auto_config(dev, &apci1516_driver, id->driver_data); } static const struct pci_device_id apci1516_pci_table[] = { { PCI_VDEVICE(ADDIDATA, 0x1000), BOARD_APCI1016 }, { PCI_VDEVICE(ADDIDATA, 0x1001), BOARD_APCI1516 }, { PCI_VDEVICE(ADDIDATA, 0x1002), BOARD_APCI2016 }, { 0 } }; MODULE_DEVICE_TABLE(pci, apci1516_pci_table); static struct pci_driver apci1516_pci_driver = { .name = "addi_apci_1516", .id_table = apci1516_pci_table, .probe = apci1516_pci_probe, .remove = comedi_pci_auto_unconfig, }; module_comedi_pci_driver(apci1516_driver, apci1516_pci_driver); MODULE_DESCRIPTION("ADDI-DATA APCI-1016/1516/2016, 16 channel DIO boards"); MODULE_AUTHOR("Comedi http://www.comedi.org"); MODULE_LICENSE("GPL");
null
null
null
null
100,641
279
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
train_val
6e5714eaf77d79ae1c8b47e3e040ff5411b717ec
165,274
linux
1
https://github.com/torvalds/linux
2011-08-06 18:33:19-07:00
u64 secure_dccp_sequence_number(__be32 saddr, __be32 daddr, __be16 sport, __be16 dport) { u64 seq; __u32 hash[4]; struct keydata *keyptr = get_keyptr(); hash[0] = (__force u32)saddr; hash[1] = (__force u32)daddr; hash[2] = ((__force u16)sport << 16) + (__force u16)dport; hash[3] = keyptr->secret[11]; seq = half_md4_transform(hash, keyptr->secret); seq |= ((u64)keyptr->count) << (32 - HASH_BITS); seq += ktime_to_ns(ktime_get_real()); seq &= (1ull << 48) - 1; return seq; }
CVE-2011-3188
null
https://github.com/torvalds/linux/commit/6e5714eaf77d79ae1c8b47e3e040ff5411b717ec
Medium
3,168
26,825
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
26,825
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* Copyright (c) 2006, 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. * * --- * Author: Sanjay Ghemawat */ // For atomic operations on statistics counters, see atomic_stats_counter.h. // For atomic operations on sequence numbers, see atomic_sequence_num.h. // For atomic operations on reference counts, see atomic_refcount.h. // Some fast atomic operations -- typically with machine-dependent // implementations. This file may need editing as Google code is // ported to different architectures. // The routines exported by this module are subtle. If you use them, even if // you get the code right, it will depend on careful reasoning about atomicity // and memory ordering; it will be less readable, and harder to maintain. If // you plan to use these routines, you should have a good reason, such as solid // evidence that performance would otherwise suffer, or there being no // alternative. You should assume only properties explicitly guaranteed by the // specifications in this file. You are almost certainly _not_ writing code // just for the x86; if you assume x86 semantics, x86 hardware bugs and // implementations on other archtectures will cause your code to break. If you // do not know what you are doing, avoid these routines, and use a Mutex. // // It is incorrect to make direct assignments to/from an atomic variable. // You should use one of the Load or Store routines. The NoBarrier // versions are provided when no barriers are needed: // NoBarrier_Store() // NoBarrier_Load() // Although there are currently no compiler enforcement, you are encouraged // to use these. Moreover, if you choose to use base::subtle::Atomic64 type, // you MUST use one of the Load or Store routines to get correct behavior // on 32-bit platforms. // // The intent is eventually to put all of these routines in namespace // base::subtle #ifndef THREAD_ATOMICOPS_H_ #define THREAD_ATOMICOPS_H_ #include <config.h> #ifdef HAVE_STDINT_H #include <stdint.h> #endif // ------------------------------------------------------------------------ // Include the platform specific implementations of the types // and operations listed below. Implementations are to provide Atomic32 // and Atomic64 operations. If there is a mismatch between intptr_t and // the Atomic32 or Atomic64 types for a platform, the platform-specific header // should define the macro, AtomicWordCastType in a clause similar to the // following: // #if ...pointers are 64 bits... // # define AtomicWordCastType base::subtle::Atomic64 // #else // # define AtomicWordCastType Atomic32 // #endif // TODO(csilvers): figure out ARCH_PIII/ARCH_K8 (perhaps via ./configure?) // ------------------------------------------------------------------------ #include "base/arm_instruction_set_select.h" // TODO(csilvers): match piii, not just __i386. Also, match k8 #if defined(__MACH__) && defined(__APPLE__) #include "base/atomicops-internals-macosx.h" #elif defined(__GNUC__) && defined(ARMV6) #include "base/atomicops-internals-arm-v6plus.h" #elif defined(ARMV3) #include "base/atomicops-internals-arm-generic.h" #elif defined(_WIN32) #include "base/atomicops-internals-windows.h" #elif defined(__GNUC__) && (defined(__i386) || defined(__x86_64__)) #include "base/atomicops-internals-x86.h" #elif defined(__linux__) && defined(__PPC__) #include "base/atomicops-internals-linuxppc.h" #else // Assume x86 for now. If you need to support a new architecture and // don't know how to implement atomic ops, you can probably get away // with using pthreads, since atomicops is only used by spinlock.h/cc //#error You need to implement atomic operations for this architecture #include "base/atomicops-internals-x86.h" #endif // Signed type that can hold a pointer and supports the atomic ops below, as // well as atomic loads and stores. Instances must be naturally-aligned. typedef intptr_t AtomicWord; #ifdef AtomicWordCastType // ------------------------------------------------------------------------ // This section is needed only when explicit type casting is required to // cast AtomicWord to one of the basic atomic types (Atomic64 or Atomic32). // It also serves to document the AtomicWord interface. // ------------------------------------------------------------------------ namespace base { namespace subtle { // Atomically execute: // result = *ptr; // if (*ptr == old_value) // *ptr = new_value; // return result; // // I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value". // Always return the old value of "*ptr" // // This routine implies no memory barriers. inline AtomicWord NoBarrier_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { return NoBarrier_CompareAndSwap( reinterpret_cast<volatile AtomicWordCastType*>(ptr), old_value, new_value); } // Atomically store new_value into *ptr, returning the previous value held in // *ptr. This routine implies no memory barriers. inline AtomicWord NoBarrier_AtomicExchange(volatile AtomicWord* ptr, AtomicWord new_value) { return NoBarrier_AtomicExchange( reinterpret_cast<volatile AtomicWordCastType*>(ptr), new_value); } // Atomically increment *ptr by "increment". Returns the new value of // *ptr with the increment applied. This routine implies no memory // barriers. inline AtomicWord NoBarrier_AtomicIncrement(volatile AtomicWord* ptr, AtomicWord increment) { return NoBarrier_AtomicIncrement( reinterpret_cast<volatile AtomicWordCastType*>(ptr), increment); } inline AtomicWord Barrier_AtomicIncrement(volatile AtomicWord* ptr, AtomicWord increment) { return Barrier_AtomicIncrement( reinterpret_cast<volatile AtomicWordCastType*>(ptr), increment); } // ------------------------------------------------------------------------ // These following lower-level operations are typically useful only to people // implementing higher-level synchronization operations like spinlocks, // mutexes, and condition-variables. They combine CompareAndSwap(), a load, or // a store with appropriate memory-ordering instructions. "Acquire" operations // ensure that no later memory access can be reordered ahead of the operation. // "Release" operations ensure that no previous memory access can be reordered // after the operation. "Barrier" operations have both "Acquire" and "Release" // semantics. A MemoryBarrier() has "Barrier" semantics, but does no memory // access. // ------------------------------------------------------------------------ inline AtomicWord Acquire_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { return base::subtle::Acquire_CompareAndSwap( reinterpret_cast<volatile AtomicWordCastType*>(ptr), old_value, new_value); } inline AtomicWord Release_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { return base::subtle::Release_CompareAndSwap( reinterpret_cast<volatile AtomicWordCastType*>(ptr), old_value, new_value); } inline void NoBarrier_Store(volatile AtomicWord *ptr, AtomicWord value) { NoBarrier_Store( reinterpret_cast<volatile AtomicWordCastType*>(ptr), value); } inline void Acquire_Store(volatile AtomicWord* ptr, AtomicWord value) { return base::subtle::Acquire_Store( reinterpret_cast<volatile AtomicWordCastType*>(ptr), value); } inline void Release_Store(volatile AtomicWord* ptr, AtomicWord value) { return base::subtle::Release_Store( reinterpret_cast<volatile AtomicWordCastType*>(ptr), value); } inline AtomicWord NoBarrier_Load(volatile const AtomicWord *ptr) { return NoBarrier_Load( reinterpret_cast<volatile const AtomicWordCastType*>(ptr)); } inline AtomicWord Acquire_Load(volatile const AtomicWord* ptr) { return base::subtle::Acquire_Load( reinterpret_cast<volatile const AtomicWordCastType*>(ptr)); } inline AtomicWord Release_Load(volatile const AtomicWord* ptr) { return base::subtle::Release_Load( reinterpret_cast<volatile const AtomicWordCastType*>(ptr)); } } // namespace base::subtle } // namespace base #endif // AtomicWordCastType // ------------------------------------------------------------------------ // Commented out type definitions and method declarations for documentation // of the interface provided by this module. // ------------------------------------------------------------------------ #if 0 // Signed 32-bit type that supports the atomic ops below, as well as atomic // loads and stores. Instances must be naturally aligned. This type differs // from AtomicWord in 64-bit binaries where AtomicWord is 64-bits. typedef int32_t Atomic32; // Corresponding operations on Atomic32 namespace base { namespace subtle { // Signed 64-bit type that supports the atomic ops below, as well as atomic // loads and stores. Instances must be naturally aligned. This type differs // from AtomicWord in 32-bit binaries where AtomicWord is 32-bits. typedef int64_t Atomic64; Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value); Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value); Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value); Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value); void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value); void Acquire_Store(volatile Atomic32* ptr, Atomic32 value); void Release_Store(volatile Atomic32* ptr, Atomic32 value); Atomic32 NoBarrier_Load(volatile const Atomic32* ptr); Atomic32 Acquire_Load(volatile const Atomic32* ptr); Atomic32 Release_Load(volatile const Atomic32* ptr); // Corresponding operations on Atomic64 Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value); Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value); Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value); Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, Atomic64 old_value, Atomic64 new_value); void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value); void Acquire_Store(volatile Atomic64* ptr, Atomic64 value); void Release_Store(volatile Atomic64* ptr, Atomic64 value); Atomic64 NoBarrier_Load(volatile const Atomic64* ptr); Atomic64 Acquire_Load(volatile const Atomic64* ptr); Atomic64 Release_Load(volatile const Atomic64* ptr); } // namespace base::subtle } // namespace base void MemoryBarrier(); #endif // 0 // ------------------------------------------------------------------------ // The following are to be deprecated when all uses have been changed to // use the base::subtle namespace. // ------------------------------------------------------------------------ #ifdef AtomicWordCastType // AtomicWord versions to be deprecated inline AtomicWord Acquire_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { return base::subtle::Acquire_CompareAndSwap(ptr, old_value, new_value); } inline AtomicWord Release_CompareAndSwap(volatile AtomicWord* ptr, AtomicWord old_value, AtomicWord new_value) { return base::subtle::Release_CompareAndSwap(ptr, old_value, new_value); } inline void Acquire_Store(volatile AtomicWord* ptr, AtomicWord value) { return base::subtle::Acquire_Store(ptr, value); } inline void Release_Store(volatile AtomicWord* ptr, AtomicWord value) { return base::subtle::Release_Store(ptr, value); } inline AtomicWord Acquire_Load(volatile const AtomicWord* ptr) { return base::subtle::Acquire_Load(ptr); } inline AtomicWord Release_Load(volatile const AtomicWord* ptr) { return base::subtle::Release_Load(ptr); } #endif // AtomicWordCastType // 32-bit Acquire/Release operations to be deprecated. inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { return base::subtle::Acquire_CompareAndSwap(ptr, old_value, new_value); } inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, Atomic32 old_value, Atomic32 new_value) { return base::subtle::Release_CompareAndSwap(ptr, old_value, new_value); } inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { base::subtle::Acquire_Store(ptr, value); } inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { return base::subtle::Release_Store(ptr, value); } inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { return base::subtle::Acquire_Load(ptr); } inline Atomic32 Release_Load(volatile const Atomic32* ptr) { return base::subtle::Release_Load(ptr); } #ifdef BASE_HAS_ATOMIC64 // 64-bit Acquire/Release operations to be deprecated. inline base::subtle::Atomic64 Acquire_CompareAndSwap( volatile base::subtle::Atomic64* ptr, base::subtle::Atomic64 old_value, base::subtle::Atomic64 new_value) { return base::subtle::Acquire_CompareAndSwap(ptr, old_value, new_value); } inline base::subtle::Atomic64 Release_CompareAndSwap( volatile base::subtle::Atomic64* ptr, base::subtle::Atomic64 old_value, base::subtle::Atomic64 new_value) { return base::subtle::Release_CompareAndSwap(ptr, old_value, new_value); } inline void Acquire_Store( volatile base::subtle::Atomic64* ptr, base::subtle::Atomic64 value) { base::subtle::Acquire_Store(ptr, value); } inline void Release_Store( volatile base::subtle::Atomic64* ptr, base::subtle::Atomic64 value) { return base::subtle::Release_Store(ptr, value); } inline base::subtle::Atomic64 Acquire_Load( volatile const base::subtle::Atomic64* ptr) { return base::subtle::Acquire_Load(ptr); } inline base::subtle::Atomic64 Release_Load( volatile const base::subtle::Atomic64* ptr) { return base::subtle::Release_Load(ptr); } #endif // BASE_HAS_ATOMIC64 #endif // THREAD_ATOMICOPS_H_
null
null
null
null
23,688
17,219
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
17,219
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
// Copyright 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. #include "components/viz/common/quads/render_pass_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/traced_value.h" #include "third_party/skia/include/core/SkImageFilter.h" namespace viz { RenderPassDrawQuad::RenderPassDrawQuad() = default; RenderPassDrawQuad::RenderPassDrawQuad(const RenderPassDrawQuad& other) = default; RenderPassDrawQuad::~RenderPassDrawQuad() = default; void RenderPassDrawQuad::SetNew(const SharedQuadState* shared_quad_state, const gfx::Rect& rect, const gfx::Rect& visible_rect, RenderPassId render_pass_id, ResourceId mask_resource_id, const gfx::RectF& mask_uv_rect, const gfx::Size& mask_texture_size, const gfx::Vector2dF& filters_scale, const gfx::PointF& filters_origin, const gfx::RectF& tex_coord_rect, bool force_anti_aliasing_off) { DCHECK(render_pass_id); bool needs_blending = true; SetAll(shared_quad_state, rect, visible_rect, needs_blending, render_pass_id, mask_resource_id, mask_uv_rect, mask_texture_size, filters_scale, filters_origin, tex_coord_rect, force_anti_aliasing_off); } void RenderPassDrawQuad::SetAll(const SharedQuadState* shared_quad_state, const gfx::Rect& rect, const gfx::Rect& visible_rect, bool needs_blending, RenderPassId render_pass_id, ResourceId mask_resource_id, const gfx::RectF& mask_uv_rect, const gfx::Size& mask_texture_size, const gfx::Vector2dF& filters_scale, const gfx::PointF& filters_origin, const gfx::RectF& tex_coord_rect, bool force_anti_aliasing_off) { DCHECK(render_pass_id); DrawQuad::SetAll(shared_quad_state, DrawQuad::RENDER_PASS, rect, visible_rect, needs_blending); this->render_pass_id = render_pass_id; resources.ids[kMaskResourceIdIndex] = mask_resource_id; resources.count = mask_resource_id ? 1 : 0; this->mask_uv_rect = mask_uv_rect; this->mask_texture_size = mask_texture_size; this->filters_scale = filters_scale; this->filters_origin = filters_origin; this->tex_coord_rect = tex_coord_rect; this->force_anti_aliasing_off = force_anti_aliasing_off; } const RenderPassDrawQuad* RenderPassDrawQuad::MaterialCast( const DrawQuad* quad) { DCHECK_EQ(quad->material, DrawQuad::RENDER_PASS); return static_cast<const RenderPassDrawQuad*>(quad); } void RenderPassDrawQuad::ExtendValue( base::trace_event::TracedValue* value) const { TracedValue::SetIDRef(reinterpret_cast<void*>(render_pass_id), value, "render_pass_id"); value->SetInteger("mask_resource_id", resources.ids[kMaskResourceIdIndex]); cc::MathUtil::AddToTracedValue("mask_texture_size", mask_texture_size, value); cc::MathUtil::AddToTracedValue("mask_uv_rect", mask_uv_rect, value); cc::MathUtil::AddToTracedValue("tex_coord_rect", tex_coord_rect, value); value->SetBoolean("force_anti_aliasing_off", force_anti_aliasing_off); } } // namespace viz
null
null
null
null
14,082
44,235
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
44,235
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 PPAPI_CPP_PRIVATE_VIDEO_FRAME_PRIVATE_H_ #define PPAPI_CPP_PRIVATE_VIDEO_FRAME_PRIVATE_H_ #include <string.h> #include "ppapi/c/pp_time.h" #include "ppapi/c/private/pp_video_frame_private.h" #include "ppapi/cpp/completion_callback.h" #include "ppapi/cpp/image_data.h" #include "ppapi/cpp/pass_ref.h" /// @file /// This file defines the struct used to hold a video frame. namespace pp { /// The <code>PP_VideoFrame_Private</code> struct represents a video frame. /// Video sources and destinations use frames to transfer video to and from /// the browser. class VideoFrame_Private { public: /// Default constructor for creating a <code>VideoFrame_Private</code> object. VideoFrame_Private(); /// Constructor that takes an existing <code>PP_VideoFrame_Private</code> /// structure. The 'image_data' PP_Resource field in the structure will be /// managed by this instance. VideoFrame_Private(PassRef, const PP_VideoFrame_Private& pp_video_frame); /// Constructor that takes an existing <code>ImageData</code> instance and /// a timestamp. VideoFrame_Private(const ImageData& image_data, PP_TimeTicks timestamp); /// The copy constructor for <code>VideoFrame_Private</code>. /// /// @param[in] other A reference to a <code>VideoFrame_Private</code>. VideoFrame_Private(const VideoFrame_Private& other); ~VideoFrame_Private(); /// The assignment operator for <code>VideoFrame_Private</code>. /// /// @param[in] other A reference to a <code>VideoFrame_Private</code>. VideoFrame_Private& operator=(const VideoFrame_Private& other); const PP_VideoFrame_Private& pp_video_frame() const { return video_frame_; } ImageData image_data() const { return image_data_; } void set_image_data(const ImageData& image_data) { image_data_ = image_data; // The assignment above manages the underlying PP_Resources. Copy the new // one into our internal video frame struct. video_frame_.image_data = image_data_.pp_resource(); } PP_TimeTicks timestamp() const { return video_frame_.timestamp; } void set_timestamp(PP_TimeTicks timestamp) { video_frame_.timestamp = timestamp; } private: ImageData image_data_; // This manages the PP_Resource in video_frame_. PP_VideoFrame_Private video_frame_; }; namespace internal { // A specialization of CallbackOutputTraits to provide the callback system the // information on how to handle pp::VideoFrame_Private. This converts // PP_VideoFrame_Private to pp::VideoFrame_Private when passing to the plugin, // and specifically manages the PP_Resource embedded in the video_frame_ field. template<> struct CallbackOutputTraits<pp::VideoFrame_Private> { typedef PP_VideoFrame_Private* APIArgType; typedef PP_VideoFrame_Private StorageType; static inline APIArgType StorageToAPIArg(StorageType& t) { return &t; } static inline pp::VideoFrame_Private StorageToPluginArg(StorageType& t) { return pp::VideoFrame_Private(PASS_REF, t); } static inline void Initialize(StorageType* t) { VideoFrame_Private dummy; *t = dummy.pp_video_frame(); } }; } // namespace internal } // namespace pp #endif // PPAPI_CPP_PRIVATE_VIDEO_FRAME_PRIVATE_H_
null
null
null
null
41,098
5,531
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
5,531
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 "pdf/document_loader.h" #include <algorithm> #include <memory> #include <string> #include <vector> #include "base/logging.h" #include "pdf/url_loader_wrapper.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/range/range.h" using ::testing::_; using ::testing::Mock; using ::testing::Sequence; using ::testing::NiceMock; using ::testing::Return; namespace chrome_pdf { namespace { constexpr uint32_t kDefaultRequestSize = DocumentLoader::kDefaultRequestSize; class TestURLLoader : public URLLoaderWrapper { public: class LoaderData { public: LoaderData() = default; ~LoaderData() { // We should call callbacks to prevent memory leaks. // The callbacks don't do anything, because the objects that created the // callbacks have been destroyed. if (IsWaitRead()) CallReadCallback(-1); if (IsWaitOpen()) CallOpenCallback(-1); } int content_length() const { return content_length_; } void set_content_length(int content_length) { content_length_ = content_length; } bool accept_ranges_bytes() const { return accept_ranges_bytes_; } void set_accept_ranges_bytes(bool accept_ranges_bytes) { accept_ranges_bytes_ = accept_ranges_bytes; } bool content_encoded() const { return content_encoded_; } void set_content_encoded(bool content_encoded) { content_encoded_ = content_encoded; } const std::string& content_type() const { return content_type_; } void set_content_type(const std::string& content_type) { content_type_ = content_type; } const std::string& content_disposition() const { return content_disposition_; } void set_content_disposition(const std::string& content_disposition) { content_disposition_ = content_disposition; } const std::string& multipart_boundary() const { return multipart_boundary_; } void set_multipart_boundary(const std::string& multipart_boundary) { multipart_boundary_ = multipart_boundary; } const gfx::Range& byte_range() const { return byte_range_; } void set_byte_range(const gfx::Range& byte_range) { byte_range_ = byte_range; } bool is_multipart() const { return is_multipart_; } void set_is_multipart(bool is_multipart) { is_multipart_ = is_multipart; } int status_code() const { return status_code_; } void set_status_code(int status_code) { status_code_ = status_code; } bool closed() const { return closed_; } void set_closed(bool closed) { closed_ = closed; } const gfx::Range& open_byte_range() const { return open_byte_range_; } void set_open_byte_range(const gfx::Range& open_byte_range) { open_byte_range_ = open_byte_range; } bool IsWaitRead() const { return !did_read_callback_.IsOptional(); } bool IsWaitOpen() const { return !did_open_callback_.IsOptional(); } char* buffer() const { return buffer_; } int buffer_size() const { return buffer_size_; } void SetReadCallback(const pp::CompletionCallback& read_callback, char* buffer, int buffer_size) { did_read_callback_ = read_callback; buffer_ = buffer; buffer_size_ = buffer_size; } void SetOpenCallback(const pp::CompletionCallback& open_callback, gfx::Range req_byte_range) { did_open_callback_ = open_callback; set_open_byte_range(req_byte_range); } void CallOpenCallback(int result) { DCHECK(IsWaitOpen()); did_open_callback_.RunAndClear(result); } void CallReadCallback(int result) { DCHECK(IsWaitRead()); did_read_callback_.RunAndClear(result); } private: pp::CompletionCallback did_open_callback_; pp::CompletionCallback did_read_callback_; char* buffer_ = nullptr; int buffer_size_ = 0; int content_length_ = -1; bool accept_ranges_bytes_ = false; bool content_encoded_ = false; std::string content_type_; std::string content_disposition_; std::string multipart_boundary_; gfx::Range byte_range_ = gfx::Range::InvalidRange(); bool is_multipart_ = false; int status_code_ = 0; bool closed_ = true; gfx::Range open_byte_range_ = gfx::Range::InvalidRange(); DISALLOW_COPY_AND_ASSIGN(LoaderData); }; explicit TestURLLoader(LoaderData* data) : data_(data) { data_->set_closed(false); } ~TestURLLoader() override { Close(); } int GetContentLength() const override { return data_->content_length(); } bool IsAcceptRangesBytes() const override { return data_->accept_ranges_bytes(); } bool IsContentEncoded() const override { return data_->content_encoded(); } std::string GetContentType() const override { return data_->content_type(); } std::string GetContentDisposition() const override { return data_->content_disposition(); } int GetStatusCode() const override { return data_->status_code(); } bool IsMultipart() const override { return data_->is_multipart(); } bool GetByteRangeStart(int* start) const override { *start = data_->byte_range().start(); return data_->byte_range().IsValid(); } void Close() override { data_->set_closed(true); } void OpenRange(const std::string& url, const std::string& referrer_url, uint32_t position, uint32_t size, const pp::CompletionCallback& cc) override { data_->SetOpenCallback(cc, gfx::Range(position, position + size)); } void ReadResponseBody(char* buffer, int buffer_size, const pp::CompletionCallback& cc) override { data_->SetReadCallback(cc, buffer, buffer_size); } bool GetDownloadProgress(int64_t* bytes_received, int64_t* total_bytes_to_be_received) const override { return false; } private: LoaderData* data_; DISALLOW_COPY_AND_ASSIGN(TestURLLoader); }; class TestClient : public DocumentLoader::Client { public: TestClient() { full_page_loader_data()->set_content_type("application/pdf"); } ~TestClient() override = default; // DocumentLoader::Client overrides: pp::Instance* GetPluginInstance() override { return nullptr; } std::unique_ptr<URLLoaderWrapper> CreateURLLoader() override { return std::unique_ptr<URLLoaderWrapper>( new TestURLLoader(partial_loader_data())); } void OnPendingRequestComplete() override {} void OnNewDataReceived() override {} void OnDocumentComplete() override {} void OnDocumentCanceled() override {} void CancelBrowserDownload() override {} std::unique_ptr<URLLoaderWrapper> CreateFullPageLoader() { return std::unique_ptr<URLLoaderWrapper>( new TestURLLoader(full_page_loader_data())); } TestURLLoader::LoaderData* full_page_loader_data() { return &full_page_loader_data_; } TestURLLoader::LoaderData* partial_loader_data() { return &partial_loader_data_; } void SetCanUsePartialLoading() { full_page_loader_data()->set_content_length(10 * 1024 * 1024); full_page_loader_data()->set_content_encoded(false); full_page_loader_data()->set_accept_ranges_bytes(true); } void SendAllPartialData() { partial_loader_data_.set_byte_range(partial_loader_data_.open_byte_range()); partial_loader_data_.CallOpenCallback(0); uint32_t length = partial_loader_data_.byte_range().length(); while (length > 0) { const uint32_t max_part_len = kDefaultRequestSize; const uint32_t part_len = std::min(length, max_part_len); partial_loader_data_.CallReadCallback(part_len); length -= part_len; } if (partial_loader_data_.IsWaitRead()) { partial_loader_data_.CallReadCallback(0); } } private: TestURLLoader::LoaderData full_page_loader_data_; TestURLLoader::LoaderData partial_loader_data_; DISALLOW_COPY_AND_ASSIGN(TestClient); }; class MockClient : public TestClient { public: MockClient() = default; MOCK_METHOD0(OnPendingRequestComplete, void()); MOCK_METHOD0(OnNewDataReceived, void()); MOCK_METHOD0(OnDocumentComplete, void()); MOCK_METHOD0(OnDocumentCanceled, void()); private: DISALLOW_COPY_AND_ASSIGN(MockClient); }; } // namespace using DocumentLoaderTest = ::testing::Test; TEST_F(DocumentLoaderTest, PartialLoadingEnabled) { TestClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(1000000, 1); EXPECT_FALSE(loader.is_partial_loader_active()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(loader.is_partial_loader_active()); } TEST_F(DocumentLoaderTest, PartialLoadingDisabledOnSmallFiles) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 2); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(1000000, 1); EXPECT_FALSE(loader.is_partial_loader_active()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_FALSE(loader.is_partial_loader_active()); } TEST_F(DocumentLoaderTest, PartialLoadingDisabledIfContentEncoded) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_encoded(true); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(1000000, 1); EXPECT_FALSE(loader.is_partial_loader_active()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_FALSE(loader.is_partial_loader_active()); } TEST_F(DocumentLoaderTest, PartialLoadingDisabledNoAcceptRangeBytes) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_accept_ranges_bytes(false); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(1000000, 1); EXPECT_FALSE(loader.is_partial_loader_active()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_FALSE(loader.is_partial_loader_active()); } TEST_F(DocumentLoaderTest, PartialLoadingReallyDisabledRequestFromBegin) { TestClient client; DocumentLoader loader(&client); client.SetCanUsePartialLoading(); loader.SetPartialLoadingEnabled(false); loader.Init(client.CreateFullPageLoader(), "http://url.com"); // We should not start partial loading if requested data is beside full page // loading position. loader.RequestData(kDefaultRequestSize, 1); EXPECT_FALSE(loader.is_partial_loader_active()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_FALSE(loader.is_partial_loader_active()); } TEST_F(DocumentLoaderTest, PartialLoadingReallyDisabledRequestFromMiddle) { TestClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.SetPartialLoadingEnabled(false); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(1000000, 1); EXPECT_FALSE(loader.is_partial_loader_active()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_FALSE(loader.is_partial_loader_active()); } TEST_F(DocumentLoaderTest, PartialLoadingSimple) { TestClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); // While we have no requests, we should not start partial loading. EXPECT_FALSE(loader.is_partial_loader_active()); loader.RequestData(5000000, 1); EXPECT_FALSE(client.partial_loader_data()->IsWaitOpen()); EXPECT_FALSE(loader.is_partial_loader_active()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); // Partial loader should request headers. EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); EXPECT_TRUE(loader.is_partial_loader_active()); // Loader should be stopped. EXPECT_TRUE(client.full_page_loader_data()->closed()); EXPECT_EQ("{4980736,10485760}", client.partial_loader_data()->open_byte_range().ToString()); } TEST_F(DocumentLoaderTest, PartialLoadingBackOrder) { TestClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); // While we have no requests, we should not start partial loading. EXPECT_FALSE(loader.is_partial_loader_active()); loader.RequestData(client.full_page_loader_data()->content_length() - 1, 1); EXPECT_FALSE(client.partial_loader_data()->IsWaitOpen()); EXPECT_FALSE(loader.is_partial_loader_active()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); // Partial loader should request headers. EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); EXPECT_TRUE(loader.is_partial_loader_active()); // Loader should be stopped. EXPECT_TRUE(client.full_page_loader_data()->closed()); // Requested range should be enlarged. EXPECT_GT(client.partial_loader_data()->open_byte_range().length(), 1u); EXPECT_EQ("{9830400,10485760}", client.partial_loader_data()->open_byte_range().ToString()); } TEST_F(DocumentLoaderTest, CompleteWithoutPartial) { TestClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_FALSE(client.full_page_loader_data()->closed()); while (client.full_page_loader_data()->IsWaitRead()) { client.full_page_loader_data()->CallReadCallback(1000); } EXPECT_TRUE(loader.IsDocumentComplete()); EXPECT_TRUE(client.full_page_loader_data()->closed()); } TEST_F(DocumentLoaderTest, ErrorDownloadFullDocument) { TestClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_TRUE(client.full_page_loader_data()->IsWaitRead()); EXPECT_FALSE(client.full_page_loader_data()->closed()); client.full_page_loader_data()->CallReadCallback(-3); EXPECT_TRUE(client.full_page_loader_data()->closed()); EXPECT_FALSE(loader.IsDocumentComplete()); } TEST_F(DocumentLoaderTest, CompleteNoContentLength) { TestClient client; DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_FALSE(client.full_page_loader_data()->closed()); for (int i = 0; i < 10; ++i) { EXPECT_TRUE(client.full_page_loader_data()->IsWaitRead()); client.full_page_loader_data()->CallReadCallback(1000); } EXPECT_TRUE(client.full_page_loader_data()->IsWaitRead()); client.full_page_loader_data()->CallReadCallback(0); EXPECT_EQ(10000ul, loader.GetDocumentSize()); EXPECT_TRUE(loader.IsDocumentComplete()); EXPECT_TRUE(client.full_page_loader_data()->closed()); } TEST_F(DocumentLoaderTest, CompleteWithPartial) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(19 * kDefaultRequestSize, kDefaultRequestSize); EXPECT_FALSE(client.full_page_loader_data()->closed()); EXPECT_FALSE(client.partial_loader_data()->IsWaitRead()); EXPECT_FALSE(client.partial_loader_data()->IsWaitOpen()); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.full_page_loader_data()->closed()); EXPECT_FALSE(client.partial_loader_data()->closed()); client.SendAllPartialData(); // Now we should send other document data. client.SendAllPartialData(); EXPECT_TRUE(client.full_page_loader_data()->closed()); EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, PartialRequestLastChunk) { const uint32_t kLastChunkSize = 300; TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20 + kLastChunkSize); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(20 * kDefaultRequestSize, 1); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); EXPECT_EQ( static_cast<int>(client.partial_loader_data()->open_byte_range().end()), client.full_page_loader_data()->content_length()); client.partial_loader_data()->set_byte_range( client.partial_loader_data()->open_byte_range()); client.partial_loader_data()->CallOpenCallback(0); uint32_t data_length = client.partial_loader_data()->byte_range().length(); while (data_length > kDefaultRequestSize) { client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); data_length -= kDefaultRequestSize; } EXPECT_EQ(kLastChunkSize, data_length); client.partial_loader_data()->CallReadCallback(kLastChunkSize); EXPECT_TRUE(loader.IsDataAvailable(kDefaultRequestSize * 20, kLastChunkSize)); } TEST_F(DocumentLoaderTest, DocumentSize) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(123456789); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_EQ(static_cast<int>(loader.GetDocumentSize()), client.full_page_loader_data()->content_length()); } TEST_F(DocumentLoaderTest, DocumentSizeNoContentLength) { TestClient client; DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_EQ(0ul, loader.GetDocumentSize()); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); client.full_page_loader_data()->CallReadCallback(1000); client.full_page_loader_data()->CallReadCallback(500); client.full_page_loader_data()->CallReadCallback(0); EXPECT_EQ(kDefaultRequestSize + 1000ul + 500ul, loader.GetDocumentSize()); EXPECT_TRUE(loader.IsDocumentComplete()); } TEST_F(DocumentLoaderTest, ClearPendingRequests) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 100 + 58383); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(17 * kDefaultRequestSize + 100, 10); loader.ClearPendingRequests(); loader.RequestData(15 * kDefaultRequestSize + 200, 20); // pending requests are accumulating, and will be processed after initial data // load. EXPECT_FALSE(client.partial_loader_data()->IsWaitOpen()); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); { EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); const gfx::Range range_requested(15 * kDefaultRequestSize, 16 * kDefaultRequestSize); EXPECT_EQ(range_requested.start(), client.partial_loader_data()->open_byte_range().start()); EXPECT_LE(range_requested.end(), client.partial_loader_data()->open_byte_range().end()); client.partial_loader_data()->set_byte_range( client.partial_loader_data()->open_byte_range()); } // clear requests before Open callback. loader.ClearPendingRequests(); // Current request should continue loading. EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); client.partial_loader_data()->CallOpenCallback(0); client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_FALSE(client.partial_loader_data()->closed()); // Current request should continue loading, because no other request queued. loader.RequestData(18 * kDefaultRequestSize + 200, 20); // Requests queue is processed only on receiving data. client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); // New request within close distance from the one currently loading. Loading // isn't restarted. EXPECT_FALSE(client.partial_loader_data()->IsWaitOpen()); loader.ClearPendingRequests(); // request again two. loader.RequestData(60 * kDefaultRequestSize + 100, 10); loader.RequestData(35 * kDefaultRequestSize + 200, 20); // Requests queue is processed only on receiving data. client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); { // new requset not with in close distance from current loading. // Loading should be restarted. EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); // The first requested chunk should be processed. const gfx::Range range_requested(35 * kDefaultRequestSize, 36 * kDefaultRequestSize); EXPECT_EQ(range_requested.start(), client.partial_loader_data()->open_byte_range().start()); EXPECT_LE(range_requested.end(), client.partial_loader_data()->open_byte_range().end()); client.partial_loader_data()->set_byte_range( client.partial_loader_data()->open_byte_range()); } EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); client.partial_loader_data()->CallOpenCallback(0); // Override pending requests. loader.ClearPendingRequests(); loader.RequestData(70 * kDefaultRequestSize + 100, 10); // Requests queue is processed only on receiving data. client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); { // New requset not with in close distance from current loading. // Loading should be restarted . EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); // The first requested chunk should be processed. const gfx::Range range_requested(70 * kDefaultRequestSize, 71 * kDefaultRequestSize); EXPECT_EQ(range_requested.start(), client.partial_loader_data()->open_byte_range().start()); EXPECT_LE(range_requested.end(), client.partial_loader_data()->open_byte_range().end()); client.partial_loader_data()->set_byte_range( client.partial_loader_data()->open_byte_range()); } EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); } TEST_F(DocumentLoaderTest, GetBlock) { std::vector<char> buffer(kDefaultRequestSize); TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20 + 58383); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_FALSE(loader.GetBlock(0, 1000, buffer.data())); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(loader.GetBlock(0, 1000, buffer.data())); EXPECT_FALSE(loader.GetBlock(kDefaultRequestSize, 1500, buffer.data())); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(loader.GetBlock(kDefaultRequestSize, 1500, buffer.data())); EXPECT_FALSE(loader.GetBlock(17 * kDefaultRequestSize, 3000, buffer.data())); loader.RequestData(17 * kDefaultRequestSize + 100, 10); EXPECT_FALSE(loader.GetBlock(17 * kDefaultRequestSize, 3000, buffer.data())); // Requests queue is processed only on receiving data. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); client.SendAllPartialData(); EXPECT_TRUE(loader.GetBlock(17 * kDefaultRequestSize, 3000, buffer.data())); } TEST_F(DocumentLoaderTest, IsDataAvailable) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20 + 58383); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_FALSE(loader.IsDataAvailable(0, 1000)); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(loader.IsDataAvailable(0, 1000)); EXPECT_FALSE(loader.IsDataAvailable(kDefaultRequestSize, 1500)); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(loader.IsDataAvailable(kDefaultRequestSize, 1500)); EXPECT_FALSE(loader.IsDataAvailable(17 * kDefaultRequestSize, 3000)); loader.RequestData(17 * kDefaultRequestSize + 100, 10); EXPECT_FALSE(loader.IsDataAvailable(17 * kDefaultRequestSize, 3000)); // Requests queue is processed only on receiving data. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); client.SendAllPartialData(); EXPECT_TRUE(loader.IsDataAvailable(17 * kDefaultRequestSize, 3000)); } TEST_F(DocumentLoaderTest, RequestData) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 100 + 58383); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(37 * kDefaultRequestSize + 200, 10); loader.RequestData(25 * kDefaultRequestSize + 600, 100); loader.RequestData(13 * kDefaultRequestSize + 900, 500); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); { EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); const gfx::Range range_requested(13 * kDefaultRequestSize, 14 * kDefaultRequestSize); EXPECT_EQ(range_requested.start(), client.partial_loader_data()->open_byte_range().start()); EXPECT_LE(range_requested.end(), client.partial_loader_data()->open_byte_range().end()); client.partial_loader_data()->set_byte_range( client.partial_loader_data()->open_byte_range()); } client.partial_loader_data()->CallOpenCallback(0); // Override pending requests. loader.ClearPendingRequests(); loader.RequestData(38 * kDefaultRequestSize + 200, 10); loader.RequestData(26 * kDefaultRequestSize + 600, 100); // Requests queue is processed only on receiving data. client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); { EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); const gfx::Range range_requested(26 * kDefaultRequestSize, 27 * kDefaultRequestSize); EXPECT_EQ(range_requested.start(), client.partial_loader_data()->open_byte_range().start()); EXPECT_LE(range_requested.end(), client.partial_loader_data()->open_byte_range().end()); client.partial_loader_data()->set_byte_range( client.partial_loader_data()->open_byte_range()); } client.partial_loader_data()->CallOpenCallback(0); // Override pending requests. loader.ClearPendingRequests(); loader.RequestData(39 * kDefaultRequestSize + 200, 10); // Requests queue is processed only on receiving data. client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); { EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); const gfx::Range range_requested(39 * kDefaultRequestSize, 40 * kDefaultRequestSize); EXPECT_EQ(range_requested.start(), client.partial_loader_data()->open_byte_range().start()); EXPECT_LE(range_requested.end(), client.partial_loader_data()->open_byte_range().end()); client.partial_loader_data()->set_byte_range( client.partial_loader_data()->open_byte_range()); } // Fill all gaps. while (!loader.IsDocumentComplete()) { client.SendAllPartialData(); } EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, DoNotLoadAvailablePartialData) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20 + 58383); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); // Send more data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); loader.RequestData(2 * kDefaultRequestSize + 200, 10); // Send more data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); // Partial loading should not have started for already available data. EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, DoNotLoadDataAfterComplete) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); for (int i = 0; i < 20; ++i) { client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); } EXPECT_TRUE(loader.IsDocumentComplete()); loader.RequestData(17 * kDefaultRequestSize + 200, 10); EXPECT_TRUE(client.partial_loader_data()->closed()); EXPECT_TRUE(client.full_page_loader_data()->closed()); } TEST_F(DocumentLoaderTest, DoNotLoadPartialDataAboveDocumentSize) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(20 * kDefaultRequestSize + 200, 10); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, MergePendingRequests) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 50 + 58383); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(17 * kDefaultRequestSize + 200, 10); loader.RequestData(16 * kDefaultRequestSize + 600, 100); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); const gfx::Range range_requested(16 * kDefaultRequestSize, 18 * kDefaultRequestSize); EXPECT_EQ(range_requested.start(), client.partial_loader_data()->open_byte_range().start()); EXPECT_LE(range_requested.end(), client.partial_loader_data()->open_byte_range().end()); EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); // Fill all gaps. while (!loader.IsDocumentComplete()) { client.SendAllPartialData(); } EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, PartialStopOnStatusCodeError) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(17 * kDefaultRequestSize + 200, 10); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); client.partial_loader_data()->set_status_code(404); client.partial_loader_data()->CallOpenCallback(0); EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, PartialAsFullDocumentLoadingRangeRequestNoRangeField) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(17 * kDefaultRequestSize + 200, 10); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); client.partial_loader_data()->set_byte_range(gfx::Range::InvalidRange()); client.partial_loader_data()->CallOpenCallback(0); EXPECT_FALSE(client.partial_loader_data()->closed()); // Partial loader is used to load the whole page, like full page loader. EXPECT_FALSE(loader.is_partial_loader_active()); } TEST_F(DocumentLoaderTest, PartialMultiPart) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(17 * kDefaultRequestSize + 200, 10); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); client.partial_loader_data()->set_is_multipart(true); client.partial_loader_data()->CallOpenCallback(0); client.partial_loader_data()->set_byte_range( gfx::Range(17 * kDefaultRequestSize, 18 * kDefaultRequestSize)); client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE( loader.IsDataAvailable(17 * kDefaultRequestSize, kDefaultRequestSize)); } TEST_F(DocumentLoaderTest, PartialMultiPartRangeError) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(17 * kDefaultRequestSize + 200, 10); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); client.partial_loader_data()->set_is_multipart(true); client.partial_loader_data()->CallOpenCallback(0); client.partial_loader_data()->set_byte_range(gfx::Range::InvalidRange()); client.partial_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_FALSE( loader.IsDataAvailable(17 * kDefaultRequestSize, kDefaultRequestSize)); EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, PartialConnectionErrorOnOpen) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(17 * kDefaultRequestSize + 200, 10); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); client.partial_loader_data()->CallOpenCallback(-3); EXPECT_TRUE(client.partial_loader_data()->closed()); // Partial loading should not restart after any error. loader.RequestData(18 * kDefaultRequestSize + 200, 10); EXPECT_FALSE(client.partial_loader_data()->IsWaitOpen()); EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, PartialConnectionErrorOnRead) { TestClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(17 * kDefaultRequestSize + 200, 10); // Send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); EXPECT_TRUE(client.partial_loader_data()->IsWaitOpen()); client.partial_loader_data()->set_byte_range( gfx::Range(17 * kDefaultRequestSize, 18 * kDefaultRequestSize)); client.partial_loader_data()->CallOpenCallback(0); EXPECT_TRUE(client.partial_loader_data()->IsWaitRead()); client.partial_loader_data()->CallReadCallback(-3); EXPECT_TRUE(client.partial_loader_data()->closed()); // Partial loading should not restart after any error. loader.RequestData(18 * kDefaultRequestSize + 200, 10); EXPECT_FALSE(client.partial_loader_data()->IsWaitOpen()); EXPECT_TRUE(client.partial_loader_data()->closed()); } TEST_F(DocumentLoaderTest, ClientCompleteCallbacks) { MockClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_CALL(client, OnDocumentComplete()).Times(0); for (int i = 0; i < 19; ++i) client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); Mock::VerifyAndClear(&client); EXPECT_CALL(client, OnDocumentComplete()).Times(1); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); Mock::VerifyAndClear(&client); } TEST_F(DocumentLoaderTest, ClientCompleteCallbacksNoContentLength) { MockClient client; DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_CALL(client, OnDocumentCanceled()).Times(0); EXPECT_CALL(client, OnDocumentComplete()).Times(0); for (int i = 0; i < 20; ++i) client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); Mock::VerifyAndClear(&client); EXPECT_CALL(client, OnDocumentCanceled()).Times(0); EXPECT_CALL(client, OnDocumentComplete()).Times(1); client.full_page_loader_data()->CallReadCallback(0); Mock::VerifyAndClear(&client); } TEST_F(DocumentLoaderTest, ClientCancelCallback) { MockClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_CALL(client, OnDocumentCanceled()).Times(0); EXPECT_CALL(client, OnDocumentComplete()).Times(0); for (int i = 0; i < 10; ++i) client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); Mock::VerifyAndClear(&client); EXPECT_CALL(client, OnDocumentComplete()).Times(0); EXPECT_CALL(client, OnDocumentCanceled()).Times(1); client.full_page_loader_data()->CallReadCallback(-3); Mock::VerifyAndClear(&client); } TEST_F(DocumentLoaderTest, NewDataAvailable) { MockClient client; client.SetCanUsePartialLoading(); client.full_page_loader_data()->set_content_length(kDefaultRequestSize * 20); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_CALL(client, OnNewDataReceived()).Times(1); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); Mock::VerifyAndClear(&client); EXPECT_CALL(client, OnNewDataReceived()).Times(1); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize - 100); Mock::VerifyAndClear(&client); EXPECT_CALL(client, OnNewDataReceived()).Times(1); client.full_page_loader_data()->CallReadCallback(100); Mock::VerifyAndClear(&client); } TEST_F(DocumentLoaderTest, ClientPendingRequestCompleteFullLoader) { MockClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); loader.RequestData(1000, 4000); EXPECT_CALL(client, OnPendingRequestComplete()).Times(1); client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); Mock::VerifyAndClear(&client); } TEST_F(DocumentLoaderTest, ClientPendingRequestCompletePartialLoader) { MockClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_CALL(client, OnPendingRequestComplete()).Times(1); loader.RequestData(15 * kDefaultRequestSize + 4000, 4000); // Always send initial data from FullPageLoader. client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); client.SendAllPartialData(); Mock::VerifyAndClear(&client); } TEST_F(DocumentLoaderTest, ClientPendingRequestCompletePartialAndFullLoader) { MockClient client; client.SetCanUsePartialLoading(); DocumentLoader loader(&client); loader.Init(client.CreateFullPageLoader(), "http://url.com"); EXPECT_CALL(client, OnPendingRequestComplete()).Times(1); loader.RequestData(16 * kDefaultRequestSize + 4000, 4000); loader.RequestData(4 * kDefaultRequestSize + 4000, 4000); for (int i = 0; i < 5; ++i) client.full_page_loader_data()->CallReadCallback(kDefaultRequestSize); Mock::VerifyAndClear(&client); EXPECT_CALL(client, OnPendingRequestComplete()).Times(1); client.SendAllPartialData(); Mock::VerifyAndClear(&client); } } // namespace chrome_pdf
null
null
null
null
2,394
694
null
train_val
31e986bc171719c9e6d40d0c2cb1501796a69e6c
259,649
php-src
0
https://github.com/php/php-src
2016-10-24 10:37:20+01:00
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP 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.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Wez Furlong ([email protected]) | +----------------------------------------------------------------------+ Based on code from ucdata-2.5, which has the following Copyright: Copyright 2001 Computing Research Labs, New Mexico State University Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #if HAVE_MBSTRING /* include case folding data generated from the official UnicodeData.txt file */ #include "mbstring.h" #include "php_unicode.h" #include "unicode_data.h" ZEND_EXTERN_MODULE_GLOBALS(mbstring) /* * A simple array of 32-bit masks for lookup. */ static unsigned long masks32[32] = { 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 }; static int prop_lookup(unsigned long code, unsigned long n) { long l, r, m; /* * There is an extra node on the end of the offsets to allow this routine * to work right. If the index is 0xffff, then there are no nodes for the * property. */ if ((l = _ucprop_offsets[n]) == 0xffff) return 0; /* * Locate the next offset that is not 0xffff. The sentinel at the end of * the array is the max index value. */ for (m = 1; n + m < _ucprop_size && _ucprop_offsets[n + m] == 0xffff; m++) ; r = _ucprop_offsets[n + m] - 1; while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a range pair. */ m = (l + r) >> 1; m -= (m & 1); if (code > _ucprop_ranges[m + 1]) l = m + 2; else if (code < _ucprop_ranges[m]) r = m - 2; else if (code >= _ucprop_ranges[m] && code <= _ucprop_ranges[m + 1]) return 1; } return 0; } MBSTRING_API int php_unicode_is_prop(unsigned long code, unsigned long mask1, unsigned long mask2) { unsigned long i; if (mask1 == 0 && mask2 == 0) return 0; for (i = 0; mask1 && i < 32; i++) { if ((mask1 & masks32[i]) && prop_lookup(code, i)) return 1; } for (i = 32; mask2 && i < _ucprop_size; i++) { if ((mask2 & masks32[i & 31]) && prop_lookup(code, i)) return 1; } return 0; } static unsigned long case_lookup(unsigned long code, long l, long r, int field) { long m; /* * Do the binary search. */ while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a case mapping triple. */ m = (l + r) >> 1; m -= (m % 3); if (code > _uccase_map[m]) l = m + 3; else if (code < _uccase_map[m]) r = m - 3; else if (code == _uccase_map[m]) return _uccase_map[m + field]; } return code; } MBSTRING_API unsigned long php_turkish_toupper(unsigned long code, long l, long r, int field) { if (code == 0x0069L) { return 0x0130L; } return case_lookup(code, l, r, field); } MBSTRING_API unsigned long php_turkish_tolower(unsigned long code, long l, long r, int field) { if (code == 0x0049L) { return 0x0131L; } return case_lookup(code, l, r, field); } MBSTRING_API unsigned long php_unicode_toupper(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_upper(code)) return code; if (php_unicode_is_lower(code)) { /* * The character is lower case. */ field = 2; l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_toupper(code, l, r, field); } } else { /* * The character is title case. */ field = 1; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } MBSTRING_API unsigned long php_unicode_tolower(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_lower(code)) return code; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ field = 1; l = 0; r = _uccase_len[0] - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_tolower(code, l, r, field); } } else { /* * The character is title case. */ field = 2; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } MBSTRING_API unsigned long php_unicode_totitle(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_title(code)) return code; /* * The offset will always be the same for converting to title case. */ field = 2; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ l = 0; r = _uccase_len[0] - 3; } else { /* * The character is lower case. */ l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; } return case_lookup(code, l, r, field); } #define BE_ARY_TO_UINT32(ptr) (\ ((unsigned char*)(ptr))[0]<<24 |\ ((unsigned char*)(ptr))[1]<<16 |\ ((unsigned char*)(ptr))[2]<< 8 |\ ((unsigned char*)(ptr))[3] ) #define UINT32_TO_BE_ARY(ptr,val) { \ unsigned int v = val; \ ((unsigned char*)(ptr))[0] = (v>>24) & 0xff,\ ((unsigned char*)(ptr))[1] = (v>>16) & 0xff,\ ((unsigned char*)(ptr))[2] = (v>> 8) & 0xff,\ ((unsigned char*)(ptr))[3] = (v ) & 0xff;\ } MBSTRING_API char *php_unicode_convert_case(int case_mode, const char *srcstr, size_t srclen, size_t *ret_len, const char *src_encoding) { char *unicode, *newstr; size_t unicode_len; unsigned char *unicode_ptr; size_t i; enum mbfl_no_encoding _src_encoding = mbfl_name2no_encoding(src_encoding); if (_src_encoding == mbfl_no_encoding_invalid) { php_error_docref(NULL, E_WARNING, "Unknown encoding \"%s\"", src_encoding); return NULL; } unicode = php_mb_convert_encoding(srcstr, srclen, "UCS-4BE", src_encoding, &unicode_len); if (unicode == NULL) return NULL; unicode_ptr = (unsigned char *)unicode; switch(case_mode) { case PHP_UNICODE_CASE_UPPER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_toupper(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_LOWER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_TITLE: { int mode = 0; for (i = 0; i < unicode_len; i+=4) { int res = php_unicode_is_prop( BE_ARY_TO_UINT32(&unicode_ptr[i]), UC_MN|UC_ME|UC_CF|UC_LM|UC_SK|UC_LU|UC_LL|UC_LT|UC_PO|UC_OS, 0); if (mode) { if (res) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } else { mode = 0; } } else { if (res) { mode = 1; UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_totitle(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } } } } break; } newstr = php_mb_convert_encoding(unicode, unicode_len, src_encoding, "UCS-4BE", ret_len); efree(unicode); return newstr; } #endif /* HAVE_MBSTRING */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
null
null
null
null
119,570
2,388
null
train_val
04b570817b2b38e35675b17328239746212f4c3f
155,445
FFmpeg
0
https://github.com/FFmpeg/FFmpeg
2018-06-01 01:23:12+05:30
/* * Copyright (c) 2001-2003 The FFmpeg project * * 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 */ /** * @file * ADPCM tables */ #ifndef AVCODEC_ADPCM_DATA_H #define AVCODEC_ADPCM_DATA_H #include <stdint.h> static const uint8_t ff_adpcm_ima_block_sizes[4] = { 4, 12, 4, 20 }; static const uint8_t ff_adpcm_ima_block_samples[4] = { 16, 32, 8, 32 }; extern const int8_t * const ff_adpcm_index_tables[4]; extern const int8_t ff_adpcm_index_table[16]; extern const int16_t ff_adpcm_step_table[89]; extern const int16_t ff_adpcm_oki_step_table[49]; extern const int16_t ff_adpcm_AdaptationTable[]; extern const uint8_t ff_adpcm_AdaptCoeff1[]; extern const int8_t ff_adpcm_AdaptCoeff2[]; extern const int16_t ff_adpcm_yamaha_indexscale[]; extern const int8_t ff_adpcm_yamaha_difflookup[]; extern const int16_t ff_adpcm_afc_coeffs[2][16]; extern const int16_t ff_adpcm_mtaf_stepsize[32][16]; #endif /* AVCODEC_ADPCM_DATA_H */
null
null
null
null
71,500
46,503
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
46,503
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 "ash/system/night_light/time_of_day.h" #include "base/i18n/rtl.h" #include "base/test/icu_test_util.h" #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash { namespace { TEST(TimeOfDayTest, TestEquality) { // Test created TimeOfDay objects with equal offsets are equal. TimeOfDay time1(18 * 60 + 32); // 6:32 PM. TimeOfDay time2(18 * 60 + 32); // 6:32 PM. EXPECT_EQ(time1, time2); TimeOfDay time3(time1); EXPECT_EQ(time1, time3); EXPECT_EQ(time2, time3); TimeOfDay time4(9 * 60 + 59); // 9:59 AM. EXPECT_FALSE(time1 == time4); time1 = time4; EXPECT_EQ(time1, time4); } TEST(TimeOfDayTest, TestSeveralOffsets) { // Ensure US locale to make sure time format is expected. base::test::ScopedRestoreICUDefaultLocale restore_locale; base::i18n::SetICUDefaultLocale("en_US"); // 6:32 PM ==> 18:32. TimeOfDay time1(18 * 60 + 32); EXPECT_EQ("6:32 PM", time1.ToString()); // 9:59 AM. TimeOfDay time2(9 * 60 + 59); EXPECT_EQ("9:59 AM", time2.ToString()); // Border times: 00:00 and 24:00. TimeOfDay time3(0); TimeOfDay time4(24 * 60); EXPECT_EQ("12:00 AM", time3.ToString()); EXPECT_EQ("12:00 AM", time4.ToString()); } TEST(TimeOfDayTest, TestFromTime) { // "Now" today and "now" tomorrow should have the same minutes offset from // 00:00. // Assume that "now" is Tuesday May 23, 2017 at 10:30 AM. base::Time::Exploded now; now.year = 2017; now.month = 5; // May. now.day_of_week = 2; // Tuesday. now.day_of_month = 23; now.hour = 10; now.minute = 30; now.second = 0; now.millisecond = 0; base::Time now_today = base::Time::Now(); ASSERT_TRUE(base::Time::FromLocalExploded(now, &now_today)); base::Time now_tomorrow = now_today + base::TimeDelta::FromDays(1); EXPECT_EQ(TimeOfDay::FromTime(now_today), TimeOfDay::FromTime(now_tomorrow)); } } // namespace } // namespace ash
null
null
null
null
43,366
330
1
train_val
dc7b094a338c6c521f918f478e993f0f74bbea0d
330
Chrome
1
https://github.com/chromium/chromium
2011-06-15 06:45:53+00:00
virtual size_t GetNumActiveInputMethods() { scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods()); return descriptors->size(); }
CVE-2011-2804
CWE-399
https://github.com/chromium/chromium/commit/dc7b094a338c6c521f918f478e993f0f74bbea0d
Low
330
64,316
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
64,316
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. #ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_ #include "base/macros.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" class Profile; namespace chromeos { namespace settings { class SmbHandler : public ::settings::SettingsPageUIHandler { public: explicit SmbHandler(Profile* profile); ~SmbHandler() override; void RegisterMessages() override; void OnJavascriptAllowed() override {} void OnJavascriptDisallowed() override {} private: // WebUI call to mount an Smb Filesystem. void HandleSmbMount(const base::ListValue* args); Profile* const profile_; DISALLOW_COPY_AND_ASSIGN(SmbHandler); }; } // namespace settings } // namespace chromeos #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_CHROMEOS_SMB_HANDLER_H_
null
null
null
null
61,179
17,147
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
182,142
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef _LINUX_UNWINDER_H #define _LINUX_UNWINDER_H #include <asm/stacktrace.h> struct unwinder { const char *name; struct list_head list; int rating; void (*dump)(struct task_struct *, struct pt_regs *, unsigned long *, const struct stacktrace_ops *, void *); }; extern int unwinder_init(void); extern int unwinder_register(struct unwinder *); extern void unwind_stack(struct task_struct *, struct pt_regs *, unsigned long *, const struct stacktrace_ops *, void *); extern void stack_reader_dump(struct task_struct *, struct pt_regs *, unsigned long *, const struct stacktrace_ops *, void *); /* * Used by fault handling code to signal to the unwinder code that it * should switch to a different unwinder. */ extern int unwinder_faulted; #endif /* _LINUX_UNWINDER_H */
null
null
null
null
90,489
35,110
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
35,110
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2011 Google Inc. All rights reserved. * Copyright (C) 2012, 2013 Apple 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_CORE_HTML_TRACK_TEXT_TRACK_CUE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_TRACK_TEXT_TRACK_CUE_H_ #include "third_party/blink/renderer/core/dom/events/event_target.h" #include "third_party/blink/renderer/core/html/html_div_element.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { class TextTrack; class TextTrackCue : public EventTargetWithInlineData { DEFINE_WRAPPERTYPEINFO(); public: static const AtomicString& CueShadowPseudoId() { DEFINE_STATIC_LOCAL(const AtomicString, cue, ("cue")); return cue; } ~TextTrackCue() override = default; TextTrack* track() const; void SetTrack(TextTrack*); Node* Owner() const; const AtomicString& id() const { return id_; } void setId(const AtomicString&); double startTime() const { return start_time_; } void setStartTime(double); double endTime() const { return end_time_; } void setEndTime(double); bool pauseOnExit() const { return pause_on_exit_; } void setPauseOnExit(bool); unsigned CueIndex(); void UpdateCueIndex(unsigned cue_index) { cue_index_ = cue_index; } void InvalidateCueIndex(); bool IsActive() const { return is_active_; } void SetIsActive(bool active) { is_active_ = active; } // Updates the display tree and appends it to container if it has not // already been added. virtual void UpdateDisplay(HTMLDivElement& container) = 0; // Marks the nodes of the display tree as past or future relative to // movieTime. If updateDisplay() has not been called there is no display // tree and nothing is done. virtual void UpdatePastAndFutureNodes(double movie_time) = 0; // FIXME: Refactor to eliminate removeDisplayTree(). https://crbug.com/322434 enum RemovalNotification { kDontNotifyRegion, kNotifyRegion }; virtual void RemoveDisplayTree(RemovalNotification = kNotifyRegion) = 0; const AtomicString& InterfaceName() const override; #ifndef NDEBUG virtual String ToString() const = 0; #endif DEFINE_ATTRIBUTE_EVENT_LISTENER(enter); DEFINE_ATTRIBUTE_EVENT_LISTENER(exit); virtual void Trace(blink::Visitor*); protected: TextTrackCue(double start, double end); enum CueMutationAffectsOrder { kCueMutationDoesNotAffectOrder, kCueMutationAffectsOrder }; void CueWillChange(); virtual void CueDidChange( CueMutationAffectsOrder = kCueMutationDoesNotAffectOrder); DispatchEventResult DispatchEventInternal(Event*) override; private: AtomicString id_; double start_time_; double end_time_; Member<TextTrack> track_; unsigned cue_index_; bool is_active_ : 1; bool pause_on_exit_ : 1; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_TRACK_TEXT_TRACK_CUE_H_
null
null
null
null
31,973
61,420
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
61,420
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. #ifndef CHROME_BROWSER_FAVICON_LARGE_ICON_SERVICE_FACTORY_H_ #define CHROME_BROWSER_FAVICON_LARGE_ICON_SERVICE_FACTORY_H_ #include "base/macros.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" namespace base { template <typename T> struct DefaultSingletonTraits; } namespace content { class BrowserContext; } namespace favicon { class LargeIconService; } // Singleton that owns all LargeIconService and associates them with // BrowserContext instances. class LargeIconServiceFactory : public BrowserContextKeyedServiceFactory { public: static favicon::LargeIconService* GetForBrowserContext( content::BrowserContext* context); static LargeIconServiceFactory* GetInstance(); private: friend struct base::DefaultSingletonTraits<LargeIconServiceFactory>; LargeIconServiceFactory(); ~LargeIconServiceFactory() override; // BrowserContextKeyedServiceFactory: content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; bool ServiceIsNULLWhileTesting() const override; DISALLOW_COPY_AND_ASSIGN(LargeIconServiceFactory); }; #endif // CHROME_BROWSER_FAVICON_LARGE_ICON_SERVICE_FACTORY_H_
null
null
null
null
58,283
19,440
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
19,440
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 COMPONENTS_VARIATIONS_SYNTHETIC_TRIALS_ACTIVE_GROUP_ID_PROVIDER_H_ #define COMPONENTS_VARIATIONS_SYNTHETIC_TRIALS_ACTIVE_GROUP_ID_PROVIDER_H_ #include <vector> #include "base/macros.h" #include "base/synchronization/lock.h" #include "components/variations/active_field_trials.h" #include "components/variations/synthetic_trials.h" namespace base { template <typename T> struct DefaultSingletonTraits; } namespace variations { // This is a helper class which can observe the creation of SyntheticTrialGroups // and later provide a list of active group IDs to be included in the crash // reports. This class is a thread-safe singleton. class SyntheticTrialsActiveGroupIdProvider : public SyntheticTrialObserver { public: static SyntheticTrialsActiveGroupIdProvider* GetInstance(); // Populates |output| with currently active synthetic trial groups. |output| // cannot be nullptr. void GetActiveGroupIds(std::vector<ActiveGroupId>* output); // Clears state for testing. void ResetForTesting(); private: friend struct base::DefaultSingletonTraits< SyntheticTrialsActiveGroupIdProvider>; SyntheticTrialsActiveGroupIdProvider(); ~SyntheticTrialsActiveGroupIdProvider() override; // metrics::SyntheticTrialObserver: void OnSyntheticTrialsChanged( const std::vector<SyntheticTrialGroup>& groups) override; std::vector<ActiveGroupId> synthetic_trials_; base::Lock lock_; DISALLOW_COPY_AND_ASSIGN(SyntheticTrialsActiveGroupIdProvider); }; } // namespace variations #endif // COMPONENTS_VARIATIONS_SYNTHETIC_TRIALS_ACTIVE_GROUP_ID_PROVIDER_H_
null
null
null
null
16,303
3,245
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
265,813
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
#ifndef HW_ACPI_AML_BUILD_H #define HW_ACPI_AML_BUILD_H #include "hw/acpi/acpi-defs.h" #include "hw/acpi/bios-linker-loader.h" /* Reserve RAM space for tables: add another order of magnitude. */ #define ACPI_BUILD_TABLE_MAX_SIZE 0x200000 #define ACPI_BUILD_APPNAME6 "BOCHS " #define ACPI_BUILD_APPNAME4 "BXPC" #define ACPI_BUILD_TABLE_FILE "etc/acpi/tables" #define ACPI_BUILD_RSDP_FILE "etc/acpi/rsdp" #define ACPI_BUILD_TPMLOG_FILE "etc/tpm/log" #define AML_NOTIFY_METHOD "NTFY" typedef enum { AML_NO_OPCODE = 0,/* has only data */ AML_OPCODE, /* has opcode optionally followed by data */ AML_PACKAGE, /* has opcode and uses PkgLength for its length */ AML_EXT_PACKAGE, /* Same as AML_PACKAGE but also has 'ExOpPrefix' */ AML_BUFFER, /* data encoded as 'DefBuffer' */ AML_RES_TEMPLATE, /* encoded as ResourceTemplate macro */ } AmlBlockFlags; struct Aml { GArray *buf; /*< private >*/ uint8_t op; AmlBlockFlags block_flags; }; typedef struct Aml Aml; typedef enum { AML_COMPATIBILITY = 0, AML_TYPEA = 1, AML_TYPEB = 2, AML_TYPEF = 3, } AmlDmaType; typedef enum { AML_NOTBUSMASTER = 0, AML_BUSMASTER = 1, } AmlDmaBusMaster; typedef enum { AML_TRANSFER8 = 0, AML_TRANSFER8_16 = 1, AML_TRANSFER16 = 2, } AmlTransferSize; typedef enum { AML_DECODE10 = 0, AML_DECODE16 = 1, } AmlIODecode; typedef enum { AML_ANY_ACC = 0, AML_BYTE_ACC = 1, AML_WORD_ACC = 2, AML_DWORD_ACC = 3, AML_QWORD_ACC = 4, AML_BUFFER_ACC = 5, } AmlAccessType; typedef enum { AML_NOLOCK = 0, AML_LOCK = 1, } AmlLockRule; typedef enum { AML_PRESERVE = 0, AML_WRITE_AS_ONES = 1, AML_WRITE_AS_ZEROS = 2, } AmlUpdateRule; typedef enum { AML_SYSTEM_MEMORY = 0X00, AML_SYSTEM_IO = 0X01, AML_PCI_CONFIG = 0X02, } AmlRegionSpace; typedef enum { AML_MEMORY_RANGE = 0, AML_IO_RANGE = 1, AML_BUS_NUMBER_RANGE = 2, } AmlResourceType; typedef enum { AML_SUB_DECODE = 1 << 1, AML_POS_DECODE = 0 } AmlDecode; typedef enum { AML_MAX_FIXED = 1 << 3, AML_MAX_NOT_FIXED = 0, } AmlMaxFixed; typedef enum { AML_MIN_FIXED = 1 << 2, AML_MIN_NOT_FIXED = 0 } AmlMinFixed; /* * ACPI 1.0b: Table 6-26 I/O Resource Flag (Resource Type = 1) Definitions * _RNG field definition */ typedef enum { AML_ISA_ONLY = 1, AML_NON_ISA_ONLY = 2, AML_ENTIRE_RANGE = 3, } AmlISARanges; /* * ACPI 1.0b: Table 6-25 Memory Resource Flag (Resource Type = 0) Definitions * _MEM field definition */ typedef enum { AML_NON_CACHEABLE = 0, AML_CACHEABLE = 1, AML_WRITE_COMBINING = 2, AML_PREFETCHABLE = 3, } AmlCacheable; /* * ACPI 1.0b: Table 6-25 Memory Resource Flag (Resource Type = 0) Definitions * _RW field definition */ typedef enum { AML_READ_ONLY = 0, AML_READ_WRITE = 1, } AmlReadAndWrite; /* * ACPI 5.0: Table 6-187 Extended Interrupt Descriptor Definition * Interrupt Vector Flags Bits[0] Consumer/Producer */ typedef enum { AML_CONSUMER_PRODUCER = 0, AML_CONSUMER = 1, } AmlConsumerAndProducer; /* * ACPI 5.0: Table 6-187 Extended Interrupt Descriptor Definition * _HE field definition */ typedef enum { AML_LEVEL = 0, AML_EDGE = 1, } AmlLevelAndEdge; /* * ACPI 5.0: Table 6-187 Extended Interrupt Descriptor Definition * _LL field definition */ typedef enum { AML_ACTIVE_HIGH = 0, AML_ACTIVE_LOW = 1, } AmlActiveHighAndLow; /* * ACPI 5.0: Table 6-187 Extended Interrupt Descriptor Definition * _SHR field definition */ typedef enum { AML_EXCLUSIVE = 0, AML_SHARED = 1, AML_EXCLUSIVE_AND_WAKE = 2, AML_SHARED_AND_WAKE = 3, } AmlShared; /* ACPI 1.0b: 16.2.5.2 Named Objects Encoding: MethodFlags */ typedef enum { AML_NOTSERIALIZED = 0, AML_SERIALIZED = 1, } AmlSerializeFlag; /* * ACPI 5.0: Table 6-189 GPIO Connection Descriptor Definition * GPIO Connection Type */ typedef enum { AML_INTERRUPT_CONNECTION = 0, AML_IO_CONNECTION = 1, } AmlGpioConnectionType; /* * ACPI 5.0: Table 6-189 GPIO Connection Descriptor Definition * _PPI field definition */ typedef enum { AML_PULL_DEFAULT = 0, AML_PULL_UP = 1, AML_PULL_DOWN = 2, AML_PULL_NONE = 3, } AmlPinConfig; typedef enum { MEM_AFFINITY_NOFLAGS = 0, MEM_AFFINITY_ENABLED = (1 << 0), MEM_AFFINITY_HOTPLUGGABLE = (1 << 1), MEM_AFFINITY_NON_VOLATILE = (1 << 2), } MemoryAffinityFlags; typedef struct AcpiBuildTables { GArray *table_data; GArray *rsdp; GArray *tcpalog; BIOSLinker *linker; } AcpiBuildTables; /** * init_aml_allocator: * * Called for initializing API allocator which allow to use * AML API. * Returns: toplevel container which accumulates all other * AML elements for a table. */ Aml *init_aml_allocator(void); /** * free_aml_allocator: * * Releases all elements used by AML API, frees associated memory * and invalidates AML allocator. After this call @init_aml_allocator * should be called again if AML API is to be used again. */ void free_aml_allocator(void); /** * aml_append: * @parent_ctx: context to which @child element is added * @child: element that is copied into @parent_ctx context * * Joins Aml elements together and helps to construct AML tables * Examle of usage: * Aml *table = aml_def_block("SSDT", ...); * Aml *sb = aml_scope("\\_SB"); * Aml *dev = aml_device("PCI0"); * * aml_append(dev, aml_name_decl("HID", aml_eisaid("PNP0A03"))); * aml_append(sb, dev); * aml_append(table, sb); */ void aml_append(Aml *parent_ctx, Aml *child); /* non block AML object primitives */ Aml *aml_name(const char *name_format, ...) GCC_FMT_ATTR(1, 2); Aml *aml_name_decl(const char *name, Aml *val); Aml *aml_debug(void); Aml *aml_return(Aml *val); Aml *aml_int(const uint64_t val); Aml *aml_arg(int pos); Aml *aml_to_integer(Aml *arg); Aml *aml_to_hexstring(Aml *src, Aml *dst); Aml *aml_to_buffer(Aml *src, Aml *dst); Aml *aml_store(Aml *val, Aml *target); Aml *aml_and(Aml *arg1, Aml *arg2, Aml *dst); Aml *aml_or(Aml *arg1, Aml *arg2, Aml *dst); Aml *aml_lor(Aml *arg1, Aml *arg2); Aml *aml_shiftleft(Aml *arg1, Aml *count); Aml *aml_shiftright(Aml *arg1, Aml *count, Aml *dst); Aml *aml_lless(Aml *arg1, Aml *arg2); Aml *aml_add(Aml *arg1, Aml *arg2, Aml *dst); Aml *aml_subtract(Aml *arg1, Aml *arg2, Aml *dst); Aml *aml_increment(Aml *arg); Aml *aml_decrement(Aml *arg); Aml *aml_index(Aml *arg1, Aml *idx); Aml *aml_notify(Aml *arg1, Aml *arg2); Aml *aml_call0(const char *method); Aml *aml_call1(const char *method, Aml *arg1); Aml *aml_call2(const char *method, Aml *arg1, Aml *arg2); Aml *aml_call3(const char *method, Aml *arg1, Aml *arg2, Aml *arg3); Aml *aml_call4(const char *method, Aml *arg1, Aml *arg2, Aml *arg3, Aml *arg4); Aml *aml_call5(const char *method, Aml *arg1, Aml *arg2, Aml *arg3, Aml *arg4, Aml *arg5); Aml *aml_gpio_int(AmlConsumerAndProducer con_and_pro, AmlLevelAndEdge edge_level, AmlActiveHighAndLow active_level, AmlShared shared, AmlPinConfig pin_config, uint16_t debounce_timeout, const uint32_t pin_list[], uint32_t pin_count, const char *resource_source_name, const uint8_t *vendor_data, uint16_t vendor_data_len); Aml *aml_memory32_fixed(uint32_t addr, uint32_t size, AmlReadAndWrite read_and_write); Aml *aml_interrupt(AmlConsumerAndProducer con_and_pro, AmlLevelAndEdge level_and_edge, AmlActiveHighAndLow high_and_low, AmlShared shared, uint32_t *irq_list, uint8_t irq_count); Aml *aml_io(AmlIODecode dec, uint16_t min_base, uint16_t max_base, uint8_t aln, uint8_t len); Aml *aml_operation_region(const char *name, AmlRegionSpace rs, Aml *offset, uint32_t len); Aml *aml_irq_no_flags(uint8_t irq); Aml *aml_named_field(const char *name, unsigned length); Aml *aml_reserved_field(unsigned length); Aml *aml_local(int num); Aml *aml_string(const char *name_format, ...) GCC_FMT_ATTR(1, 2); Aml *aml_lnot(Aml *arg); Aml *aml_equal(Aml *arg1, Aml *arg2); Aml *aml_lgreater(Aml *arg1, Aml *arg2); Aml *aml_lgreater_equal(Aml *arg1, Aml *arg2); Aml *aml_processor(uint8_t proc_id, uint32_t pblk_addr, uint8_t pblk_len, const char *name_format, ...) GCC_FMT_ATTR(4, 5); Aml *aml_eisaid(const char *str); Aml *aml_word_bus_number(AmlMinFixed min_fixed, AmlMaxFixed max_fixed, AmlDecode dec, uint16_t addr_gran, uint16_t addr_min, uint16_t addr_max, uint16_t addr_trans, uint16_t len); Aml *aml_word_io(AmlMinFixed min_fixed, AmlMaxFixed max_fixed, AmlDecode dec, AmlISARanges isa_ranges, uint16_t addr_gran, uint16_t addr_min, uint16_t addr_max, uint16_t addr_trans, uint16_t len); Aml *aml_dword_io(AmlMinFixed min_fixed, AmlMaxFixed max_fixed, AmlDecode dec, AmlISARanges isa_ranges, uint32_t addr_gran, uint32_t addr_min, uint32_t addr_max, uint32_t addr_trans, uint32_t len); Aml *aml_dword_memory(AmlDecode dec, AmlMinFixed min_fixed, AmlMaxFixed max_fixed, AmlCacheable cacheable, AmlReadAndWrite read_and_write, uint32_t addr_gran, uint32_t addr_min, uint32_t addr_max, uint32_t addr_trans, uint32_t len); Aml *aml_qword_memory(AmlDecode dec, AmlMinFixed min_fixed, AmlMaxFixed max_fixed, AmlCacheable cacheable, AmlReadAndWrite read_and_write, uint64_t addr_gran, uint64_t addr_min, uint64_t addr_max, uint64_t addr_trans, uint64_t len); Aml *aml_dma(AmlDmaType typ, AmlDmaBusMaster bm, AmlTransferSize sz, uint8_t channel); Aml *aml_sleep(uint64_t msec); /* Block AML object primitives */ Aml *aml_scope(const char *name_format, ...) GCC_FMT_ATTR(1, 2); Aml *aml_device(const char *name_format, ...) GCC_FMT_ATTR(1, 2); Aml *aml_method(const char *name, int arg_count, AmlSerializeFlag sflag); Aml *aml_if(Aml *predicate); Aml *aml_else(void); Aml *aml_while(Aml *predicate); Aml *aml_package(uint8_t num_elements); Aml *aml_buffer(int buffer_size, uint8_t *byte_list); Aml *aml_resource_template(void); Aml *aml_field(const char *name, AmlAccessType type, AmlLockRule lock, AmlUpdateRule rule); Aml *aml_mutex(const char *name, uint8_t sync_level); Aml *aml_acquire(Aml *mutex, uint16_t timeout); Aml *aml_release(Aml *mutex); Aml *aml_alias(const char *source_object, const char *alias_object); Aml *aml_create_field(Aml *srcbuf, Aml *bit_index, Aml *num_bits, const char *name); Aml *aml_create_dword_field(Aml *srcbuf, Aml *index, const char *name); Aml *aml_create_qword_field(Aml *srcbuf, Aml *index, const char *name); Aml *aml_varpackage(uint32_t num_elements); Aml *aml_touuid(const char *uuid); Aml *aml_unicode(const char *str); Aml *aml_refof(Aml *arg); Aml *aml_derefof(Aml *arg); Aml *aml_sizeof(Aml *arg); Aml *aml_concatenate(Aml *source1, Aml *source2, Aml *target); Aml *aml_object_type(Aml *object); void build_append_int_noprefix(GArray *table, uint64_t value, int size); void build_header(BIOSLinker *linker, GArray *table_data, AcpiTableHeader *h, const char *sig, int len, uint8_t rev, const char *oem_id, const char *oem_table_id); void *acpi_data_push(GArray *table_data, unsigned size); unsigned acpi_data_len(GArray *table); void acpi_add_table(GArray *table_offsets, GArray *table_data); void acpi_build_tables_init(AcpiBuildTables *tables); void acpi_build_tables_cleanup(AcpiBuildTables *tables, bool mfre); void build_rsdt(GArray *table_data, BIOSLinker *linker, GArray *table_offsets, const char *oem_id, const char *oem_table_id); int build_append_named_dword(GArray *array, const char *name_format, ...) GCC_FMT_ATTR(2, 3); void build_srat_memory(AcpiSratMemoryAffinity *numamem, uint64_t base, uint64_t len, int node, MemoryAffinityFlags flags); #endif
null
null
null
null
123,937
12,887
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
12,887
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. // Implements a custom word iterator used for our spellchecker. #include "components/spellcheck/renderer/spellcheck_worditerator.h" #include <map> #include <memory> #include <string> #include <utility> #include "base/i18n/break_iterator.h" #include "base/logging.h" #include "base/macros.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "components/spellcheck/renderer/spellcheck.h" #include "third_party/icu/source/common/unicode/normlzr.h" #include "third_party/icu/source/common/unicode/schriter.h" #include "third_party/icu/source/common/unicode/uscript.h" #include "third_party/icu/source/i18n/unicode/ulocdata.h" // SpellcheckCharAttribute implementation: SpellcheckCharAttribute::SpellcheckCharAttribute() : script_code_(USCRIPT_LATIN) { } SpellcheckCharAttribute::~SpellcheckCharAttribute() { } void SpellcheckCharAttribute::SetDefaultLanguage(const std::string& language) { CreateRuleSets(language); } base::string16 SpellcheckCharAttribute::GetRuleSet( bool allow_contraction) const { return allow_contraction ? ruleset_allow_contraction_ : ruleset_disallow_contraction_; } void SpellcheckCharAttribute::CreateRuleSets(const std::string& language) { // The template for our custom rule sets, which is based on the word-break // rules of ICU 4.0: // <http://source.icu-project.org/repos/icu/icu/tags/release-4-0/source/data/brkitr/word.txt>. // The major differences from the original one are listed below: // * It discards comments in the original rules. // * It discards characters not needed by our spellchecker (e.g. numbers, // punctuation characters, Hiraganas, Katakanas, CJK Ideographs, and so on). // * It allows customization of the $ALetter value (i.e. word characters). // * It allows customization of the $ALetterPlus value (i.e. whether or not to // use the dictionary data). // * It allows choosing whether or not to split a text at contraction // characters. // This template only changes the forward-iteration rules. So, calling // ubrk_prev() returns the same results as the original template. static const char kRuleTemplate[] = "!!chain;" "$CR = [\\p{Word_Break = CR}];" "$LF = [\\p{Word_Break = LF}];" "$Newline = [\\p{Word_Break = Newline}];" "$Extend = [\\p{Word_Break = Extend}];" "$Format = [\\p{Word_Break = Format}];" "$Katakana = [\\p{Word_Break = Katakana}];" // Not all the characters in a given script are ALetter. // For instance, U+05F4 is MidLetter. So, this may be // better, but it leads to an empty set error in Thai. // "$ALetter = [[\\p{script=%s}] & [\\p{Word_Break = ALetter}]];" "$ALetter = [\\p{script=%s}%s];" // U+0027 (single quote/apostrophe) is not in MidNumLet any more // in UAX 29 rev 21 or later. For our purpose, U+0027 // has to be treated as MidNumLet. ( http://crbug.com/364072 ) "$MidNumLet = [\\p{Word_Break = MidNumLet} \\u0027];" "$MidLetter = [\\p{Word_Break = MidLetter}%s];" "$MidNum = [\\p{Word_Break = MidNum}];" "$Numeric = [\\p{Word_Break = Numeric}];" "$ExtendNumLet = [\\p{Word_Break = ExtendNumLet}];" "$Control = [\\p{Grapheme_Cluster_Break = Control}]; " "%s" // ALetterPlus "$KatakanaEx = $Katakana ($Extend | $Format)*;" "$ALetterEx = $ALetterPlus ($Extend | $Format)*;" "$MidNumLetEx = $MidNumLet ($Extend | $Format)*;" "$MidLetterEx = $MidLetter ($Extend | $Format)*;" "$MidNumEx = $MidNum ($Extend | $Format)*;" "$NumericEx = $Numeric ($Extend | $Format)*;" "$ExtendNumLetEx = $ExtendNumLet ($Extend | $Format)*;" "$Hiragana = [\\p{script=Hiragana}];" "$Ideographic = [\\p{Ideographic}];" "$HiraganaEx = $Hiragana ($Extend | $Format)*;" "$IdeographicEx = $Ideographic ($Extend | $Format)*;" "!!forward;" "$CR $LF;" "[^$CR $LF $Newline]? ($Extend | $Format)+;" "$ALetterEx {200};" "$ALetterEx $ALetterEx {200};" "%s" // (Allow|Disallow) Contraction "!!reverse;" "$BackALetterEx = ($Format | $Extend)* $ALetterPlus;" "$BackMidNumLetEx = ($Format | $Extend)* $MidNumLet;" "$BackNumericEx = ($Format | $Extend)* $Numeric;" "$BackMidNumEx = ($Format | $Extend)* $MidNum;" "$BackMidLetterEx = ($Format | $Extend)* $MidLetter;" "$BackKatakanaEx = ($Format | $Extend)* $Katakana;" "$BackExtendNumLetEx= ($Format | $Extend)* $ExtendNumLet;" "$LF $CR;" "($Format | $Extend)* [^$CR $LF $Newline]?;" "$BackALetterEx $BackALetterEx;" "$BackALetterEx ($BackMidLetterEx | $BackMidNumLetEx) $BackALetterEx;" "$BackNumericEx $BackNumericEx;" "$BackNumericEx $BackALetterEx;" "$BackALetterEx $BackNumericEx;" "$BackNumericEx ($BackMidNumEx | $BackMidNumLetEx) $BackNumericEx;" "$BackKatakanaEx $BackKatakanaEx;" "$BackExtendNumLetEx ($BackALetterEx | $BackNumericEx |" " $BackKatakanaEx | $BackExtendNumLetEx);" "($BackALetterEx | $BackNumericEx | $BackKatakanaEx)" " $BackExtendNumLetEx;" "!!safe_reverse;" "($Extend | $Format)+ .?;" "($MidLetter | $MidNumLet) $BackALetterEx;" "($MidNum | $MidNumLet) $BackNumericEx;" "!!safe_forward;" "($Extend | $Format)+ .?;" "($MidLetterEx | $MidNumLetEx) $ALetterEx;" "($MidNumEx | $MidNumLetEx) $NumericEx;"; // Retrieve the script codes used by the given language from ICU. When the // given language consists of two or more scripts, we just use the first // script. The size of returned script codes is always < 8. Therefore, we use // an array of size 8 so we can include all script codes without insufficient // buffer errors. UErrorCode error = U_ZERO_ERROR; UScriptCode script_code[8]; int scripts = uscript_getCode(language.c_str(), script_code, arraysize(script_code), &error); if (U_SUCCESS(error) && scripts >= 1) script_code_ = script_code[0]; // Retrieve the values for $ALetter and $ALetterPlus. We use the dictionary // only for the languages which need it (i.e. Korean and Thai) to prevent ICU // from returning dictionary words (i.e. Korean or Thai words) for languages // which don't need them. const char* aletter = uscript_getName(script_code_); if (!aletter) aletter = "Latin"; const char kWithDictionary[] = "$dictionary = [:LineBreak = Complex_Context:];" "$ALetterPlus = [$ALetter [$dictionary-$Extend-$Control]];"; const char kWithoutDictionary[] = "$ALetterPlus = $ALetter;"; const char* aletter_plus = kWithoutDictionary; if (script_code_ == USCRIPT_HANGUL || script_code_ == USCRIPT_THAI || script_code_ == USCRIPT_LAO || script_code_ == USCRIPT_KHMER) aletter_plus = kWithDictionary; // Treat numbers as word characters except for Arabic and Hebrew. const char* aletter_extra = " [0123456789]"; if (script_code_ == USCRIPT_HEBREW) aletter_extra = ""; else if (script_code_ == USCRIPT_ARABIC) // When "script=Arabic", it does not include tatweel, which is // "script=Common" so add it back. Otherwise, it creates unwanted // word breaks. aletter_extra = " [\\u0640]"; const char kMidLetterExtra[] = ""; // For Hebrew, treat single/double quoation marks as MidLetter. const char kMidLetterExtraHebrew[] = "\"'"; const char* midletter_extra = kMidLetterExtra; if (script_code_ == USCRIPT_HEBREW) midletter_extra = kMidLetterExtraHebrew; // Create two custom rule-sets: one allows contraction and the other does not. // We save these strings in UTF-16 so we can use it without conversions. (ICU // needs UTF-16 strings.) const char kAllowContraction[] = "$ALetterEx ($MidLetterEx | $MidNumLetEx) $ALetterEx {200};"; const char kDisallowContraction[] = ""; ruleset_allow_contraction_ = base::ASCIIToUTF16( base::StringPrintf(kRuleTemplate, aletter, aletter_extra, midletter_extra, aletter_plus, kAllowContraction)); ruleset_disallow_contraction_ = base::ASCIIToUTF16( base::StringPrintf(kRuleTemplate, aletter, aletter_extra, midletter_extra, aletter_plus, kDisallowContraction)); } bool SpellcheckCharAttribute::OutputChar(UChar c, base::string16* output) const { // Call the language-specific function if necessary. // Otherwise, we call the default one. switch (script_code_) { case USCRIPT_ARABIC: return OutputArabic(c, output); case USCRIPT_HANGUL: return OutputHangul(c, output); case USCRIPT_HEBREW: return OutputHebrew(c, output); default: return OutputDefault(c, output); } } bool SpellcheckCharAttribute::OutputArabic(UChar c, base::string16* output) const { // Include non-Arabic characters (which should trigger a spelling error) // and Arabic characters excluding vowel marks and class "Lm". // We filter the latter because, while they are "letters", they are // optional and so don't affect the correctness of the rest of the word. if (!(0x0600 <= c && c <= 0x06FF) || (u_isalpha(c) && c != 0x0640)) output->push_back(c); return true; } bool SpellcheckCharAttribute::OutputHangul(UChar c, base::string16* output) const { // Decompose a Hangul character to a Hangul vowel and consonants used by our // spellchecker. A Hangul character of Unicode is a ligature consisting of a // Hangul vowel and consonants, e.g. U+AC01 "Gag" consists of U+1100 "G", // U+1161 "a", and U+11A8 "g". That is, we can treat each Hangul character as // a point of a cubic linear space consisting of (first consonant, vowel, last // consonant). Therefore, we can compose a Hangul character from a vowel and // two consonants with linear composition: // character = 0xAC00 + // (first consonant - 0x1100) * 28 * 21 + // (vowel - 0x1161) * 28 + // (last consonant - 0x11A7); // We can also decompose a Hangul character with linear decomposition: // first consonant = (character - 0xAC00) / 28 / 21; // vowel = (character - 0xAC00) / 28 % 21; // last consonant = (character - 0xAC00) % 28; // This code is copied from Unicode Standard Annex #15 // <http://unicode.org/reports/tr15> and added some comments. const int kSBase = 0xAC00; // U+AC00: the top of Hangul characters. const int kLBase = 0x1100; // U+1100: the top of Hangul first consonants. const int kVBase = 0x1161; // U+1161: the top of Hangul vowels. const int kTBase = 0x11A7; // U+11A7: the top of Hangul last consonants. const int kLCount = 19; // The number of Hangul first consonants. const int kVCount = 21; // The number of Hangul vowels. const int kTCount = 28; // The number of Hangul last consonants. const int kNCount = kVCount * kTCount; const int kSCount = kLCount * kNCount; int index = c - kSBase; if (index < 0 || index >= kSBase + kSCount) { // This is not a Hangul syllable. Call the default output function since we // should output this character when it is a Hangul syllable. return OutputDefault(c, output); } // This is a Hangul character. Decompose this characters into Hangul vowels // and consonants. int l = kLBase + index / kNCount; int v = kVBase + (index % kNCount) / kTCount; int t = kTBase + index % kTCount; output->push_back(l); output->push_back(v); if (t != kTBase) output->push_back(t); return true; } bool SpellcheckCharAttribute::OutputHebrew(UChar c, base::string16* output) const { // Discard characters except Hebrew alphabets. We also discard Hebrew niqquds // to prevent our Hebrew dictionary from marking a Hebrew word including // niqquds as misspelled. (Same as Arabic vowel marks, we need to check // niqquds manually and filter them out since their script codes are // USCRIPT_HEBREW.) // Pass through ASCII single/double quotation marks and Hebrew Geresh and // Gershayim. if ((0x05D0 <= c && c <= 0x05EA) || c == 0x22 || c == 0x27 || c == 0x05F4 || c == 0x05F3) output->push_back(c); return true; } bool SpellcheckCharAttribute::OutputDefault(UChar c, base::string16* output) const { // Check the script code of this character and output only if it is the one // used by the spellchecker language. UErrorCode status = U_ZERO_ERROR; UScriptCode script_code = uscript_getScript(c, &status); if (script_code == script_code_ || script_code == USCRIPT_COMMON) output->push_back(c); return true; } // SpellcheckWordIterator implementation: SpellcheckWordIterator::SpellcheckWordIterator() : text_(nullptr), attribute_(nullptr), iterator_() {} SpellcheckWordIterator::~SpellcheckWordIterator() { Reset(); } bool SpellcheckWordIterator::Initialize( const SpellcheckCharAttribute* attribute, bool allow_contraction) { // Create a custom ICU break iterator with empty text used in this object. (We // allow setting text later so we can re-use this iterator.) DCHECK(attribute); const base::string16 rule(attribute->GetRuleSet(allow_contraction)); // If there is no rule set, the attributes were invalid. if (rule.empty()) return false; std::unique_ptr<base::i18n::BreakIterator> iterator( new base::i18n::BreakIterator(base::string16(), rule)); if (!iterator->Init()) { // Since we're not passing in any text, the only reason this could fail // is if we fail to parse the rules. Since the rules are hardcoded, // that would be a bug in this class. NOTREACHED() << "failed to open iterator (broken rules)"; return false; } iterator_ = std::move(iterator); // Set the character attributes so we can normalize the words extracted by // this iterator. attribute_ = attribute; return true; } bool SpellcheckWordIterator::IsInitialized() const { // Return true iff we have an iterator. return !!iterator_; } bool SpellcheckWordIterator::SetText(const base::char16* text, size_t length) { DCHECK(!!iterator_); // Set the text to be split by this iterator. if (!iterator_->SetText(text, length)) { LOG(ERROR) << "failed to set text"; return false; } text_ = text; return true; } SpellcheckWordIterator::WordIteratorStatus SpellcheckWordIterator::GetNextWord( base::string16* word_string, int* word_start, int* word_length) { DCHECK(!!text_); word_string->clear(); *word_start = 0; *word_length = 0; if (!text_) { return IS_END_OF_TEXT; } // Find a word that can be checked for spelling or a character that can be // skipped over. Rather than moving past a skippable character this returns // IS_SKIPPABLE and defers handling the character to the calling function. while (iterator_->Advance()) { const size_t start = iterator_->prev(); const size_t length = iterator_->pos() - start; switch (iterator_->GetWordBreakStatus()) { case base::i18n::BreakIterator::IS_WORD_BREAK: { if (Normalize(start, length, word_string)) { *word_start = start; *word_length = length; return IS_WORD; } break; } case base::i18n::BreakIterator::IS_SKIPPABLE_WORD: { *word_string = iterator_->GetString(); *word_start = start; *word_length = length; return IS_SKIPPABLE; } // |iterator_| is RULE_BASED so the break status should never be // IS_LINE_OR_CHAR_BREAK. case base::i18n::BreakIterator::IS_LINE_OR_CHAR_BREAK: { NOTREACHED(); break; } } } // There aren't any more words in the given text. return IS_END_OF_TEXT; } void SpellcheckWordIterator::Reset() { iterator_.reset(); } bool SpellcheckWordIterator::Normalize(int input_start, int input_length, base::string16* output_string) const { // We use NFKC (Normalization Form, Compatible decomposition, followed by // canonical Composition) defined in Unicode Standard Annex #15 to normalize // this token because it it the most suitable normalization algorithm for our // spellchecker. Nevertheless, it is not a perfect algorithm for our // spellchecker and we need manual normalization as well. The normalized // text does not have to be NUL-terminated since its characters are copied to // string16, which adds a NUL character when we need. icu::UnicodeString input(FALSE, &text_[input_start], input_length); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString output; icu::Normalizer::normalize(input, UNORM_NFKC, 0, output, status); if (status != U_ZERO_ERROR && status != U_STRING_NOT_TERMINATED_WARNING) return false; // Copy the normalized text to the output. icu::StringCharacterIterator it(output); for (UChar c = it.first(); c != icu::CharacterIterator::DONE; c = it.next()) attribute_->OutputChar(c, output_string); return !output_string->empty(); }
null
null
null
null
9,750
66,799
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
66,799
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/sync_file_system/local/local_file_sync_context.h" #include <stdint.h> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/sync_file_system/local/canned_syncable_file_system.h" #include "chrome/browser/sync_file_system/local/local_file_change_tracker.h" #include "chrome/browser/sync_file_system/local/sync_file_system_backend.h" #include "chrome/browser/sync_file_system/sync_file_metadata.h" #include "chrome/browser/sync_file_system/sync_status_code.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "storage/browser/blob/scoped_file.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/fileapi/file_system_operation_runner.h" #include "storage/browser/fileapi/isolated_context.h" #include "storage/browser/test/mock_blob_url_request_context.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/leveldb_chrome.h" #define FPL FILE_PATH_LITERAL using content::BrowserThread; using storage::FileSystemContext; using storage::FileSystemURL; using storage::FileSystemURLSet; // This tests LocalFileSyncContext behavior in multi-thread / // multi-file-system-context environment. // Basic combined tests (single-thread / single-file-system-context) // that involve LocalFileSyncContext are also in // syncable_file_system_unittests.cc. namespace sync_file_system { namespace { const char kOrigin1[] = "http://example.com"; const char kOrigin2[] = "http://chromium.org"; } class LocalFileSyncContextTest : public testing::Test { protected: LocalFileSyncContextTest() : thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD), status_(SYNC_FILE_ERROR_FAILED), file_error_(base::File::FILE_ERROR_FAILED), async_modify_finished_(false), has_inflight_prepare_for_sync_(false) {} void SetUp() override { RegisterSyncableFileSystem(); ASSERT_TRUE(dir_.CreateUniqueTempDir()); in_memory_env_.reset(leveldb_chrome::NewMemEnv(leveldb::Env::Default())); ui_task_runner_ = base::ThreadTaskRunnerHandle::Get(); io_task_runner_ = BrowserThread::GetTaskRunnerForThread(BrowserThread::IO); file_task_runner_ = BrowserThread::GetTaskRunnerForThread(BrowserThread::IO); } void TearDown() override { RevokeSyncableFileSystem(); } void StartPrepareForSync(FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, storage::ScopedFile* snapshot) { ASSERT_TRUE(changes != nullptr); ASSERT_FALSE(has_inflight_prepare_for_sync_); status_ = SYNC_STATUS_UNKNOWN; has_inflight_prepare_for_sync_ = true; sync_context_->PrepareForSync( file_system_context, url, sync_mode, base::Bind(&LocalFileSyncContextTest::DidPrepareForSync, base::Unretained(this), metadata, changes, snapshot)); } SyncStatusCode PrepareForSync(FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, storage::ScopedFile* snapshot) { StartPrepareForSync(file_system_context, url, sync_mode, metadata, changes, snapshot); base::RunLoop().Run(); return status_; } base::Closure GetPrepareForSyncClosure( FileSystemContext* file_system_context, const FileSystemURL& url, LocalFileSyncContext::SyncMode sync_mode, SyncFileMetadata* metadata, FileChangeList* changes, storage::ScopedFile* snapshot) { return base::Bind(&LocalFileSyncContextTest::StartPrepareForSync, base::Unretained(this), base::Unretained(file_system_context), url, sync_mode, metadata, changes, snapshot); } void DidPrepareForSync(SyncFileMetadata* metadata_out, FileChangeList* changes_out, storage::ScopedFile* snapshot_out, SyncStatusCode status, const LocalFileSyncInfo& sync_file_info, storage::ScopedFile snapshot) { ASSERT_TRUE(ui_task_runner_->RunsTasksInCurrentSequence()); has_inflight_prepare_for_sync_ = false; status_ = status; *metadata_out = sync_file_info.metadata; *changes_out = sync_file_info.changes; if (snapshot_out) *snapshot_out = std::move(snapshot); base::RunLoop::QuitCurrentWhenIdleDeprecated(); } SyncStatusCode ApplyRemoteChange(FileSystemContext* file_system_context, const FileChange& change, const base::FilePath& local_path, const FileSystemURL& url, SyncFileType expected_file_type) { SCOPED_TRACE(testing::Message() << "ApplyChange for " << url.DebugString()); // First we should call PrepareForSync to disable writing. SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system_context, url, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); EXPECT_EQ(expected_file_type, metadata.file_type); status_ = SYNC_STATUS_UNKNOWN; sync_context_->ApplyRemoteChange( file_system_context, change, local_path, url, base::Bind(&LocalFileSyncContextTest::DidApplyRemoteChange, base::Unretained(this), base::RetainedRef(file_system_context), url)); base::RunLoop().Run(); return status_; } void DidApplyRemoteChange(FileSystemContext* file_system_context, const FileSystemURL& url, SyncStatusCode status) { status_ = status; sync_context_->FinalizeExclusiveSync( file_system_context, url, status == SYNC_STATUS_OK /* clear_local_changes */, base::MessageLoop::QuitWhenIdleClosure()); } void StartModifyFileOnIOThread(CannedSyncableFileSystem* file_system, const FileSystemURL& url) { ASSERT_TRUE(file_system != nullptr); if (!io_task_runner_->RunsTasksInCurrentSequence()) { async_modify_finished_ = false; ASSERT_TRUE(ui_task_runner_->RunsTasksInCurrentSequence()); io_task_runner_->PostTask( FROM_HERE, base::BindOnce(&LocalFileSyncContextTest::StartModifyFileOnIOThread, base::Unretained(this), file_system, url)); return; } ASSERT_TRUE(io_task_runner_->RunsTasksInCurrentSequence()); file_error_ = base::File::FILE_ERROR_FAILED; file_system->operation_runner()->Truncate( url, 1, base::Bind(&LocalFileSyncContextTest::DidModifyFile, base::Unretained(this))); } base::File::Error WaitUntilModifyFileIsDone() { while (!async_modify_finished_) base::RunLoop().RunUntilIdle(); return file_error_; } void DidModifyFile(base::File::Error error) { if (!ui_task_runner_->RunsTasksInCurrentSequence()) { ASSERT_TRUE(io_task_runner_->RunsTasksInCurrentSequence()); ui_task_runner_->PostTask( FROM_HERE, base::BindOnce(&LocalFileSyncContextTest::DidModifyFile, base::Unretained(this), error)); return; } ASSERT_TRUE(ui_task_runner_->RunsTasksInCurrentSequence()); file_error_ = error; async_modify_finished_ = true; } void SimulateFinishSync(FileSystemContext* file_system_context, const FileSystemURL& url, SyncStatusCode status, LocalFileSyncContext::SyncMode sync_mode) { if (sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT) { sync_context_->FinalizeSnapshotSync(file_system_context, url, status, base::DoNothing()); } else { sync_context_->FinalizeExclusiveSync( file_system_context, url, status == SYNC_STATUS_OK /* clear_local_changes */, base::DoNothing()); } } void PrepareForSync_Basic(LocalFileSyncContext::SyncMode sync_mode, SyncStatusCode simulate_sync_finish_status) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext( sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile(file_system.URL("file")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system.file_system_context(), kFile, sync_mode, &metadata, &changes, nullptr)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); // We should see the same set of changes. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); SimulateFinishSync(file_system.file_system_context(), kFile, simulate_sync_finish_status, sync_mode); file_system.GetChangesForURLInTracker(kFile, &changes); if (simulate_sync_finish_status == SYNC_STATUS_OK) { // The change's cleared. EXPECT_TRUE(changes.empty()); } else { EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); } sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } void PrepareForSync_WriteDuringSync( LocalFileSyncContext::SyncMode sync_mode) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext( sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile(file_system.URL("file")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); SyncFileMetadata metadata; FileChangeList changes; storage::ScopedFile snapshot; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system.file_system_context(), kFile, sync_mode, &metadata, &changes, &snapshot)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT, !snapshot.path().empty()); // Tracker keeps same set of changes. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); StartModifyFileOnIOThread(&file_system, kFile); if (sync_mode == LocalFileSyncContext::SYNC_SNAPSHOT) { // Write should succeed. EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); } else { base::RunLoop().RunUntilIdle(); EXPECT_FALSE(async_modify_finished_); } SimulateFinishSync(file_system.file_system_context(), kFile, SYNC_STATUS_OK, sync_mode); EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); // Sync succeeded, but the other change that was made during or // after sync is recorded. file_system.GetChangesForURLInTracker(kFile, &changes); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } base::ScopedTempDir dir_; std::unique_ptr<leveldb::Env> in_memory_env_; // These need to remain until the very end. content::TestBrowserThreadBundle thread_bundle_; scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_; scoped_refptr<LocalFileSyncContext> sync_context_; SyncStatusCode status_; base::File::Error file_error_; bool async_modify_finished_; bool has_inflight_prepare_for_sync_; }; TEST_F(LocalFileSyncContextTest, ConstructAndDestruct) { sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); sync_context_->ShutdownOnUIThread(); } TEST_F(LocalFileSyncContextTest, InitializeFileSystemContext) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); // Initializes file_system using |sync_context_|. EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); // Make sure everything's set up for file_system to be able to handle // syncable file system operations. EXPECT_TRUE(file_system.backend()->sync_context() != nullptr); EXPECT_TRUE(file_system.backend()->change_tracker() != nullptr); EXPECT_EQ(sync_context_.get(), file_system.backend()->sync_context()); // Calling MaybeInitialize for the same context multiple times must be ok. EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(sync_context_.get(), file_system.backend()->sync_context()); // Opens the file_system, perform some operation and see if the change tracker // correctly captures the change. EXPECT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kURL(file_system.URL("foo")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kURL)); FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(base::ContainsKey(urls, kURL)); // Finishing the test. sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, MultipleFileSystemContexts) { CannedSyncableFileSystem file_system1(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); CannedSyncableFileSystem file_system2(GURL(kOrigin2), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system1.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); file_system2.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); // Initializes file_system1 and file_system2. EXPECT_EQ(SYNC_STATUS_OK, file_system1.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(SYNC_STATUS_OK, file_system2.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(base::File::FILE_OK, file_system1.OpenFileSystem()); EXPECT_EQ(base::File::FILE_OK, file_system2.OpenFileSystem()); const FileSystemURL kURL1(file_system1.URL("foo")); const FileSystemURL kURL2(file_system2.URL("bar")); // Creates a file in file_system1. EXPECT_EQ(base::File::FILE_OK, file_system1.CreateFile(kURL1)); // file_system1's tracker must have recorded the change. FileSystemURLSet urls; file_system1.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(base::ContainsKey(urls, kURL1)); // file_system1's tracker must have no change. urls.clear(); file_system2.GetChangedURLsInTracker(&urls); ASSERT_TRUE(urls.empty()); // Creates a directory in file_system2. EXPECT_EQ(base::File::FILE_OK, file_system2.CreateDirectory(kURL2)); // file_system1's tracker must have the change for kURL1 as before. urls.clear(); file_system1.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(base::ContainsKey(urls, kURL1)); // file_system2's tracker now must have the change for kURL2. urls.clear(); file_system2.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(base::ContainsKey(urls, kURL2)); SyncFileMetadata metadata; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system1.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); EXPECT_EQ(0, metadata.size); changes.clear(); EXPECT_EQ(SYNC_STATUS_OK, PrepareForSync(file_system2.file_system_context(), kURL2, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); EXPECT_EQ(1U, changes.size()); EXPECT_FALSE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_DIRECTORY, metadata.file_type); EXPECT_EQ(0, metadata.size); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system1.TearDown(); file_system2.TearDown(); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncSuccess_Exclusive) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_EXCLUSIVE, SYNC_STATUS_OK); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncSuccess_Snapshot) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_SNAPSHOT, SYNC_STATUS_OK); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncFailure_Exclusive) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_EXCLUSIVE, SYNC_STATUS_FAILED); } TEST_F(LocalFileSyncContextTest, PrepareSync_SyncFailure_Snapshot) { PrepareForSync_Basic(LocalFileSyncContext::SYNC_SNAPSHOT, SYNC_STATUS_FAILED); } TEST_F(LocalFileSyncContextTest, PrepareSync_WriteDuringSync_Exclusive) { PrepareForSync_WriteDuringSync(LocalFileSyncContext::SYNC_EXCLUSIVE); } TEST_F(LocalFileSyncContextTest, PrepareSync_WriteDuringSync_Snapshot) { PrepareForSync_WriteDuringSync(LocalFileSyncContext::SYNC_SNAPSHOT); } // LocalFileSyncContextTest.PrepareSyncWhileWriting is flaky on android. // http://crbug.com/239793 // It is also flaky on the TSAN v2 bots, and hangs other bots. // http://crbug.com/305905. TEST_F(LocalFileSyncContextTest, DISABLED_PrepareSyncWhileWriting) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); EXPECT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); EXPECT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kURL1(file_system.URL("foo")); // Creates a file in file_system. EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kURL1)); // Kick file write on IO thread. StartModifyFileOnIOThread(&file_system, kURL1); // Until the operation finishes PrepareForSync should return BUSY error. SyncFileMetadata metadata; metadata.file_type = SYNC_FILE_TYPE_UNKNOWN; FileChangeList changes; EXPECT_EQ(SYNC_STATUS_FILE_BUSY, PrepareForSync(file_system.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); // Register PrepareForSync method to be invoked when kURL1 becomes // syncable. (Actually this may be done after all operations are done // on IO thread in this test.) metadata.file_type = SYNC_FILE_TYPE_UNKNOWN; changes.clear(); sync_context_->RegisterURLForWaitingSync( kURL1, GetPrepareForSyncClosure(file_system.file_system_context(), kURL1, LocalFileSyncContext::SYNC_EXCLUSIVE, &metadata, &changes, nullptr)); // Wait for the completion. EXPECT_EQ(base::File::FILE_OK, WaitUntilModifyFileIsDone()); // The PrepareForSync must have been started; wait until DidPrepareForSync // is done. base::RunLoop().Run(); ASSERT_FALSE(has_inflight_prepare_for_sync_); // Now PrepareForSync should have run and returned OK. EXPECT_EQ(SYNC_STATUS_OK, status_); EXPECT_EQ(1U, changes.size()); EXPECT_TRUE(changes.list().back().IsFile()); EXPECT_TRUE(changes.list().back().IsAddOrUpdate()); EXPECT_EQ(SYNC_FILE_TYPE_FILE, metadata.file_type); EXPECT_EQ(1, metadata.size); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForDeletion) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); // Record the initial usage (likely 0). int64_t initial_usage = -1; int64_t quota = -1; EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&initial_usage, &quota)); // Create a file and directory in the file_system. const FileSystemURL kFile(file_system.URL("file")); const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kChild(file_system.URL("dir/child")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateDirectory(kDir)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kChild)); // file_system's change tracker must have recorded the creation. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(3U, urls.size()); ASSERT_TRUE(base::ContainsKey(urls, kFile)); ASSERT_TRUE(base::ContainsKey(urls, kDir)); ASSERT_TRUE(base::ContainsKey(urls, kChild)); for (FileSystemURLSet::iterator iter = urls.begin(); iter != urls.end(); ++iter) { file_system.ClearChangeForURLInTracker(*iter); } // At this point the usage must be greater than the initial usage. int64_t new_usage = -1; EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, initial_usage); // Now let's apply remote deletion changes. FileChange change(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kFile, SYNC_FILE_TYPE_FILE)); // The implementation doesn't check file type for deletion, and it must be ok // even if we don't know if the deletion change was for a file or a directory. change = FileChange(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_UNKNOWN); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kDir, SYNC_FILE_TYPE_DIRECTORY)); // Check the directory/files are deleted successfully. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kChild)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // The quota usage data must have reflected the deletion. EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(new_usage, initial_usage); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForDeletion_ForRoot) { CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); // Record the initial usage (likely 0). int64_t initial_usage = -1; int64_t quota = -1; EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&initial_usage, &quota)); // Create a file and directory in the file_system. const FileSystemURL kFile(file_system.URL("file")); const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kChild(file_system.URL("dir/child")); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateDirectory(kDir)); EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kChild)); // At this point the usage must be greater than the initial usage. int64_t new_usage = -1; EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, initial_usage); const FileSystemURL kRoot(file_system.URL("")); // Now let's apply remote deletion changes for the root. FileChange change(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kRoot, SYNC_FILE_TYPE_DIRECTORY)); // Check the directory/files are deleted successfully. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kChild)); // All changes made for the previous creation must have been also reset. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // The quota usage data must have reflected the deletion. EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(new_usage, initial_usage); sync_context_->ShutdownOnUIThread(); sync_context_ = nullptr; file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForAddOrUpdate) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const FileSystemURL kFile1(file_system.URL("file1")); const FileSystemURL kFile2(file_system.URL("file2")); const FileSystemURL kDir(file_system.URL("dir")); const char kTestFileData0[] = "0123456789"; const char kTestFileData1[] = "Lorem ipsum!"; const char kTestFileData2[] = "This is sample test data."; // Create kFile1 and populate it with kTestFileData0. EXPECT_EQ(base::File::FILE_OK, file_system.CreateFile(kFile1)); EXPECT_EQ(static_cast<int64_t>(arraysize(kTestFileData0) - 1), file_system.WriteString(kFile1, kTestFileData0)); // kFile2 and kDir are not there yet. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile2)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.DirectoryExists(kDir)); // file_system's change tracker must have recorded the creation. FileSystemURLSet urls; file_system.GetChangedURLsInTracker(&urls); ASSERT_EQ(1U, urls.size()); EXPECT_TRUE(base::ContainsKey(urls, kFile1)); file_system.ClearChangeForURLInTracker(*urls.begin()); // Prepare temporary files which represent the remote file data. const base::FilePath kFilePath1(temp_dir.GetPath().Append(FPL("file1"))); const base::FilePath kFilePath2(temp_dir.GetPath().Append(FPL("file2"))); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData1) - 1), base::WriteFile(kFilePath1, kTestFileData1, arraysize(kTestFileData1) - 1)); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData2) - 1), base::WriteFile(kFilePath2, kTestFileData2, arraysize(kTestFileData2) - 1)); // Record the usage. int64_t usage = -1, new_usage = -1; int64_t quota = -1; EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&usage, &quota)); // Here in the local filesystem we have: // * kFile1 with kTestFileData0 // // In the remote side let's assume we have: // * kFile1 with kTestFileData1 // * kFile2 with kTestFileData2 // * kDir // // By calling ApplyChange's: // * kFile1 will be updated to have kTestFileData1 // * kFile2 will be created // * kDir will be created // Apply the remote change to kFile1 (which will update the file). FileChange change(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kFile1, SYNC_FILE_TYPE_FILE)); // Check if the usage has been increased by (kTestFileData1 - kTestFileData0). const int updated_size = arraysize(kTestFileData1) - arraysize(kTestFileData0); EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_EQ(updated_size, new_usage - usage); // Apply remote changes to kFile2 and kDir (should create a file and // directory respectively). // They are non-existent yet so their expected file type (the last // parameter of ApplyRemoteChange) are // SYNC_FILE_TYPE_UNKNOWN. change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath2, kFile2, SYNC_FILE_TYPE_UNKNOWN)); change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, base::FilePath(), kDir, SYNC_FILE_TYPE_UNKNOWN)); // Calling ApplyRemoteChange with different file type should be handled as // overwrite. change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kDir, SYNC_FILE_TYPE_DIRECTORY)); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kDir)); change = FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath1, kDir, SYNC_FILE_TYPE_FILE)); // Creating a file/directory must have increased the usage more than // the size of kTestFileData2. new_usage = usage; EXPECT_EQ(blink::mojom::QuotaStatusCode::kOk, file_system.GetUsageAndQuota(&new_usage, &quota)); EXPECT_GT(new_usage, static_cast<int64_t>(usage + arraysize(kTestFileData2) - 1)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // Make sure all three files/directory exist. EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile1)); EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile2)); EXPECT_EQ(base::File::FILE_OK, file_system.DirectoryExists(kDir)); sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } TEST_F(LocalFileSyncContextTest, ApplyRemoteChangeForAddOrUpdate_NoParent) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); CannedSyncableFileSystem file_system(GURL(kOrigin1), in_memory_env_.get(), io_task_runner_.get(), file_task_runner_.get()); file_system.SetUp(CannedSyncableFileSystem::QUOTA_ENABLED); sync_context_ = new LocalFileSyncContext(dir_.GetPath(), in_memory_env_.get(), ui_task_runner_.get(), io_task_runner_.get()); ASSERT_EQ(SYNC_STATUS_OK, file_system.MaybeInitializeFileSystemContext(sync_context_.get())); ASSERT_EQ(base::File::FILE_OK, file_system.OpenFileSystem()); const char kTestFileData[] = "Lorem ipsum!"; const FileSystemURL kDir(file_system.URL("dir")); const FileSystemURL kFile(file_system.URL("dir/file")); // Either kDir or kFile not exist yet. EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kDir)); EXPECT_EQ(base::File::FILE_ERROR_NOT_FOUND, file_system.FileExists(kFile)); // Prepare a temporary file which represents remote file data. const base::FilePath kFilePath(temp_dir.GetPath().Append(FPL("file"))); ASSERT_EQ(static_cast<int>(arraysize(kTestFileData) - 1), base::WriteFile(kFilePath, kTestFileData, arraysize(kTestFileData) - 1)); // Calling ApplyChange's with kFilePath should create // kFile along with kDir. FileChange change(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE); EXPECT_EQ(SYNC_STATUS_OK, ApplyRemoteChange(file_system.file_system_context(), change, kFilePath, kFile, SYNC_FILE_TYPE_UNKNOWN)); // The changes applied by ApplyRemoteChange should not be recorded in // the change tracker. FileSystemURLSet urls; urls.clear(); file_system.GetChangedURLsInTracker(&urls); EXPECT_TRUE(urls.empty()); // Make sure kDir and kFile are created by ApplyRemoteChange. EXPECT_EQ(base::File::FILE_OK, file_system.FileExists(kFile)); EXPECT_EQ(base::File::FILE_OK, file_system.DirectoryExists(kDir)); sync_context_->ShutdownOnUIThread(); file_system.TearDown(); } } // namespace sync_file_system
null
null
null
null
63,662
53,233
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
53,233
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. #ifndef MEDIA_FILTERS_OPUS_CONSTANTS_H_ #define MEDIA_FILTERS_OPUS_CONSTANTS_H_ #include <stdint.h> #include "media/base/media_export.h" namespace media { // The Opus specification is part of IETF RFC 6716: // http://tools.ietf.org/html/rfc6716 // Opus Extra Data contents: // - "OpusHead" magic signature (64 bits) // - version number (8 bits) // - Channels C (8 bits) // - Pre-skip (16 bits) // - Sampling rate (32 bits) // - Gain in dB (16 bits, S7.8) // - Mapping (8 bits, 0=single stream (mono/stereo) 1=Vorbis mapping, // 2..254: reserved, 255: multistream with no mapping) // // - if (mapping != 0) // - N = total number of streams (8 bits) // - M = number of paired streams (8 bits) // - C times channel origin // - if (C<2*M) // - stream = byte/2 // - if (byte&0x1 == 0) // - left // else // - right // - else // - stream = byte-M enum { // Default audio output channel layout. Used to initialize |stream_map| in // OpusExtraData, and passed to opus_multistream_decoder_create() when the // extra data does not contain mapping information. The values are valid only // for mono and stereo output: Opus streams with more than 2 channels require // a stream map. OPUS_MAX_CHANNELS_WITH_DEFAULT_LAYOUT = 2, // Opus uses Vorbis channel mapping, and Vorbis channel mapping specifies // mappings for up to 8 channels. This information is part of the Vorbis I // Specification: // http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html OPUS_MAX_VORBIS_CHANNELS = 8, // Size of the Opus extra data excluding optional mapping information. OPUS_EXTRADATA_SIZE = 19, // Offset for magic signature "OpusHead" OPUS_EXTRADATA_LABEL_OFFSET = 0, // Offset to the Opus version number OPUS_EXTRADATA_VERSION_OFFSET = 8, // Offset to the channel count byte in the Opus extra data OPUS_EXTRADATA_CHANNELS_OFFSET = 9, // Offset to the pre-skip value in the Opus extra data OPUS_EXTRADATA_SKIP_SAMPLES_OFFSET = 10, // Offset to the sampling rate value in the Opus extra data OPUS_EXTRADATA_SAMPLE_RATE_OFFSET = 12, // Offset to the gain value in the Opus extra data OPUS_EXTRADATA_GAIN_OFFSET = 16, // Offset to the channel mapping byte in the Opus extra data OPUS_EXTRADATA_CHANNEL_MAPPING_OFFSET = 18, // Extra Data contains a stream map, beyond the always present // |OPUS_EXTRADATA_SIZE| bytes of data. The mapping data contains stream // count, coupling information, and per channel mapping values: // - Byte 0: Number of streams. // - Byte 1: Number coupled. // - Byte 2: Starting at byte 2 are |extra_data->channels| uint8_t mapping // values. OPUS_EXTRADATA_NUM_STREAMS_OFFSET = OPUS_EXTRADATA_SIZE, OPUS_EXTRADATA_NUM_COUPLED_OFFSET = OPUS_EXTRADATA_NUM_STREAMS_OFFSET + 1, OPUS_EXTRADATA_STREAM_MAP_OFFSET = OPUS_EXTRADATA_NUM_STREAMS_OFFSET + 2, }; // Vorbis channel ordering for streams with >= 2 channels: // 2 Channels // L, R // 3 Channels // L, Center, R // 4 Channels // Front L, Front R, Back L, Back R // 5 Channels // Front L, Center, Front R, Back L, Back R // 6 Channels (5.1) // Front L, Center, Front R, Back L, Back R, LFE // 7 channels (6.1) // Front L, Front Center, Front R, Side L, Side R, Back Center, LFE // 8 Channels (7.1) // Front L, Center, Front R, Side L, Side R, Back L, Back R, LFE // // Channel ordering information is taken from section 4.3.9 of the Vorbis I // Specification: // http://xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9 MEDIA_EXPORT extern const uint8_t kDefaultOpusChannelLayout[OPUS_MAX_CHANNELS_WITH_DEFAULT_LAYOUT]; // These are the FFmpeg channel layouts expressed using the position of each // channel in the output stream from libopus. MEDIA_EXPORT extern const uint8_t kFFmpegChannelDecodingLayouts[OPUS_MAX_VORBIS_CHANNELS] [OPUS_MAX_VORBIS_CHANNELS]; // Opus internal to Vorbis channel order mapping written in the header. extern const uint8_t kOpusVorbisChannelMap[OPUS_MAX_VORBIS_CHANNELS][OPUS_MAX_VORBIS_CHANNELS]; } // namespace media #endif // MEDIA_FILTERS_OPUS_CONSTANTS_H_
null
null
null
null
50,096
888
1,2,3,4,5,6,7,8,9,10,11,12
train_val
baef1ffd73db183ca50c854e1779ed7f6e5100a8
888
Chrome
1
https://github.com/chromium/chromium
2012-06-29 23:27:41+00:00
std::vector<FilePath> GDataCache::GetCachePaths( const FilePath& cache_root_path) { std::vector<FilePath> cache_paths; // The order should match GDataCache::CacheSubDirectoryType enum. cache_paths.push_back(cache_root_path.Append(kGDataCacheMetaDir)); cache_paths.push_back(cache_root_path.Append(kGDataCachePinnedDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheOutgoingDir)); cache_paths.push_back(cache_root_path.Append(kGDataCachePersistentDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDownloadsDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDocumentsDir)); return cache_paths; }
CVE-2012-2895
CWE-119
https://github.com/chromium/chromium/commit/baef1ffd73db183ca50c854e1779ed7f6e5100a8
Medium
888
41,285
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
206,280
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef _LINUX_AUXVEC_H #define _LINUX_AUXVEC_H #include <uapi/linux/auxvec.h> #define AT_VECTOR_SIZE_BASE 20 /* NEW_AUX_ENT entries in auxiliary table */ /* number of "#define AT_.*" above, minus {AT_NULL, AT_IGNORE, AT_NOTELF} */ #endif /* _LINUX_AUXVEC_H */
null
null
null
null
114,627
55,788
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
55,788
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_CHROME_CONTENT_BROWSER_CLIENT_H_ #define CHROME_BROWSER_CHROME_CONTENT_BROWSER_CLIENT_H_ #include <stddef.h> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "chrome/browser/chrome_service.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/resource_type.h" #include "extensions/buildflags/buildflags.h" #include "media/media_buildflags.h" #include "ppapi/buildflags/buildflags.h" #include "services/network/public/mojom/network_service.mojom.h" #include "services/service_manager/public/cpp/binder_registry.h" class ChromeContentBrowserClientParts; class PrefRegistrySimple; namespace base { class CommandLine; } namespace blink { namespace mojom { class WindowFeatures; } } namespace content { class BrowserContext; class QuotaPermissionContext; } namespace safe_browsing { class SafeBrowsingService; class UrlCheckerDelegate; } namespace user_prefs { class PrefRegistrySyncable; } namespace version_info { enum class Channel; } namespace url { class Origin; } class ChromeContentBrowserClient : public content::ContentBrowserClient { public: ChromeContentBrowserClient(); ~ChromeContentBrowserClient() override; // TODO(https://crbug.com/787567): This file is about calls from content/ out // to chrome/ to get values or notify about events, but both of these // functions are from chrome/ to chrome/ and don't involve content/ at all. // That suggests they belong somewhere else at the chrome/ layer. static void RegisterLocalStatePrefs(PrefRegistrySimple* registry); static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); // Notification that the application locale has changed. This allows us to // update our I/O thread cache of this value. static void SetApplicationLocale(const std::string& locale); // content::ContentBrowserClient: content::BrowserMainParts* CreateBrowserMainParts( const content::MainFunctionParams& parameters) override; void PostAfterStartupTask(const base::Location& from_here, const scoped_refptr<base::TaskRunner>& task_runner, base::OnceClosure task) override; bool IsBrowserStartupComplete() override; void SetBrowserStartupIsCompleteForTesting() override; std::string GetStoragePartitionIdForSite( content::BrowserContext* browser_context, const GURL& site) override; bool IsValidStoragePartitionId(content::BrowserContext* browser_context, const std::string& partition_id) override; void GetStoragePartitionConfigForSite( content::BrowserContext* browser_context, const GURL& site, bool can_be_default, std::string* partition_domain, std::string* partition_name, bool* in_memory) override; content::WebContentsViewDelegate* GetWebContentsViewDelegate( content::WebContents* web_contents) override; void RenderProcessWillLaunch( content::RenderProcessHost* host, service_manager::mojom::ServiceRequest* service_request) override; bool AllowGpuLaunchRetryOnIOThread() override; GURL GetEffectiveURL(content::BrowserContext* browser_context, const GURL& url) override; bool ShouldUseProcessPerSite(content::BrowserContext* browser_context, const GURL& effective_url) override; bool DoesSiteRequireDedicatedProcess(content::BrowserContext* browser_context, const GURL& effective_site_url) override; bool ShouldLockToOrigin(content::BrowserContext* browser_context, const GURL& effective_site_url) override; const char* GetInitatorSchemeBypassingDocumentBlocking() override; void GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) override; void GetAdditionalViewSourceSchemes( std::vector<std::string>* additional_schemes) override; bool LogWebUIUrl(const GURL& web_ui_url) const override; bool IsHandledURL(const GURL& url) override; bool CanCommitURL(content::RenderProcessHost* process_host, const GURL& url) override; bool ShouldAllowOpenURL(content::SiteInstance* site_instance, const GURL& url) override; void OverrideNavigationParams(content::SiteInstance* site_instance, ui::PageTransition* transition, bool* is_renderer_initiated, content::Referrer* referrer) override; bool ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation( const GURL& url, content::SiteInstance* parent_site_instance) override; bool ShouldStayInParentProcessForNTP( const GURL& url, content::SiteInstance* parent_site_instance) override; bool IsSuitableHost(content::RenderProcessHost* process_host, const GURL& site_url) override; bool MayReuseHost(content::RenderProcessHost* process_host) override; bool ShouldTryToUseExistingProcessHost( content::BrowserContext* browser_context, const GURL& url) override; void SiteInstanceGotProcess(content::SiteInstance* site_instance) override; void SiteInstanceDeleting(content::SiteInstance* site_instance) override; bool ShouldSwapBrowsingInstancesForNavigation( content::SiteInstance* site_instance, const GURL& current_url, const GURL& new_url) override; bool ShouldAssignSiteForURL(const GURL& url) override; std::vector<url::Origin> GetOriginsRequiringDedicatedProcess() override; bool ShouldEnableStrictSiteIsolation() override; bool IsFileAccessAllowed(const base::FilePath& path, const base::FilePath& absolute_path, const base::FilePath& profile_path) override; void AppendExtraCommandLineSwitches(base::CommandLine* command_line, int child_process_id) override; void AdjustUtilityServiceProcessCommandLine( const service_manager::Identity& identity, base::CommandLine* command_line) override; std::string GetApplicationLocale() override; std::string GetAcceptLangs(content::BrowserContext* context) override; const gfx::ImageSkia* GetDefaultFavicon() override; bool IsDataSaverEnabled(content::BrowserContext* context) override; void NavigationRequestStarted( int frame_tree_node_id, const GURL& url, std::unique_ptr<net::HttpRequestHeaders>* extra_headers, int* extra_load_flags) override; bool AllowAppCache(const GURL& manifest_url, const GURL& first_party, content::ResourceContext* context) override; bool AllowServiceWorker( const GURL& scope, const GURL& first_party, content::ResourceContext* context, const base::Callback<content::WebContents*(void)>& wc_getter) override; bool AllowSharedWorker(const GURL& worker_url, const GURL& main_frame_url, const std::string& name, const url::Origin& constructor_origin, content::BrowserContext* context, int render_process_id, int render_frame_id) override; bool AllowGetCookie(const GURL& url, const GURL& first_party, const net::CookieList& cookie_list, content::ResourceContext* context, int render_process_id, int render_frame_id) override; bool AllowSetCookie(const GURL& url, const GURL& first_party, const net::CanonicalCookie& cookie, content::ResourceContext* context, int render_process_id, int render_frame_id, const net::CookieOptions& options) override; void AllowWorkerFileSystem( const GURL& url, content::ResourceContext* context, const std::vector<std::pair<int, int>>& render_frames, base::Callback<void(bool)> callback) override; bool AllowWorkerIndexedDB( const GURL& url, const base::string16& name, content::ResourceContext* context, const std::vector<std::pair<int, int>>& render_frames) override; AllowWebBluetoothResult AllowWebBluetooth( content::BrowserContext* browser_context, const url::Origin& requesting_origin, const url::Origin& embedding_origin) override; std::string GetWebBluetoothBlocklist() override; net::URLRequestContext* OverrideRequestContextForURL( const GURL& url, content::ResourceContext* context) override; void GetGeolocationRequestContext( base::OnceCallback<void(scoped_refptr<net::URLRequestContextGetter>)> callback) override; std::string GetGeolocationApiKey() override; content::QuotaPermissionContext* CreateQuotaPermissionContext() override; void GetQuotaSettings( content::BrowserContext* context, content::StoragePartition* partition, storage::OptionalQuotaSettingsCallback callback) override; void AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, content::ResourceType resource_type, bool strict_enforcement, bool expired_previous_decision, const base::Callback<void(content::CertificateRequestResultType)>& callback) override; void SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) override; content::MediaObserver* GetMediaObserver() override; content::PlatformNotificationService* GetPlatformNotificationService() override; bool CanCreateWindow(content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const GURL& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) override; void ResourceDispatcherHostCreated() override; content::SpeechRecognitionManagerDelegate* CreateSpeechRecognitionManagerDelegate() override; net::NetLog* GetNetLog() override; void OverrideWebkitPrefs(content::RenderViewHost* rvh, content::WebPreferences* prefs) override; void BrowserURLHandlerCreated(content::BrowserURLHandler* handler) override; base::FilePath GetDefaultDownloadDirectory() override; std::string GetDefaultDownloadName() override; base::FilePath GetShaderDiskCacheDirectory() override; void DidCreatePpapiPlugin(content::BrowserPpapiHost* browser_host) override; content::BrowserPpapiHost* GetExternalBrowserPpapiHost( int plugin_process_id) override; bool AllowPepperSocketAPI( content::BrowserContext* browser_context, const GURL& url, bool private_api, const content::SocketPermissionRequest* params) override; bool IsPepperVpnProviderAPIAllowed(content::BrowserContext* browser_context, const GURL& url) override; std::unique_ptr<content::VpnServiceProxy> GetVpnServiceProxy( content::BrowserContext* browser_context) override; std::unique_ptr<ui::SelectFilePolicy> CreateSelectFilePolicy( content::WebContents* web_contents) override; void GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) override; void GetSchemesBypassingSecureContextCheckWhitelist( std::set<std::string>* schemes) override; void GetURLRequestAutoMountHandlers( std::vector<storage::URLRequestAutoMountHandler>* handlers) override; void GetAdditionalFileSystemBackends( content::BrowserContext* browser_context, const base::FilePath& storage_partition_path, std::vector<std::unique_ptr<storage::FileSystemBackend>>* additional_backends) override; content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() override; content::TracingDelegate* GetTracingDelegate() override; bool IsPluginAllowedToCallRequestOSFileHandle( content::BrowserContext* browser_context, const GURL& url) override; bool IsPluginAllowedToUseDevChannelAPIs( content::BrowserContext* browser_context, const GURL& url) override; void OverridePageVisibilityState( content::RenderFrameHost* render_frame_host, blink::mojom::PageVisibilityState* visibility_state) override; #if defined(OS_POSIX) && !defined(OS_MACOSX) void GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) override; #endif // defined(OS_POSIX) && !defined(OS_MACOSX) #if defined(OS_WIN) bool PreSpawnRenderer(sandbox::TargetPolicy* policy) override; base::string16 GetAppContainerSidForSandboxType( int sandbox_type) const override; #endif void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) override; void ExposeInterfacesToMediaService( service_manager::BinderRegistry* registry, content::RenderFrameHost* render_frame_host) override; void BindInterfaceRequestFromFrame( content::RenderFrameHost* render_frame_host, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override; void BindInterfaceRequestFromWorker( content::RenderProcessHost* render_process_host, const url::Origin& origin, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override; void BindInterfaceRequest( const service_manager::BindSourceInfo& source_info, const std::string& interface_name, mojo::ScopedMessagePipeHandle* interface_pipe) override; void RegisterInProcessServices(StaticServiceMap* services) override; void RegisterOutOfProcessServices( OutOfProcessServiceMap* services) override; bool ShouldTerminateOnServiceQuit( const service_manager::Identity& id) override; std::unique_ptr<base::Value> GetServiceManifestOverlay( base::StringPiece name) override; std::vector<content::ContentBrowserClient::ServiceManifestInfo> GetExtraServiceManifests() override; void OpenURL(content::BrowserContext* browser_context, const content::OpenURLParams& params, const base::Callback<void(content::WebContents*)>& callback) override; content::ControllerPresentationServiceDelegate* GetControllerPresentationServiceDelegate( content::WebContents* web_contents) override; content::ReceiverPresentationServiceDelegate* GetReceiverPresentationServiceDelegate( content::WebContents* web_contents) override; void RecordURLMetric(const std::string& metric, const GURL& url) override; std::string GetMetricSuffixForURL(const GURL& url) override; std::vector<std::unique_ptr<content::NavigationThrottle>> CreateThrottlesForNavigation(content::NavigationHandle* handle) override; std::unique_ptr<content::NavigationUIData> GetNavigationUIData( content::NavigationHandle* navigation_handle) override; std::unique_ptr<content::MemoryCoordinatorDelegate> GetMemoryCoordinatorDelegate() override; ::rappor::RapporService* GetRapporService() override; #if BUILDFLAG(ENABLE_MEDIA_REMOTING) void CreateMediaRemoter(content::RenderFrameHost* render_frame_host, media::mojom::RemotingSourcePtr source, media::mojom::RemoterRequest request) final; #endif // BUILDFLAG(ENABLE_MEDIA_REMOTING) std::unique_ptr<base::TaskScheduler::InitParams> GetTaskSchedulerInitParams() override; base::FilePath GetLoggingFileName( const base::CommandLine& command_line) override; std::vector<std::unique_ptr<content::URLLoaderThrottle>> CreateURLLoaderThrottles( const network::ResourceRequest& request, content::ResourceContext* resource_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) override; void RegisterNonNetworkNavigationURLLoaderFactories( content::RenderFrameHost* frame_host, NonNetworkURLLoaderFactoryMap* factories) override; void RegisterNonNetworkSubresourceURLLoaderFactories( content::RenderFrameHost* frame_host, const GURL& frame_url, NonNetworkURLLoaderFactoryMap* factories) override; bool WillCreateURLLoaderFactory( content::RenderFrameHost* frame, bool is_navigation, network::mojom::URLLoaderFactoryRequest* factory_request) override; network::mojom::NetworkContextPtr CreateNetworkContext( content::BrowserContext* context, bool in_memory, const base::FilePath& relative_partition_path) override; bool AllowRenderingMhtmlOverHttp( content::NavigationUIData* navigation_ui_data) override; bool ShouldForceDownloadResource(const GURL& url, const std::string& mime_type) override; void CreateUsbDeviceManager( content::RenderFrameHost* render_frame_host, device::mojom::UsbDeviceManagerRequest request) override; void CreateUsbChooserService( content::RenderFrameHost* render_frame_host, device::mojom::UsbChooserServiceRequest request) override; bool ShowPaymentHandlerWindow( content::BrowserContext* browser_context, const GURL& url, base::OnceCallback<void(bool, int, int)> callback) override; bool ShouldPermitIndividualAttestationForWebauthnRPID( content::BrowserContext* browser_context, const std::string& rp_id) override; void ShouldReturnAttestationForWebauthnRPID( content::RenderFrameHost* rfh, const std::string& rp_id, const url::Origin& origin, base::OnceCallback<void(bool)> callback) override; std::unique_ptr<net::ClientCertStore> CreateClientCertStore( content::ResourceContext* resource_context) override; scoped_refptr<content::LoginDelegate> CreateLoginDelegate( net::AuthChallengeInfo* auth_info, content::ResourceRequestInfo::WebContentsGetter web_contents_getter, bool is_main_frame, const GURL& url, bool first_auth_attempt, const base::Callback<void(const base::Optional<net::AuthCredentials>&)>& auth_required_callback) override; bool HandleExternalProtocol( const GURL& url, content::ResourceRequestInfo::WebContentsGetter web_contents_getter, int child_id, content::NavigationUIData* navigation_data, bool is_main_frame, ui::PageTransition page_transition, bool has_user_gesture) override; std::unique_ptr<content::OverlayWindow> CreateWindowForPictureInPicture() override; protected: static bool HandleWebUI(GURL* url, content::BrowserContext* browser_context); static bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context); private: friend class DisableWebRtcEncryptionFlagTest; friend class InProcessBrowserTest; // Populate |frame_interfaces_|, |frame_interfaces_parameterized_| and // |worker_interfaces_parameterized_|. void InitWebContextInterfaces(); #if BUILDFLAG(ENABLE_WEBRTC) // Copies disable WebRTC encryption switch depending on the channel. static void MaybeCopyDisableWebRtcEncryptionSwitch( base::CommandLine* to_command_line, const base::CommandLine& from_command_line, version_info::Channel channel); #endif void FileSystemAccessed( const GURL& url, const std::vector<std::pair<int, int> >& render_frames, base::Callback<void(bool)> callback, bool allow); #if BUILDFLAG(ENABLE_EXTENSIONS) void GuestPermissionRequestHelper( const GURL& url, const std::vector<std::pair<int, int> >& render_frames, base::Callback<void(bool)> callback, bool allow); static void RequestFileSystemPermissionOnUIThread( int render_process_id, int render_frame_id, const GURL& url, bool allowed_by_default, const base::Callback<void(bool)>& callback); #endif // The value pointed to by |settings| should remain valid until the // the function is called again with a new value or a nullptr. static void SetDefaultQuotaSettingsForTesting( const storage::QuotaSettings *settings); safe_browsing::UrlCheckerDelegate* GetSafeBrowsingUrlCheckerDelegate( content::ResourceContext* resource_context); #if BUILDFLAG(ENABLE_PLUGINS) // Set of origins that can use TCP/UDP private APIs from NaCl. std::set<std::string> allowed_socket_origins_; // Set of origins that can get a handle for FileIO from NaCl. std::set<std::string> allowed_file_handle_origins_; // Set of origins that can use "dev chanel" APIs from NaCl, even on stable // versions of Chrome. std::set<std::string> allowed_dev_channel_origins_; #endif // Vector of additional ChromeContentBrowserClientParts. // Parts are deleted in the reverse order they are added. std::vector<ChromeContentBrowserClientParts*> extra_parts_; service_manager::BinderRegistry gpu_binder_registry_; scoped_refptr<safe_browsing::SafeBrowsingService> safe_browsing_service_; scoped_refptr<safe_browsing::UrlCheckerDelegate> safe_browsing_url_checker_delegate_; std::unique_ptr<service_manager::BinderRegistry> frame_interfaces_; std::unique_ptr< service_manager::BinderRegistryWithArgs<content::RenderFrameHost*>> frame_interfaces_parameterized_; std::unique_ptr< service_manager::BinderRegistryWithArgs<content::RenderProcessHost*, const url::Origin&>> worker_interfaces_parameterized_; base::WeakPtrFactory<ChromeContentBrowserClient> weak_factory_; DISALLOW_COPY_AND_ASSIGN(ChromeContentBrowserClient); }; #endif // CHROME_BROWSER_CHROME_CONTENT_BROWSER_CLIENT_H_
null
null
null
null
52,651
16,048
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
181,043
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2002, 2004, 2007 by Ralf Baechle <[email protected]> */ #ifndef __ASM_MIPS_MACH_MIPS_WAR_H #define __ASM_MIPS_MACH_MIPS_WAR_H #define R4600_V1_INDEX_ICACHEOP_WAR 0 #define R4600_V1_HIT_CACHEOP_WAR 0 #define R4600_V2_HIT_CACHEOP_WAR 0 #define R5432_CP0_INTERRUPT_WAR 0 #define BCM1250_M3_WAR 0 #define SIBYTE_1956_WAR 0 #define MIPS4K_ICACHE_REFILL_WAR 1 #define MIPS_CACHE_SYNC_WAR 0 #define TX49XX_ICACHE_INDEX_INV_WAR 0 #define ICACHE_REFILLS_WORKAROUND_WAR 0 #define R10000_LLSC_WAR 0 #define MIPS34K_MISSED_ITLB_WAR 0 #endif /* __ASM_MIPS_MACH_MIPS_WAR_H */
null
null
null
null
89,390
21,606
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
21,606
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 CONTENT_RENDERER_MUS_MUS_EMBEDDED_FRAME_DELEGATE_H_ #define CONTENT_RENDERER_MUS_MUS_EMBEDDED_FRAME_DELEGATE_H_ namespace viz { class FrameSinkId; class SurfaceInfo; } // namespace viz namespace content { class MusEmbeddedFrameDelegate { public: // Called when the SurfaceInfo changes. virtual void OnMusEmbeddedFrameSurfaceChanged( const viz::SurfaceInfo& surface_info) = 0; // Called when mus determines the FrameSinkId. virtual void OnMusEmbeddedFrameSinkIdAllocated( const viz::FrameSinkId& frame_sink_id) = 0; protected: virtual ~MusEmbeddedFrameDelegate() {} }; } // namespace content #endif // CONTENT_RENDERER_MUS_MUS_EMBEDDED_FRAME_DELEGATE_H_
null
null
null
null
18,469
49
1,2,3,4,5,6,7,8,9,11,12,13,14,15
train_val
ea3d1d84be3d6f97bf50e76511c9e26af6895533
49
Chrome
1
https://github.com/chromium/chromium
2010-01-29 22:35:33+00:00
WebPluginResourceClient* WebPluginDelegateImpl::CreateResourceClient( unsigned long resource_id, const GURL& url, bool notify_needed, intptr_t notify_data, intptr_t existing_stream) { // Stream already exists. This typically happens for range requests // initiated via NPN_RequestRead. if (existing_stream) { NPAPI::PluginStream* plugin_stream = reinterpret_cast<NPAPI::PluginStream*>(existing_stream); return plugin_stream->AsResourceClient(); } std::string mime_type; NPAPI::PluginStreamUrl *stream = instance()->CreateStream( resource_id, url, mime_type, notify_needed, reinterpret_cast<void*>(notify_data)); return stream; }
null
null
https://github.com/chromium/chromium/commit/ea3d1d84be3d6f97bf50e76511c9e26af6895533
null
49
32,256
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
197,251
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Freescale QorIQ AHCI SATA platform driver * * Copyright 2015 Freescale, Inc. * Tang Yuantian <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pm.h> #include <linux/ahci_platform.h> #include <linux/device.h> #include <linux/of_address.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/libata.h> #include "ahci.h" #define DRV_NAME "ahci-qoriq" /* port register definition */ #define PORT_PHY1 0xA8 #define PORT_PHY2 0xAC #define PORT_PHY3 0xB0 #define PORT_PHY4 0xB4 #define PORT_PHY5 0xB8 #define PORT_AXICC 0xBC #define PORT_TRANS 0xC8 /* port register default value */ #define AHCI_PORT_PHY_1_CFG 0xa003fffe #define AHCI_PORT_TRANS_CFG 0x08000029 #define AHCI_PORT_AXICC_CFG 0x3fffffff /* for ls1021a */ #define LS1021A_PORT_PHY2 0x28183414 #define LS1021A_PORT_PHY3 0x0e080e06 #define LS1021A_PORT_PHY4 0x064a080b #define LS1021A_PORT_PHY5 0x2aa86470 #define LS1021A_AXICC_ADDR 0xC0 #define SATA_ECC_DISABLE 0x00020000 #define ECC_DIS_ARMV8_CH2 0x80000000 enum ahci_qoriq_type { AHCI_LS1021A, AHCI_LS1043A, AHCI_LS2080A, AHCI_LS1046A, AHCI_LS2088A, }; struct ahci_qoriq_priv { struct ccsr_ahci *reg_base; enum ahci_qoriq_type type; void __iomem *ecc_addr; bool is_dmacoherent; }; static const struct of_device_id ahci_qoriq_of_match[] = { { .compatible = "fsl,ls1021a-ahci", .data = (void *)AHCI_LS1021A}, { .compatible = "fsl,ls1043a-ahci", .data = (void *)AHCI_LS1043A}, { .compatible = "fsl,ls2080a-ahci", .data = (void *)AHCI_LS2080A}, { .compatible = "fsl,ls1046a-ahci", .data = (void *)AHCI_LS1046A}, { .compatible = "fsl,ls2088a-ahci", .data = (void *)AHCI_LS2088A}, {}, }; MODULE_DEVICE_TABLE(of, ahci_qoriq_of_match); static int ahci_qoriq_hardreset(struct ata_link *link, unsigned int *class, unsigned long deadline) { const unsigned long *timing = sata_ehc_deb_timing(&link->eh_context); void __iomem *port_mmio = ahci_port_base(link->ap); u32 px_cmd, px_is, px_val; struct ata_port *ap = link->ap; struct ahci_port_priv *pp = ap->private_data; struct ahci_host_priv *hpriv = ap->host->private_data; struct ahci_qoriq_priv *qoriq_priv = hpriv->plat_data; u8 *d2h_fis = pp->rx_fis + RX_FIS_D2H_REG; struct ata_taskfile tf; bool online; int rc; bool ls1021a_workaround = (qoriq_priv->type == AHCI_LS1021A); DPRINTK("ENTER\n"); ahci_stop_engine(ap); /* * There is a errata on ls1021a Rev1.0 and Rev2.0 which is: * A-009042: The device detection initialization sequence * mistakenly resets some registers. * * Workaround for this is: * The software should read and store PxCMD and PxIS values * before issuing the device detection initialization sequence. * After the sequence is complete, software should restore the * PxCMD and PxIS with the stored values. */ if (ls1021a_workaround) { px_cmd = readl(port_mmio + PORT_CMD); px_is = readl(port_mmio + PORT_IRQ_STAT); } /* clear D2H reception area to properly wait for D2H FIS */ ata_tf_init(link->device, &tf); tf.command = ATA_BUSY; ata_tf_to_fis(&tf, 0, 0, d2h_fis); rc = sata_link_hardreset(link, timing, deadline, &online, ahci_check_ready); /* restore the PxCMD and PxIS on ls1021 */ if (ls1021a_workaround) { px_val = readl(port_mmio + PORT_CMD); if (px_val != px_cmd) writel(px_cmd, port_mmio + PORT_CMD); px_val = readl(port_mmio + PORT_IRQ_STAT); if (px_val != px_is) writel(px_is, port_mmio + PORT_IRQ_STAT); } hpriv->start_engine(ap); if (online) *class = ahci_dev_classify(ap); DPRINTK("EXIT, rc=%d, class=%u\n", rc, *class); return rc; } static struct ata_port_operations ahci_qoriq_ops = { .inherits = &ahci_ops, .hardreset = ahci_qoriq_hardreset, }; static const struct ata_port_info ahci_qoriq_port_info = { .flags = AHCI_FLAG_COMMON | ATA_FLAG_NCQ, .pio_mask = ATA_PIO4, .udma_mask = ATA_UDMA6, .port_ops = &ahci_qoriq_ops, }; static struct scsi_host_template ahci_qoriq_sht = { AHCI_SHT(DRV_NAME), }; static int ahci_qoriq_phy_init(struct ahci_host_priv *hpriv) { struct ahci_qoriq_priv *qpriv = hpriv->plat_data; void __iomem *reg_base = hpriv->mmio; switch (qpriv->type) { case AHCI_LS1021A: if (!qpriv->ecc_addr) return -EINVAL; writel(SATA_ECC_DISABLE, qpriv->ecc_addr); writel(AHCI_PORT_PHY_1_CFG, reg_base + PORT_PHY1); writel(LS1021A_PORT_PHY2, reg_base + PORT_PHY2); writel(LS1021A_PORT_PHY3, reg_base + PORT_PHY3); writel(LS1021A_PORT_PHY4, reg_base + PORT_PHY4); writel(LS1021A_PORT_PHY5, reg_base + PORT_PHY5); writel(AHCI_PORT_TRANS_CFG, reg_base + PORT_TRANS); if (qpriv->is_dmacoherent) writel(AHCI_PORT_AXICC_CFG, reg_base + LS1021A_AXICC_ADDR); break; case AHCI_LS1043A: if (!qpriv->ecc_addr) return -EINVAL; writel(readl(qpriv->ecc_addr) | ECC_DIS_ARMV8_CH2, qpriv->ecc_addr); writel(AHCI_PORT_PHY_1_CFG, reg_base + PORT_PHY1); writel(AHCI_PORT_TRANS_CFG, reg_base + PORT_TRANS); if (qpriv->is_dmacoherent) writel(AHCI_PORT_AXICC_CFG, reg_base + PORT_AXICC); break; case AHCI_LS2080A: writel(AHCI_PORT_PHY_1_CFG, reg_base + PORT_PHY1); writel(AHCI_PORT_TRANS_CFG, reg_base + PORT_TRANS); if (qpriv->is_dmacoherent) writel(AHCI_PORT_AXICC_CFG, reg_base + PORT_AXICC); break; case AHCI_LS1046A: if (!qpriv->ecc_addr) return -EINVAL; writel(readl(qpriv->ecc_addr) | ECC_DIS_ARMV8_CH2, qpriv->ecc_addr); writel(AHCI_PORT_PHY_1_CFG, reg_base + PORT_PHY1); writel(AHCI_PORT_TRANS_CFG, reg_base + PORT_TRANS); if (qpriv->is_dmacoherent) writel(AHCI_PORT_AXICC_CFG, reg_base + PORT_AXICC); break; case AHCI_LS2088A: writel(AHCI_PORT_PHY_1_CFG, reg_base + PORT_PHY1); writel(AHCI_PORT_TRANS_CFG, reg_base + PORT_TRANS); if (qpriv->is_dmacoherent) writel(AHCI_PORT_AXICC_CFG, reg_base + PORT_AXICC); break; } return 0; } static int ahci_qoriq_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; struct device *dev = &pdev->dev; struct ahci_host_priv *hpriv; struct ahci_qoriq_priv *qoriq_priv; const struct of_device_id *of_id; struct resource *res; int rc; hpriv = ahci_platform_get_resources(pdev); if (IS_ERR(hpriv)) return PTR_ERR(hpriv); of_id = of_match_node(ahci_qoriq_of_match, np); if (!of_id) return -ENODEV; qoriq_priv = devm_kzalloc(dev, sizeof(*qoriq_priv), GFP_KERNEL); if (!qoriq_priv) return -ENOMEM; qoriq_priv->type = (enum ahci_qoriq_type)of_id->data; res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "sata-ecc"); if (res) { qoriq_priv->ecc_addr = devm_ioremap_resource(dev, res); if (IS_ERR(qoriq_priv->ecc_addr)) return PTR_ERR(qoriq_priv->ecc_addr); } qoriq_priv->is_dmacoherent = of_dma_is_coherent(np); rc = ahci_platform_enable_resources(hpriv); if (rc) return rc; hpriv->plat_data = qoriq_priv; rc = ahci_qoriq_phy_init(hpriv); if (rc) goto disable_resources; rc = ahci_platform_init_host(pdev, hpriv, &ahci_qoriq_port_info, &ahci_qoriq_sht); if (rc) goto disable_resources; return 0; disable_resources: ahci_platform_disable_resources(hpriv); return rc; } #ifdef CONFIG_PM_SLEEP static int ahci_qoriq_resume(struct device *dev) { struct ata_host *host = dev_get_drvdata(dev); struct ahci_host_priv *hpriv = host->private_data; int rc; rc = ahci_platform_enable_resources(hpriv); if (rc) return rc; rc = ahci_qoriq_phy_init(hpriv); if (rc) goto disable_resources; rc = ahci_platform_resume_host(dev); if (rc) goto disable_resources; /* We resumed so update PM runtime state */ pm_runtime_disable(dev); pm_runtime_set_active(dev); pm_runtime_enable(dev); return 0; disable_resources: ahci_platform_disable_resources(hpriv); return rc; } #endif static SIMPLE_DEV_PM_OPS(ahci_qoriq_pm_ops, ahci_platform_suspend, ahci_qoriq_resume); static struct platform_driver ahci_qoriq_driver = { .probe = ahci_qoriq_probe, .remove = ata_platform_remove_one, .driver = { .name = DRV_NAME, .of_match_table = ahci_qoriq_of_match, .pm = &ahci_qoriq_pm_ops, }, }; module_platform_driver(ahci_qoriq_driver); MODULE_DESCRIPTION("Freescale QorIQ AHCI SATA platform driver"); MODULE_AUTHOR("Tang Yuantian <[email protected]>"); MODULE_LICENSE("GPL");
null
null
null
null
105,598
22,110
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
22,110
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 "content/common/cache_storage/cache_storage_mojom_traits.h" #include "base/logging.h" #include "content/public/common/referrer_struct_traits.h" namespace mojo { using blink::mojom::CacheStorageError; using blink::mojom::OperationType; OperationType EnumTraits<OperationType, content::CacheStorageCacheOperationType>::ToMojom( content::CacheStorageCacheOperationType input) { switch (input) { case content::CACHE_STORAGE_CACHE_OPERATION_TYPE_UNDEFINED: return OperationType::kUndefined; case content::CACHE_STORAGE_CACHE_OPERATION_TYPE_PUT: return OperationType::kPut; case content::CACHE_STORAGE_CACHE_OPERATION_TYPE_DELETE: return OperationType::kDelete; } NOTREACHED(); return OperationType::kUndefined; } bool EnumTraits<OperationType, content::CacheStorageCacheOperationType>:: FromMojom(OperationType input, content::CacheStorageCacheOperationType* out) { switch (input) { case OperationType::kUndefined: *out = content::CACHE_STORAGE_CACHE_OPERATION_TYPE_UNDEFINED; return true; case OperationType::kPut: *out = content::CACHE_STORAGE_CACHE_OPERATION_TYPE_PUT; return true; case OperationType::kDelete: *out = content::CACHE_STORAGE_CACHE_OPERATION_TYPE_DELETE; return true; } return false; } bool StructTraits<blink::mojom::QueryParamsDataView, content::CacheStorageCacheQueryParams>:: Read(blink::mojom::QueryParamsDataView data, content::CacheStorageCacheQueryParams* out) { base::Optional<base::string16> cache_name; if (!data.ReadCacheName(&cache_name)) return false; out->cache_name = base::NullableString16(std::move(cache_name)); out->ignore_search = data.ignore_search(); out->ignore_method = data.ignore_method(); out->ignore_vary = data.ignore_vary(); return true; } bool StructTraits<blink::mojom::BatchOperationDataView, content::CacheStorageBatchOperation>:: Read(blink::mojom::BatchOperationDataView data, content::CacheStorageBatchOperation* out) { if (!data.ReadRequest(&out->request)) return false; if (!data.ReadResponse(&out->response)) return false; if (!data.ReadMatchParams(&out->match_params)) return false; if (!data.ReadOperationType(&out->operation_type)) return false; return true; } } // namespace mojo
null
null
null
null
18,973
33,722
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
33,722
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 1999 Lars Knoll ([email protected]) * (C) 1999 Antti Koivisto ([email protected]) * (C) 2000 Dirk Mueller ([email protected]) * Copyright (C) 2004, 2006, 2009 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_LAYOUT_LAYOUT_FIELDSET_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_FIELDSET_H_ #include "third_party/blink/renderer/core/layout/layout_block_flow.h" namespace blink { class LayoutFieldset final : public LayoutBlockFlow { public: explicit LayoutFieldset(Element*); LayoutBox* FindInFlowLegend() const; const char* GetName() const override { return "LayoutFieldset"; } private: bool IsOfType(LayoutObjectType type) const override { return type == kLayoutObjectFieldset || LayoutBlockFlow::IsOfType(type); } LayoutObject* LayoutSpecialExcludedChild(bool relayout_children, SubtreeLayoutScope&) override; void ComputePreferredLogicalWidths() override; void PaintBoxDecorationBackground(const PaintInfo&, const LayoutPoint&) const override; void PaintMask(const PaintInfo&, const LayoutPoint&) const override; }; DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutFieldset, IsFieldset()); } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_FIELDSET_H_
null
null
null
null
30,585
26,518
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
191,513
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Rafał Miłecki <[email protected]> * Alex Deucher <[email protected]> */ #include <drm/drmP.h> #include "radeon.h" #include "avivod.h" #include "atom.h" #include "r600_dpm.h" #include <linux/power_supply.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #define RADEON_IDLE_LOOP_MS 100 #define RADEON_RECLOCK_DELAY_MS 200 #define RADEON_WAIT_VBLANK_TIMEOUT 200 static const char *radeon_pm_state_type_name[5] = { "", "Powersave", "Battery", "Balanced", "Performance", }; static void radeon_dynpm_idle_work_handler(struct work_struct *work); static int radeon_debugfs_pm_init(struct radeon_device *rdev); static bool radeon_pm_in_vbl(struct radeon_device *rdev); static bool radeon_pm_debug_check_in_vbl(struct radeon_device *rdev, bool finish); static void radeon_pm_update_profile(struct radeon_device *rdev); static void radeon_pm_set_clocks(struct radeon_device *rdev); static void radeon_pm_compute_clocks_dpm(struct radeon_device *rdev); int radeon_pm_get_type_index(struct radeon_device *rdev, enum radeon_pm_state_type ps_type, int instance) { int i; int found_instance = -1; for (i = 0; i < rdev->pm.num_power_states; i++) { if (rdev->pm.power_state[i].type == ps_type) { found_instance++; if (found_instance == instance) return i; } } /* return default if no match */ return rdev->pm.default_power_state_index; } void radeon_pm_acpi_event_handler(struct radeon_device *rdev) { if ((rdev->pm.pm_method == PM_METHOD_DPM) && rdev->pm.dpm_enabled) { mutex_lock(&rdev->pm.mutex); if (power_supply_is_system_supplied() > 0) rdev->pm.dpm.ac_power = true; else rdev->pm.dpm.ac_power = false; if (rdev->family == CHIP_ARUBA) { if (rdev->asic->dpm.enable_bapm) radeon_dpm_enable_bapm(rdev, rdev->pm.dpm.ac_power); } mutex_unlock(&rdev->pm.mutex); /* allow new DPM state to be picked */ radeon_pm_compute_clocks_dpm(rdev); } else if (rdev->pm.pm_method == PM_METHOD_PROFILE) { if (rdev->pm.profile == PM_PROFILE_AUTO) { mutex_lock(&rdev->pm.mutex); radeon_pm_update_profile(rdev); radeon_pm_set_clocks(rdev); mutex_unlock(&rdev->pm.mutex); } } } static void radeon_pm_update_profile(struct radeon_device *rdev) { switch (rdev->pm.profile) { case PM_PROFILE_DEFAULT: rdev->pm.profile_index = PM_PROFILE_DEFAULT_IDX; break; case PM_PROFILE_AUTO: if (power_supply_is_system_supplied() > 0) { if (rdev->pm.active_crtc_count > 1) rdev->pm.profile_index = PM_PROFILE_HIGH_MH_IDX; else rdev->pm.profile_index = PM_PROFILE_HIGH_SH_IDX; } else { if (rdev->pm.active_crtc_count > 1) rdev->pm.profile_index = PM_PROFILE_MID_MH_IDX; else rdev->pm.profile_index = PM_PROFILE_MID_SH_IDX; } break; case PM_PROFILE_LOW: if (rdev->pm.active_crtc_count > 1) rdev->pm.profile_index = PM_PROFILE_LOW_MH_IDX; else rdev->pm.profile_index = PM_PROFILE_LOW_SH_IDX; break; case PM_PROFILE_MID: if (rdev->pm.active_crtc_count > 1) rdev->pm.profile_index = PM_PROFILE_MID_MH_IDX; else rdev->pm.profile_index = PM_PROFILE_MID_SH_IDX; break; case PM_PROFILE_HIGH: if (rdev->pm.active_crtc_count > 1) rdev->pm.profile_index = PM_PROFILE_HIGH_MH_IDX; else rdev->pm.profile_index = PM_PROFILE_HIGH_SH_IDX; break; } if (rdev->pm.active_crtc_count == 0) { rdev->pm.requested_power_state_index = rdev->pm.profiles[rdev->pm.profile_index].dpms_off_ps_idx; rdev->pm.requested_clock_mode_index = rdev->pm.profiles[rdev->pm.profile_index].dpms_off_cm_idx; } else { rdev->pm.requested_power_state_index = rdev->pm.profiles[rdev->pm.profile_index].dpms_on_ps_idx; rdev->pm.requested_clock_mode_index = rdev->pm.profiles[rdev->pm.profile_index].dpms_on_cm_idx; } } static void radeon_unmap_vram_bos(struct radeon_device *rdev) { struct radeon_bo *bo, *n; if (list_empty(&rdev->gem.objects)) return; list_for_each_entry_safe(bo, n, &rdev->gem.objects, list) { if (bo->tbo.mem.mem_type == TTM_PL_VRAM) ttm_bo_unmap_virtual(&bo->tbo); } } static void radeon_sync_with_vblank(struct radeon_device *rdev) { if (rdev->pm.active_crtcs) { rdev->pm.vblank_sync = false; wait_event_timeout( rdev->irq.vblank_queue, rdev->pm.vblank_sync, msecs_to_jiffies(RADEON_WAIT_VBLANK_TIMEOUT)); } } static void radeon_set_power_state(struct radeon_device *rdev) { u32 sclk, mclk; bool misc_after = false; if ((rdev->pm.requested_clock_mode_index == rdev->pm.current_clock_mode_index) && (rdev->pm.requested_power_state_index == rdev->pm.current_power_state_index)) return; if (radeon_gui_idle(rdev)) { sclk = rdev->pm.power_state[rdev->pm.requested_power_state_index]. clock_info[rdev->pm.requested_clock_mode_index].sclk; if (sclk > rdev->pm.default_sclk) sclk = rdev->pm.default_sclk; /* starting with BTC, there is one state that is used for both * MH and SH. Difference is that we always use the high clock index for * mclk and vddci. */ if ((rdev->pm.pm_method == PM_METHOD_PROFILE) && (rdev->family >= CHIP_BARTS) && rdev->pm.active_crtc_count && ((rdev->pm.profile_index == PM_PROFILE_MID_MH_IDX) || (rdev->pm.profile_index == PM_PROFILE_LOW_MH_IDX))) mclk = rdev->pm.power_state[rdev->pm.requested_power_state_index]. clock_info[rdev->pm.profiles[PM_PROFILE_HIGH_MH_IDX].dpms_on_cm_idx].mclk; else mclk = rdev->pm.power_state[rdev->pm.requested_power_state_index]. clock_info[rdev->pm.requested_clock_mode_index].mclk; if (mclk > rdev->pm.default_mclk) mclk = rdev->pm.default_mclk; /* upvolt before raising clocks, downvolt after lowering clocks */ if (sclk < rdev->pm.current_sclk) misc_after = true; radeon_sync_with_vblank(rdev); if (rdev->pm.pm_method == PM_METHOD_DYNPM) { if (!radeon_pm_in_vbl(rdev)) return; } radeon_pm_prepare(rdev); if (!misc_after) /* voltage, pcie lanes, etc.*/ radeon_pm_misc(rdev); /* set engine clock */ if (sclk != rdev->pm.current_sclk) { radeon_pm_debug_check_in_vbl(rdev, false); radeon_set_engine_clock(rdev, sclk); radeon_pm_debug_check_in_vbl(rdev, true); rdev->pm.current_sclk = sclk; DRM_DEBUG_DRIVER("Setting: e: %d\n", sclk); } /* set memory clock */ if (rdev->asic->pm.set_memory_clock && (mclk != rdev->pm.current_mclk)) { radeon_pm_debug_check_in_vbl(rdev, false); radeon_set_memory_clock(rdev, mclk); radeon_pm_debug_check_in_vbl(rdev, true); rdev->pm.current_mclk = mclk; DRM_DEBUG_DRIVER("Setting: m: %d\n", mclk); } if (misc_after) /* voltage, pcie lanes, etc.*/ radeon_pm_misc(rdev); radeon_pm_finish(rdev); rdev->pm.current_power_state_index = rdev->pm.requested_power_state_index; rdev->pm.current_clock_mode_index = rdev->pm.requested_clock_mode_index; } else DRM_DEBUG_DRIVER("pm: GUI not idle!!!\n"); } static void radeon_pm_set_clocks(struct radeon_device *rdev) { struct drm_crtc *crtc; int i, r; /* no need to take locks, etc. if nothing's going to change */ if ((rdev->pm.requested_clock_mode_index == rdev->pm.current_clock_mode_index) && (rdev->pm.requested_power_state_index == rdev->pm.current_power_state_index)) return; down_write(&rdev->pm.mclk_lock); mutex_lock(&rdev->ring_lock); /* wait for the rings to drain */ for (i = 0; i < RADEON_NUM_RINGS; i++) { struct radeon_ring *ring = &rdev->ring[i]; if (!ring->ready) { continue; } r = radeon_fence_wait_empty(rdev, i); if (r) { /* needs a GPU reset dont reset here */ mutex_unlock(&rdev->ring_lock); up_write(&rdev->pm.mclk_lock); return; } } radeon_unmap_vram_bos(rdev); if (rdev->irq.installed) { i = 0; drm_for_each_crtc(crtc, rdev->ddev) { if (rdev->pm.active_crtcs & (1 << i)) { /* This can fail if a modeset is in progress */ if (drm_crtc_vblank_get(crtc) == 0) rdev->pm.req_vblank |= (1 << i); else DRM_DEBUG_DRIVER("crtc %d no vblank, can glitch\n", i); } i++; } } radeon_set_power_state(rdev); if (rdev->irq.installed) { i = 0; drm_for_each_crtc(crtc, rdev->ddev) { if (rdev->pm.req_vblank & (1 << i)) { rdev->pm.req_vblank &= ~(1 << i); drm_crtc_vblank_put(crtc); } i++; } } /* update display watermarks based on new power state */ radeon_update_bandwidth_info(rdev); if (rdev->pm.active_crtc_count) radeon_bandwidth_update(rdev); rdev->pm.dynpm_planned_action = DYNPM_ACTION_NONE; mutex_unlock(&rdev->ring_lock); up_write(&rdev->pm.mclk_lock); } static void radeon_pm_print_states(struct radeon_device *rdev) { int i, j; struct radeon_power_state *power_state; struct radeon_pm_clock_info *clock_info; DRM_DEBUG_DRIVER("%d Power State(s)\n", rdev->pm.num_power_states); for (i = 0; i < rdev->pm.num_power_states; i++) { power_state = &rdev->pm.power_state[i]; DRM_DEBUG_DRIVER("State %d: %s\n", i, radeon_pm_state_type_name[power_state->type]); if (i == rdev->pm.default_power_state_index) DRM_DEBUG_DRIVER("\tDefault"); if ((rdev->flags & RADEON_IS_PCIE) && !(rdev->flags & RADEON_IS_IGP)) DRM_DEBUG_DRIVER("\t%d PCIE Lanes\n", power_state->pcie_lanes); if (power_state->flags & RADEON_PM_STATE_SINGLE_DISPLAY_ONLY) DRM_DEBUG_DRIVER("\tSingle display only\n"); DRM_DEBUG_DRIVER("\t%d Clock Mode(s)\n", power_state->num_clock_modes); for (j = 0; j < power_state->num_clock_modes; j++) { clock_info = &(power_state->clock_info[j]); if (rdev->flags & RADEON_IS_IGP) DRM_DEBUG_DRIVER("\t\t%d e: %d\n", j, clock_info->sclk * 10); else DRM_DEBUG_DRIVER("\t\t%d e: %d\tm: %d\tv: %d\n", j, clock_info->sclk * 10, clock_info->mclk * 10, clock_info->voltage.voltage); } } } static ssize_t radeon_get_pm_profile(struct device *dev, struct device_attribute *attr, char *buf) { struct drm_device *ddev = dev_get_drvdata(dev); struct radeon_device *rdev = ddev->dev_private; int cp = rdev->pm.profile; return snprintf(buf, PAGE_SIZE, "%s\n", (cp == PM_PROFILE_AUTO) ? "auto" : (cp == PM_PROFILE_LOW) ? "low" : (cp == PM_PROFILE_MID) ? "mid" : (cp == PM_PROFILE_HIGH) ? "high" : "default"); } static ssize_t radeon_set_pm_profile(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct drm_device *ddev = dev_get_drvdata(dev); struct radeon_device *rdev = ddev->dev_private; /* Can't set profile when the card is off */ if ((rdev->flags & RADEON_IS_PX) && (ddev->switch_power_state != DRM_SWITCH_POWER_ON)) return -EINVAL; mutex_lock(&rdev->pm.mutex); if (rdev->pm.pm_method == PM_METHOD_PROFILE) { if (strncmp("default", buf, strlen("default")) == 0) rdev->pm.profile = PM_PROFILE_DEFAULT; else if (strncmp("auto", buf, strlen("auto")) == 0) rdev->pm.profile = PM_PROFILE_AUTO; else if (strncmp("low", buf, strlen("low")) == 0) rdev->pm.profile = PM_PROFILE_LOW; else if (strncmp("mid", buf, strlen("mid")) == 0) rdev->pm.profile = PM_PROFILE_MID; else if (strncmp("high", buf, strlen("high")) == 0) rdev->pm.profile = PM_PROFILE_HIGH; else { count = -EINVAL; goto fail; } radeon_pm_update_profile(rdev); radeon_pm_set_clocks(rdev); } else count = -EINVAL; fail: mutex_unlock(&rdev->pm.mutex); return count; } static ssize_t radeon_get_pm_method(struct device *dev, struct device_attribute *attr, char *buf) { struct drm_device *ddev = dev_get_drvdata(dev); struct radeon_device *rdev = ddev->dev_private; int pm = rdev->pm.pm_method; return snprintf(buf, PAGE_SIZE, "%s\n", (pm == PM_METHOD_DYNPM) ? "dynpm" : (pm == PM_METHOD_PROFILE) ? "profile" : "dpm"); } static ssize_t radeon_set_pm_method(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct drm_device *ddev = dev_get_drvdata(dev); struct radeon_device *rdev = ddev->dev_private; /* Can't set method when the card is off */ if ((rdev->flags & RADEON_IS_PX) && (ddev->switch_power_state != DRM_SWITCH_POWER_ON)) { count = -EINVAL; goto fail; } /* we don't support the legacy modes with dpm */ if (rdev->pm.pm_method == PM_METHOD_DPM) { count = -EINVAL; goto fail; } if (strncmp("dynpm", buf, strlen("dynpm")) == 0) { mutex_lock(&rdev->pm.mutex); rdev->pm.pm_method = PM_METHOD_DYNPM; rdev->pm.dynpm_state = DYNPM_STATE_PAUSED; rdev->pm.dynpm_planned_action = DYNPM_ACTION_DEFAULT; mutex_unlock(&rdev->pm.mutex); } else if (strncmp("profile", buf, strlen("profile")) == 0) { mutex_lock(&rdev->pm.mutex); /* disable dynpm */ rdev->pm.dynpm_state = DYNPM_STATE_DISABLED; rdev->pm.dynpm_planned_action = DYNPM_ACTION_NONE; rdev->pm.pm_method = PM_METHOD_PROFILE; mutex_unlock(&rdev->pm.mutex); cancel_delayed_work_sync(&rdev->pm.dynpm_idle_work); } else { count = -EINVAL; goto fail; } radeon_pm_compute_clocks(rdev); fail: return count; } static ssize_t radeon_get_dpm_state(struct device *dev, struct device_attribute *attr, char *buf) { struct drm_device *ddev = dev_get_drvdata(dev); struct radeon_device *rdev = ddev->dev_private; enum radeon_pm_state_type pm = rdev->pm.dpm.user_state; return snprintf(buf, PAGE_SIZE, "%s\n", (pm == POWER_STATE_TYPE_BATTERY) ? "battery" : (pm == POWER_STATE_TYPE_BALANCED) ? "balanced" : "performance"); } static ssize_t radeon_set_dpm_state(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct drm_device *ddev = dev_get_drvdata(dev); struct radeon_device *rdev = ddev->dev_private; mutex_lock(&rdev->pm.mutex); if (strncmp("battery", buf, strlen("battery")) == 0) rdev->pm.dpm.user_state = POWER_STATE_TYPE_BATTERY; else if (strncmp("balanced", buf, strlen("balanced")) == 0) rdev->pm.dpm.user_state = POWER_STATE_TYPE_BALANCED; else if (strncmp("performance", buf, strlen("performance")) == 0) rdev->pm.dpm.user_state = POWER_STATE_TYPE_PERFORMANCE; else { mutex_unlock(&rdev->pm.mutex); count = -EINVAL; goto fail; } mutex_unlock(&rdev->pm.mutex); /* Can't set dpm state when the card is off */ if (!(rdev->flags & RADEON_IS_PX) || (ddev->switch_power_state == DRM_SWITCH_POWER_ON)) radeon_pm_compute_clocks(rdev); fail: return count; } static ssize_t radeon_get_dpm_forced_performance_level(struct device *dev, struct device_attribute *attr, char *buf) { struct drm_device *ddev = dev_get_drvdata(dev); struct radeon_device *rdev = ddev->dev_private; enum radeon_dpm_forced_level level = rdev->pm.dpm.forced_level; if ((rdev->flags & RADEON_IS_PX) && (ddev->switch_power_state != DRM_SWITCH_POWER_ON)) return snprintf(buf, PAGE_SIZE, "off\n"); return snprintf(buf, PAGE_SIZE, "%s\n", (level == RADEON_DPM_FORCED_LEVEL_AUTO) ? "auto" : (level == RADEON_DPM_FORCED_LEVEL_LOW) ? "low" : "high"); } static ssize_t radeon_set_dpm_forced_performance_level(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct drm_device *ddev = dev_get_drvdata(dev); struct radeon_device *rdev = ddev->dev_private; enum radeon_dpm_forced_level level; int ret = 0; /* Can't force performance level when the card is off */ if ((rdev->flags & RADEON_IS_PX) && (ddev->switch_power_state != DRM_SWITCH_POWER_ON)) return -EINVAL; mutex_lock(&rdev->pm.mutex); if (strncmp("low", buf, strlen("low")) == 0) { level = RADEON_DPM_FORCED_LEVEL_LOW; } else if (strncmp("high", buf, strlen("high")) == 0) { level = RADEON_DPM_FORCED_LEVEL_HIGH; } else if (strncmp("auto", buf, strlen("auto")) == 0) { level = RADEON_DPM_FORCED_LEVEL_AUTO; } else { count = -EINVAL; goto fail; } if (rdev->asic->dpm.force_performance_level) { if (rdev->pm.dpm.thermal_active) { count = -EINVAL; goto fail; } ret = radeon_dpm_force_performance_level(rdev, level); if (ret) count = -EINVAL; } fail: mutex_unlock(&rdev->pm.mutex); return count; } static ssize_t radeon_hwmon_get_pwm1_enable(struct device *dev, struct device_attribute *attr, char *buf) { struct radeon_device *rdev = dev_get_drvdata(dev); u32 pwm_mode = 0; if (rdev->asic->dpm.fan_ctrl_get_mode) pwm_mode = rdev->asic->dpm.fan_ctrl_get_mode(rdev); /* never 0 (full-speed), fuse or smc-controlled always */ return sprintf(buf, "%i\n", pwm_mode == FDO_PWM_MODE_STATIC ? 1 : 2); } static ssize_t radeon_hwmon_set_pwm1_enable(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct radeon_device *rdev = dev_get_drvdata(dev); int err; int value; if(!rdev->asic->dpm.fan_ctrl_set_mode) return -EINVAL; err = kstrtoint(buf, 10, &value); if (err) return err; switch (value) { case 1: /* manual, percent-based */ rdev->asic->dpm.fan_ctrl_set_mode(rdev, FDO_PWM_MODE_STATIC); break; default: /* disable */ rdev->asic->dpm.fan_ctrl_set_mode(rdev, 0); break; } return count; } static ssize_t radeon_hwmon_get_pwm1_min(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%i\n", 0); } static ssize_t radeon_hwmon_get_pwm1_max(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%i\n", 255); } static ssize_t radeon_hwmon_set_pwm1(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct radeon_device *rdev = dev_get_drvdata(dev); int err; u32 value; err = kstrtou32(buf, 10, &value); if (err) return err; value = (value * 100) / 255; err = rdev->asic->dpm.set_fan_speed_percent(rdev, value); if (err) return err; return count; } static ssize_t radeon_hwmon_get_pwm1(struct device *dev, struct device_attribute *attr, char *buf) { struct radeon_device *rdev = dev_get_drvdata(dev); int err; u32 speed; err = rdev->asic->dpm.get_fan_speed_percent(rdev, &speed); if (err) return err; speed = (speed * 255) / 100; return sprintf(buf, "%i\n", speed); } static DEVICE_ATTR(power_profile, S_IRUGO | S_IWUSR, radeon_get_pm_profile, radeon_set_pm_profile); static DEVICE_ATTR(power_method, S_IRUGO | S_IWUSR, radeon_get_pm_method, radeon_set_pm_method); static DEVICE_ATTR(power_dpm_state, S_IRUGO | S_IWUSR, radeon_get_dpm_state, radeon_set_dpm_state); static DEVICE_ATTR(power_dpm_force_performance_level, S_IRUGO | S_IWUSR, radeon_get_dpm_forced_performance_level, radeon_set_dpm_forced_performance_level); static ssize_t radeon_hwmon_show_temp(struct device *dev, struct device_attribute *attr, char *buf) { struct radeon_device *rdev = dev_get_drvdata(dev); struct drm_device *ddev = rdev->ddev; int temp; /* Can't get temperature when the card is off */ if ((rdev->flags & RADEON_IS_PX) && (ddev->switch_power_state != DRM_SWITCH_POWER_ON)) return -EINVAL; if (rdev->asic->pm.get_temperature) temp = radeon_get_temperature(rdev); else temp = 0; return snprintf(buf, PAGE_SIZE, "%d\n", temp); } static ssize_t radeon_hwmon_show_temp_thresh(struct device *dev, struct device_attribute *attr, char *buf) { struct radeon_device *rdev = dev_get_drvdata(dev); int hyst = to_sensor_dev_attr(attr)->index; int temp; if (hyst) temp = rdev->pm.dpm.thermal.min_temp; else temp = rdev->pm.dpm.thermal.max_temp; return snprintf(buf, PAGE_SIZE, "%d\n", temp); } static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, radeon_hwmon_show_temp, NULL, 0); static SENSOR_DEVICE_ATTR(temp1_crit, S_IRUGO, radeon_hwmon_show_temp_thresh, NULL, 0); static SENSOR_DEVICE_ATTR(temp1_crit_hyst, S_IRUGO, radeon_hwmon_show_temp_thresh, NULL, 1); static SENSOR_DEVICE_ATTR(pwm1, S_IRUGO | S_IWUSR, radeon_hwmon_get_pwm1, radeon_hwmon_set_pwm1, 0); static SENSOR_DEVICE_ATTR(pwm1_enable, S_IRUGO | S_IWUSR, radeon_hwmon_get_pwm1_enable, radeon_hwmon_set_pwm1_enable, 0); static SENSOR_DEVICE_ATTR(pwm1_min, S_IRUGO, radeon_hwmon_get_pwm1_min, NULL, 0); static SENSOR_DEVICE_ATTR(pwm1_max, S_IRUGO, radeon_hwmon_get_pwm1_max, NULL, 0); static struct attribute *hwmon_attributes[] = { &sensor_dev_attr_temp1_input.dev_attr.attr, &sensor_dev_attr_temp1_crit.dev_attr.attr, &sensor_dev_attr_temp1_crit_hyst.dev_attr.attr, &sensor_dev_attr_pwm1.dev_attr.attr, &sensor_dev_attr_pwm1_enable.dev_attr.attr, &sensor_dev_attr_pwm1_min.dev_attr.attr, &sensor_dev_attr_pwm1_max.dev_attr.attr, NULL }; static umode_t hwmon_attributes_visible(struct kobject *kobj, struct attribute *attr, int index) { struct device *dev = kobj_to_dev(kobj); struct radeon_device *rdev = dev_get_drvdata(dev); umode_t effective_mode = attr->mode; /* Skip attributes if DPM is not enabled */ if (rdev->pm.pm_method != PM_METHOD_DPM && (attr == &sensor_dev_attr_temp1_crit.dev_attr.attr || attr == &sensor_dev_attr_temp1_crit_hyst.dev_attr.attr || attr == &sensor_dev_attr_pwm1.dev_attr.attr || attr == &sensor_dev_attr_pwm1_enable.dev_attr.attr || attr == &sensor_dev_attr_pwm1_max.dev_attr.attr || attr == &sensor_dev_attr_pwm1_min.dev_attr.attr)) return 0; /* Skip fan attributes if fan is not present */ if (rdev->pm.no_fan && (attr == &sensor_dev_attr_pwm1.dev_attr.attr || attr == &sensor_dev_attr_pwm1_enable.dev_attr.attr || attr == &sensor_dev_attr_pwm1_max.dev_attr.attr || attr == &sensor_dev_attr_pwm1_min.dev_attr.attr)) return 0; /* mask fan attributes if we have no bindings for this asic to expose */ if ((!rdev->asic->dpm.get_fan_speed_percent && attr == &sensor_dev_attr_pwm1.dev_attr.attr) || /* can't query fan */ (!rdev->asic->dpm.fan_ctrl_get_mode && attr == &sensor_dev_attr_pwm1_enable.dev_attr.attr)) /* can't query state */ effective_mode &= ~S_IRUGO; if ((!rdev->asic->dpm.set_fan_speed_percent && attr == &sensor_dev_attr_pwm1.dev_attr.attr) || /* can't manage fan */ (!rdev->asic->dpm.fan_ctrl_set_mode && attr == &sensor_dev_attr_pwm1_enable.dev_attr.attr)) /* can't manage state */ effective_mode &= ~S_IWUSR; /* hide max/min values if we can't both query and manage the fan */ if ((!rdev->asic->dpm.set_fan_speed_percent && !rdev->asic->dpm.get_fan_speed_percent) && (attr == &sensor_dev_attr_pwm1_max.dev_attr.attr || attr == &sensor_dev_attr_pwm1_min.dev_attr.attr)) return 0; return effective_mode; } static const struct attribute_group hwmon_attrgroup = { .attrs = hwmon_attributes, .is_visible = hwmon_attributes_visible, }; static const struct attribute_group *hwmon_groups[] = { &hwmon_attrgroup, NULL }; static int radeon_hwmon_init(struct radeon_device *rdev) { int err = 0; switch (rdev->pm.int_thermal_type) { case THERMAL_TYPE_RV6XX: case THERMAL_TYPE_RV770: case THERMAL_TYPE_EVERGREEN: case THERMAL_TYPE_NI: case THERMAL_TYPE_SUMO: case THERMAL_TYPE_SI: case THERMAL_TYPE_CI: case THERMAL_TYPE_KV: if (rdev->asic->pm.get_temperature == NULL) return err; rdev->pm.int_hwmon_dev = hwmon_device_register_with_groups(rdev->dev, "radeon", rdev, hwmon_groups); if (IS_ERR(rdev->pm.int_hwmon_dev)) { err = PTR_ERR(rdev->pm.int_hwmon_dev); dev_err(rdev->dev, "Unable to register hwmon device: %d\n", err); } break; default: break; } return err; } static void radeon_hwmon_fini(struct radeon_device *rdev) { if (rdev->pm.int_hwmon_dev) hwmon_device_unregister(rdev->pm.int_hwmon_dev); } static void radeon_dpm_thermal_work_handler(struct work_struct *work) { struct radeon_device *rdev = container_of(work, struct radeon_device, pm.dpm.thermal.work); /* switch to the thermal state */ enum radeon_pm_state_type dpm_state = POWER_STATE_TYPE_INTERNAL_THERMAL; if (!rdev->pm.dpm_enabled) return; if (rdev->asic->pm.get_temperature) { int temp = radeon_get_temperature(rdev); if (temp < rdev->pm.dpm.thermal.min_temp) /* switch back the user state */ dpm_state = rdev->pm.dpm.user_state; } else { if (rdev->pm.dpm.thermal.high_to_low) /* switch back the user state */ dpm_state = rdev->pm.dpm.user_state; } mutex_lock(&rdev->pm.mutex); if (dpm_state == POWER_STATE_TYPE_INTERNAL_THERMAL) rdev->pm.dpm.thermal_active = true; else rdev->pm.dpm.thermal_active = false; rdev->pm.dpm.state = dpm_state; mutex_unlock(&rdev->pm.mutex); radeon_pm_compute_clocks(rdev); } static bool radeon_dpm_single_display(struct radeon_device *rdev) { bool single_display = (rdev->pm.dpm.new_active_crtc_count < 2) ? true : false; /* check if the vblank period is too short to adjust the mclk */ if (single_display && rdev->asic->dpm.vblank_too_short) { if (radeon_dpm_vblank_too_short(rdev)) single_display = false; } /* 120hz tends to be problematic even if they are under the * vblank limit. */ if (single_display && (r600_dpm_get_vrefresh(rdev) >= 120)) single_display = false; return single_display; } static struct radeon_ps *radeon_dpm_pick_power_state(struct radeon_device *rdev, enum radeon_pm_state_type dpm_state) { int i; struct radeon_ps *ps; u32 ui_class; bool single_display = radeon_dpm_single_display(rdev); /* certain older asics have a separare 3D performance state, * so try that first if the user selected performance */ if (dpm_state == POWER_STATE_TYPE_PERFORMANCE) dpm_state = POWER_STATE_TYPE_INTERNAL_3DPERF; /* balanced states don't exist at the moment */ if (dpm_state == POWER_STATE_TYPE_BALANCED) dpm_state = rdev->pm.dpm.ac_power ? POWER_STATE_TYPE_PERFORMANCE : POWER_STATE_TYPE_BATTERY; restart_search: /* Pick the best power state based on current conditions */ for (i = 0; i < rdev->pm.dpm.num_ps; i++) { ps = &rdev->pm.dpm.ps[i]; ui_class = ps->class & ATOM_PPLIB_CLASSIFICATION_UI_MASK; switch (dpm_state) { /* user states */ case POWER_STATE_TYPE_BATTERY: if (ui_class == ATOM_PPLIB_CLASSIFICATION_UI_BATTERY) { if (ps->caps & ATOM_PPLIB_SINGLE_DISPLAY_ONLY) { if (single_display) return ps; } else return ps; } break; case POWER_STATE_TYPE_BALANCED: if (ui_class == ATOM_PPLIB_CLASSIFICATION_UI_BALANCED) { if (ps->caps & ATOM_PPLIB_SINGLE_DISPLAY_ONLY) { if (single_display) return ps; } else return ps; } break; case POWER_STATE_TYPE_PERFORMANCE: if (ui_class == ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE) { if (ps->caps & ATOM_PPLIB_SINGLE_DISPLAY_ONLY) { if (single_display) return ps; } else return ps; } break; /* internal states */ case POWER_STATE_TYPE_INTERNAL_UVD: if (rdev->pm.dpm.uvd_ps) return rdev->pm.dpm.uvd_ps; else break; case POWER_STATE_TYPE_INTERNAL_UVD_SD: if (ps->class & ATOM_PPLIB_CLASSIFICATION_SDSTATE) return ps; break; case POWER_STATE_TYPE_INTERNAL_UVD_HD: if (ps->class & ATOM_PPLIB_CLASSIFICATION_HDSTATE) return ps; break; case POWER_STATE_TYPE_INTERNAL_UVD_HD2: if (ps->class & ATOM_PPLIB_CLASSIFICATION_HD2STATE) return ps; break; case POWER_STATE_TYPE_INTERNAL_UVD_MVC: if (ps->class2 & ATOM_PPLIB_CLASSIFICATION2_MVC) return ps; break; case POWER_STATE_TYPE_INTERNAL_BOOT: return rdev->pm.dpm.boot_ps; case POWER_STATE_TYPE_INTERNAL_THERMAL: if (ps->class & ATOM_PPLIB_CLASSIFICATION_THERMAL) return ps; break; case POWER_STATE_TYPE_INTERNAL_ACPI: if (ps->class & ATOM_PPLIB_CLASSIFICATION_ACPI) return ps; break; case POWER_STATE_TYPE_INTERNAL_ULV: if (ps->class2 & ATOM_PPLIB_CLASSIFICATION2_ULV) return ps; break; case POWER_STATE_TYPE_INTERNAL_3DPERF: if (ps->class & ATOM_PPLIB_CLASSIFICATION_3DPERFORMANCE) return ps; break; default: break; } } /* use a fallback state if we didn't match */ switch (dpm_state) { case POWER_STATE_TYPE_INTERNAL_UVD_SD: dpm_state = POWER_STATE_TYPE_INTERNAL_UVD_HD; goto restart_search; case POWER_STATE_TYPE_INTERNAL_UVD_HD: case POWER_STATE_TYPE_INTERNAL_UVD_HD2: case POWER_STATE_TYPE_INTERNAL_UVD_MVC: if (rdev->pm.dpm.uvd_ps) { return rdev->pm.dpm.uvd_ps; } else { dpm_state = POWER_STATE_TYPE_PERFORMANCE; goto restart_search; } case POWER_STATE_TYPE_INTERNAL_THERMAL: dpm_state = POWER_STATE_TYPE_INTERNAL_ACPI; goto restart_search; case POWER_STATE_TYPE_INTERNAL_ACPI: dpm_state = POWER_STATE_TYPE_BATTERY; goto restart_search; case POWER_STATE_TYPE_BATTERY: case POWER_STATE_TYPE_BALANCED: case POWER_STATE_TYPE_INTERNAL_3DPERF: dpm_state = POWER_STATE_TYPE_PERFORMANCE; goto restart_search; default: break; } return NULL; } static void radeon_dpm_change_power_state_locked(struct radeon_device *rdev) { int i; struct radeon_ps *ps; enum radeon_pm_state_type dpm_state; int ret; bool single_display = radeon_dpm_single_display(rdev); /* if dpm init failed */ if (!rdev->pm.dpm_enabled) return; if (rdev->pm.dpm.user_state != rdev->pm.dpm.state) { /* add other state override checks here */ if ((!rdev->pm.dpm.thermal_active) && (!rdev->pm.dpm.uvd_active)) rdev->pm.dpm.state = rdev->pm.dpm.user_state; } dpm_state = rdev->pm.dpm.state; ps = radeon_dpm_pick_power_state(rdev, dpm_state); if (ps) rdev->pm.dpm.requested_ps = ps; else return; /* no need to reprogram if nothing changed unless we are on BTC+ */ if (rdev->pm.dpm.current_ps == rdev->pm.dpm.requested_ps) { /* vce just modifies an existing state so force a change */ if (ps->vce_active != rdev->pm.dpm.vce_active) goto force; /* user has made a display change (such as timing) */ if (rdev->pm.dpm.single_display != single_display) goto force; if ((rdev->family < CHIP_BARTS) || (rdev->flags & RADEON_IS_IGP)) { /* for pre-BTC and APUs if the num crtcs changed but state is the same, * all we need to do is update the display configuration. */ if (rdev->pm.dpm.new_active_crtcs != rdev->pm.dpm.current_active_crtcs) { /* update display watermarks based on new power state */ radeon_bandwidth_update(rdev); /* update displays */ radeon_dpm_display_configuration_changed(rdev); rdev->pm.dpm.current_active_crtcs = rdev->pm.dpm.new_active_crtcs; rdev->pm.dpm.current_active_crtc_count = rdev->pm.dpm.new_active_crtc_count; } return; } else { /* for BTC+ if the num crtcs hasn't changed and state is the same, * nothing to do, if the num crtcs is > 1 and state is the same, * update display configuration. */ if (rdev->pm.dpm.new_active_crtcs == rdev->pm.dpm.current_active_crtcs) { return; } else { if ((rdev->pm.dpm.current_active_crtc_count > 1) && (rdev->pm.dpm.new_active_crtc_count > 1)) { /* update display watermarks based on new power state */ radeon_bandwidth_update(rdev); /* update displays */ radeon_dpm_display_configuration_changed(rdev); rdev->pm.dpm.current_active_crtcs = rdev->pm.dpm.new_active_crtcs; rdev->pm.dpm.current_active_crtc_count = rdev->pm.dpm.new_active_crtc_count; return; } } } } force: if (radeon_dpm == 1) { printk("switching from power state:\n"); radeon_dpm_print_power_state(rdev, rdev->pm.dpm.current_ps); printk("switching to power state:\n"); radeon_dpm_print_power_state(rdev, rdev->pm.dpm.requested_ps); } down_write(&rdev->pm.mclk_lock); mutex_lock(&rdev->ring_lock); /* update whether vce is active */ ps->vce_active = rdev->pm.dpm.vce_active; ret = radeon_dpm_pre_set_power_state(rdev); if (ret) goto done; /* update display watermarks based on new power state */ radeon_bandwidth_update(rdev); /* update displays */ radeon_dpm_display_configuration_changed(rdev); /* wait for the rings to drain */ for (i = 0; i < RADEON_NUM_RINGS; i++) { struct radeon_ring *ring = &rdev->ring[i]; if (ring->ready) radeon_fence_wait_empty(rdev, i); } /* program the new power state */ radeon_dpm_set_power_state(rdev); /* update current power state */ rdev->pm.dpm.current_ps = rdev->pm.dpm.requested_ps; radeon_dpm_post_set_power_state(rdev); rdev->pm.dpm.current_active_crtcs = rdev->pm.dpm.new_active_crtcs; rdev->pm.dpm.current_active_crtc_count = rdev->pm.dpm.new_active_crtc_count; rdev->pm.dpm.single_display = single_display; if (rdev->asic->dpm.force_performance_level) { if (rdev->pm.dpm.thermal_active) { enum radeon_dpm_forced_level level = rdev->pm.dpm.forced_level; /* force low perf level for thermal */ radeon_dpm_force_performance_level(rdev, RADEON_DPM_FORCED_LEVEL_LOW); /* save the user's level */ rdev->pm.dpm.forced_level = level; } else { /* otherwise, user selected level */ radeon_dpm_force_performance_level(rdev, rdev->pm.dpm.forced_level); } } done: mutex_unlock(&rdev->ring_lock); up_write(&rdev->pm.mclk_lock); } void radeon_dpm_enable_uvd(struct radeon_device *rdev, bool enable) { enum radeon_pm_state_type dpm_state; if (rdev->asic->dpm.powergate_uvd) { mutex_lock(&rdev->pm.mutex); /* don't powergate anything if we have active but pause streams */ enable |= rdev->pm.dpm.sd > 0; enable |= rdev->pm.dpm.hd > 0; /* enable/disable UVD */ radeon_dpm_powergate_uvd(rdev, !enable); mutex_unlock(&rdev->pm.mutex); } else { if (enable) { mutex_lock(&rdev->pm.mutex); rdev->pm.dpm.uvd_active = true; /* disable this for now */ #if 0 if ((rdev->pm.dpm.sd == 1) && (rdev->pm.dpm.hd == 0)) dpm_state = POWER_STATE_TYPE_INTERNAL_UVD_SD; else if ((rdev->pm.dpm.sd == 2) && (rdev->pm.dpm.hd == 0)) dpm_state = POWER_STATE_TYPE_INTERNAL_UVD_HD; else if ((rdev->pm.dpm.sd == 0) && (rdev->pm.dpm.hd == 1)) dpm_state = POWER_STATE_TYPE_INTERNAL_UVD_HD; else if ((rdev->pm.dpm.sd == 0) && (rdev->pm.dpm.hd == 2)) dpm_state = POWER_STATE_TYPE_INTERNAL_UVD_HD2; else #endif dpm_state = POWER_STATE_TYPE_INTERNAL_UVD; rdev->pm.dpm.state = dpm_state; mutex_unlock(&rdev->pm.mutex); } else { mutex_lock(&rdev->pm.mutex); rdev->pm.dpm.uvd_active = false; mutex_unlock(&rdev->pm.mutex); } radeon_pm_compute_clocks(rdev); } } void radeon_dpm_enable_vce(struct radeon_device *rdev, bool enable) { if (enable) { mutex_lock(&rdev->pm.mutex); rdev->pm.dpm.vce_active = true; /* XXX select vce level based on ring/task */ rdev->pm.dpm.vce_level = RADEON_VCE_LEVEL_AC_ALL; mutex_unlock(&rdev->pm.mutex); } else { mutex_lock(&rdev->pm.mutex); rdev->pm.dpm.vce_active = false; mutex_unlock(&rdev->pm.mutex); } radeon_pm_compute_clocks(rdev); } static void radeon_pm_suspend_old(struct radeon_device *rdev) { mutex_lock(&rdev->pm.mutex); if (rdev->pm.pm_method == PM_METHOD_DYNPM) { if (rdev->pm.dynpm_state == DYNPM_STATE_ACTIVE) rdev->pm.dynpm_state = DYNPM_STATE_SUSPENDED; } mutex_unlock(&rdev->pm.mutex); cancel_delayed_work_sync(&rdev->pm.dynpm_idle_work); } static void radeon_pm_suspend_dpm(struct radeon_device *rdev) { mutex_lock(&rdev->pm.mutex); /* disable dpm */ radeon_dpm_disable(rdev); /* reset the power state */ rdev->pm.dpm.current_ps = rdev->pm.dpm.requested_ps = rdev->pm.dpm.boot_ps; rdev->pm.dpm_enabled = false; mutex_unlock(&rdev->pm.mutex); } void radeon_pm_suspend(struct radeon_device *rdev) { if (rdev->pm.pm_method == PM_METHOD_DPM) radeon_pm_suspend_dpm(rdev); else radeon_pm_suspend_old(rdev); } static void radeon_pm_resume_old(struct radeon_device *rdev) { /* set up the default clocks if the MC ucode is loaded */ if ((rdev->family >= CHIP_BARTS) && (rdev->family <= CHIP_CAYMAN) && rdev->mc_fw) { if (rdev->pm.default_vddc) radeon_atom_set_voltage(rdev, rdev->pm.default_vddc, SET_VOLTAGE_TYPE_ASIC_VDDC); if (rdev->pm.default_vddci) radeon_atom_set_voltage(rdev, rdev->pm.default_vddci, SET_VOLTAGE_TYPE_ASIC_VDDCI); if (rdev->pm.default_sclk) radeon_set_engine_clock(rdev, rdev->pm.default_sclk); if (rdev->pm.default_mclk) radeon_set_memory_clock(rdev, rdev->pm.default_mclk); } /* asic init will reset the default power state */ mutex_lock(&rdev->pm.mutex); rdev->pm.current_power_state_index = rdev->pm.default_power_state_index; rdev->pm.current_clock_mode_index = 0; rdev->pm.current_sclk = rdev->pm.default_sclk; rdev->pm.current_mclk = rdev->pm.default_mclk; if (rdev->pm.power_state) { rdev->pm.current_vddc = rdev->pm.power_state[rdev->pm.default_power_state_index].clock_info[0].voltage.voltage; rdev->pm.current_vddci = rdev->pm.power_state[rdev->pm.default_power_state_index].clock_info[0].voltage.vddci; } if (rdev->pm.pm_method == PM_METHOD_DYNPM && rdev->pm.dynpm_state == DYNPM_STATE_SUSPENDED) { rdev->pm.dynpm_state = DYNPM_STATE_ACTIVE; schedule_delayed_work(&rdev->pm.dynpm_idle_work, msecs_to_jiffies(RADEON_IDLE_LOOP_MS)); } mutex_unlock(&rdev->pm.mutex); radeon_pm_compute_clocks(rdev); } static void radeon_pm_resume_dpm(struct radeon_device *rdev) { int ret; /* asic init will reset to the boot state */ mutex_lock(&rdev->pm.mutex); rdev->pm.dpm.current_ps = rdev->pm.dpm.requested_ps = rdev->pm.dpm.boot_ps; radeon_dpm_setup_asic(rdev); ret = radeon_dpm_enable(rdev); mutex_unlock(&rdev->pm.mutex); if (ret) goto dpm_resume_fail; rdev->pm.dpm_enabled = true; return; dpm_resume_fail: DRM_ERROR("radeon: dpm resume failed\n"); if ((rdev->family >= CHIP_BARTS) && (rdev->family <= CHIP_CAYMAN) && rdev->mc_fw) { if (rdev->pm.default_vddc) radeon_atom_set_voltage(rdev, rdev->pm.default_vddc, SET_VOLTAGE_TYPE_ASIC_VDDC); if (rdev->pm.default_vddci) radeon_atom_set_voltage(rdev, rdev->pm.default_vddci, SET_VOLTAGE_TYPE_ASIC_VDDCI); if (rdev->pm.default_sclk) radeon_set_engine_clock(rdev, rdev->pm.default_sclk); if (rdev->pm.default_mclk) radeon_set_memory_clock(rdev, rdev->pm.default_mclk); } } void radeon_pm_resume(struct radeon_device *rdev) { if (rdev->pm.pm_method == PM_METHOD_DPM) radeon_pm_resume_dpm(rdev); else radeon_pm_resume_old(rdev); } static int radeon_pm_init_old(struct radeon_device *rdev) { int ret; rdev->pm.profile = PM_PROFILE_DEFAULT; rdev->pm.dynpm_state = DYNPM_STATE_DISABLED; rdev->pm.dynpm_planned_action = DYNPM_ACTION_NONE; rdev->pm.dynpm_can_upclock = true; rdev->pm.dynpm_can_downclock = true; rdev->pm.default_sclk = rdev->clock.default_sclk; rdev->pm.default_mclk = rdev->clock.default_mclk; rdev->pm.current_sclk = rdev->clock.default_sclk; rdev->pm.current_mclk = rdev->clock.default_mclk; rdev->pm.int_thermal_type = THERMAL_TYPE_NONE; if (rdev->bios) { if (rdev->is_atom_bios) radeon_atombios_get_power_modes(rdev); else radeon_combios_get_power_modes(rdev); radeon_pm_print_states(rdev); radeon_pm_init_profile(rdev); /* set up the default clocks if the MC ucode is loaded */ if ((rdev->family >= CHIP_BARTS) && (rdev->family <= CHIP_CAYMAN) && rdev->mc_fw) { if (rdev->pm.default_vddc) radeon_atom_set_voltage(rdev, rdev->pm.default_vddc, SET_VOLTAGE_TYPE_ASIC_VDDC); if (rdev->pm.default_vddci) radeon_atom_set_voltage(rdev, rdev->pm.default_vddci, SET_VOLTAGE_TYPE_ASIC_VDDCI); if (rdev->pm.default_sclk) radeon_set_engine_clock(rdev, rdev->pm.default_sclk); if (rdev->pm.default_mclk) radeon_set_memory_clock(rdev, rdev->pm.default_mclk); } } /* set up the internal thermal sensor if applicable */ ret = radeon_hwmon_init(rdev); if (ret) return ret; INIT_DELAYED_WORK(&rdev->pm.dynpm_idle_work, radeon_dynpm_idle_work_handler); if (rdev->pm.num_power_states > 1) { if (radeon_debugfs_pm_init(rdev)) { DRM_ERROR("Failed to register debugfs file for PM!\n"); } DRM_INFO("radeon: power management initialized\n"); } return 0; } static void radeon_dpm_print_power_states(struct radeon_device *rdev) { int i; for (i = 0; i < rdev->pm.dpm.num_ps; i++) { printk("== power state %d ==\n", i); radeon_dpm_print_power_state(rdev, &rdev->pm.dpm.ps[i]); } } static int radeon_pm_init_dpm(struct radeon_device *rdev) { int ret; /* default to balanced state */ rdev->pm.dpm.state = POWER_STATE_TYPE_BALANCED; rdev->pm.dpm.user_state = POWER_STATE_TYPE_BALANCED; rdev->pm.dpm.forced_level = RADEON_DPM_FORCED_LEVEL_AUTO; rdev->pm.default_sclk = rdev->clock.default_sclk; rdev->pm.default_mclk = rdev->clock.default_mclk; rdev->pm.current_sclk = rdev->clock.default_sclk; rdev->pm.current_mclk = rdev->clock.default_mclk; rdev->pm.int_thermal_type = THERMAL_TYPE_NONE; if (rdev->bios && rdev->is_atom_bios) radeon_atombios_get_power_modes(rdev); else return -EINVAL; /* set up the internal thermal sensor if applicable */ ret = radeon_hwmon_init(rdev); if (ret) return ret; INIT_WORK(&rdev->pm.dpm.thermal.work, radeon_dpm_thermal_work_handler); mutex_lock(&rdev->pm.mutex); radeon_dpm_init(rdev); rdev->pm.dpm.current_ps = rdev->pm.dpm.requested_ps = rdev->pm.dpm.boot_ps; if (radeon_dpm == 1) radeon_dpm_print_power_states(rdev); radeon_dpm_setup_asic(rdev); ret = radeon_dpm_enable(rdev); mutex_unlock(&rdev->pm.mutex); if (ret) goto dpm_failed; rdev->pm.dpm_enabled = true; if (radeon_debugfs_pm_init(rdev)) { DRM_ERROR("Failed to register debugfs file for dpm!\n"); } DRM_INFO("radeon: dpm initialized\n"); return 0; dpm_failed: rdev->pm.dpm_enabled = false; if ((rdev->family >= CHIP_BARTS) && (rdev->family <= CHIP_CAYMAN) && rdev->mc_fw) { if (rdev->pm.default_vddc) radeon_atom_set_voltage(rdev, rdev->pm.default_vddc, SET_VOLTAGE_TYPE_ASIC_VDDC); if (rdev->pm.default_vddci) radeon_atom_set_voltage(rdev, rdev->pm.default_vddci, SET_VOLTAGE_TYPE_ASIC_VDDCI); if (rdev->pm.default_sclk) radeon_set_engine_clock(rdev, rdev->pm.default_sclk); if (rdev->pm.default_mclk) radeon_set_memory_clock(rdev, rdev->pm.default_mclk); } DRM_ERROR("radeon: dpm initialization failed\n"); return ret; } struct radeon_dpm_quirk { u32 chip_vendor; u32 chip_device; u32 subsys_vendor; u32 subsys_device; }; /* cards with dpm stability problems */ static struct radeon_dpm_quirk radeon_dpm_quirk_list[] = { /* TURKS - https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1386534 */ { PCI_VENDOR_ID_ATI, 0x6759, 0x1682, 0x3195 }, /* TURKS - https://bugzilla.kernel.org/show_bug.cgi?id=83731 */ { PCI_VENDOR_ID_ATI, 0x6840, 0x1179, 0xfb81 }, { 0, 0, 0, 0 }, }; int radeon_pm_init(struct radeon_device *rdev) { struct radeon_dpm_quirk *p = radeon_dpm_quirk_list; bool disable_dpm = false; /* Apply dpm quirks */ while (p && p->chip_device != 0) { if (rdev->pdev->vendor == p->chip_vendor && rdev->pdev->device == p->chip_device && rdev->pdev->subsystem_vendor == p->subsys_vendor && rdev->pdev->subsystem_device == p->subsys_device) { disable_dpm = true; break; } ++p; } /* enable dpm on rv6xx+ */ switch (rdev->family) { case CHIP_RV610: case CHIP_RV630: case CHIP_RV620: case CHIP_RV635: case CHIP_RV670: case CHIP_RS780: case CHIP_RS880: case CHIP_RV770: /* DPM requires the RLC, RV770+ dGPU requires SMC */ if (!rdev->rlc_fw) rdev->pm.pm_method = PM_METHOD_PROFILE; else if ((rdev->family >= CHIP_RV770) && (!(rdev->flags & RADEON_IS_IGP)) && (!rdev->smc_fw)) rdev->pm.pm_method = PM_METHOD_PROFILE; else if (radeon_dpm == 1) rdev->pm.pm_method = PM_METHOD_DPM; else rdev->pm.pm_method = PM_METHOD_PROFILE; break; case CHIP_RV730: case CHIP_RV710: case CHIP_RV740: case CHIP_CEDAR: case CHIP_REDWOOD: case CHIP_JUNIPER: case CHIP_CYPRESS: case CHIP_HEMLOCK: case CHIP_PALM: case CHIP_SUMO: case CHIP_SUMO2: case CHIP_BARTS: case CHIP_TURKS: case CHIP_CAICOS: case CHIP_CAYMAN: case CHIP_ARUBA: case CHIP_TAHITI: case CHIP_PITCAIRN: case CHIP_VERDE: case CHIP_OLAND: case CHIP_HAINAN: case CHIP_BONAIRE: case CHIP_KABINI: case CHIP_KAVERI: case CHIP_HAWAII: case CHIP_MULLINS: /* DPM requires the RLC, RV770+ dGPU requires SMC */ if (!rdev->rlc_fw) rdev->pm.pm_method = PM_METHOD_PROFILE; else if ((rdev->family >= CHIP_RV770) && (!(rdev->flags & RADEON_IS_IGP)) && (!rdev->smc_fw)) rdev->pm.pm_method = PM_METHOD_PROFILE; else if (disable_dpm && (radeon_dpm == -1)) rdev->pm.pm_method = PM_METHOD_PROFILE; else if (radeon_dpm == 0) rdev->pm.pm_method = PM_METHOD_PROFILE; else rdev->pm.pm_method = PM_METHOD_DPM; break; default: /* default to profile method */ rdev->pm.pm_method = PM_METHOD_PROFILE; break; } if (rdev->pm.pm_method == PM_METHOD_DPM) return radeon_pm_init_dpm(rdev); else return radeon_pm_init_old(rdev); } int radeon_pm_late_init(struct radeon_device *rdev) { int ret = 0; if (rdev->pm.pm_method == PM_METHOD_DPM) { if (rdev->pm.dpm_enabled) { if (!rdev->pm.sysfs_initialized) { ret = device_create_file(rdev->dev, &dev_attr_power_dpm_state); if (ret) DRM_ERROR("failed to create device file for dpm state\n"); ret = device_create_file(rdev->dev, &dev_attr_power_dpm_force_performance_level); if (ret) DRM_ERROR("failed to create device file for dpm state\n"); /* XXX: these are noops for dpm but are here for backwards compat */ ret = device_create_file(rdev->dev, &dev_attr_power_profile); if (ret) DRM_ERROR("failed to create device file for power profile\n"); ret = device_create_file(rdev->dev, &dev_attr_power_method); if (ret) DRM_ERROR("failed to create device file for power method\n"); rdev->pm.sysfs_initialized = true; } mutex_lock(&rdev->pm.mutex); ret = radeon_dpm_late_enable(rdev); mutex_unlock(&rdev->pm.mutex); if (ret) { rdev->pm.dpm_enabled = false; DRM_ERROR("radeon_pm_late_init failed, disabling dpm\n"); } else { /* set the dpm state for PX since there won't be * a modeset to call this. */ radeon_pm_compute_clocks(rdev); } } } else { if ((rdev->pm.num_power_states > 1) && (!rdev->pm.sysfs_initialized)) { /* where's the best place to put these? */ ret = device_create_file(rdev->dev, &dev_attr_power_profile); if (ret) DRM_ERROR("failed to create device file for power profile\n"); ret = device_create_file(rdev->dev, &dev_attr_power_method); if (ret) DRM_ERROR("failed to create device file for power method\n"); if (!ret) rdev->pm.sysfs_initialized = true; } } return ret; } static void radeon_pm_fini_old(struct radeon_device *rdev) { if (rdev->pm.num_power_states > 1) { mutex_lock(&rdev->pm.mutex); if (rdev->pm.pm_method == PM_METHOD_PROFILE) { rdev->pm.profile = PM_PROFILE_DEFAULT; radeon_pm_update_profile(rdev); radeon_pm_set_clocks(rdev); } else if (rdev->pm.pm_method == PM_METHOD_DYNPM) { /* reset default clocks */ rdev->pm.dynpm_state = DYNPM_STATE_DISABLED; rdev->pm.dynpm_planned_action = DYNPM_ACTION_DEFAULT; radeon_pm_set_clocks(rdev); } mutex_unlock(&rdev->pm.mutex); cancel_delayed_work_sync(&rdev->pm.dynpm_idle_work); device_remove_file(rdev->dev, &dev_attr_power_profile); device_remove_file(rdev->dev, &dev_attr_power_method); } radeon_hwmon_fini(rdev); kfree(rdev->pm.power_state); } static void radeon_pm_fini_dpm(struct radeon_device *rdev) { if (rdev->pm.num_power_states > 1) { mutex_lock(&rdev->pm.mutex); radeon_dpm_disable(rdev); mutex_unlock(&rdev->pm.mutex); device_remove_file(rdev->dev, &dev_attr_power_dpm_state); device_remove_file(rdev->dev, &dev_attr_power_dpm_force_performance_level); /* XXX backwards compat */ device_remove_file(rdev->dev, &dev_attr_power_profile); device_remove_file(rdev->dev, &dev_attr_power_method); } radeon_dpm_fini(rdev); radeon_hwmon_fini(rdev); kfree(rdev->pm.power_state); } void radeon_pm_fini(struct radeon_device *rdev) { if (rdev->pm.pm_method == PM_METHOD_DPM) radeon_pm_fini_dpm(rdev); else radeon_pm_fini_old(rdev); } static void radeon_pm_compute_clocks_old(struct radeon_device *rdev) { struct drm_device *ddev = rdev->ddev; struct drm_crtc *crtc; struct radeon_crtc *radeon_crtc; if (rdev->pm.num_power_states < 2) return; mutex_lock(&rdev->pm.mutex); rdev->pm.active_crtcs = 0; rdev->pm.active_crtc_count = 0; if (rdev->num_crtc && rdev->mode_info.mode_config_initialized) { list_for_each_entry(crtc, &ddev->mode_config.crtc_list, head) { radeon_crtc = to_radeon_crtc(crtc); if (radeon_crtc->enabled) { rdev->pm.active_crtcs |= (1 << radeon_crtc->crtc_id); rdev->pm.active_crtc_count++; } } } if (rdev->pm.pm_method == PM_METHOD_PROFILE) { radeon_pm_update_profile(rdev); radeon_pm_set_clocks(rdev); } else if (rdev->pm.pm_method == PM_METHOD_DYNPM) { if (rdev->pm.dynpm_state != DYNPM_STATE_DISABLED) { if (rdev->pm.active_crtc_count > 1) { if (rdev->pm.dynpm_state == DYNPM_STATE_ACTIVE) { cancel_delayed_work(&rdev->pm.dynpm_idle_work); rdev->pm.dynpm_state = DYNPM_STATE_PAUSED; rdev->pm.dynpm_planned_action = DYNPM_ACTION_DEFAULT; radeon_pm_get_dynpm_state(rdev); radeon_pm_set_clocks(rdev); DRM_DEBUG_DRIVER("radeon: dynamic power management deactivated\n"); } } else if (rdev->pm.active_crtc_count == 1) { /* TODO: Increase clocks if needed for current mode */ if (rdev->pm.dynpm_state == DYNPM_STATE_MINIMUM) { rdev->pm.dynpm_state = DYNPM_STATE_ACTIVE; rdev->pm.dynpm_planned_action = DYNPM_ACTION_UPCLOCK; radeon_pm_get_dynpm_state(rdev); radeon_pm_set_clocks(rdev); schedule_delayed_work(&rdev->pm.dynpm_idle_work, msecs_to_jiffies(RADEON_IDLE_LOOP_MS)); } else if (rdev->pm.dynpm_state == DYNPM_STATE_PAUSED) { rdev->pm.dynpm_state = DYNPM_STATE_ACTIVE; schedule_delayed_work(&rdev->pm.dynpm_idle_work, msecs_to_jiffies(RADEON_IDLE_LOOP_MS)); DRM_DEBUG_DRIVER("radeon: dynamic power management activated\n"); } } else { /* count == 0 */ if (rdev->pm.dynpm_state != DYNPM_STATE_MINIMUM) { cancel_delayed_work(&rdev->pm.dynpm_idle_work); rdev->pm.dynpm_state = DYNPM_STATE_MINIMUM; rdev->pm.dynpm_planned_action = DYNPM_ACTION_MINIMUM; radeon_pm_get_dynpm_state(rdev); radeon_pm_set_clocks(rdev); } } } } mutex_unlock(&rdev->pm.mutex); } static void radeon_pm_compute_clocks_dpm(struct radeon_device *rdev) { struct drm_device *ddev = rdev->ddev; struct drm_crtc *crtc; struct radeon_crtc *radeon_crtc; if (!rdev->pm.dpm_enabled) return; mutex_lock(&rdev->pm.mutex); /* update active crtc counts */ rdev->pm.dpm.new_active_crtcs = 0; rdev->pm.dpm.new_active_crtc_count = 0; if (rdev->num_crtc && rdev->mode_info.mode_config_initialized) { list_for_each_entry(crtc, &ddev->mode_config.crtc_list, head) { radeon_crtc = to_radeon_crtc(crtc); if (crtc->enabled) { rdev->pm.dpm.new_active_crtcs |= (1 << radeon_crtc->crtc_id); rdev->pm.dpm.new_active_crtc_count++; } } } /* update battery/ac status */ if (power_supply_is_system_supplied() > 0) rdev->pm.dpm.ac_power = true; else rdev->pm.dpm.ac_power = false; radeon_dpm_change_power_state_locked(rdev); mutex_unlock(&rdev->pm.mutex); } void radeon_pm_compute_clocks(struct radeon_device *rdev) { if (rdev->pm.pm_method == PM_METHOD_DPM) radeon_pm_compute_clocks_dpm(rdev); else radeon_pm_compute_clocks_old(rdev); } static bool radeon_pm_in_vbl(struct radeon_device *rdev) { int crtc, vpos, hpos, vbl_status; bool in_vbl = true; /* Iterate over all active crtc's. All crtc's must be in vblank, * otherwise return in_vbl == false. */ for (crtc = 0; (crtc < rdev->num_crtc) && in_vbl; crtc++) { if (rdev->pm.active_crtcs & (1 << crtc)) { vbl_status = radeon_get_crtc_scanoutpos(rdev->ddev, crtc, USE_REAL_VBLANKSTART, &vpos, &hpos, NULL, NULL, &rdev->mode_info.crtcs[crtc]->base.hwmode); if ((vbl_status & DRM_SCANOUTPOS_VALID) && !(vbl_status & DRM_SCANOUTPOS_IN_VBLANK)) in_vbl = false; } } return in_vbl; } static bool radeon_pm_debug_check_in_vbl(struct radeon_device *rdev, bool finish) { u32 stat_crtc = 0; bool in_vbl = radeon_pm_in_vbl(rdev); if (in_vbl == false) DRM_DEBUG_DRIVER("not in vbl for pm change %08x at %s\n", stat_crtc, finish ? "exit" : "entry"); return in_vbl; } static void radeon_dynpm_idle_work_handler(struct work_struct *work) { struct radeon_device *rdev; int resched; rdev = container_of(work, struct radeon_device, pm.dynpm_idle_work.work); resched = ttm_bo_lock_delayed_workqueue(&rdev->mman.bdev); mutex_lock(&rdev->pm.mutex); if (rdev->pm.dynpm_state == DYNPM_STATE_ACTIVE) { int not_processed = 0; int i; for (i = 0; i < RADEON_NUM_RINGS; ++i) { struct radeon_ring *ring = &rdev->ring[i]; if (ring->ready) { not_processed += radeon_fence_count_emitted(rdev, i); if (not_processed >= 3) break; } } if (not_processed >= 3) { /* should upclock */ if (rdev->pm.dynpm_planned_action == DYNPM_ACTION_DOWNCLOCK) { rdev->pm.dynpm_planned_action = DYNPM_ACTION_NONE; } else if (rdev->pm.dynpm_planned_action == DYNPM_ACTION_NONE && rdev->pm.dynpm_can_upclock) { rdev->pm.dynpm_planned_action = DYNPM_ACTION_UPCLOCK; rdev->pm.dynpm_action_timeout = jiffies + msecs_to_jiffies(RADEON_RECLOCK_DELAY_MS); } } else if (not_processed == 0) { /* should downclock */ if (rdev->pm.dynpm_planned_action == DYNPM_ACTION_UPCLOCK) { rdev->pm.dynpm_planned_action = DYNPM_ACTION_NONE; } else if (rdev->pm.dynpm_planned_action == DYNPM_ACTION_NONE && rdev->pm.dynpm_can_downclock) { rdev->pm.dynpm_planned_action = DYNPM_ACTION_DOWNCLOCK; rdev->pm.dynpm_action_timeout = jiffies + msecs_to_jiffies(RADEON_RECLOCK_DELAY_MS); } } /* Note, radeon_pm_set_clocks is called with static_switch set * to false since we want to wait for vbl to avoid flicker. */ if (rdev->pm.dynpm_planned_action != DYNPM_ACTION_NONE && jiffies > rdev->pm.dynpm_action_timeout) { radeon_pm_get_dynpm_state(rdev); radeon_pm_set_clocks(rdev); } schedule_delayed_work(&rdev->pm.dynpm_idle_work, msecs_to_jiffies(RADEON_IDLE_LOOP_MS)); } mutex_unlock(&rdev->pm.mutex); ttm_bo_unlock_delayed_workqueue(&rdev->mman.bdev, resched); } /* * Debugfs info */ #if defined(CONFIG_DEBUG_FS) static int radeon_debugfs_pm_info(struct seq_file *m, void *data) { struct drm_info_node *node = (struct drm_info_node *) m->private; struct drm_device *dev = node->minor->dev; struct radeon_device *rdev = dev->dev_private; struct drm_device *ddev = rdev->ddev; if ((rdev->flags & RADEON_IS_PX) && (ddev->switch_power_state != DRM_SWITCH_POWER_ON)) { seq_printf(m, "PX asic powered off\n"); } else if (rdev->pm.dpm_enabled) { mutex_lock(&rdev->pm.mutex); if (rdev->asic->dpm.debugfs_print_current_performance_level) radeon_dpm_debugfs_print_current_performance_level(rdev, m); else seq_printf(m, "Debugfs support not implemented for this asic\n"); mutex_unlock(&rdev->pm.mutex); } else { seq_printf(m, "default engine clock: %u0 kHz\n", rdev->pm.default_sclk); /* radeon_get_engine_clock is not reliable on APUs so just print the current clock */ if ((rdev->family >= CHIP_PALM) && (rdev->flags & RADEON_IS_IGP)) seq_printf(m, "current engine clock: %u0 kHz\n", rdev->pm.current_sclk); else seq_printf(m, "current engine clock: %u0 kHz\n", radeon_get_engine_clock(rdev)); seq_printf(m, "default memory clock: %u0 kHz\n", rdev->pm.default_mclk); if (rdev->asic->pm.get_memory_clock) seq_printf(m, "current memory clock: %u0 kHz\n", radeon_get_memory_clock(rdev)); if (rdev->pm.current_vddc) seq_printf(m, "voltage: %u mV\n", rdev->pm.current_vddc); if (rdev->asic->pm.get_pcie_lanes) seq_printf(m, "PCIE lanes: %d\n", radeon_get_pcie_lanes(rdev)); } return 0; } static struct drm_info_list radeon_pm_info_list[] = { {"radeon_pm_info", radeon_debugfs_pm_info, 0, NULL}, }; #endif static int radeon_debugfs_pm_init(struct radeon_device *rdev) { #if defined(CONFIG_DEBUG_FS) return radeon_debugfs_add_files(rdev, radeon_pm_info_list, ARRAY_SIZE(radeon_pm_info_list)); #else return 0; #endif }
null
null
null
null
99,860
35,817
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
200,812
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * MOXA ART SoCs watchdog driver. * * Copyright (C) 2013 Jonas Jensen * * Jonas Jensen <[email protected]> * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/clk.h> #include <linux/io.h> #include <linux/module.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/watchdog.h> #include <linux/moduleparam.h> #define REG_COUNT 0x4 #define REG_MODE 0x8 #define REG_ENABLE 0xC struct moxart_wdt_dev { struct watchdog_device dev; void __iomem *base; unsigned int clock_frequency; }; static int heartbeat; static int moxart_wdt_restart(struct watchdog_device *wdt_dev, unsigned long action, void *data) { struct moxart_wdt_dev *moxart_wdt = watchdog_get_drvdata(wdt_dev); writel(1, moxart_wdt->base + REG_COUNT); writel(0x5ab9, moxart_wdt->base + REG_MODE); writel(0x03, moxart_wdt->base + REG_ENABLE); return 0; } static int moxart_wdt_stop(struct watchdog_device *wdt_dev) { struct moxart_wdt_dev *moxart_wdt = watchdog_get_drvdata(wdt_dev); writel(0, moxart_wdt->base + REG_ENABLE); return 0; } static int moxart_wdt_start(struct watchdog_device *wdt_dev) { struct moxart_wdt_dev *moxart_wdt = watchdog_get_drvdata(wdt_dev); writel(moxart_wdt->clock_frequency * wdt_dev->timeout, moxart_wdt->base + REG_COUNT); writel(0x5ab9, moxart_wdt->base + REG_MODE); writel(0x03, moxart_wdt->base + REG_ENABLE); return 0; } static int moxart_wdt_set_timeout(struct watchdog_device *wdt_dev, unsigned int timeout) { wdt_dev->timeout = timeout; return 0; } static const struct watchdog_info moxart_wdt_info = { .identity = "moxart-wdt", .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE, }; static const struct watchdog_ops moxart_wdt_ops = { .owner = THIS_MODULE, .start = moxart_wdt_start, .stop = moxart_wdt_stop, .set_timeout = moxart_wdt_set_timeout, .restart = moxart_wdt_restart, }; static int moxart_wdt_probe(struct platform_device *pdev) { struct moxart_wdt_dev *moxart_wdt; struct device *dev = &pdev->dev; struct device_node *node = dev->of_node; struct resource *res; struct clk *clk; int err; unsigned int max_timeout; bool nowayout = WATCHDOG_NOWAYOUT; moxart_wdt = devm_kzalloc(dev, sizeof(*moxart_wdt), GFP_KERNEL); if (!moxart_wdt) return -ENOMEM; platform_set_drvdata(pdev, moxart_wdt); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); moxart_wdt->base = devm_ioremap_resource(dev, res); if (IS_ERR(moxart_wdt->base)) return PTR_ERR(moxart_wdt->base); clk = of_clk_get(node, 0); if (IS_ERR(clk)) { pr_err("%s: of_clk_get failed\n", __func__); return PTR_ERR(clk); } moxart_wdt->clock_frequency = clk_get_rate(clk); if (moxart_wdt->clock_frequency == 0) { pr_err("%s: incorrect clock frequency\n", __func__); return -EINVAL; } max_timeout = UINT_MAX / moxart_wdt->clock_frequency; moxart_wdt->dev.info = &moxart_wdt_info; moxart_wdt->dev.ops = &moxart_wdt_ops; moxart_wdt->dev.timeout = max_timeout; moxart_wdt->dev.min_timeout = 1; moxart_wdt->dev.max_timeout = max_timeout; moxart_wdt->dev.parent = dev; watchdog_init_timeout(&moxart_wdt->dev, heartbeat, dev); watchdog_set_nowayout(&moxart_wdt->dev, nowayout); watchdog_set_restart_priority(&moxart_wdt->dev, 128); watchdog_set_drvdata(&moxart_wdt->dev, moxart_wdt); err = watchdog_register_device(&moxart_wdt->dev); if (err) return err; dev_dbg(dev, "Watchdog enabled (heartbeat=%d sec, nowayout=%d)\n", moxart_wdt->dev.timeout, nowayout); return 0; } static int moxart_wdt_remove(struct platform_device *pdev) { struct moxart_wdt_dev *moxart_wdt = platform_get_drvdata(pdev); moxart_wdt_stop(&moxart_wdt->dev); return 0; } static const struct of_device_id moxart_watchdog_match[] = { { .compatible = "moxa,moxart-watchdog" }, { }, }; MODULE_DEVICE_TABLE(of, moxart_watchdog_match); static struct platform_driver moxart_wdt_driver = { .probe = moxart_wdt_probe, .remove = moxart_wdt_remove, .driver = { .name = "moxart-watchdog", .of_match_table = moxart_watchdog_match, }, }; module_platform_driver(moxart_wdt_driver); module_param(heartbeat, int, 0); MODULE_PARM_DESC(heartbeat, "Watchdog heartbeat in seconds"); MODULE_DESCRIPTION("MOXART watchdog driver"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Jonas Jensen <[email protected]>");
null
null
null
null
109,159
34,787
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
199,782
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* Frontend part of the Linux driver for the WideView/ Yakumo/ Hama/ * Typhoon/ Yuan DVB-T USB2.0 receiver. * * Copyright (C) 2005 Patrick Boettcher <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, version 2. * * see Documentation/dvb/README.dvb-usb for more information */ #include "dtt200u.h" struct dtt200u_fe_state { struct dvb_usb_device *d; enum fe_status stat; struct dtv_frontend_properties fep; struct dvb_frontend frontend; unsigned char data[80]; struct mutex data_mutex; }; static int dtt200u_fe_read_status(struct dvb_frontend *fe, enum fe_status *stat) { struct dtt200u_fe_state *state = fe->demodulator_priv; int ret; mutex_lock(&state->data_mutex); state->data[0] = GET_TUNE_STATUS; ret = dvb_usb_generic_rw(state->d, state->data, 1, state->data, 3, 0); if (ret < 0) { *stat = 0; mutex_unlock(&state->data_mutex); return ret; } switch (state->data[0]) { case 0x01: *stat = FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_VITERBI | FE_HAS_SYNC | FE_HAS_LOCK; break; case 0x00: /* pending */ *stat = FE_TIMEDOUT; /* during set_frontend */ break; default: case 0x02: /* failed */ *stat = 0; break; } mutex_unlock(&state->data_mutex); return 0; } static int dtt200u_fe_read_ber(struct dvb_frontend* fe, u32 *ber) { struct dtt200u_fe_state *state = fe->demodulator_priv; int ret; mutex_lock(&state->data_mutex); state->data[0] = GET_VIT_ERR_CNT; ret = dvb_usb_generic_rw(state->d, state->data, 1, state->data, 3, 0); if (ret >= 0) *ber = (state->data[0] << 16) | (state->data[1] << 8) | state->data[2]; mutex_unlock(&state->data_mutex); return ret; } static int dtt200u_fe_read_unc_blocks(struct dvb_frontend* fe, u32 *unc) { struct dtt200u_fe_state *state = fe->demodulator_priv; int ret; mutex_lock(&state->data_mutex); state->data[0] = GET_RS_UNCOR_BLK_CNT; ret = dvb_usb_generic_rw(state->d, state->data, 1, state->data, 2, 0); if (ret >= 0) *unc = (state->data[0] << 8) | state->data[1]; mutex_unlock(&state->data_mutex); return ret; } static int dtt200u_fe_read_signal_strength(struct dvb_frontend* fe, u16 *strength) { struct dtt200u_fe_state *state = fe->demodulator_priv; int ret; mutex_lock(&state->data_mutex); state->data[0] = GET_AGC; ret = dvb_usb_generic_rw(state->d, state->data, 1, state->data, 1, 0); if (ret >= 0) *strength = (state->data[0] << 8) | state->data[0]; mutex_unlock(&state->data_mutex); return ret; } static int dtt200u_fe_read_snr(struct dvb_frontend* fe, u16 *snr) { struct dtt200u_fe_state *state = fe->demodulator_priv; int ret; mutex_lock(&state->data_mutex); state->data[0] = GET_SNR; ret = dvb_usb_generic_rw(state->d, state->data, 1, state->data, 1, 0); if (ret >= 0) *snr = ~((state->data[0] << 8) | state->data[0]); mutex_unlock(&state->data_mutex); return ret; } static int dtt200u_fe_init(struct dvb_frontend* fe) { struct dtt200u_fe_state *state = fe->demodulator_priv; int ret; mutex_lock(&state->data_mutex); state->data[0] = SET_INIT; ret = dvb_usb_generic_write(state->d, state->data, 1); mutex_unlock(&state->data_mutex); return ret; } static int dtt200u_fe_sleep(struct dvb_frontend* fe) { return dtt200u_fe_init(fe); } static int dtt200u_fe_get_tune_settings(struct dvb_frontend* fe, struct dvb_frontend_tune_settings *tune) { tune->min_delay_ms = 1500; tune->step_size = 0; tune->max_drift = 0; return 0; } static int dtt200u_fe_set_frontend(struct dvb_frontend *fe) { struct dtv_frontend_properties *fep = &fe->dtv_property_cache; struct dtt200u_fe_state *state = fe->demodulator_priv; int ret; u16 freq = fep->frequency / 250000; mutex_lock(&state->data_mutex); state->data[0] = SET_BANDWIDTH; switch (fep->bandwidth_hz) { case 8000000: state->data[1] = 8; break; case 7000000: state->data[1] = 7; break; case 6000000: state->data[1] = 6; break; default: ret = -EINVAL; goto ret; } ret = dvb_usb_generic_write(state->d, state->data, 2); if (ret < 0) goto ret; state->data[0] = SET_RF_FREQ; state->data[1] = freq & 0xff; state->data[2] = (freq >> 8) & 0xff; ret = dvb_usb_generic_write(state->d, state->data, 3); if (ret < 0) goto ret; ret: mutex_unlock(&state->data_mutex); return ret; } static int dtt200u_fe_get_frontend(struct dvb_frontend* fe, struct dtv_frontend_properties *fep) { struct dtt200u_fe_state *state = fe->demodulator_priv; memcpy(fep, &state->fep, sizeof(struct dtv_frontend_properties)); return 0; } static void dtt200u_fe_release(struct dvb_frontend* fe) { struct dtt200u_fe_state *state = (struct dtt200u_fe_state*) fe->demodulator_priv; kfree(state); } static const struct dvb_frontend_ops dtt200u_fe_ops; struct dvb_frontend* dtt200u_fe_attach(struct dvb_usb_device *d) { struct dtt200u_fe_state* state = NULL; /* allocate memory for the internal state */ state = kzalloc(sizeof(struct dtt200u_fe_state), GFP_KERNEL); if (state == NULL) goto error; deb_info("attaching frontend dtt200u\n"); state->d = d; mutex_init(&state->data_mutex); memcpy(&state->frontend.ops,&dtt200u_fe_ops,sizeof(struct dvb_frontend_ops)); state->frontend.demodulator_priv = state; return &state->frontend; error: return NULL; } static const struct dvb_frontend_ops dtt200u_fe_ops = { .delsys = { SYS_DVBT }, .info = { .name = "WideView USB DVB-T", .frequency_min = 44250000, .frequency_max = 867250000, .frequency_stepsize = 250000, .caps = FE_CAN_INVERSION_AUTO | FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 | FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO | FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO | FE_CAN_TRANSMISSION_MODE_AUTO | FE_CAN_GUARD_INTERVAL_AUTO | FE_CAN_RECOVER | FE_CAN_HIERARCHY_AUTO, }, .release = dtt200u_fe_release, .init = dtt200u_fe_init, .sleep = dtt200u_fe_sleep, .set_frontend = dtt200u_fe_set_frontend, .get_frontend = dtt200u_fe_get_frontend, .get_tune_settings = dtt200u_fe_get_tune_settings, .read_status = dtt200u_fe_read_status, .read_ber = dtt200u_fe_read_ber, .read_signal_strength = dtt200u_fe_read_signal_strength, .read_snr = dtt200u_fe_read_snr, .read_ucblocks = dtt200u_fe_read_unc_blocks, };
null
null
null
null
108,129
65,048
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
65,048
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/ui/app_list/search/common/url_icon_source.h" #include <string> #include <utility> #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "net/base/load_flags.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image_skia_operations.h" using content::BrowserThread; namespace app_list { UrlIconSource::UrlIconSource(const IconLoadedCallback& icon_loaded_callback, content::BrowserContext* browser_context, const GURL& icon_url, int icon_size, int default_icon_resource_id) : icon_loaded_callback_(icon_loaded_callback), browser_context_(browser_context), icon_url_(icon_url), icon_size_(icon_size), default_icon_resource_id_(default_icon_resource_id), icon_fetch_attempted_(false) { DCHECK(!icon_loaded_callback_.is_null()); } UrlIconSource::~UrlIconSource() { } void UrlIconSource::StartIconFetch() { icon_fetch_attempted_ = true; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = icon_url_; resource_request->load_flags = net::LOAD_DO_NOT_SAVE_COOKIES; net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("url_icon_source_fetch", R"( semantics { sender: "URL Icon Source" description: "Chrome OS downloads an icon for a web store result." trigger: "When a user initiates a web store search and views results. " data: "URL of the icon. " "No user information is sent." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "Unconditionally enabled on Chrome OS." policy_exception_justification: "Not implemented, considered not useful." })"); simple_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); network::mojom::URLLoaderFactory* loader_factory = content::BrowserContext::GetDefaultStoragePartition(browser_context_) ->GetURLLoaderFactoryForBrowserProcess() .get(); simple_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( loader_factory, base::BindOnce(&UrlIconSource::OnSimpleLoaderComplete, base::Unretained(this))); } gfx::ImageSkiaRep UrlIconSource::GetImageForScale(float scale) { if (!icon_fetch_attempted_) StartIconFetch(); if (!icon_.isNull()) return icon_.GetRepresentation(scale); return ui::ResourceBundle::GetSharedInstance() .GetImageSkiaNamed(default_icon_resource_id_)->GetRepresentation(scale); } void UrlIconSource::OnSimpleLoaderComplete( std::unique_ptr<std::string> response_body) { if (!response_body) { return; } // Call start to begin decoding. The ImageDecoder will call OnImageDecoded // with the data when it is done. ImageDecoder::Start(this, *response_body); } void UrlIconSource::OnImageDecoded(const SkBitmap& decoded_image) { icon_ = gfx::ImageSkiaOperations::CreateResizedImage( gfx::ImageSkia::CreateFrom1xBitmap(decoded_image), skia::ImageOperations::RESIZE_BEST, gfx::Size(icon_size_, icon_size_)); icon_loaded_callback_.Run(); } void UrlIconSource::OnDecodeImageFailed() { // Failed to decode image. Do nothing and just use the default icon. } } // namespace app_list
null
null
null
null
61,911
14,458
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
179,453
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
#ifndef __reg_map_h #define __reg_map_h /* * This file is autogenerated from * file: reg.rmap * * by ../../../tools/rdesc/bin/rdes2c -base 0xb0000000 -map marb_bar.r marb_foo.r ccd_top.r ccd_stat.r ccd_tg.r ccd_dp.r ccd.r iop_sap_in.r iop_sap_out.r iop_sw_cfg.r iop_sw_cpu.r iop_sw_mpu.r iop_sw_spu.r iop_version.r iop_crc_par.r iop_dmc_in.r iop_dmc_out.r iop_fifo_in_extra.r iop_fifo_in.r iop_fifo_out_extra.r iop_fifo_out.r iop_mc.r iop_mpu.r iop_scrc_in.r iop_scrc_out.r iop_spu.r iop_timer_grp.r iop_trigger_grp.r iop.r -outfile reg_map.h reg.rmap * Any changes here will be lost. * * -*- buffer-read-only: t -*- */ typedef enum { regi_ccd = 0xb0000000, regi_ccd_top = 0xb0000000, regi_ccd_dp = 0xb0000400, regi_ccd_stat = 0xb0000800, regi_ccd_tg = 0xb0001000, regi_cfg = 0xb0002000, regi_clkgen = 0xb0004000, regi_ddr2_ctrl = 0xb0006000, regi_dma0 = 0xb0008000, regi_dma1 = 0xb000a000, regi_dma11 = 0xb000c000, regi_dma2 = 0xb000e000, regi_dma3 = 0xb0010000, regi_dma4 = 0xb0012000, regi_dma5 = 0xb0014000, regi_dma6 = 0xb0016000, regi_dma7 = 0xb0018000, regi_dma9 = 0xb001a000, regi_eth = 0xb001c000, regi_gio = 0xb0020000, regi_h264 = 0xb0022000, regi_hist = 0xb0026000, regi_iop = 0xb0028000, regi_iop_version = 0xb0028000, regi_iop_fifo_in_extra = 0xb0028040, regi_iop_fifo_out_extra = 0xb0028080, regi_iop_trigger_grp0 = 0xb00280c0, regi_iop_trigger_grp1 = 0xb0028100, regi_iop_trigger_grp2 = 0xb0028140, regi_iop_trigger_grp3 = 0xb0028180, regi_iop_trigger_grp4 = 0xb00281c0, regi_iop_trigger_grp5 = 0xb0028200, regi_iop_trigger_grp6 = 0xb0028240, regi_iop_trigger_grp7 = 0xb0028280, regi_iop_crc_par = 0xb0028300, regi_iop_dmc_in = 0xb0028380, regi_iop_dmc_out = 0xb0028400, regi_iop_fifo_in = 0xb0028480, regi_iop_fifo_out = 0xb0028500, regi_iop_scrc_in = 0xb0028580, regi_iop_scrc_out = 0xb0028600, regi_iop_timer_grp0 = 0xb0028680, regi_iop_timer_grp1 = 0xb0028700, regi_iop_sap_in = 0xb0028800, regi_iop_sap_out = 0xb0028900, regi_iop_spu = 0xb0028a00, regi_iop_sw_cfg = 0xb0028b00, regi_iop_sw_cpu = 0xb0028c00, regi_iop_sw_mpu = 0xb0028d00, regi_iop_sw_spu = 0xb0028e00, regi_iop_mpu = 0xb0029000, regi_irq = 0xb002a000, regi_irq2 = 0xb006a000, regi_jpeg = 0xb002c000, regi_l2cache = 0xb0030000, regi_marb_bar = 0xb0032000, regi_marb_bar_bp0 = 0xb0032140, regi_marb_bar_bp1 = 0xb0032180, regi_marb_bar_bp2 = 0xb00321c0, regi_marb_bar_bp3 = 0xb0032200, regi_marb_foo = 0xb0034000, regi_marb_foo_bp0 = 0xb0034280, regi_marb_foo_bp1 = 0xb00342c0, regi_marb_foo_bp2 = 0xb0034300, regi_marb_foo_bp3 = 0xb0034340, regi_pinmux = 0xb0038000, regi_pio = 0xb0036000, regi_sclr = 0xb003a000, regi_sclr_fifo = 0xb003c000, regi_ser0 = 0xb003e000, regi_ser1 = 0xb0040000, regi_ser2 = 0xb0042000, regi_ser3 = 0xb0044000, regi_ser4 = 0xb0046000, regi_sser = 0xb0048000, regi_strcop = 0xb004a000, regi_strdma0 = 0xb004e000, regi_strdma1 = 0xb0050000, regi_strdma2 = 0xb0052000, regi_strdma3 = 0xb0054000, regi_strdma5 = 0xb0056000, regi_strmux = 0xb004c000, regi_timer0 = 0xb0058000, regi_timer1 = 0xb005a000, regi_timer2 = 0xb006e000, regi_trace = 0xb005c000, regi_vin = 0xb005e000, regi_vout = 0xb0060000 } reg_scope_instances; #endif /* __reg_map_h */
null
null
null
null
87,800
31,298
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
196,293
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* * SH RSPI driver * * Copyright (C) 2012, 2013 Renesas Solutions Corp. * Copyright (C) 2014 Glider bvba * * Based on spi-sh.c: * Copyright (C) 2011 Renesas Solutions Corp. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * 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/sched.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/clk.h> #include <linux/dmaengine.h> #include <linux/dma-mapping.h> #include <linux/of_device.h> #include <linux/pm_runtime.h> #include <linux/sh_dma.h> #include <linux/spi/spi.h> #include <linux/spi/rspi.h> #define RSPI_SPCR 0x00 /* Control Register */ #define RSPI_SSLP 0x01 /* Slave Select Polarity Register */ #define RSPI_SPPCR 0x02 /* Pin Control Register */ #define RSPI_SPSR 0x03 /* Status Register */ #define RSPI_SPDR 0x04 /* Data Register */ #define RSPI_SPSCR 0x08 /* Sequence Control Register */ #define RSPI_SPSSR 0x09 /* Sequence Status Register */ #define RSPI_SPBR 0x0a /* Bit Rate Register */ #define RSPI_SPDCR 0x0b /* Data Control Register */ #define RSPI_SPCKD 0x0c /* Clock Delay Register */ #define RSPI_SSLND 0x0d /* Slave Select Negation Delay Register */ #define RSPI_SPND 0x0e /* Next-Access Delay Register */ #define RSPI_SPCR2 0x0f /* Control Register 2 (SH only) */ #define RSPI_SPCMD0 0x10 /* Command Register 0 */ #define RSPI_SPCMD1 0x12 /* Command Register 1 */ #define RSPI_SPCMD2 0x14 /* Command Register 2 */ #define RSPI_SPCMD3 0x16 /* Command Register 3 */ #define RSPI_SPCMD4 0x18 /* Command Register 4 */ #define RSPI_SPCMD5 0x1a /* Command Register 5 */ #define RSPI_SPCMD6 0x1c /* Command Register 6 */ #define RSPI_SPCMD7 0x1e /* Command Register 7 */ #define RSPI_SPCMD(i) (RSPI_SPCMD0 + (i) * 2) #define RSPI_NUM_SPCMD 8 #define RSPI_RZ_NUM_SPCMD 4 #define QSPI_NUM_SPCMD 4 /* RSPI on RZ only */ #define RSPI_SPBFCR 0x20 /* Buffer Control Register */ #define RSPI_SPBFDR 0x22 /* Buffer Data Count Setting Register */ /* QSPI only */ #define QSPI_SPBFCR 0x18 /* Buffer Control Register */ #define QSPI_SPBDCR 0x1a /* Buffer Data Count Register */ #define QSPI_SPBMUL0 0x1c /* Transfer Data Length Multiplier Setting Register 0 */ #define QSPI_SPBMUL1 0x20 /* Transfer Data Length Multiplier Setting Register 1 */ #define QSPI_SPBMUL2 0x24 /* Transfer Data Length Multiplier Setting Register 2 */ #define QSPI_SPBMUL3 0x28 /* Transfer Data Length Multiplier Setting Register 3 */ #define QSPI_SPBMUL(i) (QSPI_SPBMUL0 + (i) * 4) /* SPCR - Control Register */ #define SPCR_SPRIE 0x80 /* Receive Interrupt Enable */ #define SPCR_SPE 0x40 /* Function Enable */ #define SPCR_SPTIE 0x20 /* Transmit Interrupt Enable */ #define SPCR_SPEIE 0x10 /* Error Interrupt Enable */ #define SPCR_MSTR 0x08 /* Master/Slave Mode Select */ #define SPCR_MODFEN 0x04 /* Mode Fault Error Detection Enable */ /* RSPI on SH only */ #define SPCR_TXMD 0x02 /* TX Only Mode (vs. Full Duplex) */ #define SPCR_SPMS 0x01 /* 3-wire Mode (vs. 4-wire) */ /* QSPI on R-Car Gen2 only */ #define SPCR_WSWAP 0x02 /* Word Swap of read-data for DMAC */ #define SPCR_BSWAP 0x01 /* Byte Swap of read-data for DMAC */ /* SSLP - Slave Select Polarity Register */ #define SSLP_SSL1P 0x02 /* SSL1 Signal Polarity Setting */ #define SSLP_SSL0P 0x01 /* SSL0 Signal Polarity Setting */ /* SPPCR - Pin Control Register */ #define SPPCR_MOIFE 0x20 /* MOSI Idle Value Fixing Enable */ #define SPPCR_MOIFV 0x10 /* MOSI Idle Fixed Value */ #define SPPCR_SPOM 0x04 #define SPPCR_SPLP2 0x02 /* Loopback Mode 2 (non-inverting) */ #define SPPCR_SPLP 0x01 /* Loopback Mode (inverting) */ #define SPPCR_IO3FV 0x04 /* Single-/Dual-SPI Mode IO3 Output Fixed Value */ #define SPPCR_IO2FV 0x04 /* Single-/Dual-SPI Mode IO2 Output Fixed Value */ /* SPSR - Status Register */ #define SPSR_SPRF 0x80 /* Receive Buffer Full Flag */ #define SPSR_TEND 0x40 /* Transmit End */ #define SPSR_SPTEF 0x20 /* Transmit Buffer Empty Flag */ #define SPSR_PERF 0x08 /* Parity Error Flag */ #define SPSR_MODF 0x04 /* Mode Fault Error Flag */ #define SPSR_IDLNF 0x02 /* RSPI Idle Flag */ #define SPSR_OVRF 0x01 /* Overrun Error Flag (RSPI only) */ /* SPSCR - Sequence Control Register */ #define SPSCR_SPSLN_MASK 0x07 /* Sequence Length Specification */ /* SPSSR - Sequence Status Register */ #define SPSSR_SPECM_MASK 0x70 /* Command Error Mask */ #define SPSSR_SPCP_MASK 0x07 /* Command Pointer Mask */ /* SPDCR - Data Control Register */ #define SPDCR_TXDMY 0x80 /* Dummy Data Transmission Enable */ #define SPDCR_SPLW1 0x40 /* Access Width Specification (RZ) */ #define SPDCR_SPLW0 0x20 /* Access Width Specification (RZ) */ #define SPDCR_SPLLWORD (SPDCR_SPLW1 | SPDCR_SPLW0) #define SPDCR_SPLWORD SPDCR_SPLW1 #define SPDCR_SPLBYTE SPDCR_SPLW0 #define SPDCR_SPLW 0x20 /* Access Width Specification (SH) */ #define SPDCR_SPRDTD 0x10 /* Receive Transmit Data Select (SH) */ #define SPDCR_SLSEL1 0x08 #define SPDCR_SLSEL0 0x04 #define SPDCR_SLSEL_MASK 0x0c /* SSL1 Output Select (SH) */ #define SPDCR_SPFC1 0x02 #define SPDCR_SPFC0 0x01 #define SPDCR_SPFC_MASK 0x03 /* Frame Count Setting (1-4) (SH) */ /* SPCKD - Clock Delay Register */ #define SPCKD_SCKDL_MASK 0x07 /* Clock Delay Setting (1-8) */ /* SSLND - Slave Select Negation Delay Register */ #define SSLND_SLNDL_MASK 0x07 /* SSL Negation Delay Setting (1-8) */ /* SPND - Next-Access Delay Register */ #define SPND_SPNDL_MASK 0x07 /* Next-Access Delay Setting (1-8) */ /* SPCR2 - Control Register 2 */ #define SPCR2_PTE 0x08 /* Parity Self-Test Enable */ #define SPCR2_SPIE 0x04 /* Idle Interrupt Enable */ #define SPCR2_SPOE 0x02 /* Odd Parity Enable (vs. Even) */ #define SPCR2_SPPE 0x01 /* Parity Enable */ /* SPCMDn - Command Registers */ #define SPCMD_SCKDEN 0x8000 /* Clock Delay Setting Enable */ #define SPCMD_SLNDEN 0x4000 /* SSL Negation Delay Setting Enable */ #define SPCMD_SPNDEN 0x2000 /* Next-Access Delay Enable */ #define SPCMD_LSBF 0x1000 /* LSB First */ #define SPCMD_SPB_MASK 0x0f00 /* Data Length Setting */ #define SPCMD_SPB_8_TO_16(bit) (((bit - 1) << 8) & SPCMD_SPB_MASK) #define SPCMD_SPB_8BIT 0x0000 /* QSPI only */ #define SPCMD_SPB_16BIT 0x0100 #define SPCMD_SPB_20BIT 0x0000 #define SPCMD_SPB_24BIT 0x0100 #define SPCMD_SPB_32BIT 0x0200 #define SPCMD_SSLKP 0x0080 /* SSL Signal Level Keeping */ #define SPCMD_SPIMOD_MASK 0x0060 /* SPI Operating Mode (QSPI only) */ #define SPCMD_SPIMOD1 0x0040 #define SPCMD_SPIMOD0 0x0020 #define SPCMD_SPIMOD_SINGLE 0 #define SPCMD_SPIMOD_DUAL SPCMD_SPIMOD0 #define SPCMD_SPIMOD_QUAD SPCMD_SPIMOD1 #define SPCMD_SPRW 0x0010 /* SPI Read/Write Access (Dual/Quad) */ #define SPCMD_SSLA_MASK 0x0030 /* SSL Assert Signal Setting (RSPI) */ #define SPCMD_BRDV_MASK 0x000c /* Bit Rate Division Setting */ #define SPCMD_CPOL 0x0002 /* Clock Polarity Setting */ #define SPCMD_CPHA 0x0001 /* Clock Phase Setting */ /* SPBFCR - Buffer Control Register */ #define SPBFCR_TXRST 0x80 /* Transmit Buffer Data Reset */ #define SPBFCR_RXRST 0x40 /* Receive Buffer Data Reset */ #define SPBFCR_TXTRG_MASK 0x30 /* Transmit Buffer Data Triggering Number */ #define SPBFCR_RXTRG_MASK 0x07 /* Receive Buffer Data Triggering Number */ /* QSPI on R-Car Gen2 */ #define SPBFCR_TXTRG_1B 0x00 /* 31 bytes (1 byte available) */ #define SPBFCR_TXTRG_32B 0x30 /* 0 byte (32 bytes available) */ #define SPBFCR_RXTRG_1B 0x00 /* 1 byte (31 bytes available) */ #define SPBFCR_RXTRG_32B 0x07 /* 32 bytes (0 byte available) */ #define QSPI_BUFFER_SIZE 32u struct rspi_data { void __iomem *addr; u32 max_speed_hz; struct spi_master *master; wait_queue_head_t wait; struct clk *clk; u16 spcmd; u8 spsr; u8 sppcr; int rx_irq, tx_irq; const struct spi_ops *ops; unsigned dma_callbacked:1; unsigned byte_access:1; }; static void rspi_write8(const struct rspi_data *rspi, u8 data, u16 offset) { iowrite8(data, rspi->addr + offset); } static void rspi_write16(const struct rspi_data *rspi, u16 data, u16 offset) { iowrite16(data, rspi->addr + offset); } static void rspi_write32(const struct rspi_data *rspi, u32 data, u16 offset) { iowrite32(data, rspi->addr + offset); } static u8 rspi_read8(const struct rspi_data *rspi, u16 offset) { return ioread8(rspi->addr + offset); } static u16 rspi_read16(const struct rspi_data *rspi, u16 offset) { return ioread16(rspi->addr + offset); } static void rspi_write_data(const struct rspi_data *rspi, u16 data) { if (rspi->byte_access) rspi_write8(rspi, data, RSPI_SPDR); else /* 16 bit */ rspi_write16(rspi, data, RSPI_SPDR); } static u16 rspi_read_data(const struct rspi_data *rspi) { if (rspi->byte_access) return rspi_read8(rspi, RSPI_SPDR); else /* 16 bit */ return rspi_read16(rspi, RSPI_SPDR); } /* optional functions */ struct spi_ops { int (*set_config_register)(struct rspi_data *rspi, int access_size); int (*transfer_one)(struct spi_master *master, struct spi_device *spi, struct spi_transfer *xfer); u16 mode_bits; u16 flags; u16 fifo_size; }; /* * functions for RSPI on legacy SH */ static int rspi_set_config_register(struct rspi_data *rspi, int access_size) { int spbr; /* Sets output mode, MOSI signal, and (optionally) loopback */ rspi_write8(rspi, rspi->sppcr, RSPI_SPPCR); /* Sets transfer bit rate */ spbr = DIV_ROUND_UP(clk_get_rate(rspi->clk), 2 * rspi->max_speed_hz) - 1; rspi_write8(rspi, clamp(spbr, 0, 255), RSPI_SPBR); /* Disable dummy transmission, set 16-bit word access, 1 frame */ rspi_write8(rspi, 0, RSPI_SPDCR); rspi->byte_access = 0; /* Sets RSPCK, SSL, next-access delay value */ rspi_write8(rspi, 0x00, RSPI_SPCKD); rspi_write8(rspi, 0x00, RSPI_SSLND); rspi_write8(rspi, 0x00, RSPI_SPND); /* Sets parity, interrupt mask */ rspi_write8(rspi, 0x00, RSPI_SPCR2); /* Sets SPCMD */ rspi->spcmd |= SPCMD_SPB_8_TO_16(access_size); rspi_write16(rspi, rspi->spcmd, RSPI_SPCMD0); /* Sets RSPI mode */ rspi_write8(rspi, SPCR_MSTR, RSPI_SPCR); return 0; } /* * functions for RSPI on RZ */ static int rspi_rz_set_config_register(struct rspi_data *rspi, int access_size) { int spbr; int div = 0; unsigned long clksrc; /* Sets output mode, MOSI signal, and (optionally) loopback */ rspi_write8(rspi, rspi->sppcr, RSPI_SPPCR); clksrc = clk_get_rate(rspi->clk); while (div < 3) { if (rspi->max_speed_hz >= clksrc/4) /* 4=(CLK/2)/2 */ break; div++; clksrc /= 2; } /* Sets transfer bit rate */ spbr = DIV_ROUND_UP(clksrc, 2 * rspi->max_speed_hz) - 1; rspi_write8(rspi, clamp(spbr, 0, 255), RSPI_SPBR); rspi->spcmd |= div << 2; /* Disable dummy transmission, set byte access */ rspi_write8(rspi, SPDCR_SPLBYTE, RSPI_SPDCR); rspi->byte_access = 1; /* Sets RSPCK, SSL, next-access delay value */ rspi_write8(rspi, 0x00, RSPI_SPCKD); rspi_write8(rspi, 0x00, RSPI_SSLND); rspi_write8(rspi, 0x00, RSPI_SPND); /* Sets SPCMD */ rspi->spcmd |= SPCMD_SPB_8_TO_16(access_size); rspi_write16(rspi, rspi->spcmd, RSPI_SPCMD0); /* Sets RSPI mode */ rspi_write8(rspi, SPCR_MSTR, RSPI_SPCR); return 0; } /* * functions for QSPI */ static int qspi_set_config_register(struct rspi_data *rspi, int access_size) { int spbr; /* Sets output mode, MOSI signal, and (optionally) loopback */ rspi_write8(rspi, rspi->sppcr, RSPI_SPPCR); /* Sets transfer bit rate */ spbr = DIV_ROUND_UP(clk_get_rate(rspi->clk), 2 * rspi->max_speed_hz); rspi_write8(rspi, clamp(spbr, 0, 255), RSPI_SPBR); /* Disable dummy transmission, set byte access */ rspi_write8(rspi, 0, RSPI_SPDCR); rspi->byte_access = 1; /* Sets RSPCK, SSL, next-access delay value */ rspi_write8(rspi, 0x00, RSPI_SPCKD); rspi_write8(rspi, 0x00, RSPI_SSLND); rspi_write8(rspi, 0x00, RSPI_SPND); /* Data Length Setting */ if (access_size == 8) rspi->spcmd |= SPCMD_SPB_8BIT; else if (access_size == 16) rspi->spcmd |= SPCMD_SPB_16BIT; else rspi->spcmd |= SPCMD_SPB_32BIT; rspi->spcmd |= SPCMD_SCKDEN | SPCMD_SLNDEN | SPCMD_SPNDEN; /* Resets transfer data length */ rspi_write32(rspi, 0, QSPI_SPBMUL0); /* Resets transmit and receive buffer */ rspi_write8(rspi, SPBFCR_TXRST | SPBFCR_RXRST, QSPI_SPBFCR); /* Sets buffer to allow normal operation */ rspi_write8(rspi, 0x00, QSPI_SPBFCR); /* Sets SPCMD */ rspi_write16(rspi, rspi->spcmd, RSPI_SPCMD0); /* Enables SPI function in master mode */ rspi_write8(rspi, SPCR_SPE | SPCR_MSTR, RSPI_SPCR); return 0; } static void qspi_update(const struct rspi_data *rspi, u8 mask, u8 val, u8 reg) { u8 data; data = rspi_read8(rspi, reg); data &= ~mask; data |= (val & mask); rspi_write8(rspi, data, reg); } static unsigned int qspi_set_send_trigger(struct rspi_data *rspi, unsigned int len) { unsigned int n; n = min(len, QSPI_BUFFER_SIZE); if (len >= QSPI_BUFFER_SIZE) { /* sets triggering number to 32 bytes */ qspi_update(rspi, SPBFCR_TXTRG_MASK, SPBFCR_TXTRG_32B, QSPI_SPBFCR); } else { /* sets triggering number to 1 byte */ qspi_update(rspi, SPBFCR_TXTRG_MASK, SPBFCR_TXTRG_1B, QSPI_SPBFCR); } return n; } static int qspi_set_receive_trigger(struct rspi_data *rspi, unsigned int len) { unsigned int n; n = min(len, QSPI_BUFFER_SIZE); if (len >= QSPI_BUFFER_SIZE) { /* sets triggering number to 32 bytes */ qspi_update(rspi, SPBFCR_RXTRG_MASK, SPBFCR_RXTRG_32B, QSPI_SPBFCR); } else { /* sets triggering number to 1 byte */ qspi_update(rspi, SPBFCR_RXTRG_MASK, SPBFCR_RXTRG_1B, QSPI_SPBFCR); } return n; } #define set_config_register(spi, n) spi->ops->set_config_register(spi, n) static void rspi_enable_irq(const struct rspi_data *rspi, u8 enable) { rspi_write8(rspi, rspi_read8(rspi, RSPI_SPCR) | enable, RSPI_SPCR); } static void rspi_disable_irq(const struct rspi_data *rspi, u8 disable) { rspi_write8(rspi, rspi_read8(rspi, RSPI_SPCR) & ~disable, RSPI_SPCR); } static int rspi_wait_for_interrupt(struct rspi_data *rspi, u8 wait_mask, u8 enable_bit) { int ret; rspi->spsr = rspi_read8(rspi, RSPI_SPSR); if (rspi->spsr & wait_mask) return 0; rspi_enable_irq(rspi, enable_bit); ret = wait_event_timeout(rspi->wait, rspi->spsr & wait_mask, HZ); if (ret == 0 && !(rspi->spsr & wait_mask)) return -ETIMEDOUT; return 0; } static inline int rspi_wait_for_tx_empty(struct rspi_data *rspi) { return rspi_wait_for_interrupt(rspi, SPSR_SPTEF, SPCR_SPTIE); } static inline int rspi_wait_for_rx_full(struct rspi_data *rspi) { return rspi_wait_for_interrupt(rspi, SPSR_SPRF, SPCR_SPRIE); } static int rspi_data_out(struct rspi_data *rspi, u8 data) { int error = rspi_wait_for_tx_empty(rspi); if (error < 0) { dev_err(&rspi->master->dev, "transmit timeout\n"); return error; } rspi_write_data(rspi, data); return 0; } static int rspi_data_in(struct rspi_data *rspi) { int error; u8 data; error = rspi_wait_for_rx_full(rspi); if (error < 0) { dev_err(&rspi->master->dev, "receive timeout\n"); return error; } data = rspi_read_data(rspi); return data; } static int rspi_pio_transfer(struct rspi_data *rspi, const u8 *tx, u8 *rx, unsigned int n) { while (n-- > 0) { if (tx) { int ret = rspi_data_out(rspi, *tx++); if (ret < 0) return ret; } if (rx) { int ret = rspi_data_in(rspi); if (ret < 0) return ret; *rx++ = ret; } } return 0; } static void rspi_dma_complete(void *arg) { struct rspi_data *rspi = arg; rspi->dma_callbacked = 1; wake_up_interruptible(&rspi->wait); } static int rspi_dma_transfer(struct rspi_data *rspi, struct sg_table *tx, struct sg_table *rx) { struct dma_async_tx_descriptor *desc_tx = NULL, *desc_rx = NULL; u8 irq_mask = 0; unsigned int other_irq = 0; dma_cookie_t cookie; int ret; /* First prepare and submit the DMA request(s), as this may fail */ if (rx) { desc_rx = dmaengine_prep_slave_sg(rspi->master->dma_rx, rx->sgl, rx->nents, DMA_FROM_DEVICE, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!desc_rx) { ret = -EAGAIN; goto no_dma_rx; } desc_rx->callback = rspi_dma_complete; desc_rx->callback_param = rspi; cookie = dmaengine_submit(desc_rx); if (dma_submit_error(cookie)) { ret = cookie; goto no_dma_rx; } irq_mask |= SPCR_SPRIE; } if (tx) { desc_tx = dmaengine_prep_slave_sg(rspi->master->dma_tx, tx->sgl, tx->nents, DMA_TO_DEVICE, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!desc_tx) { ret = -EAGAIN; goto no_dma_tx; } if (rx) { /* No callback */ desc_tx->callback = NULL; } else { desc_tx->callback = rspi_dma_complete; desc_tx->callback_param = rspi; } cookie = dmaengine_submit(desc_tx); if (dma_submit_error(cookie)) { ret = cookie; goto no_dma_tx; } irq_mask |= SPCR_SPTIE; } /* * DMAC needs SPxIE, but if SPxIE is set, the IRQ routine will be * called. So, this driver disables the IRQ while DMA transfer. */ if (tx) disable_irq(other_irq = rspi->tx_irq); if (rx && rspi->rx_irq != other_irq) disable_irq(rspi->rx_irq); rspi_enable_irq(rspi, irq_mask); rspi->dma_callbacked = 0; /* Now start DMA */ if (rx) dma_async_issue_pending(rspi->master->dma_rx); if (tx) dma_async_issue_pending(rspi->master->dma_tx); ret = wait_event_interruptible_timeout(rspi->wait, rspi->dma_callbacked, HZ); if (ret > 0 && rspi->dma_callbacked) ret = 0; else if (!ret) { dev_err(&rspi->master->dev, "DMA timeout\n"); ret = -ETIMEDOUT; if (tx) dmaengine_terminate_all(rspi->master->dma_tx); if (rx) dmaengine_terminate_all(rspi->master->dma_rx); } rspi_disable_irq(rspi, irq_mask); if (tx) enable_irq(rspi->tx_irq); if (rx && rspi->rx_irq != other_irq) enable_irq(rspi->rx_irq); return ret; no_dma_tx: if (rx) dmaengine_terminate_all(rspi->master->dma_rx); no_dma_rx: if (ret == -EAGAIN) { pr_warn_once("%s %s: DMA not available, falling back to PIO\n", dev_driver_string(&rspi->master->dev), dev_name(&rspi->master->dev)); } return ret; } static void rspi_receive_init(const struct rspi_data *rspi) { u8 spsr; spsr = rspi_read8(rspi, RSPI_SPSR); if (spsr & SPSR_SPRF) rspi_read_data(rspi); /* dummy read */ if (spsr & SPSR_OVRF) rspi_write8(rspi, rspi_read8(rspi, RSPI_SPSR) & ~SPSR_OVRF, RSPI_SPSR); } static void rspi_rz_receive_init(const struct rspi_data *rspi) { rspi_receive_init(rspi); rspi_write8(rspi, SPBFCR_TXRST | SPBFCR_RXRST, RSPI_SPBFCR); rspi_write8(rspi, 0, RSPI_SPBFCR); } static void qspi_receive_init(const struct rspi_data *rspi) { u8 spsr; spsr = rspi_read8(rspi, RSPI_SPSR); if (spsr & SPSR_SPRF) rspi_read_data(rspi); /* dummy read */ rspi_write8(rspi, SPBFCR_TXRST | SPBFCR_RXRST, QSPI_SPBFCR); rspi_write8(rspi, 0, QSPI_SPBFCR); } static bool __rspi_can_dma(const struct rspi_data *rspi, const struct spi_transfer *xfer) { return xfer->len > rspi->ops->fifo_size; } static bool rspi_can_dma(struct spi_master *master, struct spi_device *spi, struct spi_transfer *xfer) { struct rspi_data *rspi = spi_master_get_devdata(master); return __rspi_can_dma(rspi, xfer); } static int rspi_dma_check_then_transfer(struct rspi_data *rspi, struct spi_transfer *xfer) { if (!rspi->master->can_dma || !__rspi_can_dma(rspi, xfer)) return -EAGAIN; /* rx_buf can be NULL on RSPI on SH in TX-only Mode */ return rspi_dma_transfer(rspi, &xfer->tx_sg, xfer->rx_buf ? &xfer->rx_sg : NULL); } static int rspi_common_transfer(struct rspi_data *rspi, struct spi_transfer *xfer) { int ret; ret = rspi_dma_check_then_transfer(rspi, xfer); if (ret != -EAGAIN) return ret; ret = rspi_pio_transfer(rspi, xfer->tx_buf, xfer->rx_buf, xfer->len); if (ret < 0) return ret; /* Wait for the last transmission */ rspi_wait_for_tx_empty(rspi); return 0; } static int rspi_transfer_one(struct spi_master *master, struct spi_device *spi, struct spi_transfer *xfer) { struct rspi_data *rspi = spi_master_get_devdata(master); u8 spcr; spcr = rspi_read8(rspi, RSPI_SPCR); if (xfer->rx_buf) { rspi_receive_init(rspi); spcr &= ~SPCR_TXMD; } else { spcr |= SPCR_TXMD; } rspi_write8(rspi, spcr, RSPI_SPCR); return rspi_common_transfer(rspi, xfer); } static int rspi_rz_transfer_one(struct spi_master *master, struct spi_device *spi, struct spi_transfer *xfer) { struct rspi_data *rspi = spi_master_get_devdata(master); rspi_rz_receive_init(rspi); return rspi_common_transfer(rspi, xfer); } static int qspi_trigger_transfer_out_in(struct rspi_data *rspi, const u8 *tx, u8 *rx, unsigned int len) { unsigned int i, n; int ret; while (len > 0) { n = qspi_set_send_trigger(rspi, len); qspi_set_receive_trigger(rspi, len); if (n == QSPI_BUFFER_SIZE) { ret = rspi_wait_for_tx_empty(rspi); if (ret < 0) { dev_err(&rspi->master->dev, "transmit timeout\n"); return ret; } for (i = 0; i < n; i++) rspi_write_data(rspi, *tx++); ret = rspi_wait_for_rx_full(rspi); if (ret < 0) { dev_err(&rspi->master->dev, "receive timeout\n"); return ret; } for (i = 0; i < n; i++) *rx++ = rspi_read_data(rspi); } else { ret = rspi_pio_transfer(rspi, tx, rx, n); if (ret < 0) return ret; } len -= n; } return 0; } static int qspi_transfer_out_in(struct rspi_data *rspi, struct spi_transfer *xfer) { int ret; qspi_receive_init(rspi); ret = rspi_dma_check_then_transfer(rspi, xfer); if (ret != -EAGAIN) return ret; return qspi_trigger_transfer_out_in(rspi, xfer->tx_buf, xfer->rx_buf, xfer->len); } static int qspi_transfer_out(struct rspi_data *rspi, struct spi_transfer *xfer) { const u8 *tx = xfer->tx_buf; unsigned int n = xfer->len; unsigned int i, len; int ret; if (rspi->master->can_dma && __rspi_can_dma(rspi, xfer)) { ret = rspi_dma_transfer(rspi, &xfer->tx_sg, NULL); if (ret != -EAGAIN) return ret; } while (n > 0) { len = qspi_set_send_trigger(rspi, n); if (len == QSPI_BUFFER_SIZE) { ret = rspi_wait_for_tx_empty(rspi); if (ret < 0) { dev_err(&rspi->master->dev, "transmit timeout\n"); return ret; } for (i = 0; i < len; i++) rspi_write_data(rspi, *tx++); } else { ret = rspi_pio_transfer(rspi, tx, NULL, len); if (ret < 0) return ret; } n -= len; } /* Wait for the last transmission */ rspi_wait_for_tx_empty(rspi); return 0; } static int qspi_transfer_in(struct rspi_data *rspi, struct spi_transfer *xfer) { u8 *rx = xfer->rx_buf; unsigned int n = xfer->len; unsigned int i, len; int ret; if (rspi->master->can_dma && __rspi_can_dma(rspi, xfer)) { int ret = rspi_dma_transfer(rspi, NULL, &xfer->rx_sg); if (ret != -EAGAIN) return ret; } while (n > 0) { len = qspi_set_receive_trigger(rspi, n); if (len == QSPI_BUFFER_SIZE) { ret = rspi_wait_for_rx_full(rspi); if (ret < 0) { dev_err(&rspi->master->dev, "receive timeout\n"); return ret; } for (i = 0; i < len; i++) *rx++ = rspi_read_data(rspi); } else { ret = rspi_pio_transfer(rspi, NULL, rx, len); if (ret < 0) return ret; } n -= len; } return 0; } static int qspi_transfer_one(struct spi_master *master, struct spi_device *spi, struct spi_transfer *xfer) { struct rspi_data *rspi = spi_master_get_devdata(master); if (spi->mode & SPI_LOOP) { return qspi_transfer_out_in(rspi, xfer); } else if (xfer->tx_nbits > SPI_NBITS_SINGLE) { /* Quad or Dual SPI Write */ return qspi_transfer_out(rspi, xfer); } else if (xfer->rx_nbits > SPI_NBITS_SINGLE) { /* Quad or Dual SPI Read */ return qspi_transfer_in(rspi, xfer); } else { /* Single SPI Transfer */ return qspi_transfer_out_in(rspi, xfer); } } static int rspi_setup(struct spi_device *spi) { struct rspi_data *rspi = spi_master_get_devdata(spi->master); rspi->max_speed_hz = spi->max_speed_hz; rspi->spcmd = SPCMD_SSLKP; if (spi->mode & SPI_CPOL) rspi->spcmd |= SPCMD_CPOL; if (spi->mode & SPI_CPHA) rspi->spcmd |= SPCMD_CPHA; /* CMOS output mode and MOSI signal from previous transfer */ rspi->sppcr = 0; if (spi->mode & SPI_LOOP) rspi->sppcr |= SPPCR_SPLP; set_config_register(rspi, 8); return 0; } static u16 qspi_transfer_mode(const struct spi_transfer *xfer) { if (xfer->tx_buf) switch (xfer->tx_nbits) { case SPI_NBITS_QUAD: return SPCMD_SPIMOD_QUAD; case SPI_NBITS_DUAL: return SPCMD_SPIMOD_DUAL; default: return 0; } if (xfer->rx_buf) switch (xfer->rx_nbits) { case SPI_NBITS_QUAD: return SPCMD_SPIMOD_QUAD | SPCMD_SPRW; case SPI_NBITS_DUAL: return SPCMD_SPIMOD_DUAL | SPCMD_SPRW; default: return 0; } return 0; } static int qspi_setup_sequencer(struct rspi_data *rspi, const struct spi_message *msg) { const struct spi_transfer *xfer; unsigned int i = 0, len = 0; u16 current_mode = 0xffff, mode; list_for_each_entry(xfer, &msg->transfers, transfer_list) { mode = qspi_transfer_mode(xfer); if (mode == current_mode) { len += xfer->len; continue; } /* Transfer mode change */ if (i) { /* Set transfer data length of previous transfer */ rspi_write32(rspi, len, QSPI_SPBMUL(i - 1)); } if (i >= QSPI_NUM_SPCMD) { dev_err(&msg->spi->dev, "Too many different transfer modes"); return -EINVAL; } /* Program transfer mode for this transfer */ rspi_write16(rspi, rspi->spcmd | mode, RSPI_SPCMD(i)); current_mode = mode; len = xfer->len; i++; } if (i) { /* Set final transfer data length and sequence length */ rspi_write32(rspi, len, QSPI_SPBMUL(i - 1)); rspi_write8(rspi, i - 1, RSPI_SPSCR); } return 0; } static int rspi_prepare_message(struct spi_master *master, struct spi_message *msg) { struct rspi_data *rspi = spi_master_get_devdata(master); int ret; if (msg->spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)) { /* Setup sequencer for messages with multiple transfer modes */ ret = qspi_setup_sequencer(rspi, msg); if (ret < 0) return ret; } /* Enable SPI function in master mode */ rspi_write8(rspi, rspi_read8(rspi, RSPI_SPCR) | SPCR_SPE, RSPI_SPCR); return 0; } static int rspi_unprepare_message(struct spi_master *master, struct spi_message *msg) { struct rspi_data *rspi = spi_master_get_devdata(master); /* Disable SPI function */ rspi_write8(rspi, rspi_read8(rspi, RSPI_SPCR) & ~SPCR_SPE, RSPI_SPCR); /* Reset sequencer for Single SPI Transfers */ rspi_write16(rspi, rspi->spcmd, RSPI_SPCMD0); rspi_write8(rspi, 0, RSPI_SPSCR); return 0; } static irqreturn_t rspi_irq_mux(int irq, void *_sr) { struct rspi_data *rspi = _sr; u8 spsr; irqreturn_t ret = IRQ_NONE; u8 disable_irq = 0; rspi->spsr = spsr = rspi_read8(rspi, RSPI_SPSR); if (spsr & SPSR_SPRF) disable_irq |= SPCR_SPRIE; if (spsr & SPSR_SPTEF) disable_irq |= SPCR_SPTIE; if (disable_irq) { ret = IRQ_HANDLED; rspi_disable_irq(rspi, disable_irq); wake_up(&rspi->wait); } return ret; } static irqreturn_t rspi_irq_rx(int irq, void *_sr) { struct rspi_data *rspi = _sr; u8 spsr; rspi->spsr = spsr = rspi_read8(rspi, RSPI_SPSR); if (spsr & SPSR_SPRF) { rspi_disable_irq(rspi, SPCR_SPRIE); wake_up(&rspi->wait); return IRQ_HANDLED; } return 0; } static irqreturn_t rspi_irq_tx(int irq, void *_sr) { struct rspi_data *rspi = _sr; u8 spsr; rspi->spsr = spsr = rspi_read8(rspi, RSPI_SPSR); if (spsr & SPSR_SPTEF) { rspi_disable_irq(rspi, SPCR_SPTIE); wake_up(&rspi->wait); return IRQ_HANDLED; } return 0; } static struct dma_chan *rspi_request_dma_chan(struct device *dev, enum dma_transfer_direction dir, unsigned int id, dma_addr_t port_addr) { dma_cap_mask_t mask; struct dma_chan *chan; struct dma_slave_config cfg; int ret; dma_cap_zero(mask); dma_cap_set(DMA_SLAVE, mask); chan = dma_request_slave_channel_compat(mask, shdma_chan_filter, (void *)(unsigned long)id, dev, dir == DMA_MEM_TO_DEV ? "tx" : "rx"); if (!chan) { dev_warn(dev, "dma_request_slave_channel_compat failed\n"); return NULL; } memset(&cfg, 0, sizeof(cfg)); cfg.direction = dir; if (dir == DMA_MEM_TO_DEV) { cfg.dst_addr = port_addr; cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE; } else { cfg.src_addr = port_addr; cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE; } ret = dmaengine_slave_config(chan, &cfg); if (ret) { dev_warn(dev, "dmaengine_slave_config failed %d\n", ret); dma_release_channel(chan); return NULL; } return chan; } static int rspi_request_dma(struct device *dev, struct spi_master *master, const struct resource *res) { const struct rspi_plat_data *rspi_pd = dev_get_platdata(dev); unsigned int dma_tx_id, dma_rx_id; if (dev->of_node) { /* In the OF case we will get the slave IDs from the DT */ dma_tx_id = 0; dma_rx_id = 0; } else if (rspi_pd && rspi_pd->dma_tx_id && rspi_pd->dma_rx_id) { dma_tx_id = rspi_pd->dma_tx_id; dma_rx_id = rspi_pd->dma_rx_id; } else { /* The driver assumes no error. */ return 0; } master->dma_tx = rspi_request_dma_chan(dev, DMA_MEM_TO_DEV, dma_tx_id, res->start + RSPI_SPDR); if (!master->dma_tx) return -ENODEV; master->dma_rx = rspi_request_dma_chan(dev, DMA_DEV_TO_MEM, dma_rx_id, res->start + RSPI_SPDR); if (!master->dma_rx) { dma_release_channel(master->dma_tx); master->dma_tx = NULL; return -ENODEV; } master->can_dma = rspi_can_dma; dev_info(dev, "DMA available"); return 0; } static void rspi_release_dma(struct spi_master *master) { if (master->dma_tx) dma_release_channel(master->dma_tx); if (master->dma_rx) dma_release_channel(master->dma_rx); } static int rspi_remove(struct platform_device *pdev) { struct rspi_data *rspi = platform_get_drvdata(pdev); rspi_release_dma(rspi->master); pm_runtime_disable(&pdev->dev); return 0; } static const struct spi_ops rspi_ops = { .set_config_register = rspi_set_config_register, .transfer_one = rspi_transfer_one, .mode_bits = SPI_CPHA | SPI_CPOL | SPI_LOOP, .flags = SPI_MASTER_MUST_TX, .fifo_size = 8, }; static const struct spi_ops rspi_rz_ops = { .set_config_register = rspi_rz_set_config_register, .transfer_one = rspi_rz_transfer_one, .mode_bits = SPI_CPHA | SPI_CPOL | SPI_LOOP, .flags = SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX, .fifo_size = 8, /* 8 for TX, 32 for RX */ }; static const struct spi_ops qspi_ops = { .set_config_register = qspi_set_config_register, .transfer_one = qspi_transfer_one, .mode_bits = SPI_CPHA | SPI_CPOL | SPI_LOOP | SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD, .flags = SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX, .fifo_size = 32, }; #ifdef CONFIG_OF static const struct of_device_id rspi_of_match[] = { /* RSPI on legacy SH */ { .compatible = "renesas,rspi", .data = &rspi_ops }, /* RSPI on RZ/A1H */ { .compatible = "renesas,rspi-rz", .data = &rspi_rz_ops }, /* QSPI on R-Car Gen2 */ { .compatible = "renesas,qspi", .data = &qspi_ops }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, rspi_of_match); static int rspi_parse_dt(struct device *dev, struct spi_master *master) { u32 num_cs; int error; /* Parse DT properties */ error = of_property_read_u32(dev->of_node, "num-cs", &num_cs); if (error) { dev_err(dev, "of_property_read_u32 num-cs failed %d\n", error); return error; } master->num_chipselect = num_cs; return 0; } #else #define rspi_of_match NULL static inline int rspi_parse_dt(struct device *dev, struct spi_master *master) { return -EINVAL; } #endif /* CONFIG_OF */ static int rspi_request_irq(struct device *dev, unsigned int irq, irq_handler_t handler, const char *suffix, void *dev_id) { const char *name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s", dev_name(dev), suffix); if (!name) return -ENOMEM; return devm_request_irq(dev, irq, handler, 0, name, dev_id); } static int rspi_probe(struct platform_device *pdev) { struct resource *res; struct spi_master *master; struct rspi_data *rspi; int ret; const struct of_device_id *of_id; const struct rspi_plat_data *rspi_pd; const struct spi_ops *ops; master = spi_alloc_master(&pdev->dev, sizeof(struct rspi_data)); if (master == NULL) return -ENOMEM; of_id = of_match_device(rspi_of_match, &pdev->dev); if (of_id) { ops = of_id->data; ret = rspi_parse_dt(&pdev->dev, master); if (ret) goto error1; } else { ops = (struct spi_ops *)pdev->id_entry->driver_data; rspi_pd = dev_get_platdata(&pdev->dev); if (rspi_pd && rspi_pd->num_chipselect) master->num_chipselect = rspi_pd->num_chipselect; else master->num_chipselect = 2; /* default */ } /* ops parameter check */ if (!ops->set_config_register) { dev_err(&pdev->dev, "there is no set_config_register\n"); ret = -ENODEV; goto error1; } rspi = spi_master_get_devdata(master); platform_set_drvdata(pdev, rspi); rspi->ops = ops; rspi->master = master; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); rspi->addr = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(rspi->addr)) { ret = PTR_ERR(rspi->addr); goto error1; } rspi->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(rspi->clk)) { dev_err(&pdev->dev, "cannot get clock\n"); ret = PTR_ERR(rspi->clk); goto error1; } pm_runtime_enable(&pdev->dev); init_waitqueue_head(&rspi->wait); master->bus_num = pdev->id; master->setup = rspi_setup; master->auto_runtime_pm = true; master->transfer_one = ops->transfer_one; master->prepare_message = rspi_prepare_message; master->unprepare_message = rspi_unprepare_message; master->mode_bits = ops->mode_bits; master->flags = ops->flags; master->dev.of_node = pdev->dev.of_node; ret = platform_get_irq_byname(pdev, "rx"); if (ret < 0) { ret = platform_get_irq_byname(pdev, "mux"); if (ret < 0) ret = platform_get_irq(pdev, 0); if (ret >= 0) rspi->rx_irq = rspi->tx_irq = ret; } else { rspi->rx_irq = ret; ret = platform_get_irq_byname(pdev, "tx"); if (ret >= 0) rspi->tx_irq = ret; } if (ret < 0) { dev_err(&pdev->dev, "platform_get_irq error\n"); goto error2; } if (rspi->rx_irq == rspi->tx_irq) { /* Single multiplexed interrupt */ ret = rspi_request_irq(&pdev->dev, rspi->rx_irq, rspi_irq_mux, "mux", rspi); } else { /* Multi-interrupt mode, only SPRI and SPTI are used */ ret = rspi_request_irq(&pdev->dev, rspi->rx_irq, rspi_irq_rx, "rx", rspi); if (!ret) ret = rspi_request_irq(&pdev->dev, rspi->tx_irq, rspi_irq_tx, "tx", rspi); } if (ret < 0) { dev_err(&pdev->dev, "request_irq error\n"); goto error2; } ret = rspi_request_dma(&pdev->dev, master, res); if (ret < 0) dev_warn(&pdev->dev, "DMA not available, using PIO\n"); ret = devm_spi_register_master(&pdev->dev, master); if (ret < 0) { dev_err(&pdev->dev, "spi_register_master error.\n"); goto error3; } dev_info(&pdev->dev, "probed\n"); return 0; error3: rspi_release_dma(master); error2: pm_runtime_disable(&pdev->dev); error1: spi_master_put(master); return ret; } static const struct platform_device_id spi_driver_ids[] = { { "rspi", (kernel_ulong_t)&rspi_ops }, { "rspi-rz", (kernel_ulong_t)&rspi_rz_ops }, { "qspi", (kernel_ulong_t)&qspi_ops }, {}, }; MODULE_DEVICE_TABLE(platform, spi_driver_ids); static struct platform_driver rspi_driver = { .probe = rspi_probe, .remove = rspi_remove, .id_table = spi_driver_ids, .driver = { .name = "renesas_spi", .of_match_table = of_match_ptr(rspi_of_match), }, }; module_platform_driver(rspi_driver); MODULE_DESCRIPTION("Renesas RSPI bus driver"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Yoshihiro Shimoda"); MODULE_ALIAS("platform:rspi");
null
null
null
null
104,640
29,182
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
29,182
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 "third_party/libaddressinput/src/cpp/src/util/json.h" #include <map> #include <memory> #include "base/json/json_reader.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/values.h" namespace i18n { namespace addressinput { namespace { // Returns |json| parsed into a JSON dictionary. Sets |parser_error| to true if // parsing failed. ::std::unique_ptr<const base::DictionaryValue> Parse(const std::string& json, bool* parser_error) { DCHECK(parser_error); ::std::unique_ptr<const base::DictionaryValue> result; // |json| is converted to a |c_str()| here because rapidjson and other parts // of the standalone library use char* rather than std::string. ::std::unique_ptr<const base::Value> parsed( base::JSONReader::Read(json.c_str())); *parser_error = !parsed || !parsed->is_dict(); if (*parser_error) result.reset(new base::DictionaryValue); else result.reset(static_cast<const base::DictionaryValue*>(parsed.release())); return result; } } // namespace // Implementation of JSON parser for libaddressinput using JSON parser in // Chrome. class Json::JsonImpl { public: explicit JsonImpl(const std::string& json) : owned_(Parse(json, &parser_error_)), dict_(*owned_) {} ~JsonImpl() {} bool parser_error() const { return parser_error_; } const std::vector<const Json*>& GetSubDictionaries() { if (sub_dicts_.empty()) { for (base::DictionaryValue::Iterator it(dict_); !it.IsAtEnd(); it.Advance()) { if (it.value().is_dict()) { const base::DictionaryValue* sub_dict = NULL; it.value().GetAsDictionary(&sub_dict); owned_sub_dicts_.push_back( base::WrapUnique(new Json(new JsonImpl(*sub_dict)))); sub_dicts_.push_back(owned_sub_dicts_.back().get()); } } } return sub_dicts_; } bool GetStringValueForKey(const std::string& key, std::string* value) const { return dict_.GetStringWithoutPathExpansion(key, value); } private: explicit JsonImpl(const base::DictionaryValue& dict) : parser_error_(false), dict_(dict) {} const ::std::unique_ptr<const base::DictionaryValue> owned_; bool parser_error_; const base::DictionaryValue& dict_; std::vector<const Json*> sub_dicts_; std::vector<std::unique_ptr<Json>> owned_sub_dicts_; DISALLOW_COPY_AND_ASSIGN(JsonImpl); }; Json::Json() {} Json::~Json() {} bool Json::ParseObject(const std::string& json) { DCHECK(!impl_); impl_.reset(new JsonImpl(json)); if (impl_->parser_error()) impl_.reset(); return !!impl_; } const std::vector<const Json*>& Json::GetSubDictionaries() const { return impl_->GetSubDictionaries(); } bool Json::GetStringValueForKey(const std::string& key, std::string* value) const { return impl_->GetStringValueForKey(key, value); } Json::Json(JsonImpl* impl) : impl_(impl) {} } // namespace addressinput } // namespace i18n
null
null
null
null
26,045
28,240
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
28,240
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. // This file declares the ByteSink and ByteSource abstract interfaces. These // interfaces represent objects that consume (ByteSink) or produce (ByteSource) // a sequence of bytes. Using these abstract interfaces in your APIs can help // make your code work with a variety of input and output types. // // This file also declares the following commonly used implementations of these // interfaces. // // ByteSink: // UncheckedArrayByteSink Writes to an array, without bounds checking // CheckedArrayByteSink Writes to an array, with bounds checking // GrowingArrayByteSink Allocates and writes to a growable buffer // StringByteSink Writes to an STL string // NullByteSink Consumes a never-ending stream of bytes // // ByteSource: // ArrayByteSource Reads from an array or string/StringPiece // LimitedByteSource Limits the number of bytes read from an #ifndef GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_ #define GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_ #include <stddef.h> #include <string> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/stringpiece.h> class CordByteSink; class MemBlock; namespace google { namespace protobuf { namespace strings { // An abstract interface for an object that consumes a sequence of bytes. This // interface offers a way to append data as well as a Flush() function. // // Example: // // string my_data; // ... // ByteSink* sink = ... // sink->Append(my_data.data(), my_data.size()); // sink->Flush(); // class LIBPROTOBUF_EXPORT ByteSink { public: ByteSink() {} virtual ~ByteSink() {} // Appends the "n" bytes starting at "bytes". virtual void Append(const char* bytes, size_t n) = 0; // Flushes internal buffers. The default implemenation does nothing. ByteSink // subclasses may use internal buffers that require calling Flush() at the end // of the stream. virtual void Flush(); private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSink); }; // An abstract interface for an object that produces a fixed-size sequence of // bytes. // // Example: // // ByteSource* source = ... // while (source->Available() > 0) { // StringPiece data = source->Peek(); // ... do something with "data" ... // source->Skip(data.length()); // } // class LIBPROTOBUF_EXPORT ByteSource { public: ByteSource() {} virtual ~ByteSource() {} // Returns the number of bytes left to read from the source. Available() // should decrease by N each time Skip(N) is called. Available() may not // increase. Available() returning 0 indicates that the ByteSource is // exhausted. // // Note: Size() may have been a more appropriate name as it's more // indicative of the fixed-size nature of a ByteSource. virtual size_t Available() const = 0; // Returns a StringPiece of the next contiguous region of the source. Does not // reposition the source. The returned region is empty iff Available() == 0. // // The returned region is valid until the next call to Skip() or until this // object is destroyed, whichever occurs first. // // The length of the returned StringPiece will be <= Available(). virtual StringPiece Peek() = 0; // Skips the next n bytes. Invalidates any StringPiece returned by a previous // call to Peek(). // // REQUIRES: Available() >= n virtual void Skip(size_t n) = 0; // Writes the next n bytes in this ByteSource to the given ByteSink, and // advances this ByteSource past the copied bytes. The default implementation // of this method just copies the bytes normally, but subclasses might // override CopyTo to optimize certain cases. // // REQUIRES: Available() >= n virtual void CopyTo(ByteSink* sink, size_t n); private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ByteSource); }; // // Some commonly used implementations of ByteSink // // Implementation of ByteSink that writes to an unsized byte array. No // bounds-checking is performed--it is the caller's responsibility to ensure // that the destination array is large enough. // // Example: // // char buf[10]; // UncheckedArrayByteSink sink(buf); // sink.Append("hi", 2); // OK // sink.Append(data, 100); // WOOPS! Overflows buf[10]. // class LIBPROTOBUF_EXPORT UncheckedArrayByteSink : public ByteSink { public: explicit UncheckedArrayByteSink(char* dest) : dest_(dest) {} virtual void Append(const char* data, size_t n); // Returns the current output pointer so that a caller can see how many bytes // were produced. // // Note: this method is not part of the ByteSink interface. char* CurrentDestination() const { return dest_; } private: char* dest_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(UncheckedArrayByteSink); }; // Implementation of ByteSink that writes to a sized byte array. This sink will // not write more than "capacity" bytes to outbuf. Once "capacity" bytes are // appended, subsequent bytes will be ignored and Overflowed() will return true. // Overflowed() does not cause a runtime error (i.e., it does not CHECK fail). // // Example: // // char buf[10]; // CheckedArrayByteSink sink(buf, 10); // sink.Append("hi", 2); // OK // sink.Append(data, 100); // Will only write 8 more bytes // class LIBPROTOBUF_EXPORT CheckedArrayByteSink : public ByteSink { public: CheckedArrayByteSink(char* outbuf, size_t capacity); virtual void Append(const char* bytes, size_t n); // Returns the number of bytes actually written to the sink. size_t NumberOfBytesWritten() const { return size_; } // Returns true if any bytes were discarded, i.e., if there was an // attempt to write more than 'capacity' bytes. bool Overflowed() const { return overflowed_; } private: char* outbuf_; const size_t capacity_; size_t size_; bool overflowed_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CheckedArrayByteSink); }; // Implementation of ByteSink that allocates an internal buffer (a char array) // and expands it as needed to accommodate appended data (similar to a string), // and allows the caller to take ownership of the internal buffer via the // GetBuffer() method. The buffer returned from GetBuffer() must be deleted by // the caller with delete[]. GetBuffer() also sets the internal buffer to be // empty, and subsequent appends to the sink will create a new buffer. The // destructor will free the internal buffer if GetBuffer() was not called. // // Example: // // GrowingArrayByteSink sink(10); // sink.Append("hi", 2); // sink.Append(data, n); // const char* buf = sink.GetBuffer(); // Ownership transferred // delete[] buf; // class LIBPROTOBUF_EXPORT GrowingArrayByteSink : public strings::ByteSink { public: explicit GrowingArrayByteSink(size_t estimated_size); virtual ~GrowingArrayByteSink(); virtual void Append(const char* bytes, size_t n); // Returns the allocated buffer, and sets nbytes to its size. The caller takes // ownership of the buffer and must delete it with delete[]. char* GetBuffer(size_t* nbytes); private: void Expand(size_t amount); void ShrinkToFit(); size_t capacity_; char* buf_; size_t size_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GrowingArrayByteSink); }; // Implementation of ByteSink that appends to the given string. // Existing contents of "dest" are not modified; new data is appended. // // Example: // // string dest = "Hello "; // StringByteSink sink(&dest); // sink.Append("World", 5); // assert(dest == "Hello World"); // class LIBPROTOBUF_EXPORT StringByteSink : public ByteSink { public: explicit StringByteSink(string* dest) : dest_(dest) {} virtual void Append(const char* data, size_t n); private: string* dest_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringByteSink); }; // Implementation of ByteSink that discards all data. // // Example: // // NullByteSink sink; // sink.Append(data, data.size()); // All data ignored. // class LIBPROTOBUF_EXPORT NullByteSink : public ByteSink { public: NullByteSink() {} virtual void Append(const char *data, size_t n) {} private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(NullByteSink); }; // // Some commonly used implementations of ByteSource // // Implementation of ByteSource that reads from a StringPiece. // // Example: // // string data = "Hello"; // ArrayByteSource source(data); // assert(source.Available() == 5); // assert(source.Peek() == "Hello"); // class LIBPROTOBUF_EXPORT ArrayByteSource : public ByteSource { public: explicit ArrayByteSource(StringPiece s) : input_(s) {} virtual size_t Available() const; virtual StringPiece Peek(); virtual void Skip(size_t n); private: StringPiece input_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayByteSource); }; // Implementation of ByteSource that wraps another ByteSource, limiting the // number of bytes returned. // // The caller maintains ownership of the underlying source, and may not use the // underlying source while using the LimitByteSource object. The underlying // source's pointer is advanced by n bytes every time this LimitByteSource // object is advanced by n. // // Example: // // string data = "Hello World"; // ArrayByteSource abs(data); // assert(abs.Available() == data.size()); // // LimitByteSource limit(abs, 5); // assert(limit.Available() == 5); // assert(limit.Peek() == "Hello"); // class LIBPROTOBUF_EXPORT LimitByteSource : public ByteSource { public: // Returns at most "limit" bytes from "source". LimitByteSource(ByteSource* source, size_t limit); virtual size_t Available() const; virtual StringPiece Peek(); virtual void Skip(size_t n); // We override CopyTo so that we can forward to the underlying source, in // case it has an efficient implementation of CopyTo. virtual void CopyTo(ByteSink* sink, size_t n); private: ByteSource* source_; size_t limit_; }; } // namespace strings } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_STUBS_BYTESTREAM_H_
null
null
null
null
25,103
68,373
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
68,373
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 REMOTING_HOST_HOST_WINDOW_H_ #define REMOTING_HOST_HOST_WINDOW_H_ #include <memory> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" namespace remoting { class ClientSessionControl; class HostWindow { public: virtual ~HostWindow(); // Creates a platform-specific instance of the continue window. static std::unique_ptr<HostWindow> CreateContinueWindow(); // Creates a platform-specific instance of the disconnect window. static std::unique_ptr<HostWindow> CreateDisconnectWindow(); // Starts the UI state machine. |client_session_control| will be used to // notify the caller about the local user's actions. virtual void Start( const base::WeakPtr<ClientSessionControl>& client_session_control) = 0; protected: // Let |HostWindowProxy| to call DetachFromSequence() when passing an instance // of |HostWindow| to a different sequence. friend class HostWindowProxy; HostWindow() {} SEQUENCE_CHECKER(sequence_checker_); private: DISALLOW_COPY_AND_ASSIGN(HostWindow); }; } // namespace remoting #endif // REMOTING_HOST_HOST_WINDOW_H_
null
null
null
null
65,236
2,583
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
265,151
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
#include "qemu/osdep.h" #include "qemu-common.h" #include "sysemu/arch_init.h" #include "qapi/qmp/qerror.h" CpuModelCompareInfo *arch_query_cpu_model_comparison(CpuModelInfo *modela, CpuModelInfo *modelb, Error **errp) { error_setg(errp, QERR_UNSUPPORTED); return NULL; }
null
null
null
null
123,275
38,989
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
38,989
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2008, 2009, 2010, 2011 Apple Inc. All Rights Reserved. * Copyright 2010, The Android Open Source Project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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_MODULES_GEOLOCATION_GEOLOCATION_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_GEOLOCATION_GEOLOCATION_H_ #include "services/device/public/mojom/geolocation.mojom-blink.h" #include "third_party/blink/public/platform/modules/geolocation/geolocation_service.mojom-blink.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_position_callback.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_position_error_callback.h" #include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h" #include "third_party/blink/renderer/core/page/page_visibility_observer.h" #include "third_party/blink/renderer/modules/geolocation/geo_notifier.h" #include "third_party/blink/renderer/modules/geolocation/geolocation_watchers.h" #include "third_party/blink/renderer/modules/geolocation/geoposition.h" #include "third_party/blink/renderer/modules/geolocation/position_error.h" #include "third_party/blink/renderer/modules/geolocation/position_options.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/timer.h" namespace blink { class Document; class LocalFrame; class ExecutionContext; class MODULES_EXPORT Geolocation final : public ScriptWrappable, public ActiveScriptWrappable<Geolocation>, public ContextLifecycleObserver, public PageVisibilityObserver { DEFINE_WRAPPERTYPEINFO(); USING_GARBAGE_COLLECTED_MIXIN(Geolocation); public: static Geolocation* Create(ExecutionContext*); ~Geolocation(); void Trace(blink::Visitor*) override; void TraceWrappers(const ScriptWrappableVisitor*) const override; // Inherited from ContextLifecycleObserver and PageVisibilityObserver. void ContextDestroyed(ExecutionContext*) override; Document* GetDocument() const; LocalFrame* GetFrame() const; // Creates a oneshot and attempts to obtain a position that meets the // constraints of the options. void getCurrentPosition(V8PositionCallback*, V8PositionErrorCallback* = nullptr, const PositionOptions& = PositionOptions()); // Creates a watcher that will be notified whenever a new position is // available that meets the constraints of the options. int watchPosition(V8PositionCallback*, V8PositionErrorCallback* = nullptr, const PositionOptions& = PositionOptions()); // Removes all references to the watcher, it will not be updated again. void clearWatch(int watch_id); // Notifies this that a new position is available. Must never be called // before permission is granted by the user. void PositionChanged(); // Discards the notifier because a fatal error occurred for it. void FatalErrorOccurred(GeoNotifier*); // Adds the notifier to the set awaiting a cached position. Runs the success // callbacks for them if permission has been granted. Requests permission if // it is unknown. void RequestUsesCachedPosition(GeoNotifier*); // Discards the notifier if it is a oneshot because it timed it. void RequestTimedOut(GeoNotifier*); // Returns true if this geolocation still owns the given notifier. bool DoesOwnNotifier(GeoNotifier*) const; // Inherited from PageVisibilityObserver. void PageVisibilityChanged() override; // TODO(yukishiino): This is a short-term speculative fix for // crbug.com/792604. Remove this once the bug is fixed. bool HasPendingActivity() const final; private: // Customized HeapHashSet class that checks notifiers' timers. Notifier's // timer may be active only when the notifier is owned by the Geolocation. class GeoNotifierSet : private HeapHashSet<TraceWrapperMember<GeoNotifier>> { using BaseClass = HeapHashSet<TraceWrapperMember<GeoNotifier>>; public: using BaseClass::Trace; using BaseClass::const_iterator; using BaseClass::iterator; using BaseClass::begin; using BaseClass::end; using BaseClass::size; auto insert(GeoNotifier* value) { DCHECK(!value->IsTimerActive()); return BaseClass::insert(value); } void erase(GeoNotifier* value) { DCHECK(!value->IsTimerActive()); return BaseClass::erase(value); } void clear() { #if DCHECK_IS_ON() for (const auto& notifier : *this) { DCHECK(!notifier->IsTimerActive()); } #endif BaseClass::clear(); } using BaseClass::Contains; using BaseClass::IsEmpty; auto InsertWithoutTimerCheck(GeoNotifier* value) { return BaseClass::insert(value); } void ClearWithoutTimerCheck() { BaseClass::clear(); } }; explicit Geolocation(ExecutionContext*); bool HasListeners() const { return !one_shots_.IsEmpty() || !watchers_.IsEmpty(); } void StopTimers(); // Runs the success callbacks on all notifiers. A position must be available // and the user must have given permission. void MakeSuccessCallbacks(); // Sends the given error to all notifiers, unless the error is not fatal and // the notifier is due to receive a cached position. Clears the oneshots, // and also clears the watchers if the error is fatal. void HandleError(PositionError*); // Connects to the Geolocation mojo service and starts polling for updates. void StartUpdating(GeoNotifier*); void StopUpdating(); void UpdateGeolocationConnection(); void QueryNextPosition(); // Attempts to obtain a position for the given notifier, either by using // the cached position or by requesting one from the Geolocation. // Sets a fatal error if permission is denied or no position can be // obtained. void StartRequest(GeoNotifier*); bool HaveSuitableCachedPosition(const PositionOptions&); // Record whether the origin trying to access Geolocation would be allowed // to access a feature that can only be accessed by secure origins. // See https://goo.gl/Y0ZkNV void RecordOriginTypeAccess() const; void OnPositionUpdated(device::mojom::blink::GeopositionPtr); void OnGeolocationConnectionError(); GeoNotifierSet one_shots_; GeolocationWatchers watchers_; // GeoNotifiers that are in the middle of invocation. // // |HandleError(error)| and |MakeSuccessCallbacks| need to clear |one_shots_| // (and optionally |watchers_|) before invoking the callbacks, in order to // avoid clearing notifiers added by calls to Geolocation methods from the // callbacks. Thus, something else needs to make the notifiers being invoked // alive with wrapper-tracing because V8 GC may run during the callbacks. // |one_shots_being_invoked_| and |watchers_being_invoked_| perform // wrapper-tracing. // TODO(https://crbug.com/796145): Remove this hack once on-stack objects // get supported by either of wrapper-tracing or unified GC. GeoNotifierSet one_shots_being_invoked_; HeapVector<TraceWrapperMember<GeoNotifier>> watchers_being_invoked_; Member<Geoposition> last_position_; device::mojom::blink::RevocableGeolocationPtr geolocation_; mojom::blink::RevocableGeolocationServicePtr geolocation_service_; bool enable_high_accuracy_ = false; // Whether a GeoNotifier is waiting for a position update. bool updating_ = false; // Set to true when |geolocation_| is disconnected. This is used to // detect when |geolocation_| is disconnected and reconnected while // running callbacks in response to a call to OnPositionUpdated(). bool disconnected_geolocation_ = false; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_GEOLOCATION_GEOLOCATION_H_
null
null
null
null
35,852
34,775
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
34,775
Chrome
0
https://github.com/chromium/chromium
2018-04-07 23:43:03+00:00
/* * Copyright (C) 2010 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_CORE_HTML_FORMS_SEARCH_INPUT_TYPE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_SEARCH_INPUT_TYPE_H_ #include "third_party/blink/renderer/core/html/forms/base_text_input_type.h" #include "third_party/blink/renderer/platform/timer.h" namespace blink { class SearchInputType final : public BaseTextInputType { public: static InputType* Create(HTMLInputElement&); private: SearchInputType(HTMLInputElement&); void CountUsage() override; LayoutObject* CreateLayoutObject(const ComputedStyle&) const override; const AtomicString& FormControlType() const override; bool NeedsContainer() const override; void CreateShadowSubtree() override; void HandleKeydownEvent(KeyboardEvent*) override; void DidSetValueByUserEdit() override; bool SupportsInputModeAttribute() const override; void UpdateView() override; void DispatchSearchEvent() override; void SearchEventTimerFired(TimerBase*); bool SearchEventsShouldBeDispatched() const; void StartSearchEventTimer(); void UpdateCancelButtonVisibility(); TaskRunnerTimer<SearchInputType> search_event_timer_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_SEARCH_INPUT_TYPE_H_
null
null
null
null
31,638
52,203
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
52,203
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 <limits> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/memory/ptr_util.h" #include "base/synchronization/waitable_event.h" #include "base/sys_byteorder.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread.h" #include "media/audio/audio_debug_file_writer.h" #include "media/base/audio_bus.h" #include "media/base/audio_sample_types.h" #include "media/base/test_helpers.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { namespace { static const uint16_t kBytesPerSample = sizeof(uint16_t); static const uint16_t kPcmEncoding = 1; static const size_t kWavHeaderSize = 44; uint16_t ReadLE2(const char* buf) { return static_cast<uint8_t>(buf[0]) | (static_cast<uint8_t>(buf[1]) << 8); } uint32_t ReadLE4(const char* buf) { return static_cast<uint8_t>(buf[0]) | (static_cast<uint8_t>(buf[1]) << 8) | (static_cast<uint8_t>(buf[2]) << 16) | (static_cast<uint8_t>(buf[3]) << 24); } base::File OpenFile(const base::FilePath& file_path) { return base::File(file_path, base::File::FLAG_OPEN | base::File::FLAG_WRITE); } } // namespace // <channel layout, sample rate, frames per buffer, number of buffer writes typedef std::tuple<ChannelLayout, int, int, int> AudioDebugFileWriterTestData; class AudioDebugFileWriterTest : public testing::TestWithParam<AudioDebugFileWriterTestData> { public: explicit AudioDebugFileWriterTest( base::test::ScopedTaskEnvironment::ExecutionMode execution_mode) : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::DEFAULT, execution_mode), params_(AudioParameters::Format::AUDIO_PCM_LINEAR, std::get<0>(GetParam()), std::get<1>(GetParam()), kBytesPerSample * 8, std::get<2>(GetParam())), writes_(std::get<3>(GetParam())), source_samples_(params_.frames_per_buffer() * params_.channels() * writes_), source_interleaved_(source_samples_ ? new int16_t[source_samples_] : nullptr) { InitSourceInterleaved(source_interleaved_.get(), source_samples_); } AudioDebugFileWriterTest() : AudioDebugFileWriterTest( base::test::ScopedTaskEnvironment::ExecutionMode::ASYNC) {} protected: virtual ~AudioDebugFileWriterTest() = default; static void InitSourceInterleaved(int16_t* source_interleaved, int source_samples) { if (source_samples) { // equal steps to cover int16_t range of values int16_t step = 0xffff / source_samples; int16_t val = std::numeric_limits<int16_t>::min(); for (int i = 0; i < source_samples; ++i, val += step) source_interleaved[i] = val; } } static void VerifyHeader(const char (&wav_header)[kWavHeaderSize], const AudioParameters& params, int writes, int64_t file_length) { uint32_t block_align = params.channels() * kBytesPerSample; uint32_t data_size = static_cast<uint32_t>(params.frames_per_buffer() * params.channels() * writes * kBytesPerSample); // Offset Length Content // 0 4 "RIFF" EXPECT_EQ(0, strncmp(wav_header, "RIFF", 4)); // 4 4 <file length - 8> ASSERT_GT(file_length, 8); EXPECT_EQ(static_cast<uint64_t>(file_length - 8), ReadLE4(wav_header + 4)); EXPECT_EQ(static_cast<uint32_t>(data_size + kWavHeaderSize - 8), ReadLE4(wav_header + 4)); // 8 4 "WAVE" // 12 4 "fmt " EXPECT_EQ(0, strncmp(wav_header + 8, "WAVEfmt ", 8)); // 16 4 <length of the fmt data> (=16) EXPECT_EQ(16U, ReadLE4(wav_header + 16)); // 20 2 <WAVE file encoding tag> EXPECT_EQ(kPcmEncoding, ReadLE2(wav_header + 20)); // 22 2 <channels> EXPECT_EQ(params.channels(), ReadLE2(wav_header + 22)); // 24 4 <sample rate> EXPECT_EQ(static_cast<uint32_t>(params.sample_rate()), ReadLE4(wav_header + 24)); // 28 4 <bytes per second> (sample rate * block align) EXPECT_EQ(static_cast<uint32_t>(params.sample_rate()) * block_align, ReadLE4(wav_header + 28)); // 32 2 <block align> (channels * bits per sample / 8) EXPECT_EQ(block_align, ReadLE2(wav_header + 32)); // 34 2 <bits per sample> EXPECT_EQ(kBytesPerSample * 8, ReadLE2(wav_header + 34)); // 36 4 "data" EXPECT_EQ(0, strncmp(wav_header + 36, "data", 4)); // 40 4 <sample data size(n)> EXPECT_EQ(data_size, ReadLE4(wav_header + 40)); } // |result_interleaved| is expected to be little-endian. static void VerifyDataRecording(const int16_t* source_interleaved, const int16_t* result_interleaved, int16_t source_samples) { // Allow mismatch by 1 due to rounding error in int->float->int // calculations. for (int i = 0; i < source_samples; ++i) EXPECT_LE(std::abs(static_cast<int16_t>( base::ByteSwapToLE16(source_interleaved[i])) - result_interleaved[i]), 1) << "i = " << i << " source " << source_interleaved[i] << " result " << result_interleaved[i]; } void VerifyRecording(const base::FilePath& file_path) { base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ); ASSERT_TRUE(file.IsValid()); char wav_header[kWavHeaderSize]; EXPECT_EQ(file.Read(0, wav_header, kWavHeaderSize), static_cast<int>(kWavHeaderSize)); VerifyHeader(wav_header, params_, writes_, file.GetLength()); if (source_samples_ > 0) { std::unique_ptr<int16_t[]> result_interleaved( new int16_t[source_samples_]); memset(result_interleaved.get(), 0, source_samples_ * kBytesPerSample); // Recording is read from file as a byte sequence, so it stored as // little-endian. int read = file.Read(kWavHeaderSize, reinterpret_cast<char*>(result_interleaved.get()), source_samples_ * kBytesPerSample); EXPECT_EQ(static_cast<int>(file.GetLength() - kWavHeaderSize), read); VerifyDataRecording(source_interleaved_.get(), result_interleaved.get(), source_samples_); } } void DoDebugRecording() { for (int i = 0; i < writes_; ++i) { std::unique_ptr<AudioBus> bus = AudioBus::Create(params_.channels(), params_.frames_per_buffer()); bus->FromInterleaved<media::SignedInt16SampleTypeTraits>( source_interleaved_.get() + i * params_.channels() * params_.frames_per_buffer(), params_.frames_per_buffer()); debug_writer_->Write(std::move(bus)); } } void RecordAndVerifyOnce() { base::FilePath file_path; ASSERT_TRUE(base::CreateTemporaryFile(&file_path)); base::File file = OpenFile(file_path); ASSERT_TRUE(file.IsValid()); debug_writer_->Start(std::move(file)); DoDebugRecording(); debug_writer_->Stop(); scoped_task_environment_.RunUntilIdle(); VerifyRecording(file_path); if (::testing::Test::HasFailure()) { LOG(ERROR) << "Test failed; keeping recording(s) at [" << file_path.value().c_str() << "]."; } else { ASSERT_TRUE(base::DeleteFile(file_path, false)); } } protected: // The test task environment. base::test::ScopedTaskEnvironment scoped_task_environment_; // Writer under test. std::unique_ptr<AudioDebugFileWriter> debug_writer_; // AudioBus parameters. AudioParameters params_; // Number of times to write AudioBus to the file. int writes_; // Number of samples in the source data. int source_samples_; // Source data. std::unique_ptr<int16_t[]> source_interleaved_; private: DISALLOW_COPY_AND_ASSIGN(AudioDebugFileWriterTest); }; class AudioDebugFileWriterBehavioralTest : public AudioDebugFileWriterTest {}; class AudioDebugFileWriterSingleThreadTest : public AudioDebugFileWriterTest { public: AudioDebugFileWriterSingleThreadTest() : AudioDebugFileWriterTest( base::test::ScopedTaskEnvironment::ExecutionMode::QUEUED) {} }; TEST_P(AudioDebugFileWriterTest, WaveRecordingTest) { debug_writer_.reset(new AudioDebugFileWriter(params_)); RecordAndVerifyOnce(); } TEST_P(AudioDebugFileWriterSingleThreadTest, DeletedBeforeRecordingFinishedOnFileThread) { debug_writer_.reset(new AudioDebugFileWriter(params_)); base::FilePath file_path; ASSERT_TRUE(base::CreateTemporaryFile(&file_path)); base::File file = OpenFile(file_path); ASSERT_TRUE(file.IsValid()); debug_writer_->Start(std::move(file)); DoDebugRecording(); debug_writer_.reset(); scoped_task_environment_.RunUntilIdle(); VerifyRecording(file_path); if (::testing::Test::HasFailure()) { LOG(ERROR) << "Test failed; keeping recording(s) at [" << file_path.value().c_str() << "]."; } else { ASSERT_TRUE(base::DeleteFile(file_path, false)); } } TEST_P(AudioDebugFileWriterBehavioralTest, StartWithInvalidFile) { debug_writer_.reset(new AudioDebugFileWriter(params_)); base::File file; // Invalid file, recording should not crash debug_writer_->Start(std::move(file)); DoDebugRecording(); } TEST_P(AudioDebugFileWriterBehavioralTest, StartStopStartStop) { debug_writer_.reset(new AudioDebugFileWriter(params_)); RecordAndVerifyOnce(); RecordAndVerifyOnce(); } TEST_P(AudioDebugFileWriterBehavioralTest, DestroyNotStarted) { debug_writer_.reset(new AudioDebugFileWriter(params_)); debug_writer_.reset(); } TEST_P(AudioDebugFileWriterBehavioralTest, DestroyStarted) { debug_writer_.reset(new AudioDebugFileWriter(params_)); base::FilePath file_path; ASSERT_TRUE(base::CreateTemporaryFile(&file_path)); base::File file = OpenFile(file_path); ASSERT_TRUE(file.IsValid()); debug_writer_->Start(std::move(file)); debug_writer_.reset(); } INSTANTIATE_TEST_CASE_P( AudioDebugFileWriterTest, AudioDebugFileWriterTest, // Using 10ms frames per buffer everywhere. testing::Values( // No writes. std::make_tuple(ChannelLayout::CHANNEL_LAYOUT_MONO, 44100, 44100 / 100, 0), // 1 write of mono. std::make_tuple(ChannelLayout::CHANNEL_LAYOUT_MONO, 44100, 44100 / 100, 1), // 1 second of mono. std::make_tuple(ChannelLayout::CHANNEL_LAYOUT_MONO, 44100, 44100 / 100, 100), // 1 second of mono, higher rate. std::make_tuple(ChannelLayout::CHANNEL_LAYOUT_MONO, 48000, 48000 / 100, 100), // 1 second of stereo. std::make_tuple(ChannelLayout::CHANNEL_LAYOUT_STEREO, 44100, 44100 / 100, 100), // 15 seconds of stereo, higher rate. std::make_tuple(ChannelLayout::CHANNEL_LAYOUT_STEREO, 48000, 48000 / 100, 1500))); INSTANTIATE_TEST_CASE_P(AudioDebugFileWriterBehavioralTest, AudioDebugFileWriterBehavioralTest, // Using 10ms frames per buffer everywhere. testing::Values( // No writes. std::make_tuple(ChannelLayout::CHANNEL_LAYOUT_MONO, 44100, 44100 / 100, 100))); INSTANTIATE_TEST_CASE_P(AudioDebugFileWriterSingleThreadTest, AudioDebugFileWriterSingleThreadTest, // Using 10ms frames per buffer everywhere. testing::Values( // No writes. std::make_tuple(ChannelLayout::CHANNEL_LAYOUT_MONO, 44100, 44100 / 100, 100))); } // namespace media
null
null
null
null
49,066
65,701
null
train_val
796a0e014bc3985709c0a35538d606ef1da31e1b
65,701
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. #ifndef CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_H_ #define CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_H_ #include <memory> #include <utility> #include <vector> #include "base/strings/string16.h" #include "components/password_manager/core/common/credential_manager_types.h" #include "ui/gfx/range/range.h" namespace autofill { struct PasswordForm; } // An interface used by the password dialog (the account chooser) for setting // and retrieving the state. class PasswordDialogController { public: using FormsVector = std::vector<std::unique_ptr<autofill::PasswordForm>>; // Returns forms from the password database for the current site. virtual const FormsVector& GetLocalForms() const = 0; // Returns a title of the account chooser and a range of the Smart Lock // hyperlink if it exists. If the range is empty then no hyperlink is shown. virtual std::pair<base::string16, gfx::Range> GetAccoutChooserTitle() const = 0; // Whether the account chooser should display the "Sign in" button. virtual bool ShouldShowSignInButton() const = 0; // Returns the title for the autosignin first run dialog. virtual base::string16 GetAutoSigninPromoTitle() const = 0; // Returns a text of the auto signin first run promo and a range of the Smart // Lock hyperlink if it exists. The empty range means no hyperlink is shown. virtual std::pair<base::string16, gfx::Range> GetAutoSigninText() const = 0; // Called when the Smart Lock hyperlink is clicked. virtual void OnSmartLockLinkClicked() = 0; // Called when the user chooses a credential. virtual void OnChooseCredentials( const autofill::PasswordForm& password_form, password_manager::CredentialType credential_type) = 0; // Called when the user clicks "Sign in" in the account chooser. virtual void OnSignInClicked() = 0; // Called when user clicks OK in the auto signin first run promo. virtual void OnAutoSigninOK() = 0; // Called when user disables the auto signin setting. virtual void OnAutoSigninTurnOff() = 0; // Called when the dialog was closed. virtual void OnCloseDialog() = 0; protected: virtual ~PasswordDialogController() = default; }; #endif // CHROME_BROWSER_UI_PASSWORDS_PASSWORD_DIALOG_CONTROLLER_H_
null
null
null
null
62,564
8,491
null
train_val
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
173,486
linux
0
https://github.com/torvalds/linux
2017-05-12 08:32:58+10:00
/* MN10300 bit operations * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells ([email protected]) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. * * These have to be done with inline assembly: that way the bit-setting * is guaranteed to be atomic. All bit operations return 0 if the bit * was cleared before the operation and != 0 if it was not. * * bit 0 is the LSB of addr; bit 32 is the LSB of (addr+1). */ #ifndef __ASM_BITOPS_H #define __ASM_BITOPS_H #include <asm/cpu-regs.h> #include <asm/barrier.h> /* * set bit */ #define __set_bit(nr, addr) \ ({ \ volatile unsigned char *_a = (unsigned char *)(addr); \ const unsigned shift = (nr) & 7; \ _a += (nr) >> 3; \ \ asm volatile("bset %2,(%1) # set_bit reg" \ : "=m"(*_a) \ : "a"(_a), "d"(1 << shift), "m"(*_a) \ : "memory", "cc"); \ }) #define set_bit(nr, addr) __set_bit((nr), (addr)) /* * clear bit */ #define ___clear_bit(nr, addr) \ ({ \ volatile unsigned char *_a = (unsigned char *)(addr); \ const unsigned shift = (nr) & 7; \ _a += (nr) >> 3; \ \ asm volatile("bclr %2,(%1) # clear_bit reg" \ : "=m"(*_a) \ : "a"(_a), "d"(1 << shift), "m"(*_a) \ : "memory", "cc"); \ }) #define clear_bit(nr, addr) ___clear_bit((nr), (addr)) static inline void __clear_bit(unsigned long nr, volatile void *addr) { unsigned int *a = (unsigned int *) addr; int mask; a += nr >> 5; mask = 1 << (nr & 0x1f); *a &= ~mask; } /* * test bit */ static inline int test_bit(unsigned long nr, const volatile void *addr) { return 1UL & (((const volatile unsigned int *) addr)[nr >> 5] >> (nr & 31)); } /* * change bit */ static inline void __change_bit(unsigned long nr, volatile void *addr) { int mask; unsigned int *a = (unsigned int *) addr; a += nr >> 5; mask = 1 << (nr & 0x1f); *a ^= mask; } extern void change_bit(unsigned long nr, volatile void *addr); /* * test and set bit */ #define __test_and_set_bit(nr,addr) \ ({ \ volatile unsigned char *_a = (unsigned char *)(addr); \ const unsigned shift = (nr) & 7; \ unsigned epsw; \ _a += (nr) >> 3; \ \ asm volatile("bset %3,(%2) # test_set_bit reg\n" \ "mov epsw,%1" \ : "=m"(*_a), "=d"(epsw) \ : "a"(_a), "d"(1 << shift), "m"(*_a) \ : "memory", "cc"); \ \ !(epsw & EPSW_FLAG_Z); \ }) #define test_and_set_bit(nr, addr) __test_and_set_bit((nr), (addr)) /* * test and clear bit */ #define __test_and_clear_bit(nr, addr) \ ({ \ volatile unsigned char *_a = (unsigned char *)(addr); \ const unsigned shift = (nr) & 7; \ unsigned epsw; \ _a += (nr) >> 3; \ \ asm volatile("bclr %3,(%2) # test_clear_bit reg\n" \ "mov epsw,%1" \ : "=m"(*_a), "=d"(epsw) \ : "a"(_a), "d"(1 << shift), "m"(*_a) \ : "memory", "cc"); \ \ !(epsw & EPSW_FLAG_Z); \ }) #define test_and_clear_bit(nr, addr) __test_and_clear_bit((nr), (addr)) /* * test and change bit */ static inline int __test_and_change_bit(unsigned long nr, volatile void *addr) { int mask, retval; unsigned int *a = (unsigned int *)addr; a += nr >> 5; mask = 1 << (nr & 0x1f); retval = (mask & *a) != 0; *a ^= mask; return retval; } extern int test_and_change_bit(unsigned long nr, volatile void *addr); #include <asm-generic/bitops/lock.h> #ifdef __KERNEL__ /** * __ffs - find first bit set * @x: the word to search * * - return 31..0 to indicate bit 31..0 most least significant bit set * - if no bits are set in x, the result is undefined */ static inline __attribute__((const)) unsigned long __ffs(unsigned long x) { int bit; asm("bsch %2,%0" : "=r"(bit) : "0"(0), "r"(x & -x) : "cc"); return bit; } /* * special slimline version of fls() for calculating ilog2_u32() * - note: no protection against n == 0 */ static inline __attribute__((const)) int __ilog2_u32(u32 n) { int bit; asm("bsch %2,%0" : "=r"(bit) : "0"(0), "r"(n) : "cc"); return bit; } /** * fls - find last bit set * @x: the word to search * * This is defined the same way as ffs: * - return 32..1 to indicate bit 31..0 most significant bit set * - return 0 to indicate no bits set */ static inline __attribute__((const)) int fls(int x) { return (x != 0) ? __ilog2_u32(x) + 1 : 0; } /** * __fls - find last (most-significant) set bit in a long word * @word: the word to search * * Undefined if no set bit exists, so code should check against 0 first. */ static inline unsigned long __fls(unsigned long word) { return __ilog2_u32(word); } /** * ffs - find first bit set * @x: the word to search * * - return 32..1 to indicate bit 31..0 most least significant bit set * - return 0 to indicate no bits set */ static inline __attribute__((const)) int ffs(int x) { /* Note: (x & -x) gives us a mask that is the least significant * (rightmost) 1-bit of the value in x. */ return fls(x & -x); } #include <asm-generic/bitops/ffz.h> #include <asm-generic/bitops/fls64.h> #include <asm-generic/bitops/find.h> #include <asm-generic/bitops/sched.h> #include <asm-generic/bitops/hweight.h> #include <asm-generic/bitops/ext2-atomic-setbit.h> #include <asm-generic/bitops/le.h> #endif /* __KERNEL__ */ #endif /* __ASM_BITOPS_H */
null
null
null
null
81,833
1,343
null
train_val
1b0d3845b454eaaac0b2064c78926ca4d739a080
263,911
qemu
0
https://github.com/bonzini/qemu
2016-10-18 11:40:27+01:00
/* * QEMU Audio subsystem * * Copyright (c) 2003-2005 Vassili Karpov (malc) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "qemu/osdep.h" #include "hw/hw.h" #include "audio.h" #include "monitor/monitor.h" #include "qemu/timer.h" #include "sysemu/sysemu.h" #include "qemu/cutils.h" #define AUDIO_CAP "audio" #include "audio_int.h" /* #define DEBUG_LIVE */ /* #define DEBUG_OUT */ /* #define DEBUG_CAPTURE */ /* #define DEBUG_POLL */ #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown" /* Order of CONFIG_AUDIO_DRIVERS is import. The 1st one is the one used by default, that is the reason that we generate the list. */ static struct audio_driver *drvtab[] = { #ifdef CONFIG_SPICE &spice_audio_driver, #endif CONFIG_AUDIO_DRIVERS &no_audio_driver, &wav_audio_driver }; struct fixed_settings { int enabled; int nb_voices; int greedy; struct audsettings settings; }; static struct { struct fixed_settings fixed_out; struct fixed_settings fixed_in; union { int hertz; int64_t ticks; } period; int try_poll_in; int try_poll_out; } conf = { .fixed_out = { /* DAC fixed settings */ .enabled = 1, .nb_voices = 1, .greedy = 1, .settings = { .freq = 44100, .nchannels = 2, .fmt = AUD_FMT_S16, .endianness = AUDIO_HOST_ENDIANNESS, } }, .fixed_in = { /* ADC fixed settings */ .enabled = 1, .nb_voices = 1, .greedy = 1, .settings = { .freq = 44100, .nchannels = 2, .fmt = AUD_FMT_S16, .endianness = AUDIO_HOST_ENDIANNESS, } }, .period = { .hertz = 100 }, .try_poll_in = 1, .try_poll_out = 1, }; static AudioState glob_audio_state; const struct mixeng_volume nominal_volume = { .mute = 0, #ifdef FLOAT_MIXENG .r = 1.0, .l = 1.0, #else .r = 1ULL << 32, .l = 1ULL << 32, #endif }; #ifdef AUDIO_IS_FLAWLESS_AND_NO_CHECKS_ARE_REQURIED #error No its not #else static void audio_print_options (const char *prefix, struct audio_option *opt); int audio_bug (const char *funcname, int cond) { if (cond) { static int shown; AUD_log (NULL, "A bug was just triggered in %s\n", funcname); if (!shown) { struct audio_driver *d; shown = 1; AUD_log (NULL, "Save all your work and restart without audio\n"); AUD_log (NULL, "Please send bug report to [email protected]\n"); AUD_log (NULL, "I am sorry\n"); d = glob_audio_state.drv; if (d) { audio_print_options (d->name, d->options); } } AUD_log (NULL, "Context:\n"); #if defined AUDIO_BREAKPOINT_ON_BUG # if defined HOST_I386 # if defined __GNUC__ __asm__ ("int3"); # elif defined _MSC_VER _asm _emit 0xcc; # else abort (); # endif # else abort (); # endif #endif } return cond; } #endif static inline int audio_bits_to_index (int bits) { switch (bits) { case 8: return 0; case 16: return 1; case 32: return 2; default: audio_bug ("bits_to_index", 1); AUD_log (NULL, "invalid bits %d\n", bits); return 0; } } void *audio_calloc (const char *funcname, int nmemb, size_t size) { int cond; size_t len; len = nmemb * size; cond = !nmemb || !size; cond |= nmemb < 0; cond |= len < size; if (audio_bug ("audio_calloc", cond)) { AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n", funcname); AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len); return NULL; } return g_malloc0 (len); } static char *audio_alloc_prefix (const char *s) { const char qemu_prefix[] = "QEMU_"; size_t len, i; char *r, *u; if (!s) { return NULL; } len = strlen (s); r = g_malloc (len + sizeof (qemu_prefix)); u = r + sizeof (qemu_prefix) - 1; pstrcpy (r, len + sizeof (qemu_prefix), qemu_prefix); pstrcat (r, len + sizeof (qemu_prefix), s); for (i = 0; i < len; ++i) { u[i] = qemu_toupper(u[i]); } return r; } static const char *audio_audfmt_to_string (audfmt_e fmt) { switch (fmt) { case AUD_FMT_U8: return "U8"; case AUD_FMT_U16: return "U16"; case AUD_FMT_S8: return "S8"; case AUD_FMT_S16: return "S16"; case AUD_FMT_U32: return "U32"; case AUD_FMT_S32: return "S32"; } dolog ("Bogus audfmt %d returning S16\n", fmt); return "S16"; } static audfmt_e audio_string_to_audfmt (const char *s, audfmt_e defval, int *defaultp) { if (!strcasecmp (s, "u8")) { *defaultp = 0; return AUD_FMT_U8; } else if (!strcasecmp (s, "u16")) { *defaultp = 0; return AUD_FMT_U16; } else if (!strcasecmp (s, "u32")) { *defaultp = 0; return AUD_FMT_U32; } else if (!strcasecmp (s, "s8")) { *defaultp = 0; return AUD_FMT_S8; } else if (!strcasecmp (s, "s16")) { *defaultp = 0; return AUD_FMT_S16; } else if (!strcasecmp (s, "s32")) { *defaultp = 0; return AUD_FMT_S32; } else { dolog ("Bogus audio format `%s' using %s\n", s, audio_audfmt_to_string (defval)); *defaultp = 1; return defval; } } static audfmt_e audio_get_conf_fmt (const char *envname, audfmt_e defval, int *defaultp) { const char *var = getenv (envname); if (!var) { *defaultp = 1; return defval; } return audio_string_to_audfmt (var, defval, defaultp); } static int audio_get_conf_int (const char *key, int defval, int *defaultp) { int val; char *strval; strval = getenv (key); if (strval) { *defaultp = 0; val = atoi (strval); return val; } else { *defaultp = 1; return defval; } } static const char *audio_get_conf_str (const char *key, const char *defval, int *defaultp) { const char *val = getenv (key); if (!val) { *defaultp = 1; return defval; } else { *defaultp = 0; return val; } } void AUD_vlog (const char *cap, const char *fmt, va_list ap) { if (cap) { fprintf(stderr, "%s: ", cap); } vfprintf(stderr, fmt, ap); } void AUD_log (const char *cap, const char *fmt, ...) { va_list ap; va_start (ap, fmt); AUD_vlog (cap, fmt, ap); va_end (ap); } static void audio_print_options (const char *prefix, struct audio_option *opt) { char *uprefix; if (!prefix) { dolog ("No prefix specified\n"); return; } if (!opt) { dolog ("No options\n"); return; } uprefix = audio_alloc_prefix (prefix); for (; opt->name; opt++) { const char *state = "default"; printf (" %s_%s: ", uprefix, opt->name); if (opt->overriddenp && *opt->overriddenp) { state = "current"; } switch (opt->tag) { case AUD_OPT_BOOL: { int *intp = opt->valp; printf ("boolean, %s = %d\n", state, *intp ? 1 : 0); } break; case AUD_OPT_INT: { int *intp = opt->valp; printf ("integer, %s = %d\n", state, *intp); } break; case AUD_OPT_FMT: { audfmt_e *fmtp = opt->valp; printf ( "format, %s = %s, (one of: U8 S8 U16 S16 U32 S32)\n", state, audio_audfmt_to_string (*fmtp) ); } break; case AUD_OPT_STR: { const char **strp = opt->valp; printf ("string, %s = %s\n", state, *strp ? *strp : "(not set)"); } break; default: printf ("???\n"); dolog ("Bad value tag for option %s_%s %d\n", uprefix, opt->name, opt->tag); break; } printf (" %s\n", opt->descr); } g_free (uprefix); } static void audio_process_options (const char *prefix, struct audio_option *opt) { char *optname; const char qemu_prefix[] = "QEMU_"; size_t preflen, optlen; if (audio_bug (AUDIO_FUNC, !prefix)) { dolog ("prefix = NULL\n"); return; } if (audio_bug (AUDIO_FUNC, !opt)) { dolog ("opt = NULL\n"); return; } preflen = strlen (prefix); for (; opt->name; opt++) { size_t len, i; int def; if (!opt->valp) { dolog ("Option value pointer for `%s' is not set\n", opt->name); continue; } len = strlen (opt->name); /* len of opt->name + len of prefix + size of qemu_prefix * (includes trailing zero) + zero + underscore (on behalf of * sizeof) */ optlen = len + preflen + sizeof (qemu_prefix) + 1; optname = g_malloc (optlen); pstrcpy (optname, optlen, qemu_prefix); /* copy while upper-casing, including trailing zero */ for (i = 0; i <= preflen; ++i) { optname[i + sizeof (qemu_prefix) - 1] = qemu_toupper(prefix[i]); } pstrcat (optname, optlen, "_"); pstrcat (optname, optlen, opt->name); def = 1; switch (opt->tag) { case AUD_OPT_BOOL: case AUD_OPT_INT: { int *intp = opt->valp; *intp = audio_get_conf_int (optname, *intp, &def); } break; case AUD_OPT_FMT: { audfmt_e *fmtp = opt->valp; *fmtp = audio_get_conf_fmt (optname, *fmtp, &def); } break; case AUD_OPT_STR: { const char **strp = opt->valp; *strp = audio_get_conf_str (optname, *strp, &def); } break; default: dolog ("Bad value tag for option `%s' - %d\n", optname, opt->tag); break; } if (!opt->overriddenp) { opt->overriddenp = &opt->overridden; } *opt->overriddenp = !def; g_free (optname); } } static void audio_print_settings (struct audsettings *as) { dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels); switch (as->fmt) { case AUD_FMT_S8: AUD_log (NULL, "S8"); break; case AUD_FMT_U8: AUD_log (NULL, "U8"); break; case AUD_FMT_S16: AUD_log (NULL, "S16"); break; case AUD_FMT_U16: AUD_log (NULL, "U16"); break; case AUD_FMT_S32: AUD_log (NULL, "S32"); break; case AUD_FMT_U32: AUD_log (NULL, "U32"); break; default: AUD_log (NULL, "invalid(%d)", as->fmt); break; } AUD_log (NULL, " endianness="); switch (as->endianness) { case 0: AUD_log (NULL, "little"); break; case 1: AUD_log (NULL, "big"); break; default: AUD_log (NULL, "invalid"); break; } AUD_log (NULL, "\n"); } static int audio_validate_settings (struct audsettings *as) { int invalid; invalid = as->nchannels != 1 && as->nchannels != 2; invalid |= as->endianness != 0 && as->endianness != 1; switch (as->fmt) { case AUD_FMT_S8: case AUD_FMT_U8: case AUD_FMT_S16: case AUD_FMT_U16: case AUD_FMT_S32: case AUD_FMT_U32: break; default: invalid = 1; break; } invalid |= as->freq <= 0; return invalid ? -1 : 0; } static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as) { int bits = 8, sign = 0; switch (as->fmt) { case AUD_FMT_S8: sign = 1; /* fall through */ case AUD_FMT_U8: break; case AUD_FMT_S16: sign = 1; /* fall through */ case AUD_FMT_U16: bits = 16; break; case AUD_FMT_S32: sign = 1; /* fall through */ case AUD_FMT_U32: bits = 32; break; } return info->freq == as->freq && info->nchannels == as->nchannels && info->sign == sign && info->bits == bits && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS); } void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as) { int bits = 8, sign = 0, shift = 0; switch (as->fmt) { case AUD_FMT_S8: sign = 1; case AUD_FMT_U8: break; case AUD_FMT_S16: sign = 1; case AUD_FMT_U16: bits = 16; shift = 1; break; case AUD_FMT_S32: sign = 1; case AUD_FMT_U32: bits = 32; shift = 2; break; } info->freq = as->freq; info->bits = bits; info->sign = sign; info->nchannels = as->nchannels; info->shift = (as->nchannels == 2) + shift; info->align = (1 << info->shift) - 1; info->bytes_per_second = info->freq << info->shift; info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS); } void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len) { if (!len) { return; } if (info->sign) { memset (buf, 0x00, len << info->shift); } else { switch (info->bits) { case 8: memset (buf, 0x80, len << info->shift); break; case 16: { int i; uint16_t *p = buf; int shift = info->nchannels - 1; short s = INT16_MAX; if (info->swap_endianness) { s = bswap16 (s); } for (i = 0; i < len << shift; i++) { p[i] = s; } } break; case 32: { int i; uint32_t *p = buf; int shift = info->nchannels - 1; int32_t s = INT32_MAX; if (info->swap_endianness) { s = bswap32 (s); } for (i = 0; i < len << shift; i++) { p[i] = s; } } break; default: AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n", info->bits); break; } } } /* * Capture */ static void noop_conv (struct st_sample *dst, const void *src, int samples) { (void) src; (void) dst; (void) samples; } static CaptureVoiceOut *audio_pcm_capture_find_specific ( struct audsettings *as ) { CaptureVoiceOut *cap; AudioState *s = &glob_audio_state; for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) { if (audio_pcm_info_eq (&cap->hw.info, as)) { return cap; } } return NULL; } static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd) { struct capture_callback *cb; #ifdef DEBUG_CAPTURE dolog ("notification %d sent\n", cmd); #endif for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) { cb->ops.notify (cb->opaque, cmd); } } static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled) { if (cap->hw.enabled != enabled) { audcnotification_e cmd; cap->hw.enabled = enabled; cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE; audio_notify_capture (cap, cmd); } } static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap) { HWVoiceOut *hw = &cap->hw; SWVoiceOut *sw; int enabled = 0; for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) { if (sw->active) { enabled = 1; break; } } audio_capture_maybe_changed (cap, enabled); } static void audio_detach_capture (HWVoiceOut *hw) { SWVoiceCap *sc = hw->cap_head.lh_first; while (sc) { SWVoiceCap *sc1 = sc->entries.le_next; SWVoiceOut *sw = &sc->sw; CaptureVoiceOut *cap = sc->cap; int was_active = sw->active; if (sw->rate) { st_rate_stop (sw->rate); sw->rate = NULL; } QLIST_REMOVE (sw, entries); QLIST_REMOVE (sc, entries); g_free (sc); if (was_active) { /* We have removed soft voice from the capture: this might have changed the overall status of the capture since this might have been the only active voice */ audio_recalc_and_notify_capture (cap); } sc = sc1; } } static int audio_attach_capture (HWVoiceOut *hw) { AudioState *s = &glob_audio_state; CaptureVoiceOut *cap; audio_detach_capture (hw); for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) { SWVoiceCap *sc; SWVoiceOut *sw; HWVoiceOut *hw_cap = &cap->hw; sc = audio_calloc (AUDIO_FUNC, 1, sizeof (*sc)); if (!sc) { dolog ("Could not allocate soft capture voice (%zu bytes)\n", sizeof (*sc)); return -1; } sc->cap = cap; sw = &sc->sw; sw->hw = hw_cap; sw->info = hw->info; sw->empty = 1; sw->active = hw->enabled; sw->conv = noop_conv; sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq; sw->vol = nominal_volume; sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq); if (!sw->rate) { dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw)); g_free (sw); return -1; } QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries); QLIST_INSERT_HEAD (&hw->cap_head, sc, entries); #ifdef DEBUG_CAPTURE sw->name = g_strdup_printf ("for %p %d,%d,%d", hw, sw->info.freq, sw->info.bits, sw->info.nchannels); dolog ("Added %s active = %d\n", sw->name, sw->active); #endif if (sw->active) { audio_capture_maybe_changed (cap, 1); } } return 0; } /* * Hard voice (capture) */ static int audio_pcm_hw_find_min_in (HWVoiceIn *hw) { SWVoiceIn *sw; int m = hw->total_samples_captured; for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) { if (sw->active) { m = audio_MIN (m, sw->total_hw_samples_acquired); } } return m; } int audio_pcm_hw_get_live_in (HWVoiceIn *hw) { int live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw); if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) { dolog ("live=%d hw->samples=%d\n", live, hw->samples); return 0; } return live; } int audio_pcm_hw_clip_out (HWVoiceOut *hw, void *pcm_buf, int live, int pending) { int left = hw->samples - pending; int len = audio_MIN (left, live); int clipped = 0; while (len) { struct st_sample *src = hw->mix_buf + hw->rpos; uint8_t *dst = advance (pcm_buf, hw->rpos << hw->info.shift); int samples_till_end_of_buf = hw->samples - hw->rpos; int samples_to_clip = audio_MIN (len, samples_till_end_of_buf); hw->clip (dst, src, samples_to_clip); hw->rpos = (hw->rpos + samples_to_clip) % hw->samples; len -= samples_to_clip; clipped += samples_to_clip; } return clipped; } /* * Soft voice (capture) */ static int audio_pcm_sw_get_rpos_in (SWVoiceIn *sw) { HWVoiceIn *hw = sw->hw; int live = hw->total_samples_captured - sw->total_hw_samples_acquired; int rpos; if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) { dolog ("live=%d hw->samples=%d\n", live, hw->samples); return 0; } rpos = hw->wpos - live; if (rpos >= 0) { return rpos; } else { return hw->samples + rpos; } } int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size) { HWVoiceIn *hw = sw->hw; int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0; struct st_sample *src, *dst = sw->buf; rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples; live = hw->total_samples_captured - sw->total_hw_samples_acquired; if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) { dolog ("live_in=%d hw->samples=%d\n", live, hw->samples); return 0; } samples = size >> sw->info.shift; if (!live) { return 0; } swlim = (live * sw->ratio) >> 32; swlim = audio_MIN (swlim, samples); while (swlim) { src = hw->conv_buf + rpos; isamp = hw->wpos - rpos; /* XXX: <= ? */ if (isamp <= 0) { isamp = hw->samples - rpos; } if (!isamp) { break; } osamp = swlim; if (audio_bug (AUDIO_FUNC, osamp < 0)) { dolog ("osamp=%d\n", osamp); return 0; } st_rate_flow (sw->rate, src, dst, &isamp, &osamp); swlim -= osamp; rpos = (rpos + isamp) % hw->samples; dst += osamp; ret += osamp; total += isamp; } if (!(hw->ctl_caps & VOICE_VOLUME_CAP)) { mixeng_volume (sw->buf, ret, &sw->vol); } sw->clip (buf, sw->buf, ret); sw->total_hw_samples_acquired += total; return ret << sw->info.shift; } /* * Hard voice (playback) */ static int audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep) { SWVoiceOut *sw; int m = INT_MAX; int nb_live = 0; for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) { if (sw->active || !sw->empty) { m = audio_MIN (m, sw->total_hw_samples_mixed); nb_live += 1; } } *nb_livep = nb_live; return m; } static int audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live) { int smin; int nb_live1; smin = audio_pcm_hw_find_min_out (hw, &nb_live1); if (nb_live) { *nb_live = nb_live1; } if (nb_live1) { int live = smin; if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) { dolog ("live=%d hw->samples=%d\n", live, hw->samples); return 0; } return live; } return 0; } /* * Soft voice (playback) */ int audio_pcm_sw_write (SWVoiceOut *sw, void *buf, int size) { int hwsamples, samples, isamp, osamp, wpos, live, dead, left, swlim, blck; int ret = 0, pos = 0, total = 0; if (!sw) { return size; } hwsamples = sw->hw->samples; live = sw->total_hw_samples_mixed; if (audio_bug (AUDIO_FUNC, live < 0 || live > hwsamples)){ dolog ("live=%d hw->samples=%d\n", live, hwsamples); return 0; } if (live == hwsamples) { #ifdef DEBUG_OUT dolog ("%s is full %d\n", sw->name, live); #endif return 0; } wpos = (sw->hw->rpos + live) % hwsamples; samples = size >> sw->info.shift; dead = hwsamples - live; swlim = ((int64_t) dead << 32) / sw->ratio; swlim = audio_MIN (swlim, samples); if (swlim) { sw->conv (sw->buf, buf, swlim); if (!(sw->hw->ctl_caps & VOICE_VOLUME_CAP)) { mixeng_volume (sw->buf, swlim, &sw->vol); } } while (swlim) { dead = hwsamples - live; left = hwsamples - wpos; blck = audio_MIN (dead, left); if (!blck) { break; } isamp = swlim; osamp = blck; st_rate_flow_mix ( sw->rate, sw->buf + pos, sw->hw->mix_buf + wpos, &isamp, &osamp ); ret += isamp; swlim -= isamp; pos += isamp; live += osamp; wpos = (wpos + osamp) % hwsamples; total += osamp; } sw->total_hw_samples_mixed += total; sw->empty = sw->total_hw_samples_mixed == 0; #ifdef DEBUG_OUT dolog ( "%s: write size %d ret %d total sw %d\n", SW_NAME (sw), size >> sw->info.shift, ret, sw->total_hw_samples_mixed ); #endif return ret << sw->info.shift; } #ifdef DEBUG_AUDIO static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info) { dolog ("%s: bits %d, sign %d, freq %d, nchan %d\n", cap, info->bits, info->sign, info->freq, info->nchannels); } #endif #define DAC #include "audio_template.h" #undef DAC #include "audio_template.h" /* * Timer */ static int audio_is_timer_needed (void) { HWVoiceIn *hwi = NULL; HWVoiceOut *hwo = NULL; while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) { if (!hwo->poll_mode) return 1; } while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) { if (!hwi->poll_mode) return 1; } return 0; } static void audio_reset_timer (AudioState *s) { if (audio_is_timer_needed ()) { timer_mod (s->ts, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + conf.period.ticks); } else { timer_del (s->ts); } } static void audio_timer (void *opaque) { audio_run ("timer"); audio_reset_timer (opaque); } /* * Public API */ int AUD_write (SWVoiceOut *sw, void *buf, int size) { if (!sw) { /* XXX: Consider options */ return size; } if (!sw->hw->enabled) { dolog ("Writing to disabled voice %s\n", SW_NAME (sw)); return 0; } return sw->hw->pcm_ops->write(sw, buf, size); } int AUD_read (SWVoiceIn *sw, void *buf, int size) { if (!sw) { /* XXX: Consider options */ return size; } if (!sw->hw->enabled) { dolog ("Reading from disabled voice %s\n", SW_NAME (sw)); return 0; } return sw->hw->pcm_ops->read(sw, buf, size); } int AUD_get_buffer_size_out (SWVoiceOut *sw) { return sw->hw->samples << sw->hw->info.shift; } void AUD_set_active_out (SWVoiceOut *sw, int on) { HWVoiceOut *hw; if (!sw) { return; } hw = sw->hw; if (sw->active != on) { AudioState *s = &glob_audio_state; SWVoiceOut *temp_sw; SWVoiceCap *sc; if (on) { hw->pending_disable = 0; if (!hw->enabled) { hw->enabled = 1; if (s->vm_running) { hw->pcm_ops->ctl_out (hw, VOICE_ENABLE, conf.try_poll_out); audio_reset_timer (s); } } } else { if (hw->enabled) { int nb_active = 0; for (temp_sw = hw->sw_head.lh_first; temp_sw; temp_sw = temp_sw->entries.le_next) { nb_active += temp_sw->active != 0; } hw->pending_disable = nb_active == 1; } } for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) { sc->sw.active = hw->enabled; if (hw->enabled) { audio_capture_maybe_changed (sc->cap, 1); } } sw->active = on; } } void AUD_set_active_in (SWVoiceIn *sw, int on) { HWVoiceIn *hw; if (!sw) { return; } hw = sw->hw; if (sw->active != on) { AudioState *s = &glob_audio_state; SWVoiceIn *temp_sw; if (on) { if (!hw->enabled) { hw->enabled = 1; if (s->vm_running) { hw->pcm_ops->ctl_in (hw, VOICE_ENABLE, conf.try_poll_in); audio_reset_timer (s); } } sw->total_hw_samples_acquired = hw->total_samples_captured; } else { if (hw->enabled) { int nb_active = 0; for (temp_sw = hw->sw_head.lh_first; temp_sw; temp_sw = temp_sw->entries.le_next) { nb_active += temp_sw->active != 0; } if (nb_active == 1) { hw->enabled = 0; hw->pcm_ops->ctl_in (hw, VOICE_DISABLE); } } } sw->active = on; } } static int audio_get_avail (SWVoiceIn *sw) { int live; if (!sw) { return 0; } live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired; if (audio_bug (AUDIO_FUNC, live < 0 || live > sw->hw->samples)) { dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples); return 0; } ldebug ( "%s: get_avail live %d ret %" PRId64 "\n", SW_NAME (sw), live, (((int64_t) live << 32) / sw->ratio) << sw->info.shift ); return (((int64_t) live << 32) / sw->ratio) << sw->info.shift; } static int audio_get_free (SWVoiceOut *sw) { int live, dead; if (!sw) { return 0; } live = sw->total_hw_samples_mixed; if (audio_bug (AUDIO_FUNC, live < 0 || live > sw->hw->samples)) { dolog ("live=%d sw->hw->samples=%d\n", live, sw->hw->samples); return 0; } dead = sw->hw->samples - live; #ifdef DEBUG_OUT dolog ("%s: get_free live %d dead %d ret %" PRId64 "\n", SW_NAME (sw), live, dead, (((int64_t) dead << 32) / sw->ratio) << sw->info.shift); #endif return (((int64_t) dead << 32) / sw->ratio) << sw->info.shift; } static void audio_capture_mix_and_clear (HWVoiceOut *hw, int rpos, int samples) { int n; if (hw->enabled) { SWVoiceCap *sc; for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) { SWVoiceOut *sw = &sc->sw; int rpos2 = rpos; n = samples; while (n) { int till_end_of_hw = hw->samples - rpos2; int to_write = audio_MIN (till_end_of_hw, n); int bytes = to_write << hw->info.shift; int written; sw->buf = hw->mix_buf + rpos2; written = audio_pcm_sw_write (sw, NULL, bytes); if (written - bytes) { dolog ("Could not mix %d bytes into a capture " "buffer, mixed %d\n", bytes, written); break; } n -= to_write; rpos2 = (rpos2 + to_write) % hw->samples; } } } n = audio_MIN (samples, hw->samples - rpos); mixeng_clear (hw->mix_buf + rpos, n); mixeng_clear (hw->mix_buf, samples - n); } static void audio_run_out (AudioState *s) { HWVoiceOut *hw = NULL; SWVoiceOut *sw; while ((hw = audio_pcm_hw_find_any_enabled_out (hw))) { int played; int live, free, nb_live, cleanup_required, prev_rpos; live = audio_pcm_hw_get_live_out (hw, &nb_live); if (!nb_live) { live = 0; } if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) { dolog ("live=%d hw->samples=%d\n", live, hw->samples); continue; } if (hw->pending_disable && !nb_live) { SWVoiceCap *sc; #ifdef DEBUG_OUT dolog ("Disabling voice\n"); #endif hw->enabled = 0; hw->pending_disable = 0; hw->pcm_ops->ctl_out (hw, VOICE_DISABLE); for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) { sc->sw.active = 0; audio_recalc_and_notify_capture (sc->cap); } continue; } if (!live) { for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) { if (sw->active) { free = audio_get_free (sw); if (free > 0) { sw->callback.fn (sw->callback.opaque, free); } } } continue; } prev_rpos = hw->rpos; played = hw->pcm_ops->run_out (hw, live); if (audio_bug (AUDIO_FUNC, hw->rpos >= hw->samples)) { dolog ("hw->rpos=%d hw->samples=%d played=%d\n", hw->rpos, hw->samples, played); hw->rpos = 0; } #ifdef DEBUG_OUT dolog ("played=%d\n", played); #endif if (played) { hw->ts_helper += played; audio_capture_mix_and_clear (hw, prev_rpos, played); } cleanup_required = 0; for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) { if (!sw->active && sw->empty) { continue; } if (audio_bug (AUDIO_FUNC, played > sw->total_hw_samples_mixed)) { dolog ("played=%d sw->total_hw_samples_mixed=%d\n", played, sw->total_hw_samples_mixed); played = sw->total_hw_samples_mixed; } sw->total_hw_samples_mixed -= played; if (!sw->total_hw_samples_mixed) { sw->empty = 1; cleanup_required |= !sw->active && !sw->callback.fn; } if (sw->active) { free = audio_get_free (sw); if (free > 0) { sw->callback.fn (sw->callback.opaque, free); } } } if (cleanup_required) { SWVoiceOut *sw1; sw = hw->sw_head.lh_first; while (sw) { sw1 = sw->entries.le_next; if (!sw->active && !sw->callback.fn) { audio_close_out (sw); } sw = sw1; } } } } static void audio_run_in (AudioState *s) { HWVoiceIn *hw = NULL; while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) { SWVoiceIn *sw; int captured, min; captured = hw->pcm_ops->run_in (hw); min = audio_pcm_hw_find_min_in (hw); hw->total_samples_captured += captured - min; hw->ts_helper += captured; for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) { sw->total_hw_samples_acquired -= min; if (sw->active) { int avail; avail = audio_get_avail (sw); if (avail > 0) { sw->callback.fn (sw->callback.opaque, avail); } } } } } static void audio_run_capture (AudioState *s) { CaptureVoiceOut *cap; for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) { int live, rpos, captured; HWVoiceOut *hw = &cap->hw; SWVoiceOut *sw; captured = live = audio_pcm_hw_get_live_out (hw, NULL); rpos = hw->rpos; while (live) { int left = hw->samples - rpos; int to_capture = audio_MIN (live, left); struct st_sample *src; struct capture_callback *cb; src = hw->mix_buf + rpos; hw->clip (cap->buf, src, to_capture); mixeng_clear (src, to_capture); for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) { cb->ops.capture (cb->opaque, cap->buf, to_capture << hw->info.shift); } rpos = (rpos + to_capture) % hw->samples; live -= to_capture; } hw->rpos = rpos; for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) { if (!sw->active && sw->empty) { continue; } if (audio_bug (AUDIO_FUNC, captured > sw->total_hw_samples_mixed)) { dolog ("captured=%d sw->total_hw_samples_mixed=%d\n", captured, sw->total_hw_samples_mixed); captured = sw->total_hw_samples_mixed; } sw->total_hw_samples_mixed -= captured; sw->empty = sw->total_hw_samples_mixed == 0; } } } void audio_run (const char *msg) { AudioState *s = &glob_audio_state; audio_run_out (s); audio_run_in (s); audio_run_capture (s); #ifdef DEBUG_POLL { static double prevtime; double currtime; struct timeval tv; if (gettimeofday (&tv, NULL)) { perror ("audio_run: gettimeofday"); return; } currtime = tv.tv_sec + tv.tv_usec * 1e-6; dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime); prevtime = currtime; } #endif } static struct audio_option audio_options[] = { /* DAC */ { .name = "DAC_FIXED_SETTINGS", .tag = AUD_OPT_BOOL, .valp = &conf.fixed_out.enabled, .descr = "Use fixed settings for host DAC" }, { .name = "DAC_FIXED_FREQ", .tag = AUD_OPT_INT, .valp = &conf.fixed_out.settings.freq, .descr = "Frequency for fixed host DAC" }, { .name = "DAC_FIXED_FMT", .tag = AUD_OPT_FMT, .valp = &conf.fixed_out.settings.fmt, .descr = "Format for fixed host DAC" }, { .name = "DAC_FIXED_CHANNELS", .tag = AUD_OPT_INT, .valp = &conf.fixed_out.settings.nchannels, .descr = "Number of channels for fixed DAC (1 - mono, 2 - stereo)" }, { .name = "DAC_VOICES", .tag = AUD_OPT_INT, .valp = &conf.fixed_out.nb_voices, .descr = "Number of voices for DAC" }, { .name = "DAC_TRY_POLL", .tag = AUD_OPT_BOOL, .valp = &conf.try_poll_out, .descr = "Attempt using poll mode for DAC" }, /* ADC */ { .name = "ADC_FIXED_SETTINGS", .tag = AUD_OPT_BOOL, .valp = &conf.fixed_in.enabled, .descr = "Use fixed settings for host ADC" }, { .name = "ADC_FIXED_FREQ", .tag = AUD_OPT_INT, .valp = &conf.fixed_in.settings.freq, .descr = "Frequency for fixed host ADC" }, { .name = "ADC_FIXED_FMT", .tag = AUD_OPT_FMT, .valp = &conf.fixed_in.settings.fmt, .descr = "Format for fixed host ADC" }, { .name = "ADC_FIXED_CHANNELS", .tag = AUD_OPT_INT, .valp = &conf.fixed_in.settings.nchannels, .descr = "Number of channels for fixed ADC (1 - mono, 2 - stereo)" }, { .name = "ADC_VOICES", .tag = AUD_OPT_INT, .valp = &conf.fixed_in.nb_voices, .descr = "Number of voices for ADC" }, { .name = "ADC_TRY_POLL", .tag = AUD_OPT_BOOL, .valp = &conf.try_poll_in, .descr = "Attempt using poll mode for ADC" }, /* Misc */ { .name = "TIMER_PERIOD", .tag = AUD_OPT_INT, .valp = &conf.period.hertz, .descr = "Timer period in HZ (0 - use lowest possible)" }, { /* End of list */ } }; static void audio_pp_nb_voices (const char *typ, int nb) { switch (nb) { case 0: printf ("Does not support %s\n", typ); break; case 1: printf ("One %s voice\n", typ); break; case INT_MAX: printf ("Theoretically supports many %s voices\n", typ); break; default: printf ("Theoretically supports up to %d %s voices\n", nb, typ); break; } } void AUD_help (void) { size_t i; audio_process_options ("AUDIO", audio_options); for (i = 0; i < ARRAY_SIZE (drvtab); i++) { struct audio_driver *d = drvtab[i]; if (d->options) { audio_process_options (d->name, d->options); } } printf ("Audio options:\n"); audio_print_options ("AUDIO", audio_options); printf ("\n"); printf ("Available drivers:\n"); for (i = 0; i < ARRAY_SIZE (drvtab); i++) { struct audio_driver *d = drvtab[i]; printf ("Name: %s\n", d->name); printf ("Description: %s\n", d->descr); audio_pp_nb_voices ("playback", d->max_voices_out); audio_pp_nb_voices ("capture", d->max_voices_in); if (d->options) { printf ("Options:\n"); audio_print_options (d->name, d->options); } else { printf ("No options\n"); } printf ("\n"); } printf ( "Options are settable through environment variables.\n" "Example:\n" #ifdef _WIN32 " set QEMU_AUDIO_DRV=wav\n" " set QEMU_WAV_PATH=c:\\tune.wav\n" #else " export QEMU_AUDIO_DRV=wav\n" " export QEMU_WAV_PATH=$HOME/tune.wav\n" "(for csh replace export with setenv in the above)\n" #endif " qemu ...\n\n" ); } static int audio_driver_init (AudioState *s, struct audio_driver *drv) { if (drv->options) { audio_process_options (drv->name, drv->options); } s->drv_opaque = drv->init (); if (s->drv_opaque) { audio_init_nb_voices_out (drv); audio_init_nb_voices_in (drv); s->drv = drv; return 0; } else { dolog ("Could not init `%s' audio driver\n", drv->name); return -1; } } static void audio_vm_change_state_handler (void *opaque, int running, RunState state) { AudioState *s = opaque; HWVoiceOut *hwo = NULL; HWVoiceIn *hwi = NULL; int op = running ? VOICE_ENABLE : VOICE_DISABLE; s->vm_running = running; while ((hwo = audio_pcm_hw_find_any_enabled_out (hwo))) { hwo->pcm_ops->ctl_out (hwo, op, conf.try_poll_out); } while ((hwi = audio_pcm_hw_find_any_enabled_in (hwi))) { hwi->pcm_ops->ctl_in (hwi, op, conf.try_poll_in); } audio_reset_timer (s); } static bool is_cleaning_up; bool audio_is_cleaning_up(void) { return is_cleaning_up; } void audio_cleanup(void) { AudioState *s = &glob_audio_state; HWVoiceOut *hwo, *hwon; HWVoiceIn *hwi, *hwin; is_cleaning_up = true; QLIST_FOREACH_SAFE(hwo, &glob_audio_state.hw_head_out, entries, hwon) { SWVoiceCap *sc; if (hwo->enabled) { hwo->pcm_ops->ctl_out (hwo, VOICE_DISABLE); } hwo->pcm_ops->fini_out (hwo); for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) { CaptureVoiceOut *cap = sc->cap; struct capture_callback *cb; for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) { cb->ops.destroy (cb->opaque); } } QLIST_REMOVE(hwo, entries); } QLIST_FOREACH_SAFE(hwi, &glob_audio_state.hw_head_in, entries, hwin) { if (hwi->enabled) { hwi->pcm_ops->ctl_in (hwi, VOICE_DISABLE); } hwi->pcm_ops->fini_in (hwi); QLIST_REMOVE(hwi, entries); } if (s->drv) { s->drv->fini (s->drv_opaque); s->drv = NULL; } } static const VMStateDescription vmstate_audio = { .name = "audio", .version_id = 1, .minimum_version_id = 1, .fields = (VMStateField[]) { VMSTATE_END_OF_LIST() } }; static void audio_init (void) { size_t i; int done = 0; const char *drvname; VMChangeStateEntry *e; AudioState *s = &glob_audio_state; if (s->drv) { return; } QLIST_INIT (&s->hw_head_out); QLIST_INIT (&s->hw_head_in); QLIST_INIT (&s->cap_head); atexit(audio_cleanup); s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s); audio_process_options ("AUDIO", audio_options); s->nb_hw_voices_out = conf.fixed_out.nb_voices; s->nb_hw_voices_in = conf.fixed_in.nb_voices; if (s->nb_hw_voices_out <= 0) { dolog ("Bogus number of playback voices %d, setting to 1\n", s->nb_hw_voices_out); s->nb_hw_voices_out = 1; } if (s->nb_hw_voices_in <= 0) { dolog ("Bogus number of capture voices %d, setting to 0\n", s->nb_hw_voices_in); s->nb_hw_voices_in = 0; } { int def; drvname = audio_get_conf_str ("QEMU_AUDIO_DRV", NULL, &def); } if (drvname) { int found = 0; for (i = 0; i < ARRAY_SIZE (drvtab); i++) { if (!strcmp (drvname, drvtab[i]->name)) { done = !audio_driver_init (s, drvtab[i]); found = 1; break; } } if (!found) { dolog ("Unknown audio driver `%s'\n", drvname); dolog ("Run with -audio-help to list available drivers\n"); } } if (!done) { for (i = 0; !done && i < ARRAY_SIZE (drvtab); i++) { if (drvtab[i]->can_be_default) { done = !audio_driver_init (s, drvtab[i]); } } } if (!done) { done = !audio_driver_init (s, &no_audio_driver); assert(done); dolog("warning: Using timer based audio emulation\n"); } if (conf.period.hertz <= 0) { if (conf.period.hertz < 0) { dolog ("warning: Timer period is negative - %d " "treating as zero\n", conf.period.hertz); } conf.period.ticks = 1; } else { conf.period.ticks = NANOSECONDS_PER_SECOND / conf.period.hertz; } e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s); if (!e) { dolog ("warning: Could not register change state handler\n" "(Audio can continue looping even after stopping the VM)\n"); } QLIST_INIT (&s->card_head); vmstate_register (NULL, 0, &vmstate_audio, s); } void AUD_register_card (const char *name, QEMUSoundCard *card) { audio_init (); card->name = g_strdup (name); memset (&card->entries, 0, sizeof (card->entries)); QLIST_INSERT_HEAD (&glob_audio_state.card_head, card, entries); } void AUD_remove_card (QEMUSoundCard *card) { QLIST_REMOVE (card, entries); g_free (card->name); } CaptureVoiceOut *AUD_add_capture ( struct audsettings *as, struct audio_capture_ops *ops, void *cb_opaque ) { AudioState *s = &glob_audio_state; CaptureVoiceOut *cap; struct capture_callback *cb; if (audio_validate_settings (as)) { dolog ("Invalid settings were passed when trying to add capture\n"); audio_print_settings (as); goto err0; } cb = audio_calloc (AUDIO_FUNC, 1, sizeof (*cb)); if (!cb) { dolog ("Could not allocate capture callback information, size %zu\n", sizeof (*cb)); goto err0; } cb->ops = *ops; cb->opaque = cb_opaque; cap = audio_pcm_capture_find_specific (as); if (cap) { QLIST_INSERT_HEAD (&cap->cb_head, cb, entries); return cap; } else { HWVoiceOut *hw; CaptureVoiceOut *cap; cap = audio_calloc (AUDIO_FUNC, 1, sizeof (*cap)); if (!cap) { dolog ("Could not allocate capture voice, size %zu\n", sizeof (*cap)); goto err1; } hw = &cap->hw; QLIST_INIT (&hw->sw_head); QLIST_INIT (&cap->cb_head); /* XXX find a more elegant way */ hw->samples = 4096 * 4; hw->mix_buf = audio_calloc (AUDIO_FUNC, hw->samples, sizeof (struct st_sample)); if (!hw->mix_buf) { dolog ("Could not allocate capture mix buffer (%d samples)\n", hw->samples); goto err2; } audio_pcm_init_info (&hw->info, as); cap->buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift); if (!cap->buf) { dolog ("Could not allocate capture buffer " "(%d samples, each %d bytes)\n", hw->samples, 1 << hw->info.shift); goto err3; } hw->clip = mixeng_clip [hw->info.nchannels == 2] [hw->info.sign] [hw->info.swap_endianness] [audio_bits_to_index (hw->info.bits)]; QLIST_INSERT_HEAD (&s->cap_head, cap, entries); QLIST_INSERT_HEAD (&cap->cb_head, cb, entries); QLIST_FOREACH(hw, &glob_audio_state.hw_head_out, entries) { audio_attach_capture (hw); } return cap; err3: g_free (cap->hw.mix_buf); err2: g_free (cap); err1: g_free (cb); err0: return NULL; } } void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque) { struct capture_callback *cb; for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) { if (cb->opaque == cb_opaque) { cb->ops.destroy (cb_opaque); QLIST_REMOVE (cb, entries); g_free (cb); if (!cap->cb_head.lh_first) { SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1; while (sw) { SWVoiceCap *sc = (SWVoiceCap *) sw; #ifdef DEBUG_CAPTURE dolog ("freeing %s\n", sw->name); #endif sw1 = sw->entries.le_next; if (sw->rate) { st_rate_stop (sw->rate); sw->rate = NULL; } QLIST_REMOVE (sw, entries); QLIST_REMOVE (sc, entries); g_free (sc); sw = sw1; } QLIST_REMOVE (cap, entries); g_free (cap); } return; } } } void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol) { if (sw) { HWVoiceOut *hw = sw->hw; sw->vol.mute = mute; sw->vol.l = nominal_volume.l * lvol / 255; sw->vol.r = nominal_volume.r * rvol / 255; if (hw->pcm_ops->ctl_out) { hw->pcm_ops->ctl_out (hw, VOICE_VOLUME, sw); } } } void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol) { if (sw) { HWVoiceIn *hw = sw->hw; sw->vol.mute = mute; sw->vol.l = nominal_volume.l * lvol / 255; sw->vol.r = nominal_volume.r * rvol / 255; if (hw->pcm_ops->ctl_in) { hw->pcm_ops->ctl_in (hw, VOICE_VOLUME, sw); } } }
null
null
null
null
122,035