code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers def register_types(module): root_module = module.get_root() ## ipv4-nix-vector-routing.h: ns3::Ipv4NixVectorRouting [class] module.add_class('Ipv4NixVectorRouting', parent=root_module['ns3::Ipv4RoutingProtocol']) typehandlers.add_type_alias('std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >', 'ns3::NixMap_t') typehandlers.add_type_alias('std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >*', 'ns3::NixMap_t*') typehandlers.add_type_alias('std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >&', 'ns3::NixMap_t&') typehandlers.add_type_alias('std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >', 'ns3::Ipv4RouteMap_t') typehandlers.add_type_alias('std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >*', 'ns3::Ipv4RouteMap_t*') typehandlers.add_type_alias('std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >&', 'ns3::Ipv4RouteMap_t&') ## Register a nested module for the namespace Config nested_module = module.add_cpp_namespace('Config') register_types_ns3_Config(nested_module) ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace addressUtils nested_module = module.add_cpp_namespace('addressUtils') register_types_ns3_addressUtils(nested_module) ## Register a nested module for the namespace aodv nested_module = module.add_cpp_namespace('aodv') register_types_ns3_aodv(nested_module) ## Register a nested module for the namespace dot11s nested_module = module.add_cpp_namespace('dot11s') register_types_ns3_dot11s(nested_module) ## Register a nested module for the namespace dsdv nested_module = module.add_cpp_namespace('dsdv') register_types_ns3_dsdv(nested_module) ## Register a nested module for the namespace flame nested_module = module.add_cpp_namespace('flame') register_types_ns3_flame(nested_module) ## Register a nested module for the namespace internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) ## Register a nested module for the namespace olsr nested_module = module.add_cpp_namespace('olsr') register_types_ns3_olsr(nested_module) def register_types_ns3_Config(module): root_module = module.get_root() def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_addressUtils(module): root_module = module.get_root() def register_types_ns3_aodv(module): root_module = module.get_root() def register_types_ns3_dot11s(module): root_module = module.get_root() def register_types_ns3_dsdv(module): root_module = module.get_root() def register_types_ns3_flame(module): root_module = module.get_root() def register_types_ns3_internal(module): root_module = module.get_root() def register_types_ns3_olsr(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Ipv4NixVectorRouting_methods(root_module, root_module['ns3::Ipv4NixVectorRouting']) return def register_Ns3Ipv4NixVectorRouting_methods(root_module, cls): ## ipv4-nix-vector-routing.h: ns3::Ipv4NixVectorRouting::Ipv4NixVectorRouting(ns3::Ipv4NixVectorRouting const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4NixVectorRouting const &', 'arg0')]) ## ipv4-nix-vector-routing.h: ns3::Ipv4NixVectorRouting::Ipv4NixVectorRouting() [constructor] cls.add_constructor([]) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::FlushGlobalNixRoutingCache() [member function] cls.add_method('FlushGlobalNixRoutingCache', 'void', []) ## ipv4-nix-vector-routing.h: static ns3::TypeId ns3::Ipv4NixVectorRouting::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True, visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h: bool ns3::Ipv4NixVectorRouting::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void, ns3::Ptr<ns3::Packet const>, ns3::Ipv4Header const&, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h: ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4NixVectorRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h: void ns3::Ipv4NixVectorRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], visibility='private', is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_Config(module.get_submodule('Config'), root_module) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module) register_functions_ns3_aodv(module.get_submodule('aodv'), root_module) register_functions_ns3_dot11s(module.get_submodule('dot11s'), root_module) register_functions_ns3_dsdv(module.get_submodule('dsdv'), root_module) register_functions_ns3_flame(module.get_submodule('flame'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) register_functions_ns3_olsr(module.get_submodule('olsr'), root_module) return def register_functions_ns3_Config(module, root_module): return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_addressUtils(module, root_module): return def register_functions_ns3_aodv(module, root_module): return def register_functions_ns3_dot11s(module, root_module): return def register_functions_ns3_dsdv(module, root_module): return def register_functions_ns3_flame(module, root_module): return def register_functions_ns3_internal(module, root_module): return def register_functions_ns3_olsr(module, root_module): return
annegabrielle/secure_adhoc_network_ns-3
ns3_source_code/ns-3.10/bindings/python/apidefs/gcc-LP64/ns3_module_nix_vector_routing.py
Python
gpl-2.0
11,439
// { dg-do link } // { dg-options "-x c -lsupc++" } // Copyright (C) 2006-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // 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 General Public License for more details. // You should have received a copy of the GNU General Public License // along with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // Must be able to link C++ apps compiled with gcc and libsupc++. int main() { return 0; }
krichter722/gcc
libstdc++-v3/testsuite/abi/cxx_runtime_only_linkage.cc
C++
gpl-2.0
910
/* * FFV1 codec for libavcodec * * Copyright (c) 2003-2012 Michael Niedermayer <[email protected]> * * 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 * FF Video Codec 1 (a lossless codec) */ #include "libavutil/avassert.h" #include "libavutil/crc.h" #include "libavutil/opt.h" #include "libavutil/imgutils.h" #include "libavutil/pixdesc.h" #include "libavutil/timer.h" #include "avcodec.h" #include "internal.h" #include "rangecoder.h" #include "golomb.h" #include "mathops.h" #include "ffv1.h" av_cold int ffv1_common_init(AVCodecContext *avctx) { FFV1Context *s = avctx->priv_data; if (!avctx->width || !avctx->height) return AVERROR_INVALIDDATA; s->avctx = avctx; s->flags = avctx->flags; avcodec_get_frame_defaults(&s->picture); ff_dsputil_init(&s->dsp, avctx); s->width = avctx->width; s->height = avctx->height; // defaults s->num_h_slices = 1; s->num_v_slices = 1; return 0; } int ffv1_init_slice_state(FFV1Context *f, FFV1Context *fs) { int j; fs->plane_count = f->plane_count; fs->transparency = f->transparency; for (j = 0; j < f->plane_count; j++) { PlaneContext *const p = &fs->plane[j]; if (fs->ac) { if (!p->state) p->state = av_malloc(CONTEXT_SIZE * p->context_count * sizeof(uint8_t)); if (!p->state) return AVERROR(ENOMEM); } else { if (!p->vlc_state) p->vlc_state = av_malloc(p->context_count * sizeof(VlcState)); if (!p->vlc_state) return AVERROR(ENOMEM); } } if (fs->ac > 1) { //FIXME only redo if state_transition changed for (j = 1; j < 256; j++) { fs->c. one_state[ j] = f->state_transition[j]; fs->c.zero_state[256 - j] = 256 - fs->c.one_state[j]; } } return 0; } int ffv1_init_slices_state(FFV1Context *f) { int i, ret; for (i = 0; i < f->slice_count; i++) { FFV1Context *fs = f->slice_context[i]; if ((ret = ffv1_init_slice_state(f, fs)) < 0) return AVERROR(ENOMEM); } return 0; } av_cold int ffv1_init_slice_contexts(FFV1Context *f) { int i; f->slice_count = f->num_h_slices * f->num_v_slices; av_assert0(f->slice_count > 0); for (i = 0; i < f->slice_count; i++) { FFV1Context *fs = av_mallocz(sizeof(*fs)); int sx = i % f->num_h_slices; int sy = i / f->num_h_slices; int sxs = f->avctx->width * sx / f->num_h_slices; int sxe = f->avctx->width * (sx + 1) / f->num_h_slices; int sys = f->avctx->height * sy / f->num_v_slices; int sye = f->avctx->height * (sy + 1) / f->num_v_slices; if (!fs) return AVERROR(ENOMEM); f->slice_context[i] = fs; memcpy(fs, f, sizeof(*fs)); memset(fs->rc_stat2, 0, sizeof(fs->rc_stat2)); fs->slice_width = sxe - sxs; fs->slice_height = sye - sys; fs->slice_x = sxs; fs->slice_y = sys; fs->sample_buffer = av_malloc(3 * MAX_PLANES * (fs->width + 6) * sizeof(*fs->sample_buffer)); if (!fs->sample_buffer) return AVERROR(ENOMEM); } return 0; } int ffv1_allocate_initial_states(FFV1Context *f) { int i; for (i = 0; i < f->quant_table_count; i++) { f->initial_states[i] = av_malloc(f->context_count[i] * sizeof(*f->initial_states[i])); if (!f->initial_states[i]) return AVERROR(ENOMEM); memset(f->initial_states[i], 128, f->context_count[i] * sizeof(*f->initial_states[i])); } return 0; } void ffv1_clear_slice_state(FFV1Context *f, FFV1Context *fs) { int i, j; for (i = 0; i < f->plane_count; i++) { PlaneContext *p = &fs->plane[i]; p->interlace_bit_state[0] = 128; p->interlace_bit_state[1] = 128; if (fs->ac) { if (f->initial_states[p->quant_table_index]) { memcpy(p->state, f->initial_states[p->quant_table_index], CONTEXT_SIZE * p->context_count); } else memset(p->state, 128, CONTEXT_SIZE * p->context_count); } else { for (j = 0; j < p->context_count; j++) { p->vlc_state[j].drift = 0; p->vlc_state[j].error_sum = 4; //FFMAX((RANGE + 32)/64, 2); p->vlc_state[j].bias = 0; p->vlc_state[j].count = 1; } } } } av_cold int ffv1_close(AVCodecContext *avctx) { FFV1Context *s = avctx->priv_data; int i, j; if (avctx->codec->decode && s->picture.data[0]) avctx->release_buffer(avctx, &s->picture); if (avctx->codec->decode && s->last_picture.data[0]) avctx->release_buffer(avctx, &s->last_picture); for (j = 0; j < s->slice_count; j++) { FFV1Context *fs = s->slice_context[j]; for (i = 0; i < s->plane_count; i++) { PlaneContext *p = &fs->plane[i]; av_freep(&p->state); av_freep(&p->vlc_state); } av_freep(&fs->sample_buffer); } av_freep(&avctx->stats_out); for (j = 0; j < s->quant_table_count; j++) { av_freep(&s->initial_states[j]); for (i = 0; i < s->slice_count; i++) { FFV1Context *sf = s->slice_context[i]; av_freep(&sf->rc_stat2[j]); } av_freep(&s->rc_stat2[j]); } for (i = 0; i < s->slice_count; i++) av_freep(&s->slice_context[i]); return 0; }
kingvuplus/xbmc
lib/ffmpeg/libavcodec/ffv1.c
C
gpl-2.0
6,478
# # Makefile for ZTE FTM device drivers. # # Created by ZTE_BOOT_JIA_20120803 jia.jia # obj-$(CONFIG_ZTE_FTM) += ftm.o
MingoAllenII/draconis_msm8226
drivers/staging/zte_ftm/Makefile
Makefile
gpl-2.0
119
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Table: Column Toggle - jQuery Mobile Demos</title> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700"> <link rel="stylesheet" href="../css/themes/default/jquery.mobile-1.4.0.min.css"> <link rel="stylesheet" href="../_assets/css/jqm-demos.css"> <script src="../js/jquery.js"></script> <script src="../_assets/js/index.js"></script> <script src="../js/jquery.mobile-1.4.0.min.js"></script> </head> <body> <div data-role="page" class="jqm-demos" data-quicklinks="true"> <div data-role="header" class="jqm-header"> <h2><a href="../" title="jQuery Mobile Demos home"><img src="../_assets/img/jquery-logo.png" alt="jQuery Mobile"></a></h2> <p><span class="jqm-version"></span> Demos</p> <a href="#" class="jqm-navmenu-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-bars ui-nodisc-icon ui-alt-icon ui-btn-left">Menu</a> <a href="#" class="jqm-search-link ui-btn ui-btn-icon-notext ui-corner-all ui-icon-search ui-nodisc-icon ui-alt-icon ui-btn-right">Search</a> </div><!-- /header --> <div role="main" class="ui-content jqm-content"> <h1>Table: Column Toggle</h1> <p>The column toggle table mode selectively hides columns at narrower widths as a sensible default but also offers a menu to let users manually control which columns they want to see.</p> <h2>Column toggle basics</h2> <p>This table mode automatically hides less important columns at narrower widths and surfaces a button to open a menu that allows the user to choose what columns they want to see. In this mode, the author attempts to define which columns are most important to show across various widths by assigning a priority to each column.</p> <p>A user may choose to check as many columns as they want by tapping the "Columns..." button to open the column chooser popup. The popup contains a dynamically generated list of columns based on the table markup that can be checked and unchecked to adjust the visible columns. </p> <div data-demo-html="true"> <table data-role="table" id="table-column-toggle" data-mode="columntoggle" class="ui-responsive table-stroke"> <thead> <tr> <th data-priority="2">Rank</th> <th>Movie Title</th> <th data-priority="3">Year</th> <th data-priority="1"><abbr title="Rotten Tomato Rating">Rating</abbr></th> <th data-priority="5">Reviews</th> </tr> </thead> <tbody> <tr> <th>1</th> <td><a href="http://en.wikipedia.org/wiki/Citizen_Kane" data-rel="external">Citizen Kane</a></td> <td>1941</td> <td>100%</td> <td>74</td> </tr> <tr> <th>2</th> <td><a href="http://en.wikipedia.org/wiki/Casablanca_(film)" data-rel="external">Casablanca</a></td> <td>1942</td> <td>97%</td> <td>64</td> </tr> <tr> <th>3</th> <td><a href="http://en.wikipedia.org/wiki/The_Godfather" data-rel="external">The Godfather</a></td> <td>1972</td> <td>97%</td> <td>87</td> </tr> <tr> <th>4</th> <td><a href="http://en.wikipedia.org/wiki/Gone_with_the_Wind_(film)" data-rel="external">Gone with the Wind</a></td> <td>1939</td> <td>96%</td> <td>87</td> </tr> <tr> <th>5</th> <td><a href="http://en.wikipedia.org/wiki/Lawrence_of_Arabia_(film)" data-rel="external">Lawrence of Arabia</a></td> <td>1962</td> <td>94%</td> <td>87</td> </tr> <tr> <th>6</th> <td><a href="http://en.wikipedia.org/wiki/Dr._Strangelove" data-rel="external">Dr. Strangelove Or How I Learned to Stop Worrying and Love the Bomb</a></td> <td>1964</td> <td>92%</td> <td>74</td> </tr> <tr> <th>7</th> <td><a href="http://en.wikipedia.org/wiki/The_Graduate" data-rel="external">The Graduate</a></td> <td>1967</td> <td>91%</td> <td>122</td> </tr> <tr> <th>8</th> <td><a href="http://en.wikipedia.org/wiki/The_Wizard_of_Oz_(1939_film)" data-rel="external">The Wizard of Oz</a></td> <td>1939</td> <td>90%</td> <td>72</td> </tr> <tr> <th>9</th> <td><a href="http://en.wikipedia.org/wiki/Singin%27_in_the_Rain" data-rel="external">Singin' in the Rain</a></td> <td>1952</td> <td>89%</td> <td>85</td> </tr> <tr> <th>10</th> <td class="title"><a href="http://en.wikipedia.org/wiki/Inception" data-rel="external">Inception</a></td> <td>2010</td> <td>84%</td> <td>78</td> </tr> </tbody> </table> </div><!--/demo-html --> <h2>Applying column chooser mode to a table</h2> <p>The column chooser mode requires a <code>table</code> element with two attributes: <code>data-role=&quot;table&quot;</code> and <code>data-mode=&quot;columntoggle&quot;</code>. An <code>ID</code> attribute is also required on the table to associate it with the column chooser popup menu.</p> <pre><code> &lt;table <strong>data-role=&quot;table&quot; data-mode=&quot;columntoggle&quot; id=&quot;my-table&quot;</strong>&gt; </code></pre> <h2>Setting column priority</h2> <p>The table works by hiding and showing columns based on two inputs: available screen width or by the user checking and unchecking which columns to display in a column picker popup. Add <code>data-priority</code> attributes to each of the table headers of columns you want to responsively display and assign a priority (1 = highest, 6 = lowest). Any table header given a priority will be available in the column picker menu. </p> <p>To make a column <em>persistent</em> so it's not available for hiding, omit the <code>data-priority</code> attribute. This will make the column visible at all widths and won't be available in the column chooser menu.</p> <pre><code> &lt;th&gt;I&#x27;m critical and can&#x27;t be removed&lt;/th&gt; &lt;th <strong>data-priority=&quot;1&quot;</strong>&gt;I&#x27;m very important&lt;/th&gt; &lt;th <strong>data-priority=&quot;3&quot;</strong>&gt;I&#x27;m somewhat&lt;/th&gt; &lt;th <strong>data-priority=&quot;5&quot;</strong>&gt;I&#x27;m less important&lt;/th&gt; </code></pre> <p>You may use any priority naming convention and assign as many (or few) levels of priority for the columns. The plugin simply generates class names based on the values in the <code>data-priority</code> attribute so even though we default to using a numeric system of 1-6, any naming convention is possible. </p> <p>For example, if a priority of <code>data-priority="critical"</code> is added to the heading, a class of <code>ui-table-priority-critial</code> will be applied to each cell in that column. If a priority is assigned, the column will be made available for toggling in the column menu and the class will be added to each cell. The rest of the styling and media query creation is up to you to write in your custom stylesheet.</p> <h2>Theme & customization</h2> <p>The column chooser popup is opened via a button that is generated by the framework. The button's text is "Columns..." by default but can be set by adding the <code>data-column-btn-text</code> attribute to the table to the text string you want in the button. The button will inherit the theme from the content area, just like all buttons, but the theme can be set manually by adding the <code>data-column-btn-theme</code> attribute to any swatch letter in your theme.</p> <p>The table background is themed by adding <code>class="ui-body-d"</code> to the table element. The table header is given a themed appearance by adding the <code>class="ui-bar-d"</code> to the header row. The striped rows are created by adding the <code>table-stripe</code> class to the table element.</p> <div data-demo-html="true"> <table data-role="table" id="table-custom-2" data-mode="columntoggle" class="ui-body-d ui-shadow table-stripe ui-responsive" data-column-btn-theme="b" data-column-btn-text="Columns to display..." data-column-popup-theme="a"> <thead> <tr class="ui-bar-d"> <th data-priority="2">Rank</th> <th>Movie Title</th> <th data-priority="3">Year</th> <th data-priority="1"><abbr title="Rotten Tomato Rating">Rating</abbr></th> <th data-priority="5">Reviews</th> </tr> </thead> <tbody> <tr> <th>1</th> <td><a href="http://en.wikipedia.org/wiki/Citizen_Kane" data-rel="external">Citizen Kane</a></td> <td>1941</td> <td>100%</td> <td>74</td> </tr> <tr> <th>2</th> <td><a href="http://en.wikipedia.org/wiki/Casablanca_(film)" data-rel="external">Casablanca</a></td> <td>1942</td> <td>97%</td> <td>64</td> </tr> <tr> <th>3</th> <td><a href="http://en.wikipedia.org/wiki/The_Godfather" data-rel="external">The Godfather</a></td> <td>1972</td> <td>97%</td> <td>87</td> </tr> <tr> <th>4</th> <td><a href="http://en.wikipedia.org/wiki/Gone_with_the_Wind_(film)" data-rel="external">Gone with the Wind</a></td> <td>1939</td> <td>96%</td> <td>87</td> </tr> <tr> <th>5</th> <td><a href="http://en.wikipedia.org/wiki/Lawrence_of_Arabia_(film)" data-rel="external">Lawrence of Arabia</a></td> <td>1962</td> <td>94%</td> <td>87</td> </tr> <tr> <th>6</th> <td><a href="http://en.wikipedia.org/wiki/Dr._Strangelove" data-rel="external">Dr. Strangelove Or How I Learned to Stop Worrying and Love the Bomb</a></td> <td>1964</td> <td>92%</td> <td>74</td> </tr> <tr> <th>7</th> <td><a href="http://en.wikipedia.org/wiki/The_Graduate" data-rel="external">The Graduate</a></td> <td>1967</td> <td>91%</td> <td>122</td> </tr> <tr> <th>8</th> <td><a href="http://en.wikipedia.org/wiki/The_Wizard_of_Oz_(1939_film)" data-rel="external">The Wizard of Oz</a></td> <td>1939</td> <td>90%</td> <td>72</td> </tr> <tr> <th>9</th> <td><a href="http://en.wikipedia.org/wiki/Singin%27_in_the_Rain" data-rel="external">Singin' in the Rain</a></td> <td>1952</td> <td>89%</td> <td>85</td> </tr> <tr> <th>10</th> <td class="title"><a href="http://en.wikipedia.org/wiki/Inception" data-rel="external">Inception</a></td> <td>2010</td> <td>84%</td> <td>78</td> </tr> </tbody> </table> </div><!-- /data-demo --> <h2>Making the table responsive</h2> <p>The styles for all columns that have priorities assigned (1-6) start as <code>display:none</code> in the structure stylesheet since we're taking a mobile-first approach to our styles. This means that only columns that should be persistent are visible in the styles to start.</p> <p>The framework does not automatically include the the media queries to progressively display columns at wider widths. We do this to make it easier for developers to customize the media query widths for each priority level.</p> <p>Media queries add the responsive behavior to show and hide columns by priority. Each media query is written using <code>min-width</code> widths so they build on top of each other. The widths are set in em units so they respond to font size changes. To calculate a pixel withs in em units, divide the target width by 16 (pixels) - it's that easy.</p> <p>Inside each media query, we override the <code>display:none</code> style properties set on all the priority columns in the basic styles to <code>display:table-cell</code> so they become visible again and act as a table.</p> <p>To customize the breakpoints, copy the following style block into your custom style overrides and adjust the <code>min-width</code> media query values for each priority level to specify where various priority columns should appear.</p> <p>In the example styles below for a <code> my-custom-class</code> class on the table, the priority 1 columns are shown first, at widths above <code>20em</code> (320px), then priority 2 kicks in above <code>30em</code> (480px) and so on up to wide desktop widths with priority 6. Feel free to change these breakpoints in your stylesheet and choose how many priority levels you'd like to use.</p> <pre><code> <strong>/* Show priority 1 at 320px (20em x 16px) */</strong> @media screen and (min-width: 20em) { .my-custom-class th.ui-table-priority-1, .my-custom-class td.ui-table-priority-1 { display: table-cell; } } <strong>/* Show priority 2 at 480px (30em x 16px) */</strong> @media screen and (min-width: 30em) { .my-custom-class th.ui-table-priority-2, .my-custom-class td.ui-table-priority-2 { display: table-cell; } } ...more breakpoints... </code></pre> <p>Due to CSS specificity, you will also need to include the class definitions for the hidden and visible states <em>after</em> the custom breakpoints in your custom stylesheet so be sure to include these as well:</p> <pre><code> /* Manually hidden */ .my-custom-class th.ui-table-cell-hidden, .my-custom-class td.ui-table-cell-hidden { display: none; } /* Manually shown */ .my-custom-class th.ui-table-cell-visible, .my-custom-class td.ui-table-cell-visible { display: table-cell; } </code></pre> <h2>Applying a preset breakpoint</h2> <p>Even though we strongly encourage you to write custom breakpoints yourself, the framework includes a set of pre-configured breakpoints for each of the six priority levels that you can use if they happen work well for your content.</p> <p>These breakpoints can be applied by adding a <code>class="ui-responsive"</code> to the table element. Here is an example of a table with this class added:</p> <pre><code> &lt;table data-role=&quot;table&quot; <strong>class=&quot;ui-responsive&quot;</strong> data-mode=&quot;columntoggle&quot; id=&quot;my-table&quot;&gt; </code></pre> <p>The six preset breakpoint classes included in the column toggle stylesheet use regular increments of 10em (160 pixels). Here is a summary of the breakpoints assigned to each priority in the preset styles: </p> <dl> <dt><code>data-priority="1"</code></dt><dd> Displays the column at 320px (20em) </dd> <dt><code>data-priority="2"</code></dt><dd> Displays the column at 480px (30em) </dd> <dt><code>data-priority="3"</code></dt><dd> Displays the column at 640px (40em) </dd> <dt><code>data-priority="4"</code></dt><dd> Displays the column at 800px (50em) </dd> <dt><code>data-priority="5"</code></dt><dd> Displays the column at 960px (60em) </dd> <dt><code>data-priority="6"</code></dt><dd> Displays the column at 1,120px (70em) </dd> </dl> <p>If these preset breakpoints don't work for your content and layout needs, we recommend that you create custom breakpoints to fine tune the styles. </p> <h2>Grouped column headers</h2> <p>It's fairly common to need to logically group multiple columns under a heading group for financial or scientific data. The framework can support the most simple version of this by allowing for two rows of table headers (<code>TH</code>), with the first row containing simple <code>colspan</code> attributes to group the columns below. In this configuration, the framework will parse the first row only for the priority and expose these heading groups as the options in the column chooser popup. In this configuration, the second heading will not be exposed as columns that can be hidden or shown independently of the groupings in the chooser.</p> </div><!-- /content --> <div data-role="panel" class="jqm-navmenu-panel" data-position="left" data-display="overlay" data-theme="a"> <ul class="jqm-list ui-alt-icon ui-nodisc-icon"> <li data-filtertext="demos homepage" data-icon="home"><a href=".././">Home</a></li> <li data-filtertext="introduction overview getting started"><a href="../intro/" data-ajax="false">Introduction</a></li> <li data-filtertext="buttons button markup buttonmarkup method anchor link button element"><a href="../button-markup/" data-ajax="false">Buttons</a></li> <li data-filtertext="form button widget input button submit reset"><a href="../button/" data-ajax="false">Button widget</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Checkboxradio widget</h3> <ul> <li data-filtertext="form checkboxradio widget checkbox input checkboxes controlgroups"><a href="../checkboxradio-checkbox/" data-ajax="false">Checkboxes</a></li> <li data-filtertext="form checkboxradio widget radio input radio buttons controlgroups"><a href="../checkboxradio-radio/" data-ajax="false">Radio buttons</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Collapsible (set) widget</h3> <ul> <li data-filtertext="collapsibles content formatting"><a href="../collapsible/" data-ajax="false">Collapsible</a></li> <li data-filtertext="dynamic collapsible set accordion append expand"><a href="../collapsible-dynamic/" data-ajax="false">Dynamic collapsibles</a></li> <li data-filtertext="accordions collapsible set widget content formatting grouped collapsibles"><a href="../collapsibleset/" data-ajax="false">Collapsible set</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Controlgroup widget</h3> <ul> <li data-filtertext="controlgroups selectmenu checkboxradio input grouped buttons horizontal vertical"><a href="../controlgroup/" data-ajax="false">Controlgroup</a></li> <li data-filtertext="dynamic controlgroup dynamically add buttons"><a href="../controlgroup-dynamic/" data-ajax="false">Dynamic controlgroups</a></li> </ul> </li> <li data-filtertext="form datepicker widget date input"><a href="../datepicker/" data-ajax="false">Datepicker</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Events</h3> <ul> <li data-filtertext="swipe to delete list items listviews swipe events"><a href="../swipe-list/" data-ajax="false">Swipe list items</a></li> <li data-filtertext="swipe to navigate swipe page navigation swipe events"><a href="../swipe-page/" data-ajax="false">Swipe page navigation</a></li> </ul> </li> <li data-filtertext="filterable filter elements sorting searching listview table"><a href="../filterable/" data-ajax="false">Filterable widget</a></li> <li data-filtertext="form flipswitch widget flip toggle switch binary select checkbox input"><a href="../flipswitch/" data-ajax="false">Flipswitch widget</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Forms</h3> <ul> <li data-filtertext="forms text checkbox radio range button submit reset inputs selects textarea slider flipswitch label form elements"><a href="../forms/" data-ajax="false">Forms</a></li> <li data-filtertext="form hide labels hidden accessible ui-hidden-accessible forms"><a href="../forms-label-hidden-accessible/" data-ajax="false">Hide labels</a></li> <li data-filtertext="form field containers fieldcontain ui-field-contain forms"><a href="../forms-field-contain/" data-ajax="false">Field containers</a></li> <li data-filtertext="forms disabled form elements"><a href="../forms-disabled/" data-ajax="false">Forms disabled</a></li> <li data-filtertext="forms gallery examples overview forms text checkbox radio range button submit reset inputs selects textarea slider flipswitch label form elements"><a href="../forms-gallery/" data-ajax="false">Forms gallery</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Grids</h3> <ul> <li data-filtertext="grids columns blocks content formatting rwd responsive css framework"><a href="../grids/" data-ajax="false">Grids</a></li> <li data-filtertext="buttons in grids css framework"><a href="../grids-buttons/" data-ajax="false">Buttons in grids</a></li> <li data-filtertext="custom responsive grids rwd css framework"><a href="../grids-custom-responsive/" data-ajax="false">Custom responsive grids</a></li> </ul> </li> <li data-filtertext="blocks content formatting sections heading"><a href="../body-bar-classes/" data-ajax="false">Grouping and dividing content</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Icons</h3> <ul> <li data-filtertext="button icons svg disc alt custom icon position"><a href="../icons/" data-ajax="false">Icons</a></li> <li data-filtertext=""><a href="../icons-grunticon/" data-ajax="false">Grunticon loader</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Listview widget</h3> <ul> <li data-filtertext="listview widget thumbnails icons nested split button collapsible ul ol"><a href="../listview/" data-ajax="false">Listview</a></li> <li data-filtertext="autocomplete filterable reveal listview filtertextbeforefilter placeholder"><a href="../listview-autocomplete/" data-ajax="false">Listview autocomplete</a></li> <li data-filtertext="autocomplete filterable reveal listview remote data filtertextbeforefilter placeholder"><a href="../listview-autocomplete-remote/" data-ajax="false">Listview autocomplete remote data</a></li> <li data-filtertext="autodividers anchor jump scroll linkbars listview lists ul ol"><a href="../listview-autodividers-linkbar/" data-ajax="false">Listview autodividers linkbar</a></li> <li data-filtertext="listview autodividers selector autodividersselector lists ul ol"><a href="../listview-autodividers-selector/" data-ajax="false">Listview autodividers selector</a></li> <li data-filtertext="listview nested list items"><a href="../listview-nested-lists/" data-ajax="false">Listview Nested Listviews</a></li> <li data-filtertext="listview collapsible list items flat"><a href="../listview-collapsible-item-flat/" data-ajax="false">Listview collapsible list items (flat)</a></li> <li data-filtertext="listview collapsible list indented"><a href="../listview-collapsible-item-indented/" data-ajax="false">Listview collapsible list items (indented)</a></li> <li data-filtertext="grid listview responsive grids responsive listviews lists ul"><a href="../listview-grid/" data-ajax="false">Listview responsive grid</a></li> </ul> </li> <li data-filtertext="loader widget page loading navigation overlay spinner"><a href="../loader/" data-ajax="false">Loader widget</a></li> <li data-filtertext="navbar widget navmenu toolbars header footer"><a href="../navbar/" data-ajax="false">Navbar widget</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Navigation</h3> <ul> <li data-filtertext="ajax navigation navigate widget history event method"><a href="../navigation/" data-ajax="false">Navigation</a></li> <li data-filtertext="linking pages page links navigation ajax prefetch cache"><a href="../navigation-linking-pages/" data-ajax="false">Linking pages</a></li> <li data-filtertext="php redirect server redirection server-side navigation"><a href="../navigation-php-redirect/" data-ajax="false">PHP redirect demo</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Pages</h3> <ul> <li data-filtertext="pages page widget ajax navigation"><a href="../pages/" data-ajax="false">Pages</a></li> <li data-filtertext="single page"><a href="../pages-single-page/" data-ajax="false">Single page</a></li> <li data-filtertext="multipage multi-page page"><a href="../pages-multi-page/" data-ajax="false">Multi-page template</a></li> <li data-filtertext="dialog page widget modal popup"><a href="../pages-dialog/" data-ajax="false">Dialog page</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Panel widget</h3> <ul> <li data-filtertext="panel widget sliding panels reveal push overlay responsive"><a href="../panel/" data-ajax="false">Panel</a></li> <li data-filtertext=""><a href="../panel-external/" data-ajax="false">External panels</a></li> <li data-filtertext="panel "><a href="../panel-fixed/" data-ajax="false">Fixed panels</a></li> <li data-filtertext="panel slide panels sliding panels shadow rwd responsive breakpoint"><a href="../panel-responsive/" data-ajax="false">Panels responsive</a></li> <li data-filtertext="panel custom style custom panel width reveal shadow listview panel styling page background wrapper"><a href="../panel-styling/" data-ajax="false">Custom panel style</a></li> <li data-filtertext="panel open on swipe"><a href="../panel-swipe-open/" data-ajax="false">Panel open on swipe</a></li> <li data-filtertext="panels outside page internal external toolbars"><a href="../panel-external-internal/" data-ajax="false">Panel external and internal</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Popup widget</h3> <ul> <li data-filtertext="popup widget popups dialog modal transition tooltip lightbox form overlay screen flip pop fade transition"><a href="../popup/" data-ajax="false">Popup</a></li> <li data-filtertext="popup alignment position"><a href="../popup-alignment/" data-ajax="false">Popup alignment</a></li> <li data-filtertext="popup arrow size popups popover"><a href="../popup-arrow-size/" data-ajax="false">Popup arrow size</a></li> <li data-filtertext="dynamic popups popup images lightbox"><a href="../popup-dynamic/" data-ajax="false">Dynamic popups</a></li> <li data-filtertext="popups with iframes scaling"><a href="../popup-iframe/" data-ajax="false">Popups with iframes</a></li> <li data-filtertext="popup image scaling"><a href="../popup-image-scaling/" data-ajax="false">Popup image scaling</a></li> <li data-filtertext="external popup outside multi-page"><a href="../popup-outside-multipage" data-ajax="false">Popup outside multi-page</a></li> </ul> </li> <li data-filtertext="form rangeslider widget dual sliders dual handle sliders range input"><a href="../rangeslider/" data-ajax="false">Rangeslider widget</a></li> <li data-filtertext="responsive web design rwd adaptive progressive enhancement PE accessible mobile breakpoints media query media queries"><a href="../rwd/" data-ajax="false">Responsive Web Design</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Selectmenu widget</h3> <ul> <li data-filtertext="form selectmenu widget select input custom select menu selects"><a href="../selectmenu/" data-ajax="false">Selectmenu</a></li> <li data-filtertext="form custom select menu selectmenu widget custom menu option optgroup multiple selects"><a href="../selectmenu-custom/" data-ajax="false">Custom select menu</a></li> <li data-filtertext="filterable select filter popup dialog"><a href="../selectmenu-custom-filter/" data-ajax="false">Custom select menu with filter</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Slider widget</h3> <ul> <li data-filtertext="form slider widget range input single sliders"><a href="../slider/" data-ajax="false">Slider</a></li> <li data-filtertext="form slider widget flipswitch slider binary select flip toggle switch"><a href="../slider-flipswitch/" data-ajax="false">Slider flip toggle switch</a></li> <li data-filtertext="form slider tooltip handle value input range sliders"><a href="../slider-tooltip/" data-ajax="false">Slider tooltip</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Table widget</h3> <ul> <li data-filtertext="table widget reflow column toggle th td responsive tables rwd hide show tabular"><a href="../table-column-toggle/" data-ajax="false">Table Column Toggle</a></li> <li data-filtertext="table column toggle phone comparison demo"><a href="../table-column-toggle-example/" data-ajax="false">Table Column Toggle demo</a></li> <li data-filtertext="responsive tables table column toggle heading groups rwd breakpoint"><a href="../table-column-toggle-heading-groups/" data-ajax="false">Table Column Toggle heading groups</a></li> <li data-filtertext="responsive tables table column toggle hide rwd breakpoint customization options"><a href="../table-column-toggle-options/" data-ajax="false">Table Column Toggle options</a></li> <li data-filtertext="table reflow th td responsive rwd columns tabular"><a href="../table-reflow/" data-ajax="false">Table Reflow</a></li> <li data-filtertext="responsive tables table reflow heading groups rwd breakpoint"><a href="../table-reflow-heading-groups/" data-ajax="false">Table Reflow heading groups</a></li> <li data-filtertext="responsive tables table reflow stripes strokes table style"><a href="../table-reflow-stripes-strokes/" data-ajax="false">Table Reflow stripes and strokes</a></li> <li data-filtertext="responsive tables table reflow stack custom styles"><a href="../table-reflow-styling/" data-ajax="false">Table Reflow custom styles</a></li> </ul> </li> <li data-filtertext="ui tabs widget"><a href="../tabs/" data-ajax="false">Tabs widget</a></li> <li data-filtertext="form textinput widget text input textarea number date time tel email file color password"><a href="../textinput/" data-ajax="false">Textinput widget</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Theming</h3> <ul> <li data-filtertext="default theme swatches theming style css"><a href="../theme-default/" data-ajax="false">Default theme</a></li> <li data-filtertext="classic theme old theme swatches theming style css"><a href="../theme-classic/" data-ajax="false">Classic theme</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Toolbar widget</h3> <ul> <li data-filtertext="toolbar widget header footer toolbars fixed fullscreen external sections"><a href="../toolbar/" data-ajax="false">Toolbar</a></li> <li data-filtertext="dynamic toolbars dynamically add toolbar header footer"><a href="../toolbar-dynamic/" data-ajax="false">Dynamic toolbars</a></li> <li data-filtertext="external toolbars header footer"><a href="../toolbar-external/" data-ajax="false">External toolbars</a></li> <li data-filtertext="fixed toolbars header footer"><a href="../toolbar-fixed/" data-ajax="false">Fixed toolbars</a></li> <li data-filtertext="fixed fullscreen toolbars header footer"><a href="../toolbar-fixed-fullscreen/" data-ajax="false">Fullscreen toolbars</a></li> <li data-filtertext="external fixed toolbars header footer"><a href="../toolbar-fixed-external/" data-ajax="false">Fixed external toolbars</a></li> <li data-filtertext="external persistent toolbars header footer navbar navmenu"><a href="../toolbar-fixed-persistent/" data-ajax="false">Persistent toolbars</a></li> <li data-filtertext="external ajax optimized toolbars persistent toolbars header footer navbar"><a href="../toolbar-fixed-persistent-optimized/" data-ajax="false">AJAX optimized toolbars</a></li> <li data-filtertext="form in toolbars header footer"><a href="../toolbar-fixed-forms/" data-ajax="false">Form in toolbar</a></li> </ul> </li> <li data-filtertext="page transitions animated pages popup navigation flip slide fade pop"><a href="../transitions/" data-ajax="false">Transitions</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>3rd party API demos</h3> <ul> <li data-filtertext="backbone requirejs navigation router"><a href="../backbone-requirejs/" data-ajax="false">Backbone RequireJS</a></li> <li data-filtertext="google maps geolocation demo"><a href="../map-geolocation/" data-ajax="false">Google Maps geolocation</a></li> <li data-filtertext="google maps hybrid"><a href="../map-list-toggle/" data-ajax="false">Google Maps list toggle</a></li> </ul> </li> </ul> </div><!-- /panel --> <div data-role="footer" data-position="fixed" data-tap-toggle="false" class="jqm-footer"> <p>jQuery Mobile Demos version <span class="jqm-version"></span></p> <p>Copyright 2013 The jQuery Foundation</p> </div><!-- /footer --> <!-- TODO: This should become an external panel so we can add input to markup (unique ID) --> <div data-role="panel" class="jqm-search-panel" data-position="right" data-display="overlay" data-theme="a"> <div class="jqm-search"> <ul class="jqm-list" data-filter-placeholder="Search demos..." data-filter-reveal="true"> <li data-filtertext="demos homepage" data-icon="home"><a href=".././">Home</a></li> <li data-filtertext="introduction overview getting started"><a href="../intro/" data-ajax="false">Introduction</a></li> <li data-filtertext="buttons button markup buttonmarkup method anchor link button element"><a href="../button-markup/" data-ajax="false">Buttons</a></li> <li data-filtertext="form button widget input button submit reset"><a href="../button/" data-ajax="false">Button widget</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Checkboxradio widget</h3> <ul> <li data-filtertext="form checkboxradio widget checkbox input checkboxes controlgroups"><a href="../checkboxradio-checkbox/" data-ajax="false">Checkboxes</a></li> <li data-filtertext="form checkboxradio widget radio input radio buttons controlgroups"><a href="../checkboxradio-radio/" data-ajax="false">Radio buttons</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Collapsible (set) widget</h3> <ul> <li data-filtertext="collapsibles content formatting"><a href="../collapsible/" data-ajax="false">Collapsible</a></li> <li data-filtertext="dynamic collapsible set accordion append expand"><a href="../collapsible-dynamic/" data-ajax="false">Dynamic collapsibles</a></li> <li data-filtertext="accordions collapsible set widget content formatting grouped collapsibles"><a href="../collapsibleset/" data-ajax="false">Collapsible set</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Controlgroup widget</h3> <ul> <li data-filtertext="controlgroups selectmenu checkboxradio input grouped buttons horizontal vertical"><a href="../controlgroup/" data-ajax="false">Controlgroup</a></li> <li data-filtertext="dynamic controlgroup dynamically add buttons"><a href="../controlgroup-dynamic/" data-ajax="false">Dynamic controlgroups</a></li> </ul> </li> <li data-filtertext="form datepicker widget date input"><a href="../datepicker/" data-ajax="false">Datepicker</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Events</h3> <ul> <li data-filtertext="swipe to delete list items listviews swipe events"><a href="../swipe-list/" data-ajax="false">Swipe list items</a></li> <li data-filtertext="swipe to navigate swipe page navigation swipe events"><a href="../swipe-page/" data-ajax="false">Swipe page navigation</a></li> </ul> </li> <li data-filtertext="filterable filter elements sorting searching listview table"><a href="../filterable/" data-ajax="false">Filterable widget</a></li> <li data-filtertext="form flipswitch widget flip toggle switch binary select checkbox input"><a href="../flipswitch/" data-ajax="false">Flipswitch widget</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Forms</h3> <ul> <li data-filtertext="forms text checkbox radio range button submit reset inputs selects textarea slider flipswitch label form elements"><a href="../forms/" data-ajax="false">Forms</a></li> <li data-filtertext="form hide labels hidden accessible ui-hidden-accessible forms"><a href="../forms-label-hidden-accessible/" data-ajax="false">Hide labels</a></li> <li data-filtertext="form field containers fieldcontain ui-field-contain forms"><a href="../forms-field-contain/" data-ajax="false">Field containers</a></li> <li data-filtertext="forms disabled form elements"><a href="../forms-disabled/" data-ajax="false">Forms disabled</a></li> <li data-filtertext="forms gallery examples overview forms text checkbox radio range button submit reset inputs selects textarea slider flipswitch label form elements"><a href="../forms-gallery/" data-ajax="false">Forms gallery</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Grids</h3> <ul> <li data-filtertext="grids columns blocks content formatting rwd responsive css framework"><a href="../grids/" data-ajax="false">Grids</a></li> <li data-filtertext="buttons in grids css framework"><a href="../grids-buttons/" data-ajax="false">Buttons in grids</a></li> <li data-filtertext="custom responsive grids rwd css framework"><a href="../grids-custom-responsive/" data-ajax="false">Custom responsive grids</a></li> </ul> </li> <li data-filtertext="blocks content formatting sections heading"><a href="../body-bar-classes/" data-ajax="false">Grouping and dividing content</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Icons</h3> <ul> <li data-filtertext="button icons svg disc alt custom icon position"><a href="../icons/" data-ajax="false">Icons</a></li> <li data-filtertext=""><a href="../icons-grunticon/" data-ajax="false">Grunticon loader</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Listview widget</h3> <ul> <li data-filtertext="listview widget thumbnails icons nested split button collapsible ul ol"><a href="../listview/" data-ajax="false">Listview</a></li> <li data-filtertext="autocomplete filterable reveal listview filtertextbeforefilter placeholder"><a href="../listview-autocomplete/" data-ajax="false">Listview autocomplete</a></li> <li data-filtertext="autocomplete filterable reveal listview remote data filtertextbeforefilter placeholder"><a href="../listview-autocomplete-remote/" data-ajax="false">Listview autocomplete remote data</a></li> <li data-filtertext="autodividers anchor jump scroll linkbars listview lists ul ol"><a href="../listview-autodividers-linkbar/" data-ajax="false">Listview autodividers linkbar</a></li> <li data-filtertext="listview autodividers selector autodividersselector lists ul ol"><a href="../listview-autodividers-selector/" data-ajax="false">Listview autodividers selector</a></li> <li data-filtertext="listview nested list items"><a href="../listview-nested-lists/" data-ajax="false">Listview Nested Listviews</a></li> <li data-filtertext="listview collapsible list items flat"><a href="../listview-collapsible-item-flat/" data-ajax="false">Listview collapsible list items (flat)</a></li> <li data-filtertext="listview collapsible list indented"><a href="../listview-collapsible-item-indented/" data-ajax="false">Listview collapsible list items (indented)</a></li> <li data-filtertext="grid listview responsive grids responsive listviews lists ul"><a href="../listview-grid/" data-ajax="false">Listview responsive grid</a></li> </ul> </li> <li data-filtertext="loader widget page loading navigation overlay spinner"><a href="../loader/" data-ajax="false">Loader widget</a></li> <li data-filtertext="navbar widget navmenu toolbars header footer"><a href="../navbar/" data-ajax="false">Navbar widget</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Navigation</h3> <ul> <li data-filtertext="ajax navigation navigate widget history event method"><a href="../navigation/" data-ajax="false">Navigation</a></li> <li data-filtertext="linking pages page links navigation ajax prefetch cache"><a href="../navigation-linking-pages/" data-ajax="false">Linking pages</a></li> <li data-filtertext="php redirect server redirection server-side navigation"><a href="../navigation-php-redirect/" data-ajax="false">PHP redirect demo</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Pages</h3> <ul> <li data-filtertext="pages page widget ajax navigation"><a href="../pages/" data-ajax="false">Pages</a></li> <li data-filtertext="single page"><a href="../pages-single-page/" data-ajax="false">Single page</a></li> <li data-filtertext="multipage multi-page page"><a href="../pages-multi-page/" data-ajax="false">Multi-page template</a></li> <li data-filtertext="dialog page widget modal popup"><a href="../pages-dialog/" data-ajax="false">Dialog page</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Panel widget</h3> <ul> <li data-filtertext="panel widget sliding panels reveal push overlay responsive"><a href="../panel/" data-ajax="false">Panel</a></li> <li data-filtertext=""><a href="../panel-external/" data-ajax="false">External panels</a></li> <li data-filtertext="panel "><a href="../panel-fixed/" data-ajax="false">Fixed panels</a></li> <li data-filtertext="panel slide panels sliding panels shadow rwd responsive breakpoint"><a href="../panel-responsive/" data-ajax="false">Panels responsive</a></li> <li data-filtertext="panel custom style custom panel width reveal shadow listview panel styling page background wrapper"><a href="../panel-styling/" data-ajax="false">Custom panel style</a></li> <li data-filtertext="panel open on swipe"><a href="../panel-swipe-open/" data-ajax="false">Panel open on swipe</a></li> <li data-filtertext="panels outside page internal external toolbars"><a href="../panel-external-internal/" data-ajax="false">Panel external and internal</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Popup widget</h3> <ul> <li data-filtertext="popup widget popups dialog modal transition tooltip lightbox form overlay screen flip pop fade transition"><a href="../popup/" data-ajax="false">Popup</a></li> <li data-filtertext="popup alignment position"><a href="../popup-alignment/" data-ajax="false">Popup alignment</a></li> <li data-filtertext="popup arrow size popups popover"><a href="../popup-arrow-size/" data-ajax="false">Popup arrow size</a></li> <li data-filtertext="dynamic popups popup images lightbox"><a href="../popup-dynamic/" data-ajax="false">Dynamic popups</a></li> <li data-filtertext="popups with iframes scaling"><a href="../popup-iframe/" data-ajax="false">Popups with iframes</a></li> <li data-filtertext="popup image scaling"><a href="../popup-image-scaling/" data-ajax="false">Popup image scaling</a></li> <li data-filtertext="external popup outside multi-page"><a href="../popup-outside-multipage" data-ajax="false">Popup outside multi-page</a></li> </ul> </li> <li data-filtertext="form rangeslider widget dual sliders dual handle sliders range input"><a href="../rangeslider/" data-ajax="false">Rangeslider widget</a></li> <li data-filtertext="responsive web design rwd adaptive progressive enhancement PE accessible mobile breakpoints media query media queries"><a href="../rwd/" data-ajax="false">Responsive Web Design</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Selectmenu widget</h3> <ul> <li data-filtertext="form selectmenu widget select input custom select menu selects"><a href="../selectmenu/" data-ajax="false">Selectmenu</a></li> <li data-filtertext="form custom select menu selectmenu widget custom menu option optgroup multiple selects"><a href="../selectmenu-custom/" data-ajax="false">Custom select menu</a></li> <li data-filtertext="filterable select filter popup dialog"><a href="../selectmenu-custom-filter/" data-ajax="false">Custom select menu with filter</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Slider widget</h3> <ul> <li data-filtertext="form slider widget range input single sliders"><a href="../slider/" data-ajax="false">Slider</a></li> <li data-filtertext="form slider widget flipswitch slider binary select flip toggle switch"><a href="../slider-flipswitch/" data-ajax="false">Slider flip toggle switch</a></li> <li data-filtertext="form slider tooltip handle value input range sliders"><a href="../slider-tooltip/" data-ajax="false">Slider tooltip</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Table widget</h3> <ul> <li data-filtertext="table widget reflow column toggle th td responsive tables rwd hide show tabular"><a href="../table-column-toggle/" data-ajax="false">Table Column Toggle</a></li> <li data-filtertext="table column toggle phone comparison demo"><a href="../table-column-toggle-example/" data-ajax="false">Table Column Toggle demo</a></li> <li data-filtertext="responsive tables table column toggle heading groups rwd breakpoint"><a href="../table-column-toggle-heading-groups/" data-ajax="false">Table Column Toggle heading groups</a></li> <li data-filtertext="responsive tables table column toggle hide rwd breakpoint customization options"><a href="../table-column-toggle-options/" data-ajax="false">Table Column Toggle options</a></li> <li data-filtertext="table reflow th td responsive rwd columns tabular"><a href="../table-reflow/" data-ajax="false">Table Reflow</a></li> <li data-filtertext="responsive tables table reflow heading groups rwd breakpoint"><a href="../table-reflow-heading-groups/" data-ajax="false">Table Reflow heading groups</a></li> <li data-filtertext="responsive tables table reflow stripes strokes table style"><a href="../table-reflow-stripes-strokes/" data-ajax="false">Table Reflow stripes and strokes</a></li> <li data-filtertext="responsive tables table reflow stack custom styles"><a href="../table-reflow-styling/" data-ajax="false">Table Reflow custom styles</a></li> </ul> </li> <li data-filtertext="ui tabs widget"><a href="../tabs/" data-ajax="false">Tabs widget</a></li> <li data-filtertext="form textinput widget text input textarea number date time tel email file color password"><a href="../textinput/" data-ajax="false">Textinput widget</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Theming</h3> <ul> <li data-filtertext="default theme swatches theming style css"><a href="../theme-default/" data-ajax="false">Default theme</a></li> <li data-filtertext="classic theme old theme swatches theming style css"><a href="../theme-classic/" data-ajax="false">Classic theme</a></li> </ul> </li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>Toolbar widget</h3> <ul> <li data-filtertext="toolbar widget header footer toolbars fixed fullscreen external sections"><a href="../toolbar/" data-ajax="false">Toolbar</a></li> <li data-filtertext="dynamic toolbars dynamically add toolbar header footer"><a href="../toolbar-dynamic/" data-ajax="false">Dynamic toolbars</a></li> <li data-filtertext="external toolbars header footer"><a href="../toolbar-external/" data-ajax="false">External toolbars</a></li> <li data-filtertext="fixed toolbars header footer"><a href="../toolbar-fixed/" data-ajax="false">Fixed toolbars</a></li> <li data-filtertext="fixed fullscreen toolbars header footer"><a href="../toolbar-fixed-fullscreen/" data-ajax="false">Fullscreen toolbars</a></li> <li data-filtertext="external fixed toolbars header footer"><a href="../toolbar-fixed-external/" data-ajax="false">Fixed external toolbars</a></li> <li data-filtertext="external persistent toolbars header footer navbar navmenu"><a href="../toolbar-fixed-persistent/" data-ajax="false">Persistent toolbars</a></li> <li data-filtertext="external ajax optimized toolbars persistent toolbars header footer navbar"><a href="../toolbar-fixed-persistent-optimized/" data-ajax="false">AJAX optimized toolbars</a></li> <li data-filtertext="form in toolbars header footer"><a href="../toolbar-fixed-forms/" data-ajax="false">Form in toolbar</a></li> </ul> </li> <li data-filtertext="page transitions animated pages popup navigation flip slide fade pop"><a href="../transitions/" data-ajax="false">Transitions</a></li> <li data-role="collapsible" data-collapsed-icon="carat-d" data-expanded-icon="carat-u" data-iconpos="right" data-inset="false"> <h3>3rd party API demos</h3> <ul> <li data-filtertext="backbone requirejs navigation router"><a href="../backbone-requirejs/" data-ajax="false">Backbone RequireJS</a></li> <li data-filtertext="google maps geolocation demo"><a href="../map-geolocation/" data-ajax="false">Google Maps geolocation</a></li> <li data-filtertext="google maps hybrid"><a href="../map-list-toggle/" data-ajax="false">Google Maps list toggle</a></li> </ul> </li> </ul> </div> </div><!-- /panel --> </div><!-- /page --> </body> </html>
arthurtofani/libr-reader
www/jquerymob/demos/table-column-toggle/index.html
HTML
gpl-2.0
52,964
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * * @summary converted from VM Testbase nsk/jvmti/GetThreadState/thrstat004. * VM Testbase keywords: [quick, jpda, jvmti, noras] * VM Testbase readme: * DESCRIPTION * The test exercises JVMTI function * GetThreadState(thread, threadStatusPtr) * The test checks if the function returns: * - JVMTI_ERROR_NULL_POINTER if threadStatusPtr is null * - JVMTI_ERROR_NULL_POINTER if suspendStatusPtr is null * - JVMTI_ERROR_INVALID_THREAD if thread is not a thread object * COMMENTS * Converted the test to use GetThreadState instead of GetThreadStatus. * Ported from JVMDI. * * @library /vmTestbase * /test/lib * @run driver jdk.test.lib.FileInstaller . . * @run main/othervm/native -agentlib:thrstat004 nsk.jvmti.GetThreadState.thrstat004 */
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/jvmti/GetThreadState/thrstat004/TestDescription.java
Java
gpl-2.0
1,870
๏ปฟusing System; using Server; using System.Collections.Generic; using Server.Items; namespace Server.Multis { public class GargishGalleon : BaseGalleon { public override int NorthID { get { return 0x24 + (DamageValue * 4); } } public override int EastID { get { return 0x25 + (DamageValue * 4); } } public override int SouthID { get { return 0x26 + (DamageValue * 4); } } public override int WestID { get { return 0x27 + (DamageValue * 4); } } public override int HoldDistance { get { return 6; } } public override int TillerManDistance { get { return 1; } } public override int RuneOffset { get { return 3; } } public override int WheelDistance { get { return 2; } } public override int CaptiveOffset { get { return 3; } } public override int MaxCannons { get { return 7; } } public override double CannonDamageMod { get { return 1.0; } } public override double TurnDelay { get { return 1; } } public override int MaxHits { get { return 140; } } public override int ZSurface { get { return 16; } } public override BaseDockedBoat DockedBoat { get { return new DockedGargishGalleon(this); } } [Constructable] public GargishGalleon() : this(Direction.North) { } [Constructable] public GargishGalleon(Direction facing) : base(facing) { } public override void AddMooringLines(Direction direction) { Item line1 = AddMooringLine(new MooringLine(this)); Item line2 = AddMooringLine(new MooringLine(this)); Item line3 = AddMooringLine(new MooringLine(this)); Item line4 = AddMooringLine(new MooringLine(this)); Item line5 = AddMooringLine(new MooringLine(this)); Item line6 = AddMooringLine(new MooringLine(this)); switch (direction) { default: case Direction.North: { line1.Location = new Point3D(X + 2, Y + 3, Z + ZSurface); line2.Location = new Point3D(X - 2, Y + 3, Z + ZSurface); line3.Location = new Point3D(X + 2, Y - 1, Z + ZSurface); line4.Location = new Point3D(X - 2, Y - 1, Z + ZSurface); line5.Location = new Point3D(X + 2, Y - 6, Z + ZSurface); line6.Location = new Point3D(X - 2, Y - 6, Z + ZSurface); break; } case Direction.South: { line1.Location = new Point3D(X + 2, Y - 3, Z + ZSurface); line2.Location = new Point3D(X - 2, Y - 3, Z + ZSurface); line3.Location = new Point3D(X + 2, Y + 1, Z + ZSurface); line4.Location = new Point3D(X - 2, Y + 1, Z + ZSurface); line5.Location = new Point3D(X + 2, Y + 6, Z + ZSurface); line6.Location = new Point3D(X - 2, Y + 6, Z + ZSurface); break; } case Direction.East: { line1.Location = new Point3D(X - 3, Y - 2, Z + ZSurface); line2.Location = new Point3D(X - 3, Y + 2, Z + ZSurface); line3.Location = new Point3D(X + 1, Y - 2, Z + ZSurface); line4.Location = new Point3D(X + 1, Y + 2, Z + ZSurface); line5.Location = new Point3D(X + 6, Y - 2, Z + ZSurface); line6.Location = new Point3D(X + 6, Y + 2, Z + ZSurface); break; } case Direction.West: { line1.Location = new Point3D(X + 3, Y - 2, Z + ZSurface); line2.Location = new Point3D(X + 3, Y + 2, Z + ZSurface); line3.Location = new Point3D(X - 1, Y - 2, Z + ZSurface); line4.Location = new Point3D(X - 1, Y + 2, Z + ZSurface); line5.Location = new Point3D(X - 6, Y - 2, Z + ZSurface); line6.Location = new Point3D(X - 6, Y + 2, Z + ZSurface); break; } } } public override void AddCannonTiles(Direction direction) { int dir = GetValueForDirection(direction); Static tile1 = AddCannonTile(new Static(m_CannonTileIDs[dir][0])); Static tile2 = AddCannonTile(new Static(m_CannonTileIDs[dir][1])); Static tile3 = AddCannonTile(new Static(m_CannonTileIDs[dir][2])); Static tile4 = AddCannonTile(new Static(m_CannonTileIDs[dir][3])); Static tile5 = AddCannonTile(new Static(m_CannonTileIDs[dir][4])); Static tile6 = AddCannonTile(new Static(m_CannonTileIDs[dir][5])); Static tile7 = AddCannonTile(new Static(m_CannonTileIDs[dir][6])); switch (direction) { default: case Direction.North: { tile1.Location = new Point3D(X, Y - 8, Z); //Center Front tile2.Location = new Point3D(X + 2, Y - 5, Z); //Left Front tile3.Location = new Point3D(X - 2, Y - 5, Z); //Right Front tile4.Location = new Point3D(X + 2, Y - 2, Z); //Left Center tile5.Location = new Point3D(X - 2, Y - 2, Z); //Right Center tile6.Location = new Point3D(X + 2, Y + 1, Z); //Left Rear tile7.Location = new Point3D(X - 2, Y + 1, Z); //Right Rear break; } case Direction.South: { tile1.Location = new Point3D(X, Y + 8, Z); //Center Front tile2.Location = new Point3D(X - 2, Y + 5, Z); //Left Front tile3.Location = new Point3D(X + 2, Y + 5, Z); //Right Front tile4.Location = new Point3D(X - 2, Y + 2, Z); //Left Center tile5.Location = new Point3D(X + 2, Y + 2, Z); //Right Center tile6.Location = new Point3D(X - 2, Y - 1, Z); //Left Rear tile7.Location = new Point3D(X + 2, Y - 1, Z); //Right Rear break; } case Direction.East: { tile1.Location = new Point3D(X + 8, Y, Z); //Center Front tile2.Location = new Point3D(X + 5, Y + 2, Z); //Left Front tile3.Location = new Point3D(X + 5, Y - 2, Z); //Right Front tile4.Location = new Point3D(X + 2, Y + 2, Z); //Left Center tile5.Location = new Point3D(X + 2, Y - 2, Z); //Right Center tile6.Location = new Point3D(X - 1, Y + 2, Z); //Left Rear tile7.Location = new Point3D(X - 1, Y - 2, Z); //Right Rear break; } case Direction.West: { tile1.Location = new Point3D(X - 8, Y, Z); //Center Front tile2.Location = new Point3D(X - 5, Y - 2, Z); //Left Front tile3.Location = new Point3D(X - 5, Y + 2, Z); //Right Front tile4.Location = new Point3D(X - 2, Y - 2, Z); //Left Center tile5.Location = new Point3D(X - 2, Y + 2, Z); //Right Center tile6.Location = new Point3D(X + 1, Y - 2, Z); //Left Rear tile7.Location = new Point3D(X + 1, Y + 2, Z); //Right Rear break; } } } public override void AddHoldTiles(Direction direction) { int dir = GetValueForDirection(direction); GalleonHold gHold = AddGalleonHold(new GalleonHold(this, m_HoldItemIDs[dir][0])); HoldItem hold1 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][0])); HoldItem hold2 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][1])); HoldItem hold3 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][2])); HoldItem hold4 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][3])); HoldItem hold5 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][4])); HoldItem hold6 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][5])); HoldItem hold7 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][6])); HoldItem hold8 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][7])); HoldItem hold9 = AddHoldTile(new HoldItem(GalleonHold, m_HoldIDs[dir][8])); Static fill1 = AddFillerTile(new Static(m_FillerIDs[dir][0])); Static fill2 = AddFillerTile(new Static(m_FillerIDs[dir][1])); Static fill3 = AddFillerTile(new Static(m_FillerIDs[dir][2])); Static fill4 = AddFillerTile(new Static(m_FillerIDs[dir][3])); Static fill6 = AddFillerTile(new Static(m_FillerIDs[dir][4])); Static fill7 = AddFillerTile(new Static(m_FillerIDs[dir][5])); Static fill8 = AddFillerTile(new Static(m_FillerIDs[dir][6])); Static fill9 = AddFillerTile(new Static(m_FillerIDs[dir][7])); Static fill10 = AddFillerTile(new Static(m_FillerIDs[dir][8])); Static fill11 = AddFillerTile(new Static(m_FillerIDs[dir][9])); switch (direction) { case Direction.North: hold1.Location = new Point3D(X - 1, Y + 8, Z); hold2.Location = new Point3D(X, Y + 8, Z); hold3.Location = new Point3D(X + 1, Y + 8, Z); hold4.Location = new Point3D(X + 1, Y + 7, Z); hold5.Location = new Point3D(X , Y + 7, Z); hold6.Location = new Point3D(X - 1, Y + 7, Z); hold7.Location = new Point3D(X + 1, Y + 6, Z); hold8.Location = new Point3D(X - 1, Y + 6, Z); hold9.Location = new Point3D(X, Y + 6, Z); fill1.Location = new Point3D(X - 2, Y + 8, Z); fill2.Location = new Point3D(X - 2, Y + 7, Z); fill3.Location = new Point3D(X - 2, Y + 6, Z); fill4.Location = new Point3D(X - 2, Y + 5, Z); gHold.Location = new Point3D(X, Y + 5, Z); fill6.Location = new Point3D(X - 1, Y + 5, Z); fill7.Location = new Point3D(X + 1, Y + 5, Z); fill8.Location = new Point3D(X + 2, Y + 5, Z); fill9.Location = new Point3D(X + 2, Y + 6, Z); fill10.Location = new Point3D(X + 2,Y + 7, Z); fill11.Location = new Point3D(X + 2, Y + 8, Z); break; case Direction.South: hold1.Location = new Point3D(X + 1, Y - 8, Z); hold2.Location = new Point3D(X, Y - 8, Z); hold3.Location = new Point3D(X - 1, Y - 8, Z); hold4.Location = new Point3D(X - 1, Y - 7, Z); hold5.Location = new Point3D(X, Y - 7, Z); hold6.Location = new Point3D(X + 1, Y - 7, Z); hold7.Location = new Point3D(X - 1, Y - 6, Z); hold8.Location = new Point3D(X + 1, Y - 6, Z); hold9.Location = new Point3D(X, Y - 6, Z); fill1.Location = new Point3D(X + 2, Y - 8, Z); fill2.Location = new Point3D(X + 2, Y - 7, Z); fill3.Location = new Point3D(X + 2, Y - 6, Z); fill4.Location = new Point3D(X + 2, Y - 5, Z); gHold.Location = new Point3D(X, Y - 5, Z); fill6.Location = new Point3D(X + 1, Y - 5, Z); fill7.Location = new Point3D(X - 1, Y - 5, Z); fill8.Location = new Point3D(X - 2, Y - 5, Z); fill9.Location = new Point3D(X - 2, Y - 6, Z); fill10.Location = new Point3D(X - 2, Y - 7, Z); fill11.Location = new Point3D(X - 2, Y - 8, Z); break; case Direction.East: hold1.Location = new Point3D(X - 8, Y - 1, Z); hold2.Location = new Point3D(X - 8, Y , Z); hold3.Location = new Point3D(X - 8, Y + 1, Z); hold4.Location = new Point3D(X - 7, Y - 1, Z); hold5.Location = new Point3D(X - 7, Y , Z); hold6.Location = new Point3D(X - 7, Y + 1, Z); hold7.Location = new Point3D(X - 6, Y + 1, Z); hold8.Location = new Point3D(X - 6, Y - 1, Z); hold9.Location = new Point3D(X - 6, Y, Z); fill1.Location = new Point3D(X - 8, Y - 2, Z); fill2.Location = new Point3D(X - 7, Y - 2, Z); fill3.Location = new Point3D(X - 6, Y - 2, Z); fill4.Location = new Point3D(X - 5, Y - 2, Z); gHold.Location = new Point3D(X - 5, Y, Z); fill6.Location = new Point3D(X - 5, Y - 1, Z); fill7.Location = new Point3D(X - 5, Y + 1, Z); fill8.Location = new Point3D(X - 5, Y + 2, Z); fill9.Location = new Point3D(X - 6, Y + 2, Z); fill10.Location = new Point3D(X - 7, Y + 2, Z); fill11.Location = new Point3D(X - 8, Y + 2, Z); break; case Direction.West: hold1.Location = new Point3D(X + 8, Y + 1, Z); hold2.Location = new Point3D(X + 8, Y, Z); hold3.Location = new Point3D(X + 8, Y - 1, Z); hold4.Location = new Point3D(X + 7, Y + 1, Z); hold5.Location = new Point3D(X + 7, Y, Z); hold6.Location = new Point3D(X + 7, Y - 1, Z); hold7.Location = new Point3D(X + 6, Y - 1, Z); hold8.Location = new Point3D(X + 6, Y + 1, Z); hold9.Location = new Point3D(X + 6, Y, Z); fill1.Location = new Point3D(X + 8, Y + 2, Z); fill2.Location = new Point3D(X + 7, Y + 2, Z); fill3.Location = new Point3D(X + 6, Y + 2, Z); fill4.Location = new Point3D(X + 5, Y + 2, Z); gHold.Location = new Point3D(X + 5, Y, Z); fill6.Location = new Point3D(X + 5, Y + 1, Z); fill7.Location = new Point3D(X + 5, Y - 1, Z); fill8.Location = new Point3D(X + 5, Y - 2, Z); fill9.Location = new Point3D(X + 6, Y - 2, Z); fill10.Location = new Point3D(X + 7, Y - 2, Z); fill11.Location = new Point3D(X + 8, Y - 2, Z); break; } } public override int[][] CannonTileIDs { get { return m_CannonTileIDs; } } private int[][] m_CannonTileIDs = new int[][] { new int[] { 33463, 33440, 33438, 33327, 33322, 33357, 33355 }, //SOUTH new int[] { 33768, 33745, 33743, 33632, 33627, 33662, 33660 }, //WEST new int[] { 34070, 34047, 34045, 33934, 33929, 33964, 33962 }, //NORTH new int[] { 34373, 34350, 34348, 34237, 34232, 34267, 34265 }, //EAST new int[] { 19059, 19042, 19040, 18958, 18956, 18979, 18977 }, //SOUTH D1 new int[] { 35582, 35559, 35557, 35446, 35441, 35476, 35474 }, //WEST D1 new int[] { 34978, 34955, 34953, 34842, 34837, 34872, 34870 }, //NORTH D1 new int[] { 34674, 34651, 34649, 34538, 34533, 34568, 34566 }, //EAST D1 new int[] { 36442, 36425, 36423, 36341, 36339, 36362, 36360 }, //SOUTH D2 new int[] { 36744, 36727, 36725, 36733, 36641, 36664, 36662 }, //WEST D2 new int[] { 36140, 36123, 36121, 36039, 36037, 36060, 36058 }, //NORTH D2 new int[] { 35156, 35139, 35137, 35055, 35053, 35076, 35074 }, //EAST D2 }; public override int[][] FillerIDs { get { return m_FillerIDs; } } private int[][] m_FillerIDs = new int[][] { // 110 103 96 89 87 88 93 91 98 105 112 // BL ML1 ML2 FL F1 F2 F3 FR MR2 MR1 BR new int[] { 33410, 33403, 33396, 33389, 33388, 33393, 33391, 33398, 33405, 33412}, //SOUTH new int[] { 33715, 33708, 33701, 33694, 33693, 33698, 33696, 33703, 33710, 33717 }, //WEST new int[] { 34017, 34010, 34003, 33996, 33995, 34000, 33998, 34005, 34012, 34019 }, //NORTH new int[] { 34320, 34313, 34306, 34299, 34298, 34303, 34301, 34308, 34315, 34322 }, //EAST // 110 103 96 89 87 88 93 91 98 105 112 //35419 new int[] { 19026, 19019, 19012, 19005, 19004, 19009, 19007, 19014, 19021, 19028 }, //SOUTH D1 new int[] { 35529, 35522, 35515, 35508, 35507, 35512, 35510, 35517, 35524, 35531 }, //WEST D1 new int[] { 34925, 34918, 34911, 34904, 34903, 34908, 34906, 34913, 34920, 34927 }, //NORTH D1 new int[] { 34621, 34614, 34607, 34600, 34599, 34604, 34602, 34609, 34616, 34623 }, //EAST D1 // +86 -7 -7 -7 -2 +1 +5 -2 +7 +7 +7 // 110 103 96 89 87 88 93 91 98 105 112 new int[] { 36409, 36402, 36395, 36388, 36387, 36392, 36390, 36397, 36404, 36411 }, //SOUTH D2 new int[] { 36711, 36704, 36697, 36690, 36689, 36694, 36692, 36699, 36706, 36713 }, //WEST D2 new int[] { 36107, 36100, 36093, 36086, 36085, 36090, 36088, 36095, 36102, 36109 }, //NORTH D2 new int[] { 35123, 35116, 35109, 35102, 35101, 35106, 35104, 35111, 35118, 35125 }, //EAST D2 }; public override int[][] HoldIDs { get { return m_HoldIDs; } } private int[][] m_HoldIDs = new int[][] { // 108 109 114 94 95 100 101 102 // BL BM BR MR MM ML FL FR new int[] { 33408, 33409, 33414, 33394, 33395, 33400, 33401, 33402, 33407 }, //SOUTH new int[] { 33713, 33714, 33719, 33699, 33700, 33705, 33706, 33707, 33712 }, //WEST new int[] { 34015, 34016, 34021, 34001, 34002, 34007, 34008, 34009, 34007 }, //NORTH new int[] { 34318, 34319, 34324, 34304, 34305, 34310, 34311, 34312, 34317 }, //EAST //18940 // +85 +1 +1 -15 +1 +1 +1 +1 new int[] { 19025, 19024, 19025, 19010, 19011, 19016, 19017, 19018, 33407 }, //SOUTH D1 new int[] { 35506, 35507, 35512, 35513, 35514, 35519, 35520, 35521, 33712 }, //WEST D1 new int[] { 34902, 34903, 34908, 34909, 34910, 34915, 34916, 34917, 34007 }, //NORTH D1 new int[] { 34598, 34599, 34604, 34605, 34606, 34611, 34612, 34613, 34317 }, //EAST D1 new int[] { 36386, 36387, 36392, 36393, 36394, 36399, 36400, 36401, 33407 }, //SOUTH D2 new int[] { 36688, 36689, 36694, 36695, 36696, 36701, 36702, 36703, 33712 }, //WEST D2 new int[] { 36084, 36085, 36090, 36091, 36092, 36097, 36098, 36099, 34007 }, //NORTH D2 new int[] { 35121, 35122, 35127, 35107, 35108, 35113, 35114, 35115, 34317 }, //EAST D1 }; public override int[][] HoldItemIDs { get { return m_HoldItemIDs; } } private int[][] m_HoldItemIDs = new int[][] { new int[] { 33387 }, new int[] { 33692 }, new int[] { 33994 }, new int[] { 34297 }, new int[] { 19003 }, new int[] { 35506 }, new int[] { 34902 }, new int[] { 34598 }, new int[] { 36386 }, new int[] { 36688 }, new int[] { 36084 }, new int[] { 35100 }, }; public override int[][] WheelItemIDs { get { return m_WheelItemIDs; } } private int[][] m_WheelItemIDs = new int[][] { new int[] { 33604 }, new int[] { 33906 }, new int[] { 34208 }, new int[] { 34510 }, }; public override ShipPosition GetCannonPosition(Point3D pnt) { int x = pnt.X; int y = pnt.Y; switch (Facing) { default: case Direction.North: if (x == this.X && y < this.Y) return ShipPosition.Bow; if (x > this.X && y < this.Y) return ShipPosition.BowStarboard; if (x < this.X && y < this.Y) return ShipPosition.BowPort; if (x > this.X && y - 2 == this.Y) return ShipPosition.AmidShipStarboard; else if (x < this.X && y - 2 == this.Y) return ShipPosition.AmidShipPort; else if (x > this.X && y > this.Y) return ShipPosition.AftStarboard; else return ShipPosition.AftPort; case Direction.West: if (x < this.X && y == this.Y) return ShipPosition.Bow; else if (x < this.X && y < this.Y) return ShipPosition.BowStarboard; else if (x < this.X && y > this.Y) return ShipPosition.BowPort; else if (x - 2 == this.X && y < this.Y) return ShipPosition.AmidShipStarboard; else if (x - 2 == this.X && y > this.Y) return ShipPosition.AmidShipPort; else if (x > this.X && y < this.Y) return ShipPosition.AftStarboard; else return ShipPosition.AftPort; case Direction.South: if (x == this.X && y > this.Y) return ShipPosition.Bow; else if (x < this.X && y > this.Y) return ShipPosition.BowStarboard; else if (x > this.X && y > this.Y) return ShipPosition.BowPort; else if (x < this.X && y + 2 == this.Y) return ShipPosition.AmidShipStarboard; else if (x > this.X && y + 2 == this.Y) return ShipPosition.AmidShipPort; else if (x < this.X && y < this.Y) return ShipPosition.AftStarboard; else return ShipPosition.AftPort; case Direction.East: if (x > this.X && y == this.Y) return ShipPosition.Bow; else if (x > this.X && y > this.Y) return ShipPosition.BowStarboard; else if (x > this.X && y < this.Y) return ShipPosition.BowPort; else if (x + 2 == this.X && y > this.Y) return ShipPosition.AmidShipStarboard; else if (x + 2 == this.X && y < this.Y) return ShipPosition.AmidShipPort; else if (x < this.X && y > this.Y) return ShipPosition.AftStarboard; else return ShipPosition.AftPort; } } public GargishGalleon(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } public class GargishGalleonDeed : BaseBoatDeed { public override int LabelNumber { get { return 1116739; } } public override BaseBoat Boat { get { return new GargishGalleon(this.BoatDirection); } } [Constructable] public GargishGalleonDeed() : base(0x24, Point3D.Zero) { } public GargishGalleonDeed(Serial serial) : base(serial) { } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } } public class DockedGargishGalleon : BaseDockedBoat { public override int LabelNumber { get { return 1116748; } } //Gargoyle Ship public override BaseBoat Boat { get { return new GargishGalleon(this.BoatDirection); } } public DockedGargishGalleon(BaseBoat boat) : base(0x24, Point3D.Zero, boat) { } public DockedGargishGalleon(Serial serial) : base(serial) { } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } } }
HankTheDrunk/ServUO
Scripts/Services/High Seas/Multis/GargishGalleon.cs
C#
gpl-2.0
26,461
/* i915_irq.c -- IRQ support for the I915 -*- linux-c -*- */ /* * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/sysrq.h> #include <linux/slab.h> #include <linux/circ_buf.h> #include <drm/drmP.h> #include <drm/i915_drm.h> #include "i915_drv.h" #include "i915_trace.h" #include "intel_drv.h" static const u32 hpd_ibx[] = { [HPD_CRT] = SDE_CRT_HOTPLUG, [HPD_SDVO_B] = SDE_SDVOB_HOTPLUG, [HPD_PORT_B] = SDE_PORTB_HOTPLUG, [HPD_PORT_C] = SDE_PORTC_HOTPLUG, [HPD_PORT_D] = SDE_PORTD_HOTPLUG }; static const u32 hpd_cpt[] = { [HPD_CRT] = SDE_CRT_HOTPLUG_CPT, [HPD_SDVO_B] = SDE_SDVOB_HOTPLUG_CPT, [HPD_PORT_B] = SDE_PORTB_HOTPLUG_CPT, [HPD_PORT_C] = SDE_PORTC_HOTPLUG_CPT, [HPD_PORT_D] = SDE_PORTD_HOTPLUG_CPT }; static const u32 hpd_mask_i915[] = { [HPD_CRT] = CRT_HOTPLUG_INT_EN, [HPD_SDVO_B] = SDVOB_HOTPLUG_INT_EN, [HPD_SDVO_C] = SDVOC_HOTPLUG_INT_EN, [HPD_PORT_B] = PORTB_HOTPLUG_INT_EN, [HPD_PORT_C] = PORTC_HOTPLUG_INT_EN, [HPD_PORT_D] = PORTD_HOTPLUG_INT_EN }; static const u32 hpd_status_g4x[] = { [HPD_CRT] = CRT_HOTPLUG_INT_STATUS, [HPD_SDVO_B] = SDVOB_HOTPLUG_INT_STATUS_G4X, [HPD_SDVO_C] = SDVOC_HOTPLUG_INT_STATUS_G4X, [HPD_PORT_B] = PORTB_HOTPLUG_INT_STATUS, [HPD_PORT_C] = PORTC_HOTPLUG_INT_STATUS, [HPD_PORT_D] = PORTD_HOTPLUG_INT_STATUS }; static const u32 hpd_status_i915[] = { /* i915 and valleyview are the same */ [HPD_CRT] = CRT_HOTPLUG_INT_STATUS, [HPD_SDVO_B] = SDVOB_HOTPLUG_INT_STATUS_I915, [HPD_SDVO_C] = SDVOC_HOTPLUG_INT_STATUS_I915, [HPD_PORT_B] = PORTB_HOTPLUG_INT_STATUS, [HPD_PORT_C] = PORTC_HOTPLUG_INT_STATUS, [HPD_PORT_D] = PORTD_HOTPLUG_INT_STATUS }; /* For display hotplug interrupt */ static void ironlake_enable_display_irq(drm_i915_private_t *dev_priv, u32 mask) { assert_spin_locked(&dev_priv->irq_lock); if (dev_priv->pc8.irqs_disabled) { WARN(1, "IRQs disabled\n"); dev_priv->pc8.regsave.deimr &= ~mask; return; } if ((dev_priv->irq_mask & mask) != 0) { dev_priv->irq_mask &= ~mask; I915_WRITE(DEIMR, dev_priv->irq_mask); POSTING_READ(DEIMR); } } static void ironlake_disable_display_irq(drm_i915_private_t *dev_priv, u32 mask) { assert_spin_locked(&dev_priv->irq_lock); if (dev_priv->pc8.irqs_disabled) { WARN(1, "IRQs disabled\n"); dev_priv->pc8.regsave.deimr |= mask; return; } if ((dev_priv->irq_mask & mask) != mask) { dev_priv->irq_mask |= mask; I915_WRITE(DEIMR, dev_priv->irq_mask); POSTING_READ(DEIMR); } } /** * ilk_update_gt_irq - update GTIMR * @dev_priv: driver private * @interrupt_mask: mask of interrupt bits to update * @enabled_irq_mask: mask of interrupt bits to enable */ static void ilk_update_gt_irq(struct drm_i915_private *dev_priv, uint32_t interrupt_mask, uint32_t enabled_irq_mask) { assert_spin_locked(&dev_priv->irq_lock); if (dev_priv->pc8.irqs_disabled) { WARN(1, "IRQs disabled\n"); dev_priv->pc8.regsave.gtimr &= ~interrupt_mask; dev_priv->pc8.regsave.gtimr |= (~enabled_irq_mask & interrupt_mask); return; } dev_priv->gt_irq_mask &= ~interrupt_mask; dev_priv->gt_irq_mask |= (~enabled_irq_mask & interrupt_mask); I915_WRITE(GTIMR, dev_priv->gt_irq_mask); POSTING_READ(GTIMR); } void ilk_enable_gt_irq(struct drm_i915_private *dev_priv, uint32_t mask) { ilk_update_gt_irq(dev_priv, mask, mask); } void ilk_disable_gt_irq(struct drm_i915_private *dev_priv, uint32_t mask) { ilk_update_gt_irq(dev_priv, mask, 0); } /** * snb_update_pm_irq - update GEN6_PMIMR * @dev_priv: driver private * @interrupt_mask: mask of interrupt bits to update * @enabled_irq_mask: mask of interrupt bits to enable */ static void snb_update_pm_irq(struct drm_i915_private *dev_priv, uint32_t interrupt_mask, uint32_t enabled_irq_mask) { uint32_t new_val; assert_spin_locked(&dev_priv->irq_lock); if (dev_priv->pc8.irqs_disabled) { WARN(1, "IRQs disabled\n"); dev_priv->pc8.regsave.gen6_pmimr &= ~interrupt_mask; dev_priv->pc8.regsave.gen6_pmimr |= (~enabled_irq_mask & interrupt_mask); return; } new_val = dev_priv->pm_irq_mask; new_val &= ~interrupt_mask; new_val |= (~enabled_irq_mask & interrupt_mask); if (new_val != dev_priv->pm_irq_mask) { dev_priv->pm_irq_mask = new_val; I915_WRITE(GEN6_PMIMR, dev_priv->pm_irq_mask); POSTING_READ(GEN6_PMIMR); } } void snb_enable_pm_irq(struct drm_i915_private *dev_priv, uint32_t mask) { snb_update_pm_irq(dev_priv, mask, mask); } void snb_disable_pm_irq(struct drm_i915_private *dev_priv, uint32_t mask) { snb_update_pm_irq(dev_priv, mask, 0); } static bool ivb_can_enable_err_int(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; struct intel_crtc *crtc; enum pipe pipe; assert_spin_locked(&dev_priv->irq_lock); for_each_pipe(pipe) { crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]); if (crtc->cpu_fifo_underrun_disabled) return false; } return true; } static bool cpt_can_enable_serr_int(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; enum pipe pipe; struct intel_crtc *crtc; assert_spin_locked(&dev_priv->irq_lock); for_each_pipe(pipe) { crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]); if (crtc->pch_fifo_underrun_disabled) return false; } return true; } static void i9xx_clear_fifo_underrun(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; u32 reg = PIPESTAT(pipe); u32 pipestat = I915_READ(reg) & 0x7fff0000; assert_spin_locked(&dev_priv->irq_lock); I915_WRITE(reg, pipestat | PIPE_FIFO_UNDERRUN_STATUS); POSTING_READ(reg); } static void ironlake_set_fifo_underrun_reporting(struct drm_device *dev, enum pipe pipe, bool enable) { struct drm_i915_private *dev_priv = dev->dev_private; uint32_t bit = (pipe == PIPE_A) ? DE_PIPEA_FIFO_UNDERRUN : DE_PIPEB_FIFO_UNDERRUN; if (enable) ironlake_enable_display_irq(dev_priv, bit); else ironlake_disable_display_irq(dev_priv, bit); } static void ivybridge_set_fifo_underrun_reporting(struct drm_device *dev, enum pipe pipe, bool enable) { struct drm_i915_private *dev_priv = dev->dev_private; if (enable) { I915_WRITE(GEN7_ERR_INT, ERR_INT_FIFO_UNDERRUN(pipe)); if (!ivb_can_enable_err_int(dev)) return; ironlake_enable_display_irq(dev_priv, DE_ERR_INT_IVB); } else { bool was_enabled = !(I915_READ(DEIMR) & DE_ERR_INT_IVB); /* Change the state _after_ we've read out the current one. */ ironlake_disable_display_irq(dev_priv, DE_ERR_INT_IVB); if (!was_enabled && (I915_READ(GEN7_ERR_INT) & ERR_INT_FIFO_UNDERRUN(pipe))) { DRM_DEBUG_KMS("uncleared fifo underrun on pipe %c\n", pipe_name(pipe)); } } } static void broadwell_set_fifo_underrun_reporting(struct drm_device *dev, enum pipe pipe, bool enable) { struct drm_i915_private *dev_priv = dev->dev_private; assert_spin_locked(&dev_priv->irq_lock); if (enable) dev_priv->de_irq_mask[pipe] &= ~GEN8_PIPE_FIFO_UNDERRUN; else dev_priv->de_irq_mask[pipe] |= GEN8_PIPE_FIFO_UNDERRUN; I915_WRITE(GEN8_DE_PIPE_IMR(pipe), dev_priv->de_irq_mask[pipe]); POSTING_READ(GEN8_DE_PIPE_IMR(pipe)); } /** * ibx_display_interrupt_update - update SDEIMR * @dev_priv: driver private * @interrupt_mask: mask of interrupt bits to update * @enabled_irq_mask: mask of interrupt bits to enable */ static void ibx_display_interrupt_update(struct drm_i915_private *dev_priv, uint32_t interrupt_mask, uint32_t enabled_irq_mask) { uint32_t sdeimr = I915_READ(SDEIMR); sdeimr &= ~interrupt_mask; sdeimr |= (~enabled_irq_mask & interrupt_mask); assert_spin_locked(&dev_priv->irq_lock); if (dev_priv->pc8.irqs_disabled && (interrupt_mask & SDE_HOTPLUG_MASK_CPT)) { WARN(1, "IRQs disabled\n"); dev_priv->pc8.regsave.sdeimr &= ~interrupt_mask; dev_priv->pc8.regsave.sdeimr |= (~enabled_irq_mask & interrupt_mask); return; } I915_WRITE(SDEIMR, sdeimr); POSTING_READ(SDEIMR); } #define ibx_enable_display_interrupt(dev_priv, bits) \ ibx_display_interrupt_update((dev_priv), (bits), (bits)) #define ibx_disable_display_interrupt(dev_priv, bits) \ ibx_display_interrupt_update((dev_priv), (bits), 0) static void ibx_set_fifo_underrun_reporting(struct drm_device *dev, enum transcoder pch_transcoder, bool enable) { struct drm_i915_private *dev_priv = dev->dev_private; uint32_t bit = (pch_transcoder == TRANSCODER_A) ? SDE_TRANSA_FIFO_UNDER : SDE_TRANSB_FIFO_UNDER; if (enable) ibx_enable_display_interrupt(dev_priv, bit); else ibx_disable_display_interrupt(dev_priv, bit); } static void cpt_set_fifo_underrun_reporting(struct drm_device *dev, enum transcoder pch_transcoder, bool enable) { struct drm_i915_private *dev_priv = dev->dev_private; if (enable) { I915_WRITE(SERR_INT, SERR_INT_TRANS_FIFO_UNDERRUN(pch_transcoder)); if (!cpt_can_enable_serr_int(dev)) return; ibx_enable_display_interrupt(dev_priv, SDE_ERROR_CPT); } else { uint32_t tmp = I915_READ(SERR_INT); bool was_enabled = !(I915_READ(SDEIMR) & SDE_ERROR_CPT); /* Change the state _after_ we've read out the current one. */ ibx_disable_display_interrupt(dev_priv, SDE_ERROR_CPT); if (!was_enabled && (tmp & SERR_INT_TRANS_FIFO_UNDERRUN(pch_transcoder))) { DRM_DEBUG_KMS("uncleared pch fifo underrun on pch transcoder %c\n", transcoder_name(pch_transcoder)); } } } /** * intel_set_cpu_fifo_underrun_reporting - enable/disable FIFO underrun messages * @dev: drm device * @pipe: pipe * @enable: true if we want to report FIFO underrun errors, false otherwise * * This function makes us disable or enable CPU fifo underruns for a specific * pipe. Notice that on some Gens (e.g. IVB, HSW), disabling FIFO underrun * reporting for one pipe may also disable all the other CPU error interruts for * the other pipes, due to the fact that there's just one interrupt mask/enable * bit for all the pipes. * * Returns the previous state of underrun reporting. */ bool __intel_set_cpu_fifo_underrun_reporting(struct drm_device *dev, enum pipe pipe, bool enable) { struct drm_i915_private *dev_priv = dev->dev_private; struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe]; struct intel_crtc *intel_crtc = to_intel_crtc(crtc); bool ret; assert_spin_locked(&dev_priv->irq_lock); ret = !intel_crtc->cpu_fifo_underrun_disabled; if (enable == ret) goto done; intel_crtc->cpu_fifo_underrun_disabled = !enable; if (enable && (INTEL_INFO(dev)->gen < 5 || IS_VALLEYVIEW(dev))) i9xx_clear_fifo_underrun(dev, pipe); else if (IS_GEN5(dev) || IS_GEN6(dev)) ironlake_set_fifo_underrun_reporting(dev, pipe, enable); else if (IS_GEN7(dev)) ivybridge_set_fifo_underrun_reporting(dev, pipe, enable); else if (IS_GEN8(dev)) broadwell_set_fifo_underrun_reporting(dev, pipe, enable); done: return ret; } bool intel_set_cpu_fifo_underrun_reporting(struct drm_device *dev, enum pipe pipe, bool enable) { struct drm_i915_private *dev_priv = dev->dev_private; unsigned long flags; bool ret; spin_lock_irqsave(&dev_priv->irq_lock, flags); ret = __intel_set_cpu_fifo_underrun_reporting(dev, pipe, enable); spin_unlock_irqrestore(&dev_priv->irq_lock, flags); return ret; } static bool __cpu_fifo_underrun_reporting_enabled(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe]; struct intel_crtc *intel_crtc = to_intel_crtc(crtc); return !intel_crtc->cpu_fifo_underrun_disabled; } /** * intel_set_pch_fifo_underrun_reporting - enable/disable FIFO underrun messages * @dev: drm device * @pch_transcoder: the PCH transcoder (same as pipe on IVB and older) * @enable: true if we want to report FIFO underrun errors, false otherwise * * This function makes us disable or enable PCH fifo underruns for a specific * PCH transcoder. Notice that on some PCHs (e.g. CPT/PPT), disabling FIFO * underrun reporting for one transcoder may also disable all the other PCH * error interruts for the other transcoders, due to the fact that there's just * one interrupt mask/enable bit for all the transcoders. * * Returns the previous state of underrun reporting. */ bool intel_set_pch_fifo_underrun_reporting(struct drm_device *dev, enum transcoder pch_transcoder, bool enable) { struct drm_i915_private *dev_priv = dev->dev_private; struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pch_transcoder]; struct intel_crtc *intel_crtc = to_intel_crtc(crtc); unsigned long flags; bool ret; /* * NOTE: Pre-LPT has a fixed cpu pipe -> pch transcoder mapping, but LPT * has only one pch transcoder A that all pipes can use. To avoid racy * pch transcoder -> pipe lookups from interrupt code simply store the * underrun statistics in crtc A. Since we never expose this anywhere * nor use it outside of the fifo underrun code here using the "wrong" * crtc on LPT won't cause issues. */ spin_lock_irqsave(&dev_priv->irq_lock, flags); ret = !intel_crtc->pch_fifo_underrun_disabled; if (enable == ret) goto done; intel_crtc->pch_fifo_underrun_disabled = !enable; if (HAS_PCH_IBX(dev)) ibx_set_fifo_underrun_reporting(dev, pch_transcoder, enable); else cpt_set_fifo_underrun_reporting(dev, pch_transcoder, enable); done: spin_unlock_irqrestore(&dev_priv->irq_lock, flags); return ret; } static void __i915_enable_pipestat(struct drm_i915_private *dev_priv, enum pipe pipe, u32 enable_mask, u32 status_mask) { u32 reg = PIPESTAT(pipe); u32 pipestat = I915_READ(reg) & PIPESTAT_INT_ENABLE_MASK; assert_spin_locked(&dev_priv->irq_lock); if (WARN_ON_ONCE(enable_mask & ~PIPESTAT_INT_ENABLE_MASK || status_mask & ~PIPESTAT_INT_STATUS_MASK)) return; if ((pipestat & enable_mask) == enable_mask) return; dev_priv->pipestat_irq_mask[pipe] |= status_mask; /* Enable the interrupt, clear any pending status */ pipestat |= enable_mask | status_mask; I915_WRITE(reg, pipestat); POSTING_READ(reg); } static void __i915_disable_pipestat(struct drm_i915_private *dev_priv, enum pipe pipe, u32 enable_mask, u32 status_mask) { u32 reg = PIPESTAT(pipe); u32 pipestat = I915_READ(reg) & PIPESTAT_INT_ENABLE_MASK; assert_spin_locked(&dev_priv->irq_lock); if (WARN_ON_ONCE(enable_mask & ~PIPESTAT_INT_ENABLE_MASK || status_mask & ~PIPESTAT_INT_STATUS_MASK)) return; if ((pipestat & enable_mask) == 0) return; dev_priv->pipestat_irq_mask[pipe] &= ~status_mask; pipestat &= ~enable_mask; I915_WRITE(reg, pipestat); POSTING_READ(reg); } static u32 vlv_get_pipestat_enable_mask(struct drm_device *dev, u32 status_mask) { u32 enable_mask = status_mask << 16; /* * On pipe A we don't support the PSR interrupt yet, on pipe B the * same bit MBZ. */ if (WARN_ON_ONCE(status_mask & PIPE_A_PSR_STATUS_VLV)) return 0; enable_mask &= ~(PIPE_FIFO_UNDERRUN_STATUS | SPRITE0_FLIP_DONE_INT_EN_VLV | SPRITE1_FLIP_DONE_INT_EN_VLV); if (status_mask & SPRITE0_FLIP_DONE_INT_STATUS_VLV) enable_mask |= SPRITE0_FLIP_DONE_INT_EN_VLV; if (status_mask & SPRITE1_FLIP_DONE_INT_STATUS_VLV) enable_mask |= SPRITE1_FLIP_DONE_INT_EN_VLV; return enable_mask; } void i915_enable_pipestat(struct drm_i915_private *dev_priv, enum pipe pipe, u32 status_mask) { u32 enable_mask; if (IS_VALLEYVIEW(dev_priv->dev)) enable_mask = vlv_get_pipestat_enable_mask(dev_priv->dev, status_mask); else enable_mask = status_mask << 16; __i915_enable_pipestat(dev_priv, pipe, enable_mask, status_mask); } void i915_disable_pipestat(struct drm_i915_private *dev_priv, enum pipe pipe, u32 status_mask) { u32 enable_mask; if (IS_VALLEYVIEW(dev_priv->dev)) enable_mask = vlv_get_pipestat_enable_mask(dev_priv->dev, status_mask); else enable_mask = status_mask << 16; __i915_disable_pipestat(dev_priv, pipe, enable_mask, status_mask); } /** * i915_enable_asle_pipestat - enable ASLE pipestat for OpRegion */ static void i915_enable_asle_pipestat(struct drm_device *dev) { drm_i915_private_t *dev_priv = dev->dev_private; unsigned long irqflags; if (!dev_priv->opregion.asle || !IS_MOBILE(dev)) return; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); i915_enable_pipestat(dev_priv, PIPE_B, PIPE_LEGACY_BLC_EVENT_STATUS); if (INTEL_INFO(dev)->gen >= 4) i915_enable_pipestat(dev_priv, PIPE_A, PIPE_LEGACY_BLC_EVENT_STATUS); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } /** * i915_pipe_enabled - check if a pipe is enabled * @dev: DRM device * @pipe: pipe to check * * Reading certain registers when the pipe is disabled can hang the chip. * Use this routine to make sure the PLL is running and the pipe is active * before reading such registers if unsure. */ static int i915_pipe_enabled(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; if (drm_core_check_feature(dev, DRIVER_MODESET)) { /* Locking is horribly broken here, but whatever. */ struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe]; struct intel_crtc *intel_crtc = to_intel_crtc(crtc); return intel_crtc->active; } else { return I915_READ(PIPECONF(pipe)) & PIPECONF_ENABLE; } } static u32 i8xx_get_vblank_counter(struct drm_device *dev, int pipe) { /* Gen2 doesn't have a hardware frame counter */ return 0; } /* Called from drm generic code, passed a 'crtc', which * we use as a pipe index */ static u32 i915_get_vblank_counter(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long high_frame; unsigned long low_frame; u32 high1, high2, low, pixel, vbl_start; if (!i915_pipe_enabled(dev, pipe)) { DRM_DEBUG_DRIVER("trying to get vblank count for disabled " "pipe %c\n", pipe_name(pipe)); return 0; } if (drm_core_check_feature(dev, DRIVER_MODESET)) { struct intel_crtc *intel_crtc = to_intel_crtc(dev_priv->pipe_to_crtc_mapping[pipe]); const struct drm_display_mode *mode = &intel_crtc->config.adjusted_mode; vbl_start = mode->crtc_vblank_start * mode->crtc_htotal; } else { enum transcoder cpu_transcoder = intel_pipe_to_cpu_transcoder(dev_priv, pipe); u32 htotal; htotal = ((I915_READ(HTOTAL(cpu_transcoder)) >> 16) & 0x1fff) + 1; vbl_start = (I915_READ(VBLANK(cpu_transcoder)) & 0x1fff) + 1; vbl_start *= htotal; } high_frame = PIPEFRAME(pipe); low_frame = PIPEFRAMEPIXEL(pipe); /* * High & low register fields aren't synchronized, so make sure * we get a low value that's stable across two reads of the high * register. */ do { high1 = I915_READ(high_frame) & PIPE_FRAME_HIGH_MASK; low = I915_READ(low_frame); high2 = I915_READ(high_frame) & PIPE_FRAME_HIGH_MASK; } while (high1 != high2); high1 >>= PIPE_FRAME_HIGH_SHIFT; pixel = low & PIPE_PIXEL_MASK; low >>= PIPE_FRAME_LOW_SHIFT; /* * The frame counter increments at beginning of active. * Cook up a vblank counter by also checking the pixel * counter against vblank start. */ return (((high1 << 8) | low) + (pixel >= vbl_start)) & 0xffffff; } static u32 gm45_get_vblank_counter(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int reg = PIPE_FRMCOUNT_GM45(pipe); if (!i915_pipe_enabled(dev, pipe)) { DRM_DEBUG_DRIVER("trying to get vblank count for disabled " "pipe %c\n", pipe_name(pipe)); return 0; } return I915_READ(reg); } /* raw reads, only for fast reads of display block, no need for forcewake etc. */ #define __raw_i915_read32(dev_priv__, reg__) readl((dev_priv__)->regs + (reg__)) static bool ilk_pipe_in_vblank_locked(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; uint32_t status; int reg; if (INTEL_INFO(dev)->gen >= 8) { status = GEN8_PIPE_VBLANK; reg = GEN8_DE_PIPE_ISR(pipe); } else if (INTEL_INFO(dev)->gen >= 7) { status = DE_PIPE_VBLANK_IVB(pipe); reg = DEISR; } else { status = DE_PIPE_VBLANK(pipe); reg = DEISR; } return __raw_i915_read32(dev_priv, reg) & status; } static int i915_get_crtc_scanoutpos(struct drm_device *dev, int pipe, unsigned int flags, int *vpos, int *hpos, ktime_t *stime, ktime_t *etime) { struct drm_i915_private *dev_priv = dev->dev_private; struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe]; struct intel_crtc *intel_crtc = to_intel_crtc(crtc); const struct drm_display_mode *mode = &intel_crtc->config.adjusted_mode; int position; int vbl_start, vbl_end, htotal, vtotal; bool in_vbl = true; int ret = 0; unsigned long irqflags; if (!intel_crtc->active) { DRM_DEBUG_DRIVER("trying to get scanoutpos for disabled " "pipe %c\n", pipe_name(pipe)); return 0; } htotal = mode->crtc_htotal; vtotal = mode->crtc_vtotal; vbl_start = mode->crtc_vblank_start; vbl_end = mode->crtc_vblank_end; if (mode->flags & DRM_MODE_FLAG_INTERLACE) { vbl_start = DIV_ROUND_UP(vbl_start, 2); vbl_end /= 2; vtotal /= 2; } ret |= DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_ACCURATE; /* * Lock uncore.lock, as we will do multiple timing critical raw * register reads, potentially with preemption disabled, so the * following code must not block on uncore.lock. */ spin_lock_irqsave(&dev_priv->uncore.lock, irqflags); /* preempt_disable_rt() should go right here in PREEMPT_RT patchset. */ /* Get optional system timestamp before query. */ if (stime) *stime = ktime_get(); if (IS_GEN2(dev) || IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5) { /* No obvious pixelcount register. Only query vertical * scanout position from Display scan line register. */ if (IS_GEN2(dev)) position = __raw_i915_read32(dev_priv, PIPEDSL(pipe)) & DSL_LINEMASK_GEN2; else position = __raw_i915_read32(dev_priv, PIPEDSL(pipe)) & DSL_LINEMASK_GEN3; if (HAS_PCH_SPLIT(dev)) { /* * The scanline counter increments at the leading edge * of hsync, ie. it completely misses the active portion * of the line. Fix up the counter at both edges of vblank * to get a more accurate picture whether we're in vblank * or not. */ in_vbl = ilk_pipe_in_vblank_locked(dev, pipe); if ((in_vbl && position == vbl_start - 1) || (!in_vbl && position == vbl_end - 1)) position = (position + 1) % vtotal; } else { /* * ISR vblank status bits don't work the way we'd want * them to work on non-PCH platforms (for * ilk_pipe_in_vblank_locked()), and there doesn't * appear any other way to determine if we're currently * in vblank. * * Instead let's assume that we're already in vblank if * we got called from the vblank interrupt and the * scanline counter value indicates that we're on the * line just prior to vblank start. This should result * in the correct answer, unless the vblank interrupt * delivery really got delayed for almost exactly one * full frame/field. */ if (flags & DRM_CALLED_FROM_VBLIRQ && position == vbl_start - 1) { position = (position + 1) % vtotal; /* Signal this correction as "applied". */ ret |= 0x8; } } } else { /* Have access to pixelcount since start of frame. * We can split this into vertical and horizontal * scanout position. */ position = (__raw_i915_read32(dev_priv, PIPEFRAMEPIXEL(pipe)) & PIPE_PIXEL_MASK) >> PIPE_PIXEL_SHIFT; /* convert to pixel counts */ vbl_start *= htotal; vbl_end *= htotal; vtotal *= htotal; } /* Get optional system timestamp after query. */ if (etime) *etime = ktime_get(); /* preempt_enable_rt() should go right here in PREEMPT_RT patchset. */ spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags); in_vbl = position >= vbl_start && position < vbl_end; /* * While in vblank, position will be negative * counting up towards 0 at vbl_end. And outside * vblank, position will be positive counting * up since vbl_end. */ if (position >= vbl_start) position -= vbl_end; else position += vtotal - vbl_end; if (IS_GEN2(dev) || IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5) { *vpos = position; *hpos = 0; } else { *vpos = position / htotal; *hpos = position - (*vpos * htotal); } /* In vblank? */ if (in_vbl) ret |= DRM_SCANOUTPOS_INVBL; return ret; } static int i915_get_vblank_timestamp(struct drm_device *dev, int pipe, int *max_error, struct timeval *vblank_time, unsigned flags) { struct drm_crtc *crtc; if (pipe < 0 || pipe >= INTEL_INFO(dev)->num_pipes) { DRM_ERROR("Invalid crtc %d\n", pipe); return -EINVAL; } /* Get drm_crtc to timestamp: */ crtc = intel_get_crtc_for_pipe(dev, pipe); if (crtc == NULL) { DRM_ERROR("Invalid crtc %d\n", pipe); return -EINVAL; } if (!crtc->enabled) { DRM_DEBUG_KMS("crtc %d is disabled\n", pipe); return -EBUSY; } /* Helper routine in DRM core does all the work: */ return drm_calc_vbltimestamp_from_scanoutpos(dev, pipe, max_error, vblank_time, flags, crtc, &to_intel_crtc(crtc)->config.adjusted_mode); } static bool intel_hpd_irq_event(struct drm_device *dev, struct drm_connector *connector) { enum drm_connector_status old_status; WARN_ON(!mutex_is_locked(&dev->mode_config.mutex)); old_status = connector->status; connector->status = connector->funcs->detect(connector, false); if (old_status == connector->status) return false; DRM_DEBUG_KMS("[CONNECTOR:%d:%s] status updated from %s to %s\n", connector->base.id, drm_get_connector_name(connector), drm_get_connector_status_name(old_status), drm_get_connector_status_name(connector->status)); return true; } /* * Handle hotplug events outside the interrupt handler proper. */ #define I915_REENABLE_HOTPLUG_DELAY (2*60*1000) static void i915_hotplug_work_func(struct work_struct *work) { drm_i915_private_t *dev_priv = container_of(work, drm_i915_private_t, hotplug_work); struct drm_device *dev = dev_priv->dev; struct drm_mode_config *mode_config = &dev->mode_config; struct intel_connector *intel_connector; struct intel_encoder *intel_encoder; struct drm_connector *connector; unsigned long irqflags; bool hpd_disabled = false; bool changed = false; u32 hpd_event_bits; /* HPD irq before everything is fully set up. */ if (!dev_priv->enable_hotplug_processing) return; mutex_lock(&mode_config->mutex); DRM_DEBUG_KMS("running encoder hotplug functions\n"); spin_lock_irqsave(&dev_priv->irq_lock, irqflags); hpd_event_bits = dev_priv->hpd_event_bits; dev_priv->hpd_event_bits = 0; list_for_each_entry(connector, &mode_config->connector_list, head) { intel_connector = to_intel_connector(connector); intel_encoder = intel_connector->encoder; if (intel_encoder->hpd_pin > HPD_NONE && dev_priv->hpd_stats[intel_encoder->hpd_pin].hpd_mark == HPD_MARK_DISABLED && connector->polled == DRM_CONNECTOR_POLL_HPD) { DRM_INFO("HPD interrupt storm detected on connector %s: " "switching from hotplug detection to polling\n", drm_get_connector_name(connector)); dev_priv->hpd_stats[intel_encoder->hpd_pin].hpd_mark = HPD_DISABLED; connector->polled = DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT; hpd_disabled = true; } if (hpd_event_bits & (1 << intel_encoder->hpd_pin)) { DRM_DEBUG_KMS("Connector %s (pin %i) received hotplug event.\n", drm_get_connector_name(connector), intel_encoder->hpd_pin); } } /* if there were no outputs to poll, poll was disabled, * therefore make sure it's enabled when disabling HPD on * some connectors */ if (hpd_disabled) { drm_kms_helper_poll_enable(dev); mod_timer(&dev_priv->hotplug_reenable_timer, jiffies + msecs_to_jiffies(I915_REENABLE_HOTPLUG_DELAY)); } spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); list_for_each_entry(connector, &mode_config->connector_list, head) { intel_connector = to_intel_connector(connector); intel_encoder = intel_connector->encoder; if (hpd_event_bits & (1 << intel_encoder->hpd_pin)) { if (intel_encoder->hot_plug) intel_encoder->hot_plug(intel_encoder); if (intel_hpd_irq_event(dev, connector)) changed = true; } } mutex_unlock(&mode_config->mutex); if (changed) drm_kms_helper_hotplug_event(dev); } static void intel_hpd_irq_uninstall(struct drm_i915_private *dev_priv) { del_timer_sync(&dev_priv->hotplug_reenable_timer); } static void ironlake_rps_change_irq_handler(struct drm_device *dev) { drm_i915_private_t *dev_priv = dev->dev_private; u32 busy_up, busy_down, max_avg, min_avg; u8 new_delay; spin_lock(&mchdev_lock); I915_WRITE16(MEMINTRSTS, I915_READ(MEMINTRSTS)); new_delay = dev_priv->ips.cur_delay; I915_WRITE16(MEMINTRSTS, MEMINT_EVAL_CHG); busy_up = I915_READ(RCPREVBSYTUPAVG); busy_down = I915_READ(RCPREVBSYTDNAVG); max_avg = I915_READ(RCBMAXAVG); min_avg = I915_READ(RCBMINAVG); /* Handle RCS change request from hw */ if (busy_up > max_avg) { if (dev_priv->ips.cur_delay != dev_priv->ips.max_delay) new_delay = dev_priv->ips.cur_delay - 1; if (new_delay < dev_priv->ips.max_delay) new_delay = dev_priv->ips.max_delay; } else if (busy_down < min_avg) { if (dev_priv->ips.cur_delay != dev_priv->ips.min_delay) new_delay = dev_priv->ips.cur_delay + 1; if (new_delay > dev_priv->ips.min_delay) new_delay = dev_priv->ips.min_delay; } if (ironlake_set_drps(dev, new_delay)) dev_priv->ips.cur_delay = new_delay; spin_unlock(&mchdev_lock); return; } static void notify_ring(struct drm_device *dev, struct intel_ring_buffer *ring) { if (ring->obj == NULL) return; trace_i915_gem_request_complete(ring); wake_up_all(&ring->irq_queue); i915_queue_hangcheck(dev); } void gen6_set_pm_mask(struct drm_i915_private *dev_priv, u32 pm_iir, int new_delay) { if (pm_iir & GEN6_PM_RP_UP_THRESHOLD) { if (new_delay >= dev_priv->rps.max_delay) { /* Mask UP THRESHOLD Interrupts */ I915_WRITE(GEN6_PMINTRMSK, I915_READ(GEN6_PMINTRMSK) | GEN6_PM_RP_UP_THRESHOLD); dev_priv->rps.rp_up_masked = true; } if (dev_priv->rps.rp_down_masked) { /* UnMask DOWN THRESHOLD Interrupts */ I915_WRITE(GEN6_PMINTRMSK, I915_READ(GEN6_PMINTRMSK) & ~GEN6_PM_RP_DOWN_THRESHOLD); dev_priv->rps.rp_down_masked = false; } } else if (pm_iir & GEN6_PM_RP_DOWN_THRESHOLD) { if (new_delay <= dev_priv->rps.min_delay) { /* Mask DOWN THRESHOLD Interrupts */ I915_WRITE(GEN6_PMINTRMSK, I915_READ(GEN6_PMINTRMSK) | GEN6_PM_RP_DOWN_THRESHOLD); dev_priv->rps.rp_down_masked = true; } if (dev_priv->rps.rp_up_masked) { /* UnMask UP THRESHOLD Interrupts */ I915_WRITE(GEN6_PMINTRMSK, I915_READ(GEN6_PMINTRMSK) & ~GEN6_PM_RP_UP_THRESHOLD); dev_priv->rps.rp_up_masked = false; } } } static void gen6_pm_rps_work(struct work_struct *work) { drm_i915_private_t *dev_priv = container_of(work, drm_i915_private_t, rps.work); u32 pm_iir; int new_delay, adj; spin_lock_irq(&dev_priv->irq_lock); pm_iir = dev_priv->rps.pm_iir; dev_priv->rps.pm_iir = 0; /* Make sure not to corrupt PMIMR state used by ringbuffer code */ snb_enable_pm_irq(dev_priv, GEN6_PM_RPS_EVENTS); spin_unlock_irq(&dev_priv->irq_lock); /* Make sure we didn't queue anything we're not going to process. */ WARN_ON(pm_iir & ~GEN6_PM_RPS_EVENTS); if ((pm_iir & GEN6_PM_RPS_EVENTS) == 0) return; mutex_lock(&dev_priv->rps.hw_lock); adj = dev_priv->rps.last_adj; if (pm_iir & GEN6_PM_RP_UP_THRESHOLD) { if (adj > 0) adj *= 2; else adj = 1; new_delay = dev_priv->rps.cur_delay + adj; /* * For better performance, jump directly * to RPe if we're below it. */ if (new_delay < dev_priv->rps.rpe_delay) new_delay = dev_priv->rps.rpe_delay; } else if (pm_iir & GEN6_PM_RP_DOWN_TIMEOUT) { if (dev_priv->rps.cur_delay > dev_priv->rps.rpe_delay) new_delay = dev_priv->rps.rpe_delay; else new_delay = dev_priv->rps.min_delay; adj = 0; } else if (pm_iir & GEN6_PM_RP_DOWN_THRESHOLD) { if (adj < 0) adj *= 2; else adj = -1; new_delay = dev_priv->rps.cur_delay + adj; } else { /* unknown event */ new_delay = dev_priv->rps.cur_delay; } /* sysfs frequency interfaces may have snuck in while servicing the * interrupt */ new_delay = clamp_t(int, new_delay, dev_priv->rps.min_delay, dev_priv->rps.max_delay); gen6_set_pm_mask(dev_priv, pm_iir, new_delay); dev_priv->rps.last_adj = new_delay - dev_priv->rps.cur_delay; if (IS_VALLEYVIEW(dev_priv->dev)) valleyview_set_rps(dev_priv->dev, new_delay); else gen6_set_rps(dev_priv->dev, new_delay); mutex_unlock(&dev_priv->rps.hw_lock); } /** * ivybridge_parity_work - Workqueue called when a parity error interrupt * occurred. * @work: workqueue struct * * Doesn't actually do anything except notify userspace. As a consequence of * this event, userspace should try to remap the bad rows since statistically * it is likely the same row is more likely to go bad again. */ static void ivybridge_parity_work(struct work_struct *work) { drm_i915_private_t *dev_priv = container_of(work, drm_i915_private_t, l3_parity.error_work); u32 error_status, row, bank, subbank; char *parity_event[6]; uint32_t misccpctl; unsigned long flags; uint8_t slice = 0; /* We must turn off DOP level clock gating to access the L3 registers. * In order to prevent a get/put style interface, acquire struct mutex * any time we access those registers. */ mutex_lock(&dev_priv->dev->struct_mutex); /* If we've screwed up tracking, just let the interrupt fire again */ if (WARN_ON(!dev_priv->l3_parity.which_slice)) goto out; misccpctl = I915_READ(GEN7_MISCCPCTL); I915_WRITE(GEN7_MISCCPCTL, misccpctl & ~GEN7_DOP_CLOCK_GATE_ENABLE); POSTING_READ(GEN7_MISCCPCTL); while ((slice = ffs(dev_priv->l3_parity.which_slice)) != 0) { u32 reg; slice--; if (WARN_ON_ONCE(slice >= NUM_L3_SLICES(dev_priv->dev))) break; dev_priv->l3_parity.which_slice &= ~(1<<slice); reg = GEN7_L3CDERRST1 + (slice * 0x200); error_status = I915_READ(reg); row = GEN7_PARITY_ERROR_ROW(error_status); bank = GEN7_PARITY_ERROR_BANK(error_status); subbank = GEN7_PARITY_ERROR_SUBBANK(error_status); I915_WRITE(reg, GEN7_PARITY_ERROR_VALID | GEN7_L3CDERRST1_ENABLE); POSTING_READ(reg); parity_event[0] = I915_L3_PARITY_UEVENT "=1"; parity_event[1] = kasprintf(GFP_KERNEL, "ROW=%d", row); parity_event[2] = kasprintf(GFP_KERNEL, "BANK=%d", bank); parity_event[3] = kasprintf(GFP_KERNEL, "SUBBANK=%d", subbank); parity_event[4] = kasprintf(GFP_KERNEL, "SLICE=%d", slice); parity_event[5] = NULL; kobject_uevent_env(&dev_priv->dev->primary->kdev->kobj, KOBJ_CHANGE, parity_event); DRM_DEBUG("Parity error: Slice = %d, Row = %d, Bank = %d, Sub bank = %d.\n", slice, row, bank, subbank); kfree(parity_event[4]); kfree(parity_event[3]); kfree(parity_event[2]); kfree(parity_event[1]); } I915_WRITE(GEN7_MISCCPCTL, misccpctl); out: WARN_ON(dev_priv->l3_parity.which_slice); spin_lock_irqsave(&dev_priv->irq_lock, flags); ilk_enable_gt_irq(dev_priv, GT_PARITY_ERROR(dev_priv->dev)); spin_unlock_irqrestore(&dev_priv->irq_lock, flags); mutex_unlock(&dev_priv->dev->struct_mutex); } static void ivybridge_parity_error_irq_handler(struct drm_device *dev, u32 iir) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; if (!HAS_L3_DPF(dev)) return; spin_lock(&dev_priv->irq_lock); ilk_disable_gt_irq(dev_priv, GT_PARITY_ERROR(dev)); spin_unlock(&dev_priv->irq_lock); iir &= GT_PARITY_ERROR(dev); if (iir & GT_RENDER_L3_PARITY_ERROR_INTERRUPT_S1) dev_priv->l3_parity.which_slice |= 1 << 1; if (iir & GT_RENDER_L3_PARITY_ERROR_INTERRUPT) dev_priv->l3_parity.which_slice |= 1 << 0; queue_work(dev_priv->wq, &dev_priv->l3_parity.error_work); } static void ilk_gt_irq_handler(struct drm_device *dev, struct drm_i915_private *dev_priv, u32 gt_iir) { if (gt_iir & (GT_RENDER_USER_INTERRUPT | GT_RENDER_PIPECTL_NOTIFY_INTERRUPT)) notify_ring(dev, &dev_priv->ring[RCS]); if (gt_iir & ILK_BSD_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[VCS]); } static void snb_gt_irq_handler(struct drm_device *dev, struct drm_i915_private *dev_priv, u32 gt_iir) { if (gt_iir & (GT_RENDER_USER_INTERRUPT | GT_RENDER_PIPECTL_NOTIFY_INTERRUPT)) notify_ring(dev, &dev_priv->ring[RCS]); if (gt_iir & GT_BSD_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[VCS]); if (gt_iir & GT_BLT_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[BCS]); if (gt_iir & (GT_BLT_CS_ERROR_INTERRUPT | GT_BSD_CS_ERROR_INTERRUPT | GT_RENDER_CS_MASTER_ERROR_INTERRUPT)) { i915_handle_error(dev, false, "GT error interrupt 0x%08x", gt_iir); } if (gt_iir & GT_PARITY_ERROR(dev)) ivybridge_parity_error_irq_handler(dev, gt_iir); } static irqreturn_t gen8_gt_irq_handler(struct drm_device *dev, struct drm_i915_private *dev_priv, u32 master_ctl) { u32 rcs, bcs, vcs; uint32_t tmp = 0; irqreturn_t ret = IRQ_NONE; if (master_ctl & (GEN8_GT_RCS_IRQ | GEN8_GT_BCS_IRQ)) { tmp = I915_READ(GEN8_GT_IIR(0)); if (tmp) { ret = IRQ_HANDLED; rcs = tmp >> GEN8_RCS_IRQ_SHIFT; bcs = tmp >> GEN8_BCS_IRQ_SHIFT; if (rcs & GT_RENDER_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[RCS]); if (bcs & GT_RENDER_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[BCS]); I915_WRITE(GEN8_GT_IIR(0), tmp); } else DRM_ERROR("The master control interrupt lied (GT0)!\n"); } if (master_ctl & GEN8_GT_VCS1_IRQ) { tmp = I915_READ(GEN8_GT_IIR(1)); if (tmp) { ret = IRQ_HANDLED; vcs = tmp >> GEN8_VCS1_IRQ_SHIFT; if (vcs & GT_RENDER_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[VCS]); I915_WRITE(GEN8_GT_IIR(1), tmp); } else DRM_ERROR("The master control interrupt lied (GT1)!\n"); } if (master_ctl & GEN8_GT_VECS_IRQ) { tmp = I915_READ(GEN8_GT_IIR(3)); if (tmp) { ret = IRQ_HANDLED; vcs = tmp >> GEN8_VECS_IRQ_SHIFT; if (vcs & GT_RENDER_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[VECS]); I915_WRITE(GEN8_GT_IIR(3), tmp); } else DRM_ERROR("The master control interrupt lied (GT3)!\n"); } return ret; } #define HPD_STORM_DETECT_PERIOD 1000 #define HPD_STORM_THRESHOLD 5 static inline void intel_hpd_irq_handler(struct drm_device *dev, u32 hotplug_trigger, const u32 *hpd) { drm_i915_private_t *dev_priv = dev->dev_private; int i; bool storm_detected = false; if (!hotplug_trigger) return; DRM_DEBUG_DRIVER("hotplug event received, stat 0x%08x\n", hotplug_trigger); spin_lock(&dev_priv->irq_lock); for (i = 1; i < HPD_NUM_PINS; i++) { WARN_ONCE(hpd[i] & hotplug_trigger && dev_priv->hpd_stats[i].hpd_mark == HPD_DISABLED, "Received HPD interrupt (0x%08x) on pin %d (0x%08x) although disabled\n", hotplug_trigger, i, hpd[i]); if (!(hpd[i] & hotplug_trigger) || dev_priv->hpd_stats[i].hpd_mark != HPD_ENABLED) continue; dev_priv->hpd_event_bits |= (1 << i); if (!time_in_range(jiffies, dev_priv->hpd_stats[i].hpd_last_jiffies, dev_priv->hpd_stats[i].hpd_last_jiffies + msecs_to_jiffies(HPD_STORM_DETECT_PERIOD))) { dev_priv->hpd_stats[i].hpd_last_jiffies = jiffies; dev_priv->hpd_stats[i].hpd_cnt = 0; DRM_DEBUG_KMS("Received HPD interrupt on PIN %d - cnt: 0\n", i); } else if (dev_priv->hpd_stats[i].hpd_cnt > HPD_STORM_THRESHOLD) { dev_priv->hpd_stats[i].hpd_mark = HPD_MARK_DISABLED; dev_priv->hpd_event_bits &= ~(1 << i); DRM_DEBUG_KMS("HPD interrupt storm detected on PIN %d\n", i); storm_detected = true; } else { dev_priv->hpd_stats[i].hpd_cnt++; DRM_DEBUG_KMS("Received HPD interrupt on PIN %d - cnt: %d\n", i, dev_priv->hpd_stats[i].hpd_cnt); } } if (storm_detected) dev_priv->display.hpd_irq_setup(dev); spin_unlock(&dev_priv->irq_lock); /* * Our hotplug handler can grab modeset locks (by calling down into the * fb helpers). Hence it must not be run on our own dev-priv->wq work * queue for otherwise the flush_work in the pageflip code will * deadlock. */ schedule_work(&dev_priv->hotplug_work); } static void gmbus_irq_handler(struct drm_device *dev) { struct drm_i915_private *dev_priv = (drm_i915_private_t *) dev->dev_private; wake_up_all(&dev_priv->gmbus_wait_queue); } static void dp_aux_irq_handler(struct drm_device *dev) { struct drm_i915_private *dev_priv = (drm_i915_private_t *) dev->dev_private; wake_up_all(&dev_priv->gmbus_wait_queue); } #if defined(CONFIG_DEBUG_FS) static void display_pipe_crc_irq_handler(struct drm_device *dev, enum pipe pipe, uint32_t crc0, uint32_t crc1, uint32_t crc2, uint32_t crc3, uint32_t crc4) { struct drm_i915_private *dev_priv = dev->dev_private; struct intel_pipe_crc *pipe_crc = &dev_priv->pipe_crc[pipe]; struct intel_pipe_crc_entry *entry; int head, tail; spin_lock(&pipe_crc->lock); if (!pipe_crc->entries) { spin_unlock(&pipe_crc->lock); DRM_ERROR("spurious interrupt\n"); return; } head = pipe_crc->head; tail = pipe_crc->tail; if (CIRC_SPACE(head, tail, INTEL_PIPE_CRC_ENTRIES_NR) < 1) { spin_unlock(&pipe_crc->lock); DRM_ERROR("CRC buffer overflowing\n"); return; } entry = &pipe_crc->entries[head]; entry->frame = dev->driver->get_vblank_counter(dev, pipe); entry->crc[0] = crc0; entry->crc[1] = crc1; entry->crc[2] = crc2; entry->crc[3] = crc3; entry->crc[4] = crc4; head = (head + 1) & (INTEL_PIPE_CRC_ENTRIES_NR - 1); pipe_crc->head = head; spin_unlock(&pipe_crc->lock); wake_up_interruptible(&pipe_crc->wq); } #else static inline void display_pipe_crc_irq_handler(struct drm_device *dev, enum pipe pipe, uint32_t crc0, uint32_t crc1, uint32_t crc2, uint32_t crc3, uint32_t crc4) {} #endif static void hsw_pipe_crc_irq_handler(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; display_pipe_crc_irq_handler(dev, pipe, I915_READ(PIPE_CRC_RES_1_IVB(pipe)), 0, 0, 0, 0); } static void ivb_pipe_crc_irq_handler(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; display_pipe_crc_irq_handler(dev, pipe, I915_READ(PIPE_CRC_RES_1_IVB(pipe)), I915_READ(PIPE_CRC_RES_2_IVB(pipe)), I915_READ(PIPE_CRC_RES_3_IVB(pipe)), I915_READ(PIPE_CRC_RES_4_IVB(pipe)), I915_READ(PIPE_CRC_RES_5_IVB(pipe))); } static void i9xx_pipe_crc_irq_handler(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; uint32_t res1, res2; if (INTEL_INFO(dev)->gen >= 3) res1 = I915_READ(PIPE_CRC_RES_RES1_I915(pipe)); else res1 = 0; if (INTEL_INFO(dev)->gen >= 5 || IS_G4X(dev)) res2 = I915_READ(PIPE_CRC_RES_RES2_G4X(pipe)); else res2 = 0; display_pipe_crc_irq_handler(dev, pipe, I915_READ(PIPE_CRC_RES_RED(pipe)), I915_READ(PIPE_CRC_RES_GREEN(pipe)), I915_READ(PIPE_CRC_RES_BLUE(pipe)), res1, res2); } /* The RPS events need forcewake, so we add them to a work queue and mask their * IMR bits until the work is done. Other interrupts can be processed without * the work queue. */ static void gen6_rps_irq_handler(struct drm_i915_private *dev_priv, u32 pm_iir) { if (pm_iir & GEN6_PM_RPS_EVENTS) { spin_lock(&dev_priv->irq_lock); dev_priv->rps.pm_iir |= pm_iir & GEN6_PM_RPS_EVENTS; snb_disable_pm_irq(dev_priv, pm_iir & GEN6_PM_RPS_EVENTS); spin_unlock(&dev_priv->irq_lock); queue_work(dev_priv->wq, &dev_priv->rps.work); } if (HAS_VEBOX(dev_priv->dev)) { if (pm_iir & PM_VEBOX_USER_INTERRUPT) notify_ring(dev_priv->dev, &dev_priv->ring[VECS]); if (pm_iir & PM_VEBOX_CS_ERROR_INTERRUPT) { i915_handle_error(dev_priv->dev, false, "VEBOX CS error interrupt 0x%08x", pm_iir); } } } static void valleyview_pipestat_irq_handler(struct drm_device *dev, u32 iir) { struct drm_i915_private *dev_priv = dev->dev_private; u32 pipe_stats[I915_MAX_PIPES] = { }; int pipe; spin_lock(&dev_priv->irq_lock); for_each_pipe(pipe) { int reg; u32 mask, iir_bit = 0; /* * PIPESTAT bits get signalled even when the interrupt is * disabled with the mask bits, and some of the status bits do * not generate interrupts at all (like the underrun bit). Hence * we need to be careful that we only handle what we want to * handle. */ mask = 0; if (__cpu_fifo_underrun_reporting_enabled(dev, pipe)) mask |= PIPE_FIFO_UNDERRUN_STATUS; switch (pipe) { case PIPE_A: iir_bit = I915_DISPLAY_PIPE_A_EVENT_INTERRUPT; break; case PIPE_B: iir_bit = I915_DISPLAY_PIPE_B_EVENT_INTERRUPT; break; } if (iir & iir_bit) mask |= dev_priv->pipestat_irq_mask[pipe]; if (!mask) continue; reg = PIPESTAT(pipe); mask |= PIPESTAT_INT_ENABLE_MASK; pipe_stats[pipe] = I915_READ(reg) & mask; /* * Clear the PIPE*STAT regs before the IIR */ if (pipe_stats[pipe] & (PIPE_FIFO_UNDERRUN_STATUS | PIPESTAT_INT_STATUS_MASK)) I915_WRITE(reg, pipe_stats[pipe]); } spin_unlock(&dev_priv->irq_lock); for_each_pipe(pipe) { if (pipe_stats[pipe] & PIPE_START_VBLANK_INTERRUPT_STATUS) drm_handle_vblank(dev, pipe); if (pipe_stats[pipe] & PLANE_FLIP_DONE_INT_STATUS_VLV) { intel_prepare_page_flip(dev, pipe); intel_finish_page_flip(dev, pipe); } if (pipe_stats[pipe] & PIPE_CRC_DONE_INTERRUPT_STATUS) i9xx_pipe_crc_irq_handler(dev, pipe); if (pipe_stats[pipe] & PIPE_FIFO_UNDERRUN_STATUS && intel_set_cpu_fifo_underrun_reporting(dev, pipe, false)) DRM_ERROR("pipe %c underrun\n", pipe_name(pipe)); } if (pipe_stats[0] & PIPE_GMBUS_INTERRUPT_STATUS) gmbus_irq_handler(dev); } static irqreturn_t valleyview_irq_handler(int irq, void *arg) { struct drm_device *dev = (struct drm_device *) arg; drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u32 iir, gt_iir, pm_iir; irqreturn_t ret = IRQ_NONE; while (true) { iir = I915_READ(VLV_IIR); gt_iir = I915_READ(GTIIR); pm_iir = I915_READ(GEN6_PMIIR); if (gt_iir == 0 && pm_iir == 0 && iir == 0) goto out; ret = IRQ_HANDLED; snb_gt_irq_handler(dev, dev_priv, gt_iir); valleyview_pipestat_irq_handler(dev, iir); /* Consume port. Then clear IIR or we'll miss events */ if (iir & I915_DISPLAY_PORT_INTERRUPT) { u32 hotplug_status = I915_READ(PORT_HOTPLUG_STAT); u32 hotplug_trigger = hotplug_status & HOTPLUG_INT_STATUS_I915; intel_hpd_irq_handler(dev, hotplug_trigger, hpd_status_i915); if (hotplug_status & DP_AUX_CHANNEL_MASK_INT_STATUS_G4X) dp_aux_irq_handler(dev); I915_WRITE(PORT_HOTPLUG_STAT, hotplug_status); I915_READ(PORT_HOTPLUG_STAT); } if (pm_iir) gen6_rps_irq_handler(dev_priv, pm_iir); I915_WRITE(GTIIR, gt_iir); I915_WRITE(GEN6_PMIIR, pm_iir); I915_WRITE(VLV_IIR, iir); } out: return ret; } static void ibx_irq_handler(struct drm_device *dev, u32 pch_iir) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; u32 hotplug_trigger = pch_iir & SDE_HOTPLUG_MASK; intel_hpd_irq_handler(dev, hotplug_trigger, hpd_ibx); if (pch_iir & SDE_AUDIO_POWER_MASK) { int port = ffs((pch_iir & SDE_AUDIO_POWER_MASK) >> SDE_AUDIO_POWER_SHIFT); DRM_DEBUG_DRIVER("PCH audio power change on port %d\n", port_name(port)); } if (pch_iir & SDE_AUX_MASK) dp_aux_irq_handler(dev); if (pch_iir & SDE_GMBUS) gmbus_irq_handler(dev); if (pch_iir & SDE_AUDIO_HDCP_MASK) DRM_DEBUG_DRIVER("PCH HDCP audio interrupt\n"); if (pch_iir & SDE_AUDIO_TRANS_MASK) DRM_DEBUG_DRIVER("PCH transcoder audio interrupt\n"); if (pch_iir & SDE_POISON) DRM_ERROR("PCH poison interrupt\n"); if (pch_iir & SDE_FDI_MASK) for_each_pipe(pipe) DRM_DEBUG_DRIVER(" pipe %c FDI IIR: 0x%08x\n", pipe_name(pipe), I915_READ(FDI_RX_IIR(pipe))); if (pch_iir & (SDE_TRANSB_CRC_DONE | SDE_TRANSA_CRC_DONE)) DRM_DEBUG_DRIVER("PCH transcoder CRC done interrupt\n"); if (pch_iir & (SDE_TRANSB_CRC_ERR | SDE_TRANSA_CRC_ERR)) DRM_DEBUG_DRIVER("PCH transcoder CRC error interrupt\n"); if (pch_iir & SDE_TRANSA_FIFO_UNDER) if (intel_set_pch_fifo_underrun_reporting(dev, TRANSCODER_A, false)) DRM_ERROR("PCH transcoder A FIFO underrun\n"); if (pch_iir & SDE_TRANSB_FIFO_UNDER) if (intel_set_pch_fifo_underrun_reporting(dev, TRANSCODER_B, false)) DRM_ERROR("PCH transcoder B FIFO underrun\n"); } static void ivb_err_int_handler(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; u32 err_int = I915_READ(GEN7_ERR_INT); enum pipe pipe; if (err_int & ERR_INT_POISON) DRM_ERROR("Poison interrupt\n"); for_each_pipe(pipe) { if (err_int & ERR_INT_FIFO_UNDERRUN(pipe)) { if (intel_set_cpu_fifo_underrun_reporting(dev, pipe, false)) DRM_ERROR("Pipe %c FIFO underrun\n", pipe_name(pipe)); } if (err_int & ERR_INT_PIPE_CRC_DONE(pipe)) { if (IS_IVYBRIDGE(dev)) ivb_pipe_crc_irq_handler(dev, pipe); else hsw_pipe_crc_irq_handler(dev, pipe); } } I915_WRITE(GEN7_ERR_INT, err_int); } static void cpt_serr_int_handler(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; u32 serr_int = I915_READ(SERR_INT); if (serr_int & SERR_INT_POISON) DRM_ERROR("PCH poison interrupt\n"); if (serr_int & SERR_INT_TRANS_A_FIFO_UNDERRUN) if (intel_set_pch_fifo_underrun_reporting(dev, TRANSCODER_A, false)) DRM_ERROR("PCH transcoder A FIFO underrun\n"); if (serr_int & SERR_INT_TRANS_B_FIFO_UNDERRUN) if (intel_set_pch_fifo_underrun_reporting(dev, TRANSCODER_B, false)) DRM_ERROR("PCH transcoder B FIFO underrun\n"); if (serr_int & SERR_INT_TRANS_C_FIFO_UNDERRUN) if (intel_set_pch_fifo_underrun_reporting(dev, TRANSCODER_C, false)) DRM_ERROR("PCH transcoder C FIFO underrun\n"); I915_WRITE(SERR_INT, serr_int); } static void cpt_irq_handler(struct drm_device *dev, u32 pch_iir) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; u32 hotplug_trigger = pch_iir & SDE_HOTPLUG_MASK_CPT; intel_hpd_irq_handler(dev, hotplug_trigger, hpd_cpt); if (pch_iir & SDE_AUDIO_POWER_MASK_CPT) { int port = ffs((pch_iir & SDE_AUDIO_POWER_MASK_CPT) >> SDE_AUDIO_POWER_SHIFT_CPT); DRM_DEBUG_DRIVER("PCH audio power change on port %c\n", port_name(port)); } if (pch_iir & SDE_AUX_MASK_CPT) dp_aux_irq_handler(dev); if (pch_iir & SDE_GMBUS_CPT) gmbus_irq_handler(dev); if (pch_iir & SDE_AUDIO_CP_REQ_CPT) DRM_DEBUG_DRIVER("Audio CP request interrupt\n"); if (pch_iir & SDE_AUDIO_CP_CHG_CPT) DRM_DEBUG_DRIVER("Audio CP change interrupt\n"); if (pch_iir & SDE_FDI_MASK_CPT) for_each_pipe(pipe) DRM_DEBUG_DRIVER(" pipe %c FDI IIR: 0x%08x\n", pipe_name(pipe), I915_READ(FDI_RX_IIR(pipe))); if (pch_iir & SDE_ERROR_CPT) cpt_serr_int_handler(dev); } static void ilk_display_irq_handler(struct drm_device *dev, u32 de_iir) { struct drm_i915_private *dev_priv = dev->dev_private; enum pipe pipe; if (de_iir & DE_AUX_CHANNEL_A) dp_aux_irq_handler(dev); if (de_iir & DE_GSE) intel_opregion_asle_intr(dev); if (de_iir & DE_POISON) DRM_ERROR("Poison interrupt\n"); for_each_pipe(pipe) { if (de_iir & DE_PIPE_VBLANK(pipe)) drm_handle_vblank(dev, pipe); if (de_iir & DE_PIPE_FIFO_UNDERRUN(pipe)) if (intel_set_cpu_fifo_underrun_reporting(dev, pipe, false)) DRM_ERROR("Pipe %c FIFO underrun\n", pipe_name(pipe)); if (de_iir & DE_PIPE_CRC_DONE(pipe)) i9xx_pipe_crc_irq_handler(dev, pipe); /* plane/pipes map 1:1 on ilk+ */ if (de_iir & DE_PLANE_FLIP_DONE(pipe)) { intel_prepare_page_flip(dev, pipe); intel_finish_page_flip_plane(dev, pipe); } } /* check event from PCH */ if (de_iir & DE_PCH_EVENT) { u32 pch_iir = I915_READ(SDEIIR); if (HAS_PCH_CPT(dev)) cpt_irq_handler(dev, pch_iir); else ibx_irq_handler(dev, pch_iir); /* should clear PCH hotplug event before clear CPU irq */ I915_WRITE(SDEIIR, pch_iir); } if (IS_GEN5(dev) && de_iir & DE_PCU_EVENT) ironlake_rps_change_irq_handler(dev); } static void ivb_display_irq_handler(struct drm_device *dev, u32 de_iir) { struct drm_i915_private *dev_priv = dev->dev_private; enum pipe pipe; if (de_iir & DE_ERR_INT_IVB) ivb_err_int_handler(dev); if (de_iir & DE_AUX_CHANNEL_A_IVB) dp_aux_irq_handler(dev); if (de_iir & DE_GSE_IVB) intel_opregion_asle_intr(dev); for_each_pipe(pipe) { if (de_iir & (DE_PIPE_VBLANK_IVB(pipe))) drm_handle_vblank(dev, pipe); /* plane/pipes map 1:1 on ilk+ */ if (de_iir & DE_PLANE_FLIP_DONE_IVB(pipe)) { intel_prepare_page_flip(dev, pipe); intel_finish_page_flip_plane(dev, pipe); } } /* check event from PCH */ if (!HAS_PCH_NOP(dev) && (de_iir & DE_PCH_EVENT_IVB)) { u32 pch_iir = I915_READ(SDEIIR); cpt_irq_handler(dev, pch_iir); /* clear PCH hotplug event before clear CPU irq */ I915_WRITE(SDEIIR, pch_iir); } } static irqreturn_t ironlake_irq_handler(int irq, void *arg) { struct drm_device *dev = (struct drm_device *) arg; drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u32 de_iir, gt_iir, de_ier, sde_ier = 0; irqreturn_t ret = IRQ_NONE; /* We get interrupts on unclaimed registers, so check for this before we * do any I915_{READ,WRITE}. */ intel_uncore_check_errors(dev); /* disable master interrupt before clearing iir */ de_ier = I915_READ(DEIER); I915_WRITE(DEIER, de_ier & ~DE_MASTER_IRQ_CONTROL); POSTING_READ(DEIER); /* Disable south interrupts. We'll only write to SDEIIR once, so further * interrupts will will be stored on its back queue, and then we'll be * able to process them after we restore SDEIER (as soon as we restore * it, we'll get an interrupt if SDEIIR still has something to process * due to its back queue). */ if (!HAS_PCH_NOP(dev)) { sde_ier = I915_READ(SDEIER); I915_WRITE(SDEIER, 0); POSTING_READ(SDEIER); } gt_iir = I915_READ(GTIIR); if (gt_iir) { if (INTEL_INFO(dev)->gen >= 6) snb_gt_irq_handler(dev, dev_priv, gt_iir); else ilk_gt_irq_handler(dev, dev_priv, gt_iir); I915_WRITE(GTIIR, gt_iir); ret = IRQ_HANDLED; } de_iir = I915_READ(DEIIR); if (de_iir) { if (INTEL_INFO(dev)->gen >= 7) ivb_display_irq_handler(dev, de_iir); else ilk_display_irq_handler(dev, de_iir); I915_WRITE(DEIIR, de_iir); ret = IRQ_HANDLED; } if (INTEL_INFO(dev)->gen >= 6) { u32 pm_iir = I915_READ(GEN6_PMIIR); if (pm_iir) { gen6_rps_irq_handler(dev_priv, pm_iir); I915_WRITE(GEN6_PMIIR, pm_iir); ret = IRQ_HANDLED; } } I915_WRITE(DEIER, de_ier); POSTING_READ(DEIER); if (!HAS_PCH_NOP(dev)) { I915_WRITE(SDEIER, sde_ier); POSTING_READ(SDEIER); } return ret; } static irqreturn_t gen8_irq_handler(int irq, void *arg) { struct drm_device *dev = arg; struct drm_i915_private *dev_priv = dev->dev_private; u32 master_ctl; irqreturn_t ret = IRQ_NONE; uint32_t tmp = 0; enum pipe pipe; master_ctl = I915_READ(GEN8_MASTER_IRQ); master_ctl &= ~GEN8_MASTER_IRQ_CONTROL; if (!master_ctl) return IRQ_NONE; I915_WRITE(GEN8_MASTER_IRQ, 0); POSTING_READ(GEN8_MASTER_IRQ); ret = gen8_gt_irq_handler(dev, dev_priv, master_ctl); if (master_ctl & GEN8_DE_MISC_IRQ) { tmp = I915_READ(GEN8_DE_MISC_IIR); if (tmp & GEN8_DE_MISC_GSE) intel_opregion_asle_intr(dev); else if (tmp) DRM_ERROR("Unexpected DE Misc interrupt\n"); else DRM_ERROR("The master control interrupt lied (DE MISC)!\n"); if (tmp) { I915_WRITE(GEN8_DE_MISC_IIR, tmp); ret = IRQ_HANDLED; } } if (master_ctl & GEN8_DE_PORT_IRQ) { tmp = I915_READ(GEN8_DE_PORT_IIR); if (tmp & GEN8_AUX_CHANNEL_A) dp_aux_irq_handler(dev); else if (tmp) DRM_ERROR("Unexpected DE Port interrupt\n"); else DRM_ERROR("The master control interrupt lied (DE PORT)!\n"); if (tmp) { I915_WRITE(GEN8_DE_PORT_IIR, tmp); ret = IRQ_HANDLED; } } for_each_pipe(pipe) { uint32_t pipe_iir; if (!(master_ctl & GEN8_DE_PIPE_IRQ(pipe))) continue; pipe_iir = I915_READ(GEN8_DE_PIPE_IIR(pipe)); if (pipe_iir & GEN8_PIPE_VBLANK) drm_handle_vblank(dev, pipe); if (pipe_iir & GEN8_PIPE_FLIP_DONE) { intel_prepare_page_flip(dev, pipe); intel_finish_page_flip_plane(dev, pipe); } if (pipe_iir & GEN8_PIPE_CDCLK_CRC_DONE) hsw_pipe_crc_irq_handler(dev, pipe); if (pipe_iir & GEN8_PIPE_FIFO_UNDERRUN) { if (intel_set_cpu_fifo_underrun_reporting(dev, pipe, false)) DRM_ERROR("Pipe %c FIFO underrun\n", pipe_name(pipe)); } if (pipe_iir & GEN8_DE_PIPE_IRQ_FAULT_ERRORS) { DRM_ERROR("Fault errors on pipe %c\n: 0x%08x", pipe_name(pipe), pipe_iir & GEN8_DE_PIPE_IRQ_FAULT_ERRORS); } if (pipe_iir) { ret = IRQ_HANDLED; I915_WRITE(GEN8_DE_PIPE_IIR(pipe), pipe_iir); } else DRM_ERROR("The master control interrupt lied (DE PIPE)!\n"); } if (!HAS_PCH_NOP(dev) && master_ctl & GEN8_DE_PCH_IRQ) { /* * FIXME(BDW): Assume for now that the new interrupt handling * scheme also closed the SDE interrupt handling race we've seen * on older pch-split platforms. But this needs testing. */ u32 pch_iir = I915_READ(SDEIIR); cpt_irq_handler(dev, pch_iir); if (pch_iir) { I915_WRITE(SDEIIR, pch_iir); ret = IRQ_HANDLED; } } I915_WRITE(GEN8_MASTER_IRQ, GEN8_MASTER_IRQ_CONTROL); POSTING_READ(GEN8_MASTER_IRQ); return ret; } static void i915_error_wake_up(struct drm_i915_private *dev_priv, bool reset_completed) { struct intel_ring_buffer *ring; int i; /* * Notify all waiters for GPU completion events that reset state has * been changed, and that they need to restart their wait after * checking for potential errors (and bail out to drop locks if there is * a gpu reset pending so that i915_error_work_func can acquire them). */ /* Wake up __wait_seqno, potentially holding dev->struct_mutex. */ for_each_ring(ring, dev_priv, i) wake_up_all(&ring->irq_queue); /* Wake up intel_crtc_wait_for_pending_flips, holding crtc->mutex. */ wake_up_all(&dev_priv->pending_flip_queue); /* * Signal tasks blocked in i915_gem_wait_for_error that the pending * reset state is cleared. */ if (reset_completed) wake_up_all(&dev_priv->gpu_error.reset_queue); } /** * i915_error_work_func - do process context error handling work * @work: work struct * * Fire an error uevent so userspace can see that a hang or error * was detected. */ static void i915_error_work_func(struct work_struct *work) { struct i915_gpu_error *error = container_of(work, struct i915_gpu_error, work); drm_i915_private_t *dev_priv = container_of(error, drm_i915_private_t, gpu_error); struct drm_device *dev = dev_priv->dev; char *error_event[] = { I915_ERROR_UEVENT "=1", NULL }; char *reset_event[] = { I915_RESET_UEVENT "=1", NULL }; char *reset_done_event[] = { I915_ERROR_UEVENT "=0", NULL }; int ret; kobject_uevent_env(&dev->primary->kdev->kobj, KOBJ_CHANGE, error_event); /* * Note that there's only one work item which does gpu resets, so we * need not worry about concurrent gpu resets potentially incrementing * error->reset_counter twice. We only need to take care of another * racing irq/hangcheck declaring the gpu dead for a second time. A * quick check for that is good enough: schedule_work ensures the * correct ordering between hang detection and this work item, and since * the reset in-progress bit is only ever set by code outside of this * work we don't need to worry about any other races. */ if (i915_reset_in_progress(error) && !i915_terminally_wedged(error)) { DRM_DEBUG_DRIVER("resetting chip\n"); kobject_uevent_env(&dev->primary->kdev->kobj, KOBJ_CHANGE, reset_event); /* * All state reset _must_ be completed before we update the * reset counter, for otherwise waiters might miss the reset * pending state and not properly drop locks, resulting in * deadlocks with the reset work. */ ret = i915_reset(dev); intel_display_handle_reset(dev); if (ret == 0) { /* * After all the gem state is reset, increment the reset * counter and wake up everyone waiting for the reset to * complete. * * Since unlock operations are a one-sided barrier only, * we need to insert a barrier here to order any seqno * updates before * the counter increment. */ smp_mb__before_atomic_inc(); atomic_inc(&dev_priv->gpu_error.reset_counter); kobject_uevent_env(&dev->primary->kdev->kobj, KOBJ_CHANGE, reset_done_event); } else { atomic_set_mask(I915_WEDGED, &error->reset_counter); } /* * Note: The wake_up also serves as a memory barrier so that * waiters see the update value of the reset counter atomic_t. */ i915_error_wake_up(dev_priv, true); } } static void i915_report_and_clear_eir(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; uint32_t instdone[I915_NUM_INSTDONE_REG]; u32 eir = I915_READ(EIR); int pipe, i; if (!eir) return; pr_err("render error detected, EIR: 0x%08x\n", eir); i915_get_extra_instdone(dev, instdone); if (IS_G4X(dev)) { if (eir & (GM45_ERROR_MEM_PRIV | GM45_ERROR_CP_PRIV)) { u32 ipeir = I915_READ(IPEIR_I965); pr_err(" IPEIR: 0x%08x\n", I915_READ(IPEIR_I965)); pr_err(" IPEHR: 0x%08x\n", I915_READ(IPEHR_I965)); for (i = 0; i < ARRAY_SIZE(instdone); i++) pr_err(" INSTDONE_%d: 0x%08x\n", i, instdone[i]); pr_err(" INSTPS: 0x%08x\n", I915_READ(INSTPS)); pr_err(" ACTHD: 0x%08x\n", I915_READ(ACTHD_I965)); I915_WRITE(IPEIR_I965, ipeir); POSTING_READ(IPEIR_I965); } if (eir & GM45_ERROR_PAGE_TABLE) { u32 pgtbl_err = I915_READ(PGTBL_ER); pr_err("page table error\n"); pr_err(" PGTBL_ER: 0x%08x\n", pgtbl_err); I915_WRITE(PGTBL_ER, pgtbl_err); POSTING_READ(PGTBL_ER); } } if (!IS_GEN2(dev)) { if (eir & I915_ERROR_PAGE_TABLE) { u32 pgtbl_err = I915_READ(PGTBL_ER); pr_err("page table error\n"); pr_err(" PGTBL_ER: 0x%08x\n", pgtbl_err); I915_WRITE(PGTBL_ER, pgtbl_err); POSTING_READ(PGTBL_ER); } } if (eir & I915_ERROR_MEMORY_REFRESH) { pr_err("memory refresh error:\n"); for_each_pipe(pipe) pr_err("pipe %c stat: 0x%08x\n", pipe_name(pipe), I915_READ(PIPESTAT(pipe))); /* pipestat has already been acked */ } if (eir & I915_ERROR_INSTRUCTION) { pr_err("instruction error\n"); pr_err(" INSTPM: 0x%08x\n", I915_READ(INSTPM)); for (i = 0; i < ARRAY_SIZE(instdone); i++) pr_err(" INSTDONE_%d: 0x%08x\n", i, instdone[i]); if (INTEL_INFO(dev)->gen < 4) { u32 ipeir = I915_READ(IPEIR); pr_err(" IPEIR: 0x%08x\n", I915_READ(IPEIR)); pr_err(" IPEHR: 0x%08x\n", I915_READ(IPEHR)); pr_err(" ACTHD: 0x%08x\n", I915_READ(ACTHD)); I915_WRITE(IPEIR, ipeir); POSTING_READ(IPEIR); } else { u32 ipeir = I915_READ(IPEIR_I965); pr_err(" IPEIR: 0x%08x\n", I915_READ(IPEIR_I965)); pr_err(" IPEHR: 0x%08x\n", I915_READ(IPEHR_I965)); pr_err(" INSTPS: 0x%08x\n", I915_READ(INSTPS)); pr_err(" ACTHD: 0x%08x\n", I915_READ(ACTHD_I965)); I915_WRITE(IPEIR_I965, ipeir); POSTING_READ(IPEIR_I965); } } I915_WRITE(EIR, eir); POSTING_READ(EIR); eir = I915_READ(EIR); if (eir) { /* * some errors might have become stuck, * mask them. */ DRM_ERROR("EIR stuck: 0x%08x, masking\n", eir); I915_WRITE(EMR, I915_READ(EMR) | eir); I915_WRITE(IIR, I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT); } } /** * i915_handle_error - handle an error interrupt * @dev: drm device * * Do some basic checking of regsiter state at error interrupt time and * dump it to the syslog. Also call i915_capture_error_state() to make * sure we get a record and make it available in debugfs. Fire a uevent * so userspace knows something bad happened (should trigger collection * of a ring dump etc.). */ void i915_handle_error(struct drm_device *dev, bool wedged, const char *fmt, ...) { struct drm_i915_private *dev_priv = dev->dev_private; va_list args; char error_msg[80]; va_start(args, fmt); vscnprintf(error_msg, sizeof(error_msg), fmt, args); va_end(args); i915_capture_error_state(dev, wedged, error_msg); i915_report_and_clear_eir(dev); if (wedged) { atomic_set_mask(I915_RESET_IN_PROGRESS_FLAG, &dev_priv->gpu_error.reset_counter); /* * Wakeup waiting processes so that the reset work function * i915_error_work_func doesn't deadlock trying to grab various * locks. By bumping the reset counter first, the woken * processes will see a reset in progress and back off, * releasing their locks and then wait for the reset completion. * We must do this for _all_ gpu waiters that might hold locks * that the reset work needs to acquire. * * Note: The wake_up serves as the required memory barrier to * ensure that the waiters see the updated value of the reset * counter atomic_t. */ i915_error_wake_up(dev_priv, false); } /* * Our reset work can grab modeset locks (since it needs to reset the * state of outstanding pagelips). Hence it must not be run on our own * dev-priv->wq work queue for otherwise the flush_work in the pageflip * code will deadlock. */ schedule_work(&dev_priv->gpu_error.work); } static void __always_unused i915_pageflip_stall_check(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = dev->dev_private; struct drm_crtc *crtc = dev_priv->pipe_to_crtc_mapping[pipe]; struct intel_crtc *intel_crtc = to_intel_crtc(crtc); struct drm_i915_gem_object *obj; struct intel_unpin_work *work; unsigned long flags; bool stall_detected; /* Ignore early vblank irqs */ if (intel_crtc == NULL) return; spin_lock_irqsave(&dev->event_lock, flags); work = intel_crtc->unpin_work; if (work == NULL || atomic_read(&work->pending) >= INTEL_FLIP_COMPLETE || !work->enable_stall_check) { /* Either the pending flip IRQ arrived, or we're too early. Don't check */ spin_unlock_irqrestore(&dev->event_lock, flags); return; } /* Potential stall - if we see that the flip has happened, assume a missed interrupt */ obj = work->pending_flip_obj; if (INTEL_INFO(dev)->gen >= 4) { int dspsurf = DSPSURF(intel_crtc->plane); stall_detected = I915_HI_DISPBASE(I915_READ(dspsurf)) == i915_gem_obj_ggtt_offset(obj); } else { int dspaddr = DSPADDR(intel_crtc->plane); stall_detected = I915_READ(dspaddr) == (i915_gem_obj_ggtt_offset(obj) + crtc->y * crtc->fb->pitches[0] + crtc->x * crtc->fb->bits_per_pixel/8); } spin_unlock_irqrestore(&dev->event_lock, flags); if (stall_detected) { DRM_DEBUG_DRIVER("Pageflip stall detected\n"); intel_prepare_page_flip(dev, intel_crtc->plane); } } /* Called from drm generic code, passed 'crtc' which * we use as a pipe index */ static int i915_enable_vblank(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; if (!i915_pipe_enabled(dev, pipe)) return -EINVAL; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); if (INTEL_INFO(dev)->gen >= 4) i915_enable_pipestat(dev_priv, pipe, PIPE_START_VBLANK_INTERRUPT_STATUS); else i915_enable_pipestat(dev_priv, pipe, PIPE_VBLANK_INTERRUPT_STATUS); /* maintain vblank delivery even in deep C-states */ if (INTEL_INFO(dev)->gen == 3) I915_WRITE(INSTPM, _MASKED_BIT_DISABLE(INSTPM_AGPBUSY_DIS)); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); return 0; } static int ironlake_enable_vblank(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; uint32_t bit = (INTEL_INFO(dev)->gen >= 7) ? DE_PIPE_VBLANK_IVB(pipe) : DE_PIPE_VBLANK(pipe); if (!i915_pipe_enabled(dev, pipe)) return -EINVAL; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); ironlake_enable_display_irq(dev_priv, bit); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); return 0; } static int valleyview_enable_vblank(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; if (!i915_pipe_enabled(dev, pipe)) return -EINVAL; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); i915_enable_pipestat(dev_priv, pipe, PIPE_START_VBLANK_INTERRUPT_STATUS); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); return 0; } static int gen8_enable_vblank(struct drm_device *dev, int pipe) { struct drm_i915_private *dev_priv = dev->dev_private; unsigned long irqflags; if (!i915_pipe_enabled(dev, pipe)) return -EINVAL; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); dev_priv->de_irq_mask[pipe] &= ~GEN8_PIPE_VBLANK; I915_WRITE(GEN8_DE_PIPE_IMR(pipe), dev_priv->de_irq_mask[pipe]); POSTING_READ(GEN8_DE_PIPE_IMR(pipe)); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); return 0; } /* Called from drm generic code, passed 'crtc' which * we use as a pipe index */ static void i915_disable_vblank(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); if (INTEL_INFO(dev)->gen == 3) I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_AGPBUSY_DIS)); i915_disable_pipestat(dev_priv, pipe, PIPE_VBLANK_INTERRUPT_STATUS | PIPE_START_VBLANK_INTERRUPT_STATUS); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } static void ironlake_disable_vblank(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; uint32_t bit = (INTEL_INFO(dev)->gen >= 7) ? DE_PIPE_VBLANK_IVB(pipe) : DE_PIPE_VBLANK(pipe); spin_lock_irqsave(&dev_priv->irq_lock, irqflags); ironlake_disable_display_irq(dev_priv, bit); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } static void valleyview_disable_vblank(struct drm_device *dev, int pipe) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); i915_disable_pipestat(dev_priv, pipe, PIPE_START_VBLANK_INTERRUPT_STATUS); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } static void gen8_disable_vblank(struct drm_device *dev, int pipe) { struct drm_i915_private *dev_priv = dev->dev_private; unsigned long irqflags; if (!i915_pipe_enabled(dev, pipe)) return; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); dev_priv->de_irq_mask[pipe] |= GEN8_PIPE_VBLANK; I915_WRITE(GEN8_DE_PIPE_IMR(pipe), dev_priv->de_irq_mask[pipe]); POSTING_READ(GEN8_DE_PIPE_IMR(pipe)); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } static u32 ring_last_seqno(struct intel_ring_buffer *ring) { return list_entry(ring->request_list.prev, struct drm_i915_gem_request, list)->seqno; } static bool ring_idle(struct intel_ring_buffer *ring, u32 seqno) { return (list_empty(&ring->request_list) || i915_seqno_passed(seqno, ring_last_seqno(ring))); } static struct intel_ring_buffer * semaphore_waits_for(struct intel_ring_buffer *ring, u32 *seqno) { struct drm_i915_private *dev_priv = ring->dev->dev_private; u32 cmd, ipehr, acthd, acthd_min; ipehr = I915_READ(RING_IPEHR(ring->mmio_base)); if ((ipehr & ~(0x3 << 16)) != (MI_SEMAPHORE_MBOX | MI_SEMAPHORE_COMPARE | MI_SEMAPHORE_REGISTER)) return NULL; /* ACTHD is likely pointing to the dword after the actual command, * so scan backwards until we find the MBOX. */ acthd = intel_ring_get_active_head(ring) & HEAD_ADDR; acthd_min = max((int)acthd - 3 * 4, 0); do { cmd = ioread32(ring->virtual_start + acthd); if (cmd == ipehr) break; acthd -= 4; if (acthd < acthd_min) return NULL; } while (1); *seqno = ioread32(ring->virtual_start+acthd+4)+1; return &dev_priv->ring[(ring->id + (((ipehr >> 17) & 1) + 1)) % 3]; } static int semaphore_passed(struct intel_ring_buffer *ring) { struct drm_i915_private *dev_priv = ring->dev->dev_private; struct intel_ring_buffer *signaller; u32 seqno, ctl; ring->hangcheck.deadlock = true; signaller = semaphore_waits_for(ring, &seqno); if (signaller == NULL || signaller->hangcheck.deadlock) return -1; /* cursory check for an unkickable deadlock */ ctl = I915_READ_CTL(signaller); if (ctl & RING_WAIT_SEMAPHORE && semaphore_passed(signaller) < 0) return -1; return i915_seqno_passed(signaller->get_seqno(signaller, false), seqno); } static void semaphore_clear_deadlocks(struct drm_i915_private *dev_priv) { struct intel_ring_buffer *ring; int i; for_each_ring(ring, dev_priv, i) ring->hangcheck.deadlock = false; } static enum intel_ring_hangcheck_action ring_stuck(struct intel_ring_buffer *ring, u64 acthd) { struct drm_device *dev = ring->dev; struct drm_i915_private *dev_priv = dev->dev_private; u32 tmp; if (ring->hangcheck.acthd != acthd) return HANGCHECK_ACTIVE; if (IS_GEN2(dev)) return HANGCHECK_HUNG; /* Is the chip hanging on a WAIT_FOR_EVENT? * If so we can simply poke the RB_WAIT bit * and break the hang. This should work on * all but the second generation chipsets. */ tmp = I915_READ_CTL(ring); if (tmp & RING_WAIT) { i915_handle_error(dev, false, "Kicking stuck wait on %s", ring->name); I915_WRITE_CTL(ring, tmp); return HANGCHECK_KICK; } if (INTEL_INFO(dev)->gen >= 6 && tmp & RING_WAIT_SEMAPHORE) { switch (semaphore_passed(ring)) { default: return HANGCHECK_HUNG; case 1: i915_handle_error(dev, false, "Kicking stuck semaphore on %s", ring->name); I915_WRITE_CTL(ring, tmp); return HANGCHECK_KICK; case 0: return HANGCHECK_WAIT; } } return HANGCHECK_HUNG; } /** * This is called when the chip hasn't reported back with completed * batchbuffers in a long time. We keep track per ring seqno progress and * if there are no progress, hangcheck score for that ring is increased. * Further, acthd is inspected to see if the ring is stuck. On stuck case * we kick the ring. If we see no progress on three subsequent calls * we assume chip is wedged and try to fix it by resetting the chip. */ static void i915_hangcheck_elapsed(unsigned long data) { struct drm_device *dev = (struct drm_device *)data; drm_i915_private_t *dev_priv = dev->dev_private; struct intel_ring_buffer *ring; int i; int busy_count = 0, rings_hung = 0; bool stuck[I915_NUM_RINGS] = { 0 }; #define BUSY 1 #define KICK 5 #define HUNG 20 if (!i915.enable_hangcheck) return; for_each_ring(ring, dev_priv, i) { u64 acthd; u32 seqno; bool busy = true; semaphore_clear_deadlocks(dev_priv); seqno = ring->get_seqno(ring, false); acthd = intel_ring_get_active_head(ring); if (ring->hangcheck.seqno == seqno) { if (ring_idle(ring, seqno)) { ring->hangcheck.action = HANGCHECK_IDLE; if (waitqueue_active(&ring->irq_queue)) { /* Issue a wake-up to catch stuck h/w. */ if (!test_and_set_bit(ring->id, &dev_priv->gpu_error.missed_irq_rings)) { if (!(dev_priv->gpu_error.test_irq_rings & intel_ring_flag(ring))) DRM_ERROR("Hangcheck timer elapsed... %s idle\n", ring->name); else DRM_INFO("Fake missed irq on %s\n", ring->name); wake_up_all(&ring->irq_queue); } /* Safeguard against driver failure */ ring->hangcheck.score += BUSY; } else busy = false; } else { /* We always increment the hangcheck score * if the ring is busy and still processing * the same request, so that no single request * can run indefinitely (such as a chain of * batches). The only time we do not increment * the hangcheck score on this ring, if this * ring is in a legitimate wait for another * ring. In that case the waiting ring is a * victim and we want to be sure we catch the * right culprit. Then every time we do kick * the ring, add a small increment to the * score so that we can catch a batch that is * being repeatedly kicked and so responsible * for stalling the machine. */ ring->hangcheck.action = ring_stuck(ring, acthd); switch (ring->hangcheck.action) { case HANGCHECK_IDLE: case HANGCHECK_WAIT: break; case HANGCHECK_ACTIVE: ring->hangcheck.score += BUSY; break; case HANGCHECK_KICK: ring->hangcheck.score += KICK; break; case HANGCHECK_HUNG: ring->hangcheck.score += HUNG; stuck[i] = true; break; } } } else { ring->hangcheck.action = HANGCHECK_ACTIVE; /* Gradually reduce the count so that we catch DoS * attempts across multiple batches. */ if (ring->hangcheck.score > 0) ring->hangcheck.score--; } ring->hangcheck.seqno = seqno; ring->hangcheck.acthd = acthd; busy_count += busy; } for_each_ring(ring, dev_priv, i) { if (ring->hangcheck.score >= HANGCHECK_SCORE_RING_HUNG) { DRM_INFO("%s on %s\n", stuck[i] ? "stuck" : "no progress", ring->name); rings_hung++; } } if (rings_hung) return i915_handle_error(dev, true, "Ring hung"); if (busy_count) /* Reset timer case chip hangs without another request * being added */ i915_queue_hangcheck(dev); } void i915_queue_hangcheck(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; if (!i915.enable_hangcheck) return; mod_timer(&dev_priv->gpu_error.hangcheck_timer, round_jiffies_up(jiffies + DRM_I915_HANGCHECK_JIFFIES)); } static void ibx_irq_preinstall(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; if (HAS_PCH_NOP(dev)) return; /* south display irq */ I915_WRITE(SDEIMR, 0xffffffff); /* * SDEIER is also touched by the interrupt handler to work around missed * PCH interrupts. Hence we can't update it after the interrupt handler * is enabled - instead we unconditionally enable all PCH interrupt * sources here, but then only unmask them as needed with SDEIMR. */ I915_WRITE(SDEIER, 0xffffffff); POSTING_READ(SDEIER); } static void gen5_gt_irq_preinstall(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; /* and GT */ I915_WRITE(GTIMR, 0xffffffff); I915_WRITE(GTIER, 0x0); POSTING_READ(GTIER); if (INTEL_INFO(dev)->gen >= 6) { /* and PM */ I915_WRITE(GEN6_PMIMR, 0xffffffff); I915_WRITE(GEN6_PMIER, 0x0); POSTING_READ(GEN6_PMIER); } } /* drm_dma.h hooks */ static void ironlake_irq_preinstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; I915_WRITE(HWSTAM, 0xeffe); I915_WRITE(DEIMR, 0xffffffff); I915_WRITE(DEIER, 0x0); POSTING_READ(DEIER); gen5_gt_irq_preinstall(dev); ibx_irq_preinstall(dev); } static void valleyview_irq_preinstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; /* VLV magic */ I915_WRITE(VLV_IMR, 0); I915_WRITE(RING_IMR(RENDER_RING_BASE), 0); I915_WRITE(RING_IMR(GEN6_BSD_RING_BASE), 0); I915_WRITE(RING_IMR(BLT_RING_BASE), 0); /* and GT */ I915_WRITE(GTIIR, I915_READ(GTIIR)); I915_WRITE(GTIIR, I915_READ(GTIIR)); gen5_gt_irq_preinstall(dev); I915_WRITE(DPINVGTT, 0xff); I915_WRITE(PORT_HOTPLUG_EN, 0); I915_WRITE(PORT_HOTPLUG_STAT, I915_READ(PORT_HOTPLUG_STAT)); for_each_pipe(pipe) I915_WRITE(PIPESTAT(pipe), 0xffff); I915_WRITE(VLV_IIR, 0xffffffff); I915_WRITE(VLV_IMR, 0xffffffff); I915_WRITE(VLV_IER, 0x0); POSTING_READ(VLV_IER); } static void gen8_irq_preinstall(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int pipe; I915_WRITE(GEN8_MASTER_IRQ, 0); POSTING_READ(GEN8_MASTER_IRQ); /* IIR can theoretically queue up two events. Be paranoid */ #define GEN8_IRQ_INIT_NDX(type, which) do { \ I915_WRITE(GEN8_##type##_IMR(which), 0xffffffff); \ POSTING_READ(GEN8_##type##_IMR(which)); \ I915_WRITE(GEN8_##type##_IER(which), 0); \ I915_WRITE(GEN8_##type##_IIR(which), 0xffffffff); \ POSTING_READ(GEN8_##type##_IIR(which)); \ I915_WRITE(GEN8_##type##_IIR(which), 0xffffffff); \ } while (0) #define GEN8_IRQ_INIT(type) do { \ I915_WRITE(GEN8_##type##_IMR, 0xffffffff); \ POSTING_READ(GEN8_##type##_IMR); \ I915_WRITE(GEN8_##type##_IER, 0); \ I915_WRITE(GEN8_##type##_IIR, 0xffffffff); \ POSTING_READ(GEN8_##type##_IIR); \ I915_WRITE(GEN8_##type##_IIR, 0xffffffff); \ } while (0) GEN8_IRQ_INIT_NDX(GT, 0); GEN8_IRQ_INIT_NDX(GT, 1); GEN8_IRQ_INIT_NDX(GT, 2); GEN8_IRQ_INIT_NDX(GT, 3); for_each_pipe(pipe) { GEN8_IRQ_INIT_NDX(DE_PIPE, pipe); } GEN8_IRQ_INIT(DE_PORT); GEN8_IRQ_INIT(DE_MISC); GEN8_IRQ_INIT(PCU); #undef GEN8_IRQ_INIT #undef GEN8_IRQ_INIT_NDX POSTING_READ(GEN8_PCU_IIR); ibx_irq_preinstall(dev); } static void ibx_hpd_irq_setup(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; struct drm_mode_config *mode_config = &dev->mode_config; struct intel_encoder *intel_encoder; u32 hotplug_irqs, hotplug, enabled_irqs = 0; if (HAS_PCH_IBX(dev)) { hotplug_irqs = SDE_HOTPLUG_MASK; list_for_each_entry(intel_encoder, &mode_config->encoder_list, base.head) if (dev_priv->hpd_stats[intel_encoder->hpd_pin].hpd_mark == HPD_ENABLED) enabled_irqs |= hpd_ibx[intel_encoder->hpd_pin]; } else { hotplug_irqs = SDE_HOTPLUG_MASK_CPT; list_for_each_entry(intel_encoder, &mode_config->encoder_list, base.head) if (dev_priv->hpd_stats[intel_encoder->hpd_pin].hpd_mark == HPD_ENABLED) enabled_irqs |= hpd_cpt[intel_encoder->hpd_pin]; } ibx_display_interrupt_update(dev_priv, hotplug_irqs, enabled_irqs); /* * Enable digital hotplug on the PCH, and configure the DP short pulse * duration to 2ms (which is the minimum in the Display Port spec) * * This register is the same on all known PCH chips. */ hotplug = I915_READ(PCH_PORT_HOTPLUG); hotplug &= ~(PORTD_PULSE_DURATION_MASK|PORTC_PULSE_DURATION_MASK|PORTB_PULSE_DURATION_MASK); hotplug |= PORTD_HOTPLUG_ENABLE | PORTD_PULSE_DURATION_2ms; hotplug |= PORTC_HOTPLUG_ENABLE | PORTC_PULSE_DURATION_2ms; hotplug |= PORTB_HOTPLUG_ENABLE | PORTB_PULSE_DURATION_2ms; I915_WRITE(PCH_PORT_HOTPLUG, hotplug); } static void ibx_irq_postinstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u32 mask; if (HAS_PCH_NOP(dev)) return; if (HAS_PCH_IBX(dev)) { mask = SDE_GMBUS | SDE_AUX_MASK | SDE_TRANSB_FIFO_UNDER | SDE_TRANSA_FIFO_UNDER | SDE_POISON; } else { mask = SDE_GMBUS_CPT | SDE_AUX_MASK_CPT | SDE_ERROR_CPT; I915_WRITE(SERR_INT, I915_READ(SERR_INT)); } I915_WRITE(SDEIIR, I915_READ(SDEIIR)); I915_WRITE(SDEIMR, ~mask); } static void gen5_gt_irq_postinstall(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; u32 pm_irqs, gt_irqs; pm_irqs = gt_irqs = 0; dev_priv->gt_irq_mask = ~0; if (HAS_L3_DPF(dev)) { /* L3 parity interrupt is always unmasked. */ dev_priv->gt_irq_mask = ~GT_PARITY_ERROR(dev); gt_irqs |= GT_PARITY_ERROR(dev); } gt_irqs |= GT_RENDER_USER_INTERRUPT; if (IS_GEN5(dev)) { gt_irqs |= GT_RENDER_PIPECTL_NOTIFY_INTERRUPT | ILK_BSD_USER_INTERRUPT; } else { gt_irqs |= GT_BLT_USER_INTERRUPT | GT_BSD_USER_INTERRUPT; } I915_WRITE(GTIIR, I915_READ(GTIIR)); I915_WRITE(GTIMR, dev_priv->gt_irq_mask); I915_WRITE(GTIER, gt_irqs); POSTING_READ(GTIER); if (INTEL_INFO(dev)->gen >= 6) { pm_irqs |= GEN6_PM_RPS_EVENTS; if (HAS_VEBOX(dev)) pm_irqs |= PM_VEBOX_USER_INTERRUPT; dev_priv->pm_irq_mask = 0xffffffff; I915_WRITE(GEN6_PMIIR, I915_READ(GEN6_PMIIR)); I915_WRITE(GEN6_PMIMR, dev_priv->pm_irq_mask); I915_WRITE(GEN6_PMIER, pm_irqs); POSTING_READ(GEN6_PMIER); } } static int ironlake_irq_postinstall(struct drm_device *dev) { unsigned long irqflags; drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u32 display_mask, extra_mask; if (INTEL_INFO(dev)->gen >= 7) { display_mask = (DE_MASTER_IRQ_CONTROL | DE_GSE_IVB | DE_PCH_EVENT_IVB | DE_PLANEC_FLIP_DONE_IVB | DE_PLANEB_FLIP_DONE_IVB | DE_PLANEA_FLIP_DONE_IVB | DE_AUX_CHANNEL_A_IVB | DE_ERR_INT_IVB); extra_mask = (DE_PIPEC_VBLANK_IVB | DE_PIPEB_VBLANK_IVB | DE_PIPEA_VBLANK_IVB); I915_WRITE(GEN7_ERR_INT, I915_READ(GEN7_ERR_INT)); } else { display_mask = (DE_MASTER_IRQ_CONTROL | DE_GSE | DE_PCH_EVENT | DE_PLANEA_FLIP_DONE | DE_PLANEB_FLIP_DONE | DE_AUX_CHANNEL_A | DE_PIPEB_FIFO_UNDERRUN | DE_PIPEA_FIFO_UNDERRUN | DE_PIPEB_CRC_DONE | DE_PIPEA_CRC_DONE | DE_POISON); extra_mask = DE_PIPEA_VBLANK | DE_PIPEB_VBLANK | DE_PCU_EVENT; } dev_priv->irq_mask = ~display_mask; /* should always can generate irq */ I915_WRITE(DEIIR, I915_READ(DEIIR)); I915_WRITE(DEIMR, dev_priv->irq_mask); I915_WRITE(DEIER, display_mask | extra_mask); POSTING_READ(DEIER); gen5_gt_irq_postinstall(dev); ibx_irq_postinstall(dev); if (IS_IRONLAKE_M(dev)) { /* Enable PCU event interrupts * * spinlocking not required here for correctness since interrupt * setup is guaranteed to run in single-threaded context. But we * need it to make the assert_spin_locked happy. */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); ironlake_enable_display_irq(dev_priv, DE_PCU_EVENT); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } return 0; } static void valleyview_display_irqs_install(struct drm_i915_private *dev_priv) { u32 pipestat_mask; u32 iir_mask; pipestat_mask = PIPESTAT_INT_STATUS_MASK | PIPE_FIFO_UNDERRUN_STATUS; I915_WRITE(PIPESTAT(PIPE_A), pipestat_mask); I915_WRITE(PIPESTAT(PIPE_B), pipestat_mask); POSTING_READ(PIPESTAT(PIPE_A)); pipestat_mask = PLANE_FLIP_DONE_INT_STATUS_VLV | PIPE_CRC_DONE_INTERRUPT_STATUS; i915_enable_pipestat(dev_priv, PIPE_A, pipestat_mask | PIPE_GMBUS_INTERRUPT_STATUS); i915_enable_pipestat(dev_priv, PIPE_B, pipestat_mask); iir_mask = I915_DISPLAY_PORT_INTERRUPT | I915_DISPLAY_PIPE_A_EVENT_INTERRUPT | I915_DISPLAY_PIPE_B_EVENT_INTERRUPT; dev_priv->irq_mask &= ~iir_mask; I915_WRITE(VLV_IIR, iir_mask); I915_WRITE(VLV_IIR, iir_mask); I915_WRITE(VLV_IMR, dev_priv->irq_mask); I915_WRITE(VLV_IER, ~dev_priv->irq_mask); POSTING_READ(VLV_IER); } static void valleyview_display_irqs_uninstall(struct drm_i915_private *dev_priv) { u32 pipestat_mask; u32 iir_mask; iir_mask = I915_DISPLAY_PORT_INTERRUPT | I915_DISPLAY_PIPE_A_EVENT_INTERRUPT | I915_DISPLAY_PIPE_A_EVENT_INTERRUPT; dev_priv->irq_mask |= iir_mask; I915_WRITE(VLV_IER, ~dev_priv->irq_mask); I915_WRITE(VLV_IMR, dev_priv->irq_mask); I915_WRITE(VLV_IIR, iir_mask); I915_WRITE(VLV_IIR, iir_mask); POSTING_READ(VLV_IIR); pipestat_mask = PLANE_FLIP_DONE_INT_STATUS_VLV | PIPE_CRC_DONE_INTERRUPT_STATUS; i915_disable_pipestat(dev_priv, PIPE_A, pipestat_mask | PIPE_GMBUS_INTERRUPT_STATUS); i915_disable_pipestat(dev_priv, PIPE_B, pipestat_mask); pipestat_mask = PIPESTAT_INT_STATUS_MASK | PIPE_FIFO_UNDERRUN_STATUS; I915_WRITE(PIPESTAT(PIPE_A), pipestat_mask); I915_WRITE(PIPESTAT(PIPE_B), pipestat_mask); POSTING_READ(PIPESTAT(PIPE_A)); } void valleyview_enable_display_irqs(struct drm_i915_private *dev_priv) { assert_spin_locked(&dev_priv->irq_lock); if (dev_priv->display_irqs_enabled) return; dev_priv->display_irqs_enabled = true; if (dev_priv->dev->irq_enabled) valleyview_display_irqs_install(dev_priv); } void valleyview_disable_display_irqs(struct drm_i915_private *dev_priv) { assert_spin_locked(&dev_priv->irq_lock); if (!dev_priv->display_irqs_enabled) return; dev_priv->display_irqs_enabled = false; if (dev_priv->dev->irq_enabled) valleyview_display_irqs_uninstall(dev_priv); } static int valleyview_irq_postinstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; dev_priv->irq_mask = ~0; I915_WRITE(PORT_HOTPLUG_EN, 0); POSTING_READ(PORT_HOTPLUG_EN); I915_WRITE(VLV_IMR, dev_priv->irq_mask); I915_WRITE(VLV_IER, ~dev_priv->irq_mask); I915_WRITE(VLV_IIR, 0xffffffff); POSTING_READ(VLV_IER); /* Interrupt setup is already guaranteed to be single-threaded, this is * just to make the assert_spin_locked check happy. */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); if (dev_priv->display_irqs_enabled) valleyview_display_irqs_install(dev_priv); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); I915_WRITE(VLV_IIR, 0xffffffff); I915_WRITE(VLV_IIR, 0xffffffff); gen5_gt_irq_postinstall(dev); /* ack & enable invalid PTE error interrupts */ #if 0 /* FIXME: add support to irq handler for checking these bits */ I915_WRITE(DPINVGTT, DPINVGTT_STATUS_MASK); I915_WRITE(DPINVGTT, DPINVGTT_EN_MASK); #endif I915_WRITE(VLV_MASTER_IER, MASTER_INTERRUPT_ENABLE); return 0; } static void gen8_gt_irq_postinstall(struct drm_i915_private *dev_priv) { int i; /* These are interrupts we'll toggle with the ring mask register */ uint32_t gt_interrupts[] = { GT_RENDER_USER_INTERRUPT << GEN8_RCS_IRQ_SHIFT | GT_RENDER_L3_PARITY_ERROR_INTERRUPT | GT_RENDER_USER_INTERRUPT << GEN8_BCS_IRQ_SHIFT, GT_RENDER_USER_INTERRUPT << GEN8_VCS1_IRQ_SHIFT | GT_RENDER_USER_INTERRUPT << GEN8_VCS2_IRQ_SHIFT, 0, GT_RENDER_USER_INTERRUPT << GEN8_VECS_IRQ_SHIFT }; for (i = 0; i < ARRAY_SIZE(gt_interrupts); i++) { u32 tmp = I915_READ(GEN8_GT_IIR(i)); if (tmp) DRM_ERROR("Interrupt (%d) should have been masked in pre-install 0x%08x\n", i, tmp); I915_WRITE(GEN8_GT_IMR(i), ~gt_interrupts[i]); I915_WRITE(GEN8_GT_IER(i), gt_interrupts[i]); } POSTING_READ(GEN8_GT_IER(0)); } static void gen8_de_irq_postinstall(struct drm_i915_private *dev_priv) { struct drm_device *dev = dev_priv->dev; uint32_t de_pipe_masked = GEN8_PIPE_FLIP_DONE | GEN8_PIPE_CDCLK_CRC_DONE | GEN8_PIPE_FIFO_UNDERRUN | GEN8_DE_PIPE_IRQ_FAULT_ERRORS; uint32_t de_pipe_enables = de_pipe_masked | GEN8_PIPE_VBLANK; int pipe; dev_priv->de_irq_mask[PIPE_A] = ~de_pipe_masked; dev_priv->de_irq_mask[PIPE_B] = ~de_pipe_masked; dev_priv->de_irq_mask[PIPE_C] = ~de_pipe_masked; for_each_pipe(pipe) { u32 tmp = I915_READ(GEN8_DE_PIPE_IIR(pipe)); if (tmp) DRM_ERROR("Interrupt (%d) should have been masked in pre-install 0x%08x\n", pipe, tmp); I915_WRITE(GEN8_DE_PIPE_IMR(pipe), dev_priv->de_irq_mask[pipe]); I915_WRITE(GEN8_DE_PIPE_IER(pipe), de_pipe_enables); } POSTING_READ(GEN8_DE_PIPE_ISR(0)); I915_WRITE(GEN8_DE_PORT_IMR, ~GEN8_AUX_CHANNEL_A); I915_WRITE(GEN8_DE_PORT_IER, GEN8_AUX_CHANNEL_A); POSTING_READ(GEN8_DE_PORT_IER); } static int gen8_irq_postinstall(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; gen8_gt_irq_postinstall(dev_priv); gen8_de_irq_postinstall(dev_priv); ibx_irq_postinstall(dev); I915_WRITE(GEN8_MASTER_IRQ, DE_MASTER_IRQ_CONTROL); POSTING_READ(GEN8_MASTER_IRQ); return 0; } static void gen8_irq_uninstall(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int pipe; if (!dev_priv) return; I915_WRITE(GEN8_MASTER_IRQ, 0); #define GEN8_IRQ_FINI_NDX(type, which) do { \ I915_WRITE(GEN8_##type##_IMR(which), 0xffffffff); \ I915_WRITE(GEN8_##type##_IER(which), 0); \ I915_WRITE(GEN8_##type##_IIR(which), 0xffffffff); \ } while (0) #define GEN8_IRQ_FINI(type) do { \ I915_WRITE(GEN8_##type##_IMR, 0xffffffff); \ I915_WRITE(GEN8_##type##_IER, 0); \ I915_WRITE(GEN8_##type##_IIR, 0xffffffff); \ } while (0) GEN8_IRQ_FINI_NDX(GT, 0); GEN8_IRQ_FINI_NDX(GT, 1); GEN8_IRQ_FINI_NDX(GT, 2); GEN8_IRQ_FINI_NDX(GT, 3); for_each_pipe(pipe) { GEN8_IRQ_FINI_NDX(DE_PIPE, pipe); } GEN8_IRQ_FINI(DE_PORT); GEN8_IRQ_FINI(DE_MISC); GEN8_IRQ_FINI(PCU); #undef GEN8_IRQ_FINI #undef GEN8_IRQ_FINI_NDX POSTING_READ(GEN8_PCU_IIR); } static void valleyview_irq_uninstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; int pipe; if (!dev_priv) return; intel_hpd_irq_uninstall(dev_priv); for_each_pipe(pipe) I915_WRITE(PIPESTAT(pipe), 0xffff); I915_WRITE(HWSTAM, 0xffffffff); I915_WRITE(PORT_HOTPLUG_EN, 0); I915_WRITE(PORT_HOTPLUG_STAT, I915_READ(PORT_HOTPLUG_STAT)); spin_lock_irqsave(&dev_priv->irq_lock, irqflags); if (dev_priv->display_irqs_enabled) valleyview_display_irqs_uninstall(dev_priv); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); dev_priv->irq_mask = 0; I915_WRITE(VLV_IIR, 0xffffffff); I915_WRITE(VLV_IMR, 0xffffffff); I915_WRITE(VLV_IER, 0x0); POSTING_READ(VLV_IER); } static void ironlake_irq_uninstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; if (!dev_priv) return; intel_hpd_irq_uninstall(dev_priv); I915_WRITE(HWSTAM, 0xffffffff); I915_WRITE(DEIMR, 0xffffffff); I915_WRITE(DEIER, 0x0); I915_WRITE(DEIIR, I915_READ(DEIIR)); if (IS_GEN7(dev)) I915_WRITE(GEN7_ERR_INT, I915_READ(GEN7_ERR_INT)); I915_WRITE(GTIMR, 0xffffffff); I915_WRITE(GTIER, 0x0); I915_WRITE(GTIIR, I915_READ(GTIIR)); if (HAS_PCH_NOP(dev)) return; I915_WRITE(SDEIMR, 0xffffffff); I915_WRITE(SDEIER, 0x0); I915_WRITE(SDEIIR, I915_READ(SDEIIR)); if (HAS_PCH_CPT(dev) || HAS_PCH_LPT(dev)) I915_WRITE(SERR_INT, I915_READ(SERR_INT)); } static void i8xx_irq_preinstall(struct drm_device * dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; for_each_pipe(pipe) I915_WRITE(PIPESTAT(pipe), 0); I915_WRITE16(IMR, 0xffff); I915_WRITE16(IER, 0x0); POSTING_READ16(IER); } static int i8xx_irq_postinstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; unsigned long irqflags; I915_WRITE16(EMR, ~(I915_ERROR_PAGE_TABLE | I915_ERROR_MEMORY_REFRESH)); /* Unmask the interrupts that we always want on. */ dev_priv->irq_mask = ~(I915_DISPLAY_PIPE_A_EVENT_INTERRUPT | I915_DISPLAY_PIPE_B_EVENT_INTERRUPT | I915_DISPLAY_PLANE_A_FLIP_PENDING_INTERRUPT | I915_DISPLAY_PLANE_B_FLIP_PENDING_INTERRUPT | I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT); I915_WRITE16(IMR, dev_priv->irq_mask); I915_WRITE16(IER, I915_DISPLAY_PIPE_A_EVENT_INTERRUPT | I915_DISPLAY_PIPE_B_EVENT_INTERRUPT | I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT | I915_USER_INTERRUPT); POSTING_READ16(IER); /* Interrupt setup is already guaranteed to be single-threaded, this is * just to make the assert_spin_locked check happy. */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); i915_enable_pipestat(dev_priv, PIPE_A, PIPE_CRC_DONE_INTERRUPT_STATUS); i915_enable_pipestat(dev_priv, PIPE_B, PIPE_CRC_DONE_INTERRUPT_STATUS); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); return 0; } /* * Returns true when a page flip has completed. */ static bool i8xx_handle_vblank(struct drm_device *dev, int plane, int pipe, u32 iir) { drm_i915_private_t *dev_priv = dev->dev_private; u16 flip_pending = DISPLAY_PLANE_FLIP_PENDING(plane); if (!drm_handle_vblank(dev, pipe)) return false; if ((iir & flip_pending) == 0) return false; intel_prepare_page_flip(dev, plane); /* We detect FlipDone by looking for the change in PendingFlip from '1' * to '0' on the following vblank, i.e. IIR has the Pendingflip * asserted following the MI_DISPLAY_FLIP, but ISR is deasserted, hence * the flip is completed (no longer pending). Since this doesn't raise * an interrupt per se, we watch for the change at vblank. */ if (I915_READ16(ISR) & flip_pending) return false; intel_finish_page_flip(dev, pipe); return true; } static irqreturn_t i8xx_irq_handler(int irq, void *arg) { struct drm_device *dev = (struct drm_device *) arg; drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u16 iir, new_iir; u32 pipe_stats[2]; unsigned long irqflags; int pipe; u16 flip_mask = I915_DISPLAY_PLANE_A_FLIP_PENDING_INTERRUPT | I915_DISPLAY_PLANE_B_FLIP_PENDING_INTERRUPT; iir = I915_READ16(IIR); if (iir == 0) return IRQ_NONE; while (iir & ~flip_mask) { /* Can't rely on pipestat interrupt bit in iir as it might * have been cleared after the pipestat interrupt was received. * It doesn't set the bit in iir again, but it still produces * interrupts (for non-MSI). */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); if (iir & I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT) i915_handle_error(dev, false, "Command parser error, iir 0x%08x", iir); for_each_pipe(pipe) { int reg = PIPESTAT(pipe); pipe_stats[pipe] = I915_READ(reg); /* * Clear the PIPE*STAT regs before the IIR */ if (pipe_stats[pipe] & 0x8000ffff) I915_WRITE(reg, pipe_stats[pipe]); } spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); I915_WRITE16(IIR, iir & ~flip_mask); new_iir = I915_READ16(IIR); /* Flush posted writes */ i915_update_dri1_breadcrumb(dev); if (iir & I915_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[RCS]); for_each_pipe(pipe) { int plane = pipe; if (HAS_FBC(dev)) plane = !plane; if (pipe_stats[pipe] & PIPE_VBLANK_INTERRUPT_STATUS && i8xx_handle_vblank(dev, plane, pipe, iir)) flip_mask &= ~DISPLAY_PLANE_FLIP_PENDING(plane); if (pipe_stats[pipe] & PIPE_CRC_DONE_INTERRUPT_STATUS) i9xx_pipe_crc_irq_handler(dev, pipe); if (pipe_stats[pipe] & PIPE_FIFO_UNDERRUN_STATUS && intel_set_cpu_fifo_underrun_reporting(dev, pipe, false)) DRM_ERROR("pipe %c underrun\n", pipe_name(pipe)); } iir = new_iir; } return IRQ_HANDLED; } static void i8xx_irq_uninstall(struct drm_device * dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; for_each_pipe(pipe) { /* Clear enable bits; then clear status bits */ I915_WRITE(PIPESTAT(pipe), 0); I915_WRITE(PIPESTAT(pipe), I915_READ(PIPESTAT(pipe))); } I915_WRITE16(IMR, 0xffff); I915_WRITE16(IER, 0x0); I915_WRITE16(IIR, I915_READ16(IIR)); } static void i915_irq_preinstall(struct drm_device * dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; if (I915_HAS_HOTPLUG(dev)) { I915_WRITE(PORT_HOTPLUG_EN, 0); I915_WRITE(PORT_HOTPLUG_STAT, I915_READ(PORT_HOTPLUG_STAT)); } I915_WRITE16(HWSTAM, 0xeffe); for_each_pipe(pipe) I915_WRITE(PIPESTAT(pipe), 0); I915_WRITE(IMR, 0xffffffff); I915_WRITE(IER, 0x0); POSTING_READ(IER); } static int i915_irq_postinstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u32 enable_mask; unsigned long irqflags; I915_WRITE(EMR, ~(I915_ERROR_PAGE_TABLE | I915_ERROR_MEMORY_REFRESH)); /* Unmask the interrupts that we always want on. */ dev_priv->irq_mask = ~(I915_ASLE_INTERRUPT | I915_DISPLAY_PIPE_A_EVENT_INTERRUPT | I915_DISPLAY_PIPE_B_EVENT_INTERRUPT | I915_DISPLAY_PLANE_A_FLIP_PENDING_INTERRUPT | I915_DISPLAY_PLANE_B_FLIP_PENDING_INTERRUPT | I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT); enable_mask = I915_ASLE_INTERRUPT | I915_DISPLAY_PIPE_A_EVENT_INTERRUPT | I915_DISPLAY_PIPE_B_EVENT_INTERRUPT | I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT | I915_USER_INTERRUPT; if (I915_HAS_HOTPLUG(dev)) { I915_WRITE(PORT_HOTPLUG_EN, 0); POSTING_READ(PORT_HOTPLUG_EN); /* Enable in IER... */ enable_mask |= I915_DISPLAY_PORT_INTERRUPT; /* and unmask in IMR */ dev_priv->irq_mask &= ~I915_DISPLAY_PORT_INTERRUPT; } I915_WRITE(IMR, dev_priv->irq_mask); I915_WRITE(IER, enable_mask); POSTING_READ(IER); i915_enable_asle_pipestat(dev); /* Interrupt setup is already guaranteed to be single-threaded, this is * just to make the assert_spin_locked check happy. */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); i915_enable_pipestat(dev_priv, PIPE_A, PIPE_CRC_DONE_INTERRUPT_STATUS); i915_enable_pipestat(dev_priv, PIPE_B, PIPE_CRC_DONE_INTERRUPT_STATUS); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); return 0; } /* * Returns true when a page flip has completed. */ static bool i915_handle_vblank(struct drm_device *dev, int plane, int pipe, u32 iir) { drm_i915_private_t *dev_priv = dev->dev_private; u32 flip_pending = DISPLAY_PLANE_FLIP_PENDING(plane); if (!drm_handle_vblank(dev, pipe)) return false; if ((iir & flip_pending) == 0) return false; intel_prepare_page_flip(dev, plane); /* We detect FlipDone by looking for the change in PendingFlip from '1' * to '0' on the following vblank, i.e. IIR has the Pendingflip * asserted following the MI_DISPLAY_FLIP, but ISR is deasserted, hence * the flip is completed (no longer pending). Since this doesn't raise * an interrupt per se, we watch for the change at vblank. */ if (I915_READ(ISR) & flip_pending) return false; intel_finish_page_flip(dev, pipe); return true; } static irqreturn_t i915_irq_handler(int irq, void *arg) { struct drm_device *dev = (struct drm_device *) arg; drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u32 iir, new_iir, pipe_stats[I915_MAX_PIPES]; unsigned long irqflags; u32 flip_mask = I915_DISPLAY_PLANE_A_FLIP_PENDING_INTERRUPT | I915_DISPLAY_PLANE_B_FLIP_PENDING_INTERRUPT; int pipe, ret = IRQ_NONE; iir = I915_READ(IIR); do { bool irq_received = (iir & ~flip_mask) != 0; bool blc_event = false; /* Can't rely on pipestat interrupt bit in iir as it might * have been cleared after the pipestat interrupt was received. * It doesn't set the bit in iir again, but it still produces * interrupts (for non-MSI). */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); if (iir & I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT) i915_handle_error(dev, false, "Command parser error, iir 0x%08x", iir); for_each_pipe(pipe) { int reg = PIPESTAT(pipe); pipe_stats[pipe] = I915_READ(reg); /* Clear the PIPE*STAT regs before the IIR */ if (pipe_stats[pipe] & 0x8000ffff) { I915_WRITE(reg, pipe_stats[pipe]); irq_received = true; } } spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); if (!irq_received) break; /* Consume port. Then clear IIR or we'll miss events */ if ((I915_HAS_HOTPLUG(dev)) && (iir & I915_DISPLAY_PORT_INTERRUPT)) { u32 hotplug_status = I915_READ(PORT_HOTPLUG_STAT); u32 hotplug_trigger = hotplug_status & HOTPLUG_INT_STATUS_I915; intel_hpd_irq_handler(dev, hotplug_trigger, hpd_status_i915); I915_WRITE(PORT_HOTPLUG_STAT, hotplug_status); POSTING_READ(PORT_HOTPLUG_STAT); } I915_WRITE(IIR, iir & ~flip_mask); new_iir = I915_READ(IIR); /* Flush posted writes */ if (iir & I915_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[RCS]); for_each_pipe(pipe) { int plane = pipe; if (HAS_FBC(dev)) plane = !plane; if (pipe_stats[pipe] & PIPE_VBLANK_INTERRUPT_STATUS && i915_handle_vblank(dev, plane, pipe, iir)) flip_mask &= ~DISPLAY_PLANE_FLIP_PENDING(plane); if (pipe_stats[pipe] & PIPE_LEGACY_BLC_EVENT_STATUS) blc_event = true; if (pipe_stats[pipe] & PIPE_CRC_DONE_INTERRUPT_STATUS) i9xx_pipe_crc_irq_handler(dev, pipe); if (pipe_stats[pipe] & PIPE_FIFO_UNDERRUN_STATUS && intel_set_cpu_fifo_underrun_reporting(dev, pipe, false)) DRM_ERROR("pipe %c underrun\n", pipe_name(pipe)); } if (blc_event || (iir & I915_ASLE_INTERRUPT)) intel_opregion_asle_intr(dev); /* With MSI, interrupts are only generated when iir * transitions from zero to nonzero. If another bit got * set while we were handling the existing iir bits, then * we would never get another interrupt. * * This is fine on non-MSI as well, as if we hit this path * we avoid exiting the interrupt handler only to generate * another one. * * Note that for MSI this could cause a stray interrupt report * if an interrupt landed in the time between writing IIR and * the posting read. This should be rare enough to never * trigger the 99% of 100,000 interrupts test for disabling * stray interrupts. */ ret = IRQ_HANDLED; iir = new_iir; } while (iir & ~flip_mask); i915_update_dri1_breadcrumb(dev); return ret; } static void i915_irq_uninstall(struct drm_device * dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; intel_hpd_irq_uninstall(dev_priv); if (I915_HAS_HOTPLUG(dev)) { I915_WRITE(PORT_HOTPLUG_EN, 0); I915_WRITE(PORT_HOTPLUG_STAT, I915_READ(PORT_HOTPLUG_STAT)); } I915_WRITE16(HWSTAM, 0xffff); for_each_pipe(pipe) { /* Clear enable bits; then clear status bits */ I915_WRITE(PIPESTAT(pipe), 0); I915_WRITE(PIPESTAT(pipe), I915_READ(PIPESTAT(pipe))); } I915_WRITE(IMR, 0xffffffff); I915_WRITE(IER, 0x0); I915_WRITE(IIR, I915_READ(IIR)); } static void i965_irq_preinstall(struct drm_device * dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; I915_WRITE(PORT_HOTPLUG_EN, 0); I915_WRITE(PORT_HOTPLUG_STAT, I915_READ(PORT_HOTPLUG_STAT)); I915_WRITE(HWSTAM, 0xeffe); for_each_pipe(pipe) I915_WRITE(PIPESTAT(pipe), 0); I915_WRITE(IMR, 0xffffffff); I915_WRITE(IER, 0x0); POSTING_READ(IER); } static int i965_irq_postinstall(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u32 enable_mask; u32 error_mask; unsigned long irqflags; /* Unmask the interrupts that we always want on. */ dev_priv->irq_mask = ~(I915_ASLE_INTERRUPT | I915_DISPLAY_PORT_INTERRUPT | I915_DISPLAY_PIPE_A_EVENT_INTERRUPT | I915_DISPLAY_PIPE_B_EVENT_INTERRUPT | I915_DISPLAY_PLANE_A_FLIP_PENDING_INTERRUPT | I915_DISPLAY_PLANE_B_FLIP_PENDING_INTERRUPT | I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT); enable_mask = ~dev_priv->irq_mask; enable_mask &= ~(I915_DISPLAY_PLANE_A_FLIP_PENDING_INTERRUPT | I915_DISPLAY_PLANE_B_FLIP_PENDING_INTERRUPT); enable_mask |= I915_USER_INTERRUPT; if (IS_G4X(dev)) enable_mask |= I915_BSD_USER_INTERRUPT; /* Interrupt setup is already guaranteed to be single-threaded, this is * just to make the assert_spin_locked check happy. */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); i915_enable_pipestat(dev_priv, PIPE_A, PIPE_GMBUS_INTERRUPT_STATUS); i915_enable_pipestat(dev_priv, PIPE_A, PIPE_CRC_DONE_INTERRUPT_STATUS); i915_enable_pipestat(dev_priv, PIPE_B, PIPE_CRC_DONE_INTERRUPT_STATUS); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); /* * Enable some error detection, note the instruction error mask * bit is reserved, so we leave it masked. */ if (IS_G4X(dev)) { error_mask = ~(GM45_ERROR_PAGE_TABLE | GM45_ERROR_MEM_PRIV | GM45_ERROR_CP_PRIV | I915_ERROR_MEMORY_REFRESH); } else { error_mask = ~(I915_ERROR_PAGE_TABLE | I915_ERROR_MEMORY_REFRESH); } I915_WRITE(EMR, error_mask); I915_WRITE(IMR, dev_priv->irq_mask); I915_WRITE(IER, enable_mask); POSTING_READ(IER); I915_WRITE(PORT_HOTPLUG_EN, 0); POSTING_READ(PORT_HOTPLUG_EN); i915_enable_asle_pipestat(dev); return 0; } static void i915_hpd_irq_setup(struct drm_device *dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; struct drm_mode_config *mode_config = &dev->mode_config; struct intel_encoder *intel_encoder; u32 hotplug_en; assert_spin_locked(&dev_priv->irq_lock); if (I915_HAS_HOTPLUG(dev)) { hotplug_en = I915_READ(PORT_HOTPLUG_EN); hotplug_en &= ~HOTPLUG_INT_EN_MASK; /* Note HDMI and DP share hotplug bits */ /* enable bits are the same for all generations */ list_for_each_entry(intel_encoder, &mode_config->encoder_list, base.head) if (dev_priv->hpd_stats[intel_encoder->hpd_pin].hpd_mark == HPD_ENABLED) hotplug_en |= hpd_mask_i915[intel_encoder->hpd_pin]; /* Programming the CRT detection parameters tends to generate a spurious hotplug event about three seconds later. So just do it once. */ if (IS_G4X(dev)) hotplug_en |= CRT_HOTPLUG_ACTIVATION_PERIOD_64; hotplug_en &= ~CRT_HOTPLUG_VOLTAGE_COMPARE_MASK; hotplug_en |= CRT_HOTPLUG_VOLTAGE_COMPARE_50; /* Ignore TV since it's buggy */ I915_WRITE(PORT_HOTPLUG_EN, hotplug_en); } } static irqreturn_t i965_irq_handler(int irq, void *arg) { struct drm_device *dev = (struct drm_device *) arg; drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; u32 iir, new_iir; u32 pipe_stats[I915_MAX_PIPES]; unsigned long irqflags; int ret = IRQ_NONE, pipe; u32 flip_mask = I915_DISPLAY_PLANE_A_FLIP_PENDING_INTERRUPT | I915_DISPLAY_PLANE_B_FLIP_PENDING_INTERRUPT; iir = I915_READ(IIR); for (;;) { bool irq_received = (iir & ~flip_mask) != 0; bool blc_event = false; /* Can't rely on pipestat interrupt bit in iir as it might * have been cleared after the pipestat interrupt was received. * It doesn't set the bit in iir again, but it still produces * interrupts (for non-MSI). */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); if (iir & I915_RENDER_COMMAND_PARSER_ERROR_INTERRUPT) i915_handle_error(dev, false, "Command parser error, iir 0x%08x", iir); for_each_pipe(pipe) { int reg = PIPESTAT(pipe); pipe_stats[pipe] = I915_READ(reg); /* * Clear the PIPE*STAT regs before the IIR */ if (pipe_stats[pipe] & 0x8000ffff) { I915_WRITE(reg, pipe_stats[pipe]); irq_received = true; } } spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); if (!irq_received) break; ret = IRQ_HANDLED; /* Consume port. Then clear IIR or we'll miss events */ if (iir & I915_DISPLAY_PORT_INTERRUPT) { u32 hotplug_status = I915_READ(PORT_HOTPLUG_STAT); u32 hotplug_trigger = hotplug_status & (IS_G4X(dev) ? HOTPLUG_INT_STATUS_G4X : HOTPLUG_INT_STATUS_I915); intel_hpd_irq_handler(dev, hotplug_trigger, IS_G4X(dev) ? hpd_status_g4x : hpd_status_i915); if (IS_G4X(dev) && (hotplug_status & DP_AUX_CHANNEL_MASK_INT_STATUS_G4X)) dp_aux_irq_handler(dev); I915_WRITE(PORT_HOTPLUG_STAT, hotplug_status); I915_READ(PORT_HOTPLUG_STAT); } I915_WRITE(IIR, iir & ~flip_mask); new_iir = I915_READ(IIR); /* Flush posted writes */ if (iir & I915_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[RCS]); if (iir & I915_BSD_USER_INTERRUPT) notify_ring(dev, &dev_priv->ring[VCS]); for_each_pipe(pipe) { if (pipe_stats[pipe] & PIPE_START_VBLANK_INTERRUPT_STATUS && i915_handle_vblank(dev, pipe, pipe, iir)) flip_mask &= ~DISPLAY_PLANE_FLIP_PENDING(pipe); if (pipe_stats[pipe] & PIPE_LEGACY_BLC_EVENT_STATUS) blc_event = true; if (pipe_stats[pipe] & PIPE_CRC_DONE_INTERRUPT_STATUS) i9xx_pipe_crc_irq_handler(dev, pipe); if (pipe_stats[pipe] & PIPE_FIFO_UNDERRUN_STATUS && intel_set_cpu_fifo_underrun_reporting(dev, pipe, false)) DRM_ERROR("pipe %c underrun\n", pipe_name(pipe)); } if (blc_event || (iir & I915_ASLE_INTERRUPT)) intel_opregion_asle_intr(dev); if (pipe_stats[0] & PIPE_GMBUS_INTERRUPT_STATUS) gmbus_irq_handler(dev); /* With MSI, interrupts are only generated when iir * transitions from zero to nonzero. If another bit got * set while we were handling the existing iir bits, then * we would never get another interrupt. * * This is fine on non-MSI as well, as if we hit this path * we avoid exiting the interrupt handler only to generate * another one. * * Note that for MSI this could cause a stray interrupt report * if an interrupt landed in the time between writing IIR and * the posting read. This should be rare enough to never * trigger the 99% of 100,000 interrupts test for disabling * stray interrupts. */ iir = new_iir; } i915_update_dri1_breadcrumb(dev); return ret; } static void i965_irq_uninstall(struct drm_device * dev) { drm_i915_private_t *dev_priv = (drm_i915_private_t *) dev->dev_private; int pipe; if (!dev_priv) return; intel_hpd_irq_uninstall(dev_priv); I915_WRITE(PORT_HOTPLUG_EN, 0); I915_WRITE(PORT_HOTPLUG_STAT, I915_READ(PORT_HOTPLUG_STAT)); I915_WRITE(HWSTAM, 0xffffffff); for_each_pipe(pipe) I915_WRITE(PIPESTAT(pipe), 0); I915_WRITE(IMR, 0xffffffff); I915_WRITE(IER, 0x0); for_each_pipe(pipe) I915_WRITE(PIPESTAT(pipe), I915_READ(PIPESTAT(pipe)) & 0x8000ffff); I915_WRITE(IIR, I915_READ(IIR)); } static void intel_hpd_irq_reenable(unsigned long data) { drm_i915_private_t *dev_priv = (drm_i915_private_t *)data; struct drm_device *dev = dev_priv->dev; struct drm_mode_config *mode_config = &dev->mode_config; unsigned long irqflags; int i; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); for (i = (HPD_NONE + 1); i < HPD_NUM_PINS; i++) { struct drm_connector *connector; if (dev_priv->hpd_stats[i].hpd_mark != HPD_DISABLED) continue; dev_priv->hpd_stats[i].hpd_mark = HPD_ENABLED; list_for_each_entry(connector, &mode_config->connector_list, head) { struct intel_connector *intel_connector = to_intel_connector(connector); if (intel_connector->encoder->hpd_pin == i) { if (connector->polled != intel_connector->polled) DRM_DEBUG_DRIVER("Reenabling HPD on connector %s\n", drm_get_connector_name(connector)); connector->polled = intel_connector->polled; if (!connector->polled) connector->polled = DRM_CONNECTOR_POLL_HPD; } } } if (dev_priv->display.hpd_irq_setup) dev_priv->display.hpd_irq_setup(dev); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } void intel_irq_init(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; INIT_WORK(&dev_priv->hotplug_work, i915_hotplug_work_func); INIT_WORK(&dev_priv->gpu_error.work, i915_error_work_func); INIT_WORK(&dev_priv->rps.work, gen6_pm_rps_work); INIT_WORK(&dev_priv->l3_parity.error_work, ivybridge_parity_work); setup_timer(&dev_priv->gpu_error.hangcheck_timer, i915_hangcheck_elapsed, (unsigned long) dev); setup_timer(&dev_priv->hotplug_reenable_timer, intel_hpd_irq_reenable, (unsigned long) dev_priv); pm_qos_add_request(&dev_priv->pm_qos, PM_QOS_CPU_DMA_LATENCY, PM_QOS_DEFAULT_VALUE); if (IS_GEN2(dev)) { dev->max_vblank_count = 0; dev->driver->get_vblank_counter = i8xx_get_vblank_counter; } else if (IS_G4X(dev) || INTEL_INFO(dev)->gen >= 5) { dev->max_vblank_count = 0xffffffff; /* full 32 bit counter */ dev->driver->get_vblank_counter = gm45_get_vblank_counter; } else { dev->driver->get_vblank_counter = i915_get_vblank_counter; dev->max_vblank_count = 0xffffff; /* only 24 bits of frame count */ } if (drm_core_check_feature(dev, DRIVER_MODESET)) { dev->driver->get_vblank_timestamp = i915_get_vblank_timestamp; dev->driver->get_scanout_position = i915_get_crtc_scanoutpos; } if (IS_VALLEYVIEW(dev)) { dev->driver->irq_handler = valleyview_irq_handler; dev->driver->irq_preinstall = valleyview_irq_preinstall; dev->driver->irq_postinstall = valleyview_irq_postinstall; dev->driver->irq_uninstall = valleyview_irq_uninstall; dev->driver->enable_vblank = valleyview_enable_vblank; dev->driver->disable_vblank = valleyview_disable_vblank; dev_priv->display.hpd_irq_setup = i915_hpd_irq_setup; } else if (IS_GEN8(dev)) { dev->driver->irq_handler = gen8_irq_handler; dev->driver->irq_preinstall = gen8_irq_preinstall; dev->driver->irq_postinstall = gen8_irq_postinstall; dev->driver->irq_uninstall = gen8_irq_uninstall; dev->driver->enable_vblank = gen8_enable_vblank; dev->driver->disable_vblank = gen8_disable_vblank; dev_priv->display.hpd_irq_setup = ibx_hpd_irq_setup; } else if (HAS_PCH_SPLIT(dev)) { dev->driver->irq_handler = ironlake_irq_handler; dev->driver->irq_preinstall = ironlake_irq_preinstall; dev->driver->irq_postinstall = ironlake_irq_postinstall; dev->driver->irq_uninstall = ironlake_irq_uninstall; dev->driver->enable_vblank = ironlake_enable_vblank; dev->driver->disable_vblank = ironlake_disable_vblank; dev_priv->display.hpd_irq_setup = ibx_hpd_irq_setup; } else { if (INTEL_INFO(dev)->gen == 2) { dev->driver->irq_preinstall = i8xx_irq_preinstall; dev->driver->irq_postinstall = i8xx_irq_postinstall; dev->driver->irq_handler = i8xx_irq_handler; dev->driver->irq_uninstall = i8xx_irq_uninstall; } else if (INTEL_INFO(dev)->gen == 3) { dev->driver->irq_preinstall = i915_irq_preinstall; dev->driver->irq_postinstall = i915_irq_postinstall; dev->driver->irq_uninstall = i915_irq_uninstall; dev->driver->irq_handler = i915_irq_handler; dev_priv->display.hpd_irq_setup = i915_hpd_irq_setup; } else { dev->driver->irq_preinstall = i965_irq_preinstall; dev->driver->irq_postinstall = i965_irq_postinstall; dev->driver->irq_uninstall = i965_irq_uninstall; dev->driver->irq_handler = i965_irq_handler; dev_priv->display.hpd_irq_setup = i915_hpd_irq_setup; } dev->driver->enable_vblank = i915_enable_vblank; dev->driver->disable_vblank = i915_disable_vblank; } } void intel_hpd_init(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; struct drm_mode_config *mode_config = &dev->mode_config; struct drm_connector *connector; unsigned long irqflags; int i; for (i = 1; i < HPD_NUM_PINS; i++) { dev_priv->hpd_stats[i].hpd_cnt = 0; dev_priv->hpd_stats[i].hpd_mark = HPD_ENABLED; } list_for_each_entry(connector, &mode_config->connector_list, head) { struct intel_connector *intel_connector = to_intel_connector(connector); connector->polled = intel_connector->polled; if (!connector->polled && I915_HAS_HOTPLUG(dev) && intel_connector->encoder->hpd_pin > HPD_NONE) connector->polled = DRM_CONNECTOR_POLL_HPD; } /* Interrupt setup is already guaranteed to be single-threaded, this is * just to make the assert_spin_locked checks happy. */ spin_lock_irqsave(&dev_priv->irq_lock, irqflags); if (dev_priv->display.hpd_irq_setup) dev_priv->display.hpd_irq_setup(dev); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } /* Disable interrupts so we can allow Package C8+. */ void hsw_pc8_disable_interrupts(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; unsigned long irqflags; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); dev_priv->pc8.regsave.deimr = I915_READ(DEIMR); dev_priv->pc8.regsave.sdeimr = I915_READ(SDEIMR); dev_priv->pc8.regsave.gtimr = I915_READ(GTIMR); dev_priv->pc8.regsave.gtier = I915_READ(GTIER); dev_priv->pc8.regsave.gen6_pmimr = I915_READ(GEN6_PMIMR); ironlake_disable_display_irq(dev_priv, 0xffffffff); ibx_disable_display_interrupt(dev_priv, 0xffffffff); ilk_disable_gt_irq(dev_priv, 0xffffffff); snb_disable_pm_irq(dev_priv, 0xffffffff); dev_priv->pc8.irqs_disabled = true; spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); } /* Restore interrupts so we can recover from Package C8+. */ void hsw_pc8_restore_interrupts(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; unsigned long irqflags; uint32_t val; spin_lock_irqsave(&dev_priv->irq_lock, irqflags); val = I915_READ(DEIMR); WARN(val != 0xffffffff, "DEIMR is 0x%08x\n", val); val = I915_READ(SDEIMR); WARN(val != 0xffffffff, "SDEIMR is 0x%08x\n", val); val = I915_READ(GTIMR); WARN(val != 0xffffffff, "GTIMR is 0x%08x\n", val); val = I915_READ(GEN6_PMIMR); WARN(val != 0xffffffff, "GEN6_PMIMR is 0x%08x\n", val); dev_priv->pc8.irqs_disabled = false; ironlake_enable_display_irq(dev_priv, ~dev_priv->pc8.regsave.deimr); ibx_enable_display_interrupt(dev_priv, ~dev_priv->pc8.regsave.sdeimr); ilk_enable_gt_irq(dev_priv, ~dev_priv->pc8.regsave.gtimr); snb_enable_pm_irq(dev_priv, ~dev_priv->pc8.regsave.gen6_pmimr); I915_WRITE(GTIER, dev_priv->pc8.regsave.gtier); spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags); }
rjmccabe3701/LinuxViewPageTables
ubuntu/i915/i915_irq.c
C
gpl-2.0
121,231
<?php /** * @version $Id: index.php 10885 2013-05-30 06:31:41Z btowles $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ /** * @var $layout RokSprocket_Layout_Headlines * @var $items RokSprocket_Item[] * @var $parameters RokCommon_Registry */ ?> <div class="sprocket-headlines navigation-active animation-<?php echo $parameters->get('headlines_animation'); ?>" data-headlines="<?php echo $parameters->get('module_id'); ?>"> <div class="sprocket-headlines-container"> <?php if ($parameters->get('headlines_label_text')) : ?> <div class="sprocket-headlines-badge"> <span><?php echo $parameters->get('headlines_label_text'); ?></span> </div> <?php endif; ?> <ul class="sprocket-headlines-list"> <?php $index = 0; foreach ($items as $item){ echo $layout->getThemeContext()->load('item.php', array('item'=> $item, 'index'=>$index)); $index++; } ?> </ul> <?php if ($parameters->get('headlines_show_arrows')!='hide') : ?> <div class="sprocket-headlines-navigation"> <span class="arrow next" data-headlines-next><span>&rsaquo;</span></span> <span class="arrow prev" data-headlines-previous><span>&lsaquo;</span></span> </div> <?php endif; ?> </div> </div>
moveloaded/moveloaded
wp-content/plugins/wp_roksprocket/layouts/headlines/themes/default/index.php
PHP
gpl-2.0
1,360
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2008, 2009 Intel Corporation * Authors: Andi Kleen, Fengguang Wu * * High level machine check handler. Handles pages reported by the * hardware as being corrupted usually due to a multi-bit ECC memory or cache * failure. * * In addition there is a "soft offline" entry point that allows stop using * not-yet-corrupted-by-suspicious pages without killing anything. * * Handles page cache pages in various states. The tricky part * here is that we can access any page asynchronously in respect to * other VM users, because memory failures could happen anytime and * anywhere. This could violate some of their assumptions. This is why * this code has to be extremely careful. Generally it tries to use * normal locking rules, as in get the standard locks, even if that means * the error handling takes potentially a long time. * * It can be very tempting to add handling for obscure cases here. * In general any code for handling new cases should only be added iff: * - You know how to test it. * - You have a test that can be added to mce-test * https://git.kernel.org/cgit/utils/cpu/mce/mce-test.git/ * - The case actually shows up as a frequent (top 10) page state in * tools/vm/page-types when running a real workload. * * There are several operations here with exponential complexity because * of unsuitable VM data structures. For example the operation to map back * from RMAP chains to processes has to walk the complete process list and * has non linear complexity with the number. But since memory corruptions * are rare we hope to get away with this. This avoids impacting the core * VM. */ #include <linux/kernel.h> #include <linux/mm.h> #include <linux/page-flags.h> #include <linux/kernel-page-flags.h> #include <linux/sched/signal.h> #include <linux/sched/task.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/export.h> #include <linux/pagemap.h> #include <linux/swap.h> #include <linux/backing-dev.h> #include <linux/migrate.h> #include <linux/suspend.h> #include <linux/slab.h> #include <linux/swapops.h> #include <linux/hugetlb.h> #include <linux/memory_hotplug.h> #include <linux/mm_inline.h> #include <linux/memremap.h> #include <linux/kfifo.h> #include <linux/ratelimit.h> #include <linux/page-isolation.h> #include "internal.h" #include "ras/ras_event.h" int sysctl_memory_failure_early_kill __read_mostly = 0; int sysctl_memory_failure_recovery __read_mostly = 1; atomic_long_t num_poisoned_pages __read_mostly = ATOMIC_LONG_INIT(0); static bool page_handle_poison(struct page *page, bool hugepage_or_freepage, bool release) { if (hugepage_or_freepage) { /* * Doing this check for free pages is also fine since dissolve_free_huge_page * returns 0 for non-hugetlb pages as well. */ if (dissolve_free_huge_page(page) || !take_page_off_buddy(page)) /* * We could fail to take off the target page from buddy * for example due to racy page allocation, but that's * acceptable because soft-offlined page is not broken * and if someone really want to use it, they should * take it. */ return false; } SetPageHWPoison(page); if (release) put_page(page); page_ref_inc(page); num_poisoned_pages_inc(); return true; } #if defined(CONFIG_HWPOISON_INJECT) || defined(CONFIG_HWPOISON_INJECT_MODULE) u32 hwpoison_filter_enable = 0; u32 hwpoison_filter_dev_major = ~0U; u32 hwpoison_filter_dev_minor = ~0U; u64 hwpoison_filter_flags_mask; u64 hwpoison_filter_flags_value; EXPORT_SYMBOL_GPL(hwpoison_filter_enable); EXPORT_SYMBOL_GPL(hwpoison_filter_dev_major); EXPORT_SYMBOL_GPL(hwpoison_filter_dev_minor); EXPORT_SYMBOL_GPL(hwpoison_filter_flags_mask); EXPORT_SYMBOL_GPL(hwpoison_filter_flags_value); static int hwpoison_filter_dev(struct page *p) { struct address_space *mapping; dev_t dev; if (hwpoison_filter_dev_major == ~0U && hwpoison_filter_dev_minor == ~0U) return 0; /* * page_mapping() does not accept slab pages. */ if (PageSlab(p)) return -EINVAL; mapping = page_mapping(p); if (mapping == NULL || mapping->host == NULL) return -EINVAL; dev = mapping->host->i_sb->s_dev; if (hwpoison_filter_dev_major != ~0U && hwpoison_filter_dev_major != MAJOR(dev)) return -EINVAL; if (hwpoison_filter_dev_minor != ~0U && hwpoison_filter_dev_minor != MINOR(dev)) return -EINVAL; return 0; } static int hwpoison_filter_flags(struct page *p) { if (!hwpoison_filter_flags_mask) return 0; if ((stable_page_flags(p) & hwpoison_filter_flags_mask) == hwpoison_filter_flags_value) return 0; else return -EINVAL; } /* * This allows stress tests to limit test scope to a collection of tasks * by putting them under some memcg. This prevents killing unrelated/important * processes such as /sbin/init. Note that the target task may share clean * pages with init (eg. libc text), which is harmless. If the target task * share _dirty_ pages with another task B, the test scheme must make sure B * is also included in the memcg. At last, due to race conditions this filter * can only guarantee that the page either belongs to the memcg tasks, or is * a freed page. */ #ifdef CONFIG_MEMCG u64 hwpoison_filter_memcg; EXPORT_SYMBOL_GPL(hwpoison_filter_memcg); static int hwpoison_filter_task(struct page *p) { if (!hwpoison_filter_memcg) return 0; if (page_cgroup_ino(p) != hwpoison_filter_memcg) return -EINVAL; return 0; } #else static int hwpoison_filter_task(struct page *p) { return 0; } #endif int hwpoison_filter(struct page *p) { if (!hwpoison_filter_enable) return 0; if (hwpoison_filter_dev(p)) return -EINVAL; if (hwpoison_filter_flags(p)) return -EINVAL; if (hwpoison_filter_task(p)) return -EINVAL; return 0; } #else int hwpoison_filter(struct page *p) { return 0; } #endif EXPORT_SYMBOL_GPL(hwpoison_filter); /* * Kill all processes that have a poisoned page mapped and then isolate * the page. * * General strategy: * Find all processes having the page mapped and kill them. * But we keep a page reference around so that the page is not * actually freed yet. * Then stash the page away * * There's no convenient way to get back to mapped processes * from the VMAs. So do a brute-force search over all * running processes. * * Remember that machine checks are not common (or rather * if they are common you have other problems), so this shouldn't * be a performance issue. * * Also there are some races possible while we get from the * error detection to actually handle it. */ struct to_kill { struct list_head nd; struct task_struct *tsk; unsigned long addr; short size_shift; }; /* * Send all the processes who have the page mapped a signal. * ``action optional'' if they are not immediately affected by the error * ``action required'' if error happened in current execution context */ static int kill_proc(struct to_kill *tk, unsigned long pfn, int flags) { struct task_struct *t = tk->tsk; short addr_lsb = tk->size_shift; int ret = 0; pr_err("Memory failure: %#lx: Sending SIGBUS to %s:%d due to hardware memory corruption\n", pfn, t->comm, t->pid); if (flags & MF_ACTION_REQUIRED) { if (t == current) ret = force_sig_mceerr(BUS_MCEERR_AR, (void __user *)tk->addr, addr_lsb); else /* Signal other processes sharing the page if they have PF_MCE_EARLY set. */ ret = send_sig_mceerr(BUS_MCEERR_AO, (void __user *)tk->addr, addr_lsb, t); } else { /* * Don't use force here, it's convenient if the signal * can be temporarily blocked. * This could cause a loop when the user sets SIGBUS * to SIG_IGN, but hopefully no one will do that? */ ret = send_sig_mceerr(BUS_MCEERR_AO, (void __user *)tk->addr, addr_lsb, t); /* synchronous? */ } if (ret < 0) pr_info("Memory failure: Error sending signal to %s:%d: %d\n", t->comm, t->pid, ret); return ret; } /* * Unknown page type encountered. Try to check whether it can turn PageLRU by * lru_add_drain_all, or a free page by reclaiming slabs when possible. */ void shake_page(struct page *p, int access) { if (PageHuge(p)) return; if (!PageSlab(p)) { lru_add_drain_all(); if (PageLRU(p) || is_free_buddy_page(p)) return; } /* * Only call shrink_node_slabs here (which would also shrink * other caches) if access is not potentially fatal. */ if (access) drop_slab_node(page_to_nid(p)); } EXPORT_SYMBOL_GPL(shake_page); static unsigned long dev_pagemap_mapping_shift(struct page *page, struct vm_area_struct *vma) { unsigned long address = vma_address(page, vma); pgd_t *pgd; p4d_t *p4d; pud_t *pud; pmd_t *pmd; pte_t *pte; pgd = pgd_offset(vma->vm_mm, address); if (!pgd_present(*pgd)) return 0; p4d = p4d_offset(pgd, address); if (!p4d_present(*p4d)) return 0; pud = pud_offset(p4d, address); if (!pud_present(*pud)) return 0; if (pud_devmap(*pud)) return PUD_SHIFT; pmd = pmd_offset(pud, address); if (!pmd_present(*pmd)) return 0; if (pmd_devmap(*pmd)) return PMD_SHIFT; pte = pte_offset_map(pmd, address); if (!pte_present(*pte)) return 0; if (pte_devmap(*pte)) return PAGE_SHIFT; return 0; } /* * Failure handling: if we can't find or can't kill a process there's * not much we can do. We just print a message and ignore otherwise. */ /* * Schedule a process for later kill. * Uses GFP_ATOMIC allocations to avoid potential recursions in the VM. */ static void add_to_kill(struct task_struct *tsk, struct page *p, struct vm_area_struct *vma, struct list_head *to_kill) { struct to_kill *tk; tk = kmalloc(sizeof(struct to_kill), GFP_ATOMIC); if (!tk) { pr_err("Memory failure: Out of memory while machine check handling\n"); return; } tk->addr = page_address_in_vma(p, vma); if (is_zone_device_page(p)) tk->size_shift = dev_pagemap_mapping_shift(p, vma); else tk->size_shift = page_shift(compound_head(p)); /* * Send SIGKILL if "tk->addr == -EFAULT". Also, as * "tk->size_shift" is always non-zero for !is_zone_device_page(), * so "tk->size_shift == 0" effectively checks no mapping on * ZONE_DEVICE. Indeed, when a devdax page is mmapped N times * to a process' address space, it's possible not all N VMAs * contain mappings for the page, but at least one VMA does. * Only deliver SIGBUS with payload derived from the VMA that * has a mapping for the page. */ if (tk->addr == -EFAULT) { pr_info("Memory failure: Unable to find user space address %lx in %s\n", page_to_pfn(p), tsk->comm); } else if (tk->size_shift == 0) { kfree(tk); return; } get_task_struct(tsk); tk->tsk = tsk; list_add_tail(&tk->nd, to_kill); } /* * Kill the processes that have been collected earlier. * * Only do anything when DOIT is set, otherwise just free the list * (this is used for clean pages which do not need killing) * Also when FAIL is set do a force kill because something went * wrong earlier. */ static void kill_procs(struct list_head *to_kill, int forcekill, bool fail, unsigned long pfn, int flags) { struct to_kill *tk, *next; list_for_each_entry_safe (tk, next, to_kill, nd) { if (forcekill) { /* * In case something went wrong with munmapping * make sure the process doesn't catch the * signal and then access the memory. Just kill it. */ if (fail || tk->addr == -EFAULT) { pr_err("Memory failure: %#lx: forcibly killing %s:%d because of failure to unmap corrupted page\n", pfn, tk->tsk->comm, tk->tsk->pid); do_send_sig_info(SIGKILL, SEND_SIG_PRIV, tk->tsk, PIDTYPE_PID); } /* * In theory the process could have mapped * something else on the address in-between. We could * check for that, but we need to tell the * process anyways. */ else if (kill_proc(tk, pfn, flags) < 0) pr_err("Memory failure: %#lx: Cannot send advisory machine check signal to %s:%d\n", pfn, tk->tsk->comm, tk->tsk->pid); } put_task_struct(tk->tsk); kfree(tk); } } /* * Find a dedicated thread which is supposed to handle SIGBUS(BUS_MCEERR_AO) * on behalf of the thread group. Return task_struct of the (first found) * dedicated thread if found, and return NULL otherwise. * * We already hold read_lock(&tasklist_lock) in the caller, so we don't * have to call rcu_read_lock/unlock() in this function. */ static struct task_struct *find_early_kill_thread(struct task_struct *tsk) { struct task_struct *t; for_each_thread(tsk, t) { if (t->flags & PF_MCE_PROCESS) { if (t->flags & PF_MCE_EARLY) return t; } else { if (sysctl_memory_failure_early_kill) return t; } } return NULL; } /* * Determine whether a given process is "early kill" process which expects * to be signaled when some page under the process is hwpoisoned. * Return task_struct of the dedicated thread (main thread unless explicitly * specified) if the process is "early kill" and otherwise returns NULL. * * Note that the above is true for Action Optional case. For Action Required * case, it's only meaningful to the current thread which need to be signaled * with SIGBUS, this error is Action Optional for other non current * processes sharing the same error page,if the process is "early kill", the * task_struct of the dedicated thread will also be returned. */ static struct task_struct *task_early_kill(struct task_struct *tsk, int force_early) { if (!tsk->mm) return NULL; /* * Comparing ->mm here because current task might represent * a subthread, while tsk always points to the main thread. */ if (force_early && tsk->mm == current->mm) return current; return find_early_kill_thread(tsk); } /* * Collect processes when the error hit an anonymous page. */ static void collect_procs_anon(struct page *page, struct list_head *to_kill, int force_early) { struct vm_area_struct *vma; struct task_struct *tsk; struct anon_vma *av; pgoff_t pgoff; av = page_lock_anon_vma_read(page); if (av == NULL) /* Not actually mapped anymore */ return; pgoff = page_to_pgoff(page); read_lock(&tasklist_lock); for_each_process (tsk) { struct anon_vma_chain *vmac; struct task_struct *t = task_early_kill(tsk, force_early); if (!t) continue; anon_vma_interval_tree_foreach(vmac, &av->rb_root, pgoff, pgoff) { vma = vmac->vma; if (!page_mapped_in_vma(page, vma)) continue; if (vma->vm_mm == t->mm) add_to_kill(t, page, vma, to_kill); } } read_unlock(&tasklist_lock); page_unlock_anon_vma_read(av); } /* * Collect processes when the error hit a file mapped page. */ static void collect_procs_file(struct page *page, struct list_head *to_kill, int force_early) { struct vm_area_struct *vma; struct task_struct *tsk; struct address_space *mapping = page->mapping; pgoff_t pgoff; i_mmap_lock_read(mapping); read_lock(&tasklist_lock); pgoff = page_to_pgoff(page); for_each_process(tsk) { struct task_struct *t = task_early_kill(tsk, force_early); if (!t) continue; vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) { /* * Send early kill signal to tasks where a vma covers * the page but the corrupted page is not necessarily * mapped it in its pte. * Assume applications who requested early kill want * to be informed of all such data corruptions. */ if (vma->vm_mm == t->mm) add_to_kill(t, page, vma, to_kill); } } read_unlock(&tasklist_lock); i_mmap_unlock_read(mapping); } /* * Collect the processes who have the corrupted page mapped to kill. */ static void collect_procs(struct page *page, struct list_head *tokill, int force_early) { if (!page->mapping) return; if (PageAnon(page)) collect_procs_anon(page, tokill, force_early); else collect_procs_file(page, tokill, force_early); } static const char *action_name[] = { [MF_IGNORED] = "Ignored", [MF_FAILED] = "Failed", [MF_DELAYED] = "Delayed", [MF_RECOVERED] = "Recovered", }; static const char * const action_page_types[] = { [MF_MSG_KERNEL] = "reserved kernel page", [MF_MSG_KERNEL_HIGH_ORDER] = "high-order kernel page", [MF_MSG_SLAB] = "kernel slab page", [MF_MSG_DIFFERENT_COMPOUND] = "different compound page after locking", [MF_MSG_POISONED_HUGE] = "huge page already hardware poisoned", [MF_MSG_HUGE] = "huge page", [MF_MSG_FREE_HUGE] = "free huge page", [MF_MSG_NON_PMD_HUGE] = "non-pmd-sized huge page", [MF_MSG_UNMAP_FAILED] = "unmapping failed page", [MF_MSG_DIRTY_SWAPCACHE] = "dirty swapcache page", [MF_MSG_CLEAN_SWAPCACHE] = "clean swapcache page", [MF_MSG_DIRTY_MLOCKED_LRU] = "dirty mlocked LRU page", [MF_MSG_CLEAN_MLOCKED_LRU] = "clean mlocked LRU page", [MF_MSG_DIRTY_UNEVICTABLE_LRU] = "dirty unevictable LRU page", [MF_MSG_CLEAN_UNEVICTABLE_LRU] = "clean unevictable LRU page", [MF_MSG_DIRTY_LRU] = "dirty LRU page", [MF_MSG_CLEAN_LRU] = "clean LRU page", [MF_MSG_TRUNCATED_LRU] = "already truncated LRU page", [MF_MSG_BUDDY] = "free buddy page", [MF_MSG_BUDDY_2ND] = "free buddy page (2nd try)", [MF_MSG_DAX] = "dax page", [MF_MSG_UNSPLIT_THP] = "unsplit thp", [MF_MSG_UNKNOWN] = "unknown page", }; /* * XXX: It is possible that a page is isolated from LRU cache, * and then kept in swap cache or failed to remove from page cache. * The page count will stop it from being freed by unpoison. * Stress tests should be aware of this memory leak problem. */ static int delete_from_lru_cache(struct page *p) { if (!isolate_lru_page(p)) { /* * Clear sensible page flags, so that the buddy system won't * complain when the page is unpoison-and-freed. */ ClearPageActive(p); ClearPageUnevictable(p); /* * Poisoned page might never drop its ref count to 0 so we have * to uncharge it manually from its memcg. */ mem_cgroup_uncharge(p); /* * drop the page count elevated by isolate_lru_page() */ put_page(p); return 0; } return -EIO; } static int truncate_error_page(struct page *p, unsigned long pfn, struct address_space *mapping) { int ret = MF_FAILED; if (mapping->a_ops->error_remove_page) { int err = mapping->a_ops->error_remove_page(mapping, p); if (err != 0) { pr_info("Memory failure: %#lx: Failed to punch page: %d\n", pfn, err); } else if (page_has_private(p) && !try_to_release_page(p, GFP_NOIO)) { pr_info("Memory failure: %#lx: failed to release buffers\n", pfn); } else { ret = MF_RECOVERED; } } else { /* * If the file system doesn't support it just invalidate * This fails on dirty or anything with private pages */ if (invalidate_inode_page(p)) ret = MF_RECOVERED; else pr_info("Memory failure: %#lx: Failed to invalidate\n", pfn); } return ret; } /* * Error hit kernel page. * Do nothing, try to be lucky and not touch this instead. For a few cases we * could be more sophisticated. */ static int me_kernel(struct page *p, unsigned long pfn) { return MF_IGNORED; } /* * Page in unknown state. Do nothing. */ static int me_unknown(struct page *p, unsigned long pfn) { pr_err("Memory failure: %#lx: Unknown page state\n", pfn); return MF_FAILED; } /* * Clean (or cleaned) page cache page. */ static int me_pagecache_clean(struct page *p, unsigned long pfn) { struct address_space *mapping; delete_from_lru_cache(p); /* * For anonymous pages we're done the only reference left * should be the one m_f() holds. */ if (PageAnon(p)) return MF_RECOVERED; /* * Now truncate the page in the page cache. This is really * more like a "temporary hole punch" * Don't do this for block devices when someone else * has a reference, because it could be file system metadata * and that's not safe to truncate. */ mapping = page_mapping(p); if (!mapping) { /* * Page has been teared down in the meanwhile */ return MF_FAILED; } /* * Truncation is a bit tricky. Enable it per file system for now. * * Open: to take i_mutex or not for this? Right now we don't. */ return truncate_error_page(p, pfn, mapping); } /* * Dirty pagecache page * Issues: when the error hit a hole page the error is not properly * propagated. */ static int me_pagecache_dirty(struct page *p, unsigned long pfn) { struct address_space *mapping = page_mapping(p); SetPageError(p); /* TBD: print more information about the file. */ if (mapping) { /* * IO error will be reported by write(), fsync(), etc. * who check the mapping. * This way the application knows that something went * wrong with its dirty file data. * * There's one open issue: * * The EIO will be only reported on the next IO * operation and then cleared through the IO map. * Normally Linux has two mechanisms to pass IO error * first through the AS_EIO flag in the address space * and then through the PageError flag in the page. * Since we drop pages on memory failure handling the * only mechanism open to use is through AS_AIO. * * This has the disadvantage that it gets cleared on * the first operation that returns an error, while * the PageError bit is more sticky and only cleared * when the page is reread or dropped. If an * application assumes it will always get error on * fsync, but does other operations on the fd before * and the page is dropped between then the error * will not be properly reported. * * This can already happen even without hwpoisoned * pages: first on metadata IO errors (which only * report through AS_EIO) or when the page is dropped * at the wrong time. * * So right now we assume that the application DTRT on * the first EIO, but we're not worse than other parts * of the kernel. */ mapping_set_error(mapping, -EIO); } return me_pagecache_clean(p, pfn); } /* * Clean and dirty swap cache. * * Dirty swap cache page is tricky to handle. The page could live both in page * cache and swap cache(ie. page is freshly swapped in). So it could be * referenced concurrently by 2 types of PTEs: * normal PTEs and swap PTEs. We try to handle them consistently by calling * try_to_unmap(TTU_IGNORE_HWPOISON) to convert the normal PTEs to swap PTEs, * and then * - clear dirty bit to prevent IO * - remove from LRU * - but keep in the swap cache, so that when we return to it on * a later page fault, we know the application is accessing * corrupted data and shall be killed (we installed simple * interception code in do_swap_page to catch it). * * Clean swap cache pages can be directly isolated. A later page fault will * bring in the known good data from disk. */ static int me_swapcache_dirty(struct page *p, unsigned long pfn) { ClearPageDirty(p); /* Trigger EIO in shmem: */ ClearPageUptodate(p); if (!delete_from_lru_cache(p)) return MF_DELAYED; else return MF_FAILED; } static int me_swapcache_clean(struct page *p, unsigned long pfn) { delete_from_swap_cache(p); if (!delete_from_lru_cache(p)) return MF_RECOVERED; else return MF_FAILED; } /* * Huge pages. Needs work. * Issues: * - Error on hugepage is contained in hugepage unit (not in raw page unit.) * To narrow down kill region to one page, we need to break up pmd. */ static int me_huge_page(struct page *p, unsigned long pfn) { int res; struct page *hpage = compound_head(p); struct address_space *mapping; if (!PageHuge(hpage)) return MF_DELAYED; mapping = page_mapping(hpage); if (mapping) { res = truncate_error_page(hpage, pfn, mapping); } else { res = MF_FAILED; unlock_page(hpage); /* * migration entry prevents later access on error anonymous * hugepage, so we can free and dissolve it into buddy to * save healthy subpages. */ if (PageAnon(hpage)) put_page(hpage); if (!dissolve_free_huge_page(p) && take_page_off_buddy(p)) { page_ref_inc(p); res = MF_RECOVERED; } lock_page(hpage); } return res; } /* * Various page states we can handle. * * A page state is defined by its current page->flags bits. * The table matches them in order and calls the right handler. * * This is quite tricky because we can access page at any time * in its live cycle, so all accesses have to be extremely careful. * * This is not complete. More states could be added. * For any missing state don't attempt recovery. */ #define dirty (1UL << PG_dirty) #define sc ((1UL << PG_swapcache) | (1UL << PG_swapbacked)) #define unevict (1UL << PG_unevictable) #define mlock (1UL << PG_mlocked) #define lru (1UL << PG_lru) #define head (1UL << PG_head) #define slab (1UL << PG_slab) #define reserved (1UL << PG_reserved) static struct page_state { unsigned long mask; unsigned long res; enum mf_action_page_type type; int (*action)(struct page *p, unsigned long pfn); } error_states[] = { { reserved, reserved, MF_MSG_KERNEL, me_kernel }, /* * free pages are specially detected outside this table: * PG_buddy pages only make a small fraction of all free pages. */ /* * Could in theory check if slab page is free or if we can drop * currently unused objects without touching them. But just * treat it as standard kernel for now. */ { slab, slab, MF_MSG_SLAB, me_kernel }, { head, head, MF_MSG_HUGE, me_huge_page }, { sc|dirty, sc|dirty, MF_MSG_DIRTY_SWAPCACHE, me_swapcache_dirty }, { sc|dirty, sc, MF_MSG_CLEAN_SWAPCACHE, me_swapcache_clean }, { mlock|dirty, mlock|dirty, MF_MSG_DIRTY_MLOCKED_LRU, me_pagecache_dirty }, { mlock|dirty, mlock, MF_MSG_CLEAN_MLOCKED_LRU, me_pagecache_clean }, { unevict|dirty, unevict|dirty, MF_MSG_DIRTY_UNEVICTABLE_LRU, me_pagecache_dirty }, { unevict|dirty, unevict, MF_MSG_CLEAN_UNEVICTABLE_LRU, me_pagecache_clean }, { lru|dirty, lru|dirty, MF_MSG_DIRTY_LRU, me_pagecache_dirty }, { lru|dirty, lru, MF_MSG_CLEAN_LRU, me_pagecache_clean }, /* * Catchall entry: must be at end. */ { 0, 0, MF_MSG_UNKNOWN, me_unknown }, }; #undef dirty #undef sc #undef unevict #undef mlock #undef lru #undef head #undef slab #undef reserved /* * "Dirty/Clean" indication is not 100% accurate due to the possibility of * setting PG_dirty outside page lock. See also comment above set_page_dirty(). */ static void action_result(unsigned long pfn, enum mf_action_page_type type, enum mf_result result) { trace_memory_failure_event(pfn, type, result); pr_err("Memory failure: %#lx: recovery action for %s: %s\n", pfn, action_page_types[type], action_name[result]); } static int page_action(struct page_state *ps, struct page *p, unsigned long pfn) { int result; int count; result = ps->action(p, pfn); count = page_count(p) - 1; if (ps->action == me_swapcache_dirty && result == MF_DELAYED) count--; if (count > 0) { pr_err("Memory failure: %#lx: %s still referenced by %d users\n", pfn, action_page_types[ps->type], count); result = MF_FAILED; } action_result(pfn, ps->type, result); /* Could do more checks here if page looks ok */ /* * Could adjust zone counters here to correct for the missing page. */ return (result == MF_RECOVERED || result == MF_DELAYED) ? 0 : -EBUSY; } /* * Return true if a page type of a given page is supported by hwpoison * mechanism (while handling could fail), otherwise false. This function * does not return true for hugetlb or device memory pages, so it's assumed * to be called only in the context where we never have such pages. */ static inline bool HWPoisonHandlable(struct page *page) { return PageLRU(page) || __PageMovable(page); } /** * __get_hwpoison_page() - Get refcount for memory error handling: * @page: raw error page (hit by memory error) * * Return: return 0 if failed to grab the refcount, otherwise true (some * non-zero value.) */ static int __get_hwpoison_page(struct page *page) { struct page *head = compound_head(page); int ret = 0; bool hugetlb = false; ret = get_hwpoison_huge_page(head, &hugetlb); if (hugetlb) return ret; /* * This check prevents from calling get_hwpoison_unless_zero() * for any unsupported type of page in order to reduce the risk of * unexpected races caused by taking a page refcount. */ if (!HWPoisonHandlable(head)) return 0; if (PageTransHuge(head)) { /* * Non anonymous thp exists only in allocation/free time. We * can't handle such a case correctly, so let's give it up. * This should be better than triggering BUG_ON when kernel * tries to touch the "partially handled" page. */ if (!PageAnon(head)) { pr_err("Memory failure: %#lx: non anonymous thp\n", page_to_pfn(page)); return 0; } } if (get_page_unless_zero(head)) { if (head == compound_head(page)) return 1; pr_info("Memory failure: %#lx cannot catch tail\n", page_to_pfn(page)); put_page(head); } return 0; } /* * Safely get reference count of an arbitrary page. * * Returns 0 for a free page, 1 for an in-use page, * -EIO for a page-type we cannot handle and -EBUSY if we raced with an * allocation. * We only incremented refcount in case the page was already in-use and it * is a known type we can handle. */ static int get_any_page(struct page *p, unsigned long flags) { int ret = 0, pass = 0; bool count_increased = false; if (flags & MF_COUNT_INCREASED) count_increased = true; try_again: if (!count_increased && !__get_hwpoison_page(p)) { if (page_count(p)) { /* We raced with an allocation, retry. */ if (pass++ < 3) goto try_again; ret = -EBUSY; } else if (!PageHuge(p) && !is_free_buddy_page(p)) { /* We raced with put_page, retry. */ if (pass++ < 3) goto try_again; ret = -EIO; } } else { if (PageHuge(p) || HWPoisonHandlable(p)) { ret = 1; } else { /* * A page we cannot handle. Check whether we can turn * it into something we can handle. */ if (pass++ < 3) { put_page(p); shake_page(p, 1); count_increased = false; goto try_again; } put_page(p); ret = -EIO; } } return ret; } static int get_hwpoison_page(struct page *p, unsigned long flags, enum mf_flags ctxt) { int ret; zone_pcp_disable(page_zone(p)); if (ctxt == MF_SOFT_OFFLINE) ret = get_any_page(p, flags); else ret = __get_hwpoison_page(p); zone_pcp_enable(page_zone(p)); return ret; } /* * Do all that is necessary to remove user space mappings. Unmap * the pages and send SIGBUS to the processes if the data was dirty. */ static bool hwpoison_user_mappings(struct page *p, unsigned long pfn, int flags, struct page **hpagep) { enum ttu_flags ttu = TTU_IGNORE_MLOCK; struct address_space *mapping; LIST_HEAD(tokill); bool unmap_success = true; int kill = 1, forcekill; struct page *hpage = *hpagep; bool mlocked = PageMlocked(hpage); /* * Here we are interested only in user-mapped pages, so skip any * other types of pages. */ if (PageReserved(p) || PageSlab(p)) return true; if (!(PageLRU(hpage) || PageHuge(p))) return true; /* * This check implies we don't kill processes if their pages * are in the swap cache early. Those are always late kills. */ if (!page_mapped(hpage)) return true; if (PageKsm(p)) { pr_err("Memory failure: %#lx: can't handle KSM pages.\n", pfn); return false; } if (PageSwapCache(p)) { pr_err("Memory failure: %#lx: keeping poisoned page in swap cache\n", pfn); ttu |= TTU_IGNORE_HWPOISON; } /* * Propagate the dirty bit from PTEs to struct page first, because we * need this to decide if we should kill or just drop the page. * XXX: the dirty test could be racy: set_page_dirty() may not always * be called inside page lock (it's recommended but not enforced). */ mapping = page_mapping(hpage); if (!(flags & MF_MUST_KILL) && !PageDirty(hpage) && mapping && mapping_can_writeback(mapping)) { if (page_mkclean(hpage)) { SetPageDirty(hpage); } else { kill = 0; ttu |= TTU_IGNORE_HWPOISON; pr_info("Memory failure: %#lx: corrupted page was clean: dropped without side effects\n", pfn); } } /* * First collect all the processes that have the page * mapped in dirty form. This has to be done before try_to_unmap, * because ttu takes the rmap data structures down. * * Error handling: We ignore errors here because * there's nothing that can be done. */ if (kill) collect_procs(hpage, &tokill, flags & MF_ACTION_REQUIRED); if (!PageHuge(hpage)) { unmap_success = try_to_unmap(hpage, ttu); } else { if (!PageAnon(hpage)) { /* * For hugetlb pages in shared mappings, try_to_unmap * could potentially call huge_pmd_unshare. Because of * this, take semaphore in write mode here and set * TTU_RMAP_LOCKED to indicate we have taken the lock * at this higer level. */ mapping = hugetlb_page_mapping_lock_write(hpage); if (mapping) { unmap_success = try_to_unmap(hpage, ttu|TTU_RMAP_LOCKED); i_mmap_unlock_write(mapping); } else { pr_info("Memory failure: %#lx: could not lock mapping for mapped huge page\n", pfn); unmap_success = false; } } else { unmap_success = try_to_unmap(hpage, ttu); } } if (!unmap_success) pr_err("Memory failure: %#lx: failed to unmap page (mapcount=%d)\n", pfn, page_mapcount(hpage)); /* * try_to_unmap() might put mlocked page in lru cache, so call * shake_page() again to ensure that it's flushed. */ if (mlocked) shake_page(hpage, 0); /* * Now that the dirty bit has been propagated to the * struct page and all unmaps done we can decide if * killing is needed or not. Only kill when the page * was dirty or the process is not restartable, * otherwise the tokill list is merely * freed. When there was a problem unmapping earlier * use a more force-full uncatchable kill to prevent * any accesses to the poisoned memory. */ forcekill = PageDirty(hpage) || (flags & MF_MUST_KILL); kill_procs(&tokill, forcekill, !unmap_success, pfn, flags); return unmap_success; } static int identify_page_state(unsigned long pfn, struct page *p, unsigned long page_flags) { struct page_state *ps; /* * The first check uses the current page flags which may not have any * relevant information. The second check with the saved page flags is * carried out only if the first check can't determine the page status. */ for (ps = error_states;; ps++) if ((p->flags & ps->mask) == ps->res) break; page_flags |= (p->flags & (1UL << PG_dirty)); if (!ps->mask) for (ps = error_states;; ps++) if ((page_flags & ps->mask) == ps->res) break; return page_action(ps, p, pfn); } static int try_to_split_thp_page(struct page *page, const char *msg) { lock_page(page); if (!PageAnon(page) || unlikely(split_huge_page(page))) { unsigned long pfn = page_to_pfn(page); unlock_page(page); if (!PageAnon(page)) pr_info("%s: %#lx: non anonymous thp\n", msg, pfn); else pr_info("%s: %#lx: thp split failed\n", msg, pfn); put_page(page); return -EBUSY; } unlock_page(page); return 0; } static int memory_failure_hugetlb(unsigned long pfn, int flags) { struct page *p = pfn_to_page(pfn); struct page *head = compound_head(p); int res; unsigned long page_flags; if (TestSetPageHWPoison(head)) { pr_err("Memory failure: %#lx: already hardware poisoned\n", pfn); return 0; } num_poisoned_pages_inc(); if (!(flags & MF_COUNT_INCREASED) && !get_hwpoison_page(p, flags, 0)) { /* * Check "filter hit" and "race with other subpage." */ lock_page(head); if (PageHWPoison(head)) { if ((hwpoison_filter(p) && TestClearPageHWPoison(p)) || (p != head && TestSetPageHWPoison(head))) { num_poisoned_pages_dec(); unlock_page(head); return 0; } } unlock_page(head); res = MF_FAILED; if (!dissolve_free_huge_page(p) && take_page_off_buddy(p)) { page_ref_inc(p); res = MF_RECOVERED; } action_result(pfn, MF_MSG_FREE_HUGE, res); return res == MF_RECOVERED ? 0 : -EBUSY; } lock_page(head); page_flags = head->flags; if (!PageHWPoison(head)) { pr_err("Memory failure: %#lx: just unpoisoned\n", pfn); num_poisoned_pages_dec(); unlock_page(head); put_page(head); return 0; } /* * TODO: hwpoison for pud-sized hugetlb doesn't work right now, so * simply disable it. In order to make it work properly, we need * make sure that: * - conversion of a pud that maps an error hugetlb into hwpoison * entry properly works, and * - other mm code walking over page table is aware of pud-aligned * hwpoison entries. */ if (huge_page_size(page_hstate(head)) > PMD_SIZE) { action_result(pfn, MF_MSG_NON_PMD_HUGE, MF_IGNORED); res = -EBUSY; goto out; } if (!hwpoison_user_mappings(p, pfn, flags, &head)) { action_result(pfn, MF_MSG_UNMAP_FAILED, MF_IGNORED); res = -EBUSY; goto out; } res = identify_page_state(pfn, p, page_flags); out: unlock_page(head); return res; } static int memory_failure_dev_pagemap(unsigned long pfn, int flags, struct dev_pagemap *pgmap) { struct page *page = pfn_to_page(pfn); const bool unmap_success = true; unsigned long size = 0; struct to_kill *tk; LIST_HEAD(tokill); int rc = -EBUSY; loff_t start; dax_entry_t cookie; if (flags & MF_COUNT_INCREASED) /* * Drop the extra refcount in case we come from madvise(). */ put_page(page); /* device metadata space is not recoverable */ if (!pgmap_pfn_valid(pgmap, pfn)) { rc = -ENXIO; goto out; } /* * Prevent the inode from being freed while we are interrogating * the address_space, typically this would be handled by * lock_page(), but dax pages do not use the page lock. This * also prevents changes to the mapping of this pfn until * poison signaling is complete. */ cookie = dax_lock_page(page); if (!cookie) goto out; if (hwpoison_filter(page)) { rc = 0; goto unlock; } if (pgmap->type == MEMORY_DEVICE_PRIVATE) { /* * TODO: Handle HMM pages which may need coordination * with device-side memory. */ goto unlock; } /* * Use this flag as an indication that the dax page has been * remapped UC to prevent speculative consumption of poison. */ SetPageHWPoison(page); /* * Unlike System-RAM there is no possibility to swap in a * different physical page at a given virtual address, so all * userspace consumption of ZONE_DEVICE memory necessitates * SIGBUS (i.e. MF_MUST_KILL) */ flags |= MF_ACTION_REQUIRED | MF_MUST_KILL; collect_procs(page, &tokill, flags & MF_ACTION_REQUIRED); list_for_each_entry(tk, &tokill, nd) if (tk->size_shift) size = max(size, 1UL << tk->size_shift); if (size) { /* * Unmap the largest mapping to avoid breaking up * device-dax mappings which are constant size. The * actual size of the mapping being torn down is * communicated in siginfo, see kill_proc() */ start = (page->index << PAGE_SHIFT) & ~(size - 1); unmap_mapping_range(page->mapping, start, size, 0); } kill_procs(&tokill, flags & MF_MUST_KILL, !unmap_success, pfn, flags); rc = 0; unlock: dax_unlock_page(page, cookie); out: /* drop pgmap ref acquired in caller */ put_dev_pagemap(pgmap); action_result(pfn, MF_MSG_DAX, rc ? MF_FAILED : MF_RECOVERED); return rc; } /** * memory_failure - Handle memory failure of a page. * @pfn: Page Number of the corrupted page * @flags: fine tune action taken * * This function is called by the low level machine check code * of an architecture when it detects hardware memory corruption * of a page. It tries its best to recover, which includes * dropping pages, killing processes etc. * * The function is primarily of use for corruptions that * happen outside the current execution context (e.g. when * detected by a background scrubber) * * Must run in process context (e.g. a work queue) with interrupts * enabled and no spinlocks hold. */ int memory_failure(unsigned long pfn, int flags) { struct page *p; struct page *hpage; struct page *orig_head; struct dev_pagemap *pgmap; int res; unsigned long page_flags; bool retry = true; if (!sysctl_memory_failure_recovery) panic("Memory failure on page %lx", pfn); p = pfn_to_online_page(pfn); if (!p) { if (pfn_valid(pfn)) { pgmap = get_dev_pagemap(pfn, NULL); if (pgmap) return memory_failure_dev_pagemap(pfn, flags, pgmap); } pr_err("Memory failure: %#lx: memory outside kernel control\n", pfn); return -ENXIO; } try_again: if (PageHuge(p)) return memory_failure_hugetlb(pfn, flags); if (TestSetPageHWPoison(p)) { pr_err("Memory failure: %#lx: already hardware poisoned\n", pfn); return 0; } orig_head = hpage = compound_head(p); num_poisoned_pages_inc(); /* * We need/can do nothing about count=0 pages. * 1) it's a free page, and therefore in safe hand: * prep_new_page() will be the gate keeper. * 2) it's part of a non-compound high order page. * Implies some kernel user: cannot stop them from * R/W the page; let's pray that the page has been * used and will be freed some time later. * In fact it's dangerous to directly bump up page count from 0, * that may make page_ref_freeze()/page_ref_unfreeze() mismatch. */ if (!(flags & MF_COUNT_INCREASED) && !get_hwpoison_page(p, flags, 0)) { if (is_free_buddy_page(p)) { if (take_page_off_buddy(p)) { page_ref_inc(p); res = MF_RECOVERED; } else { /* We lost the race, try again */ if (retry) { ClearPageHWPoison(p); num_poisoned_pages_dec(); retry = false; goto try_again; } res = MF_FAILED; } action_result(pfn, MF_MSG_BUDDY, res); return res == MF_RECOVERED ? 0 : -EBUSY; } else { action_result(pfn, MF_MSG_KERNEL_HIGH_ORDER, MF_IGNORED); return -EBUSY; } } if (PageTransHuge(hpage)) { if (try_to_split_thp_page(p, "Memory Failure") < 0) { action_result(pfn, MF_MSG_UNSPLIT_THP, MF_IGNORED); return -EBUSY; } VM_BUG_ON_PAGE(!page_count(p), p); } /* * We ignore non-LRU pages for good reasons. * - PG_locked is only well defined for LRU pages and a few others * - to avoid races with __SetPageLocked() * - to avoid races with __SetPageSlab*() (and more non-atomic ops) * The check (unnecessarily) ignores LRU pages being isolated and * walked by the page reclaim code, however that's not a big loss. */ shake_page(p, 0); lock_page(p); /* * The page could have changed compound pages during the locking. * If this happens just bail out. */ if (PageCompound(p) && compound_head(p) != orig_head) { action_result(pfn, MF_MSG_DIFFERENT_COMPOUND, MF_IGNORED); res = -EBUSY; goto out; } /* * We use page flags to determine what action should be taken, but * the flags can be modified by the error containment action. One * example is an mlocked page, where PG_mlocked is cleared by * page_remove_rmap() in try_to_unmap_one(). So to determine page status * correctly, we save a copy of the page flags at this time. */ page_flags = p->flags; /* * unpoison always clear PG_hwpoison inside page lock */ if (!PageHWPoison(p)) { pr_err("Memory failure: %#lx: just unpoisoned\n", pfn); num_poisoned_pages_dec(); unlock_page(p); put_page(p); return 0; } if (hwpoison_filter(p)) { if (TestClearPageHWPoison(p)) num_poisoned_pages_dec(); unlock_page(p); put_page(p); return 0; } /* * __munlock_pagevec may clear a writeback page's LRU flag without * page_lock. We need wait writeback completion for this page or it * may trigger vfs BUG while evict inode. */ if (!PageTransTail(p) && !PageLRU(p) && !PageWriteback(p)) goto identify_page_state; /* * It's very difficult to mess with pages currently under IO * and in many cases impossible, so we just avoid it here. */ wait_on_page_writeback(p); /* * Now take care of user space mappings. * Abort on fail: __delete_from_page_cache() assumes unmapped page. */ if (!hwpoison_user_mappings(p, pfn, flags, &p)) { action_result(pfn, MF_MSG_UNMAP_FAILED, MF_IGNORED); res = -EBUSY; goto out; } /* * Torn down by someone else? */ if (PageLRU(p) && !PageSwapCache(p) && p->mapping == NULL) { action_result(pfn, MF_MSG_TRUNCATED_LRU, MF_IGNORED); res = -EBUSY; goto out; } identify_page_state: res = identify_page_state(pfn, p, page_flags); out: unlock_page(p); return res; } EXPORT_SYMBOL_GPL(memory_failure); #define MEMORY_FAILURE_FIFO_ORDER 4 #define MEMORY_FAILURE_FIFO_SIZE (1 << MEMORY_FAILURE_FIFO_ORDER) struct memory_failure_entry { unsigned long pfn; int flags; }; struct memory_failure_cpu { DECLARE_KFIFO(fifo, struct memory_failure_entry, MEMORY_FAILURE_FIFO_SIZE); spinlock_t lock; struct work_struct work; }; static DEFINE_PER_CPU(struct memory_failure_cpu, memory_failure_cpu); /** * memory_failure_queue - Schedule handling memory failure of a page. * @pfn: Page Number of the corrupted page * @flags: Flags for memory failure handling * * This function is called by the low level hardware error handler * when it detects hardware memory corruption of a page. It schedules * the recovering of error page, including dropping pages, killing * processes etc. * * The function is primarily of use for corruptions that * happen outside the current execution context (e.g. when * detected by a background scrubber) * * Can run in IRQ context. */ void memory_failure_queue(unsigned long pfn, int flags) { struct memory_failure_cpu *mf_cpu; unsigned long proc_flags; struct memory_failure_entry entry = { .pfn = pfn, .flags = flags, }; mf_cpu = &get_cpu_var(memory_failure_cpu); spin_lock_irqsave(&mf_cpu->lock, proc_flags); if (kfifo_put(&mf_cpu->fifo, entry)) schedule_work_on(smp_processor_id(), &mf_cpu->work); else pr_err("Memory failure: buffer overflow when queuing memory failure at %#lx\n", pfn); spin_unlock_irqrestore(&mf_cpu->lock, proc_flags); put_cpu_var(memory_failure_cpu); } EXPORT_SYMBOL_GPL(memory_failure_queue); static void memory_failure_work_func(struct work_struct *work) { struct memory_failure_cpu *mf_cpu; struct memory_failure_entry entry = { 0, }; unsigned long proc_flags; int gotten; mf_cpu = container_of(work, struct memory_failure_cpu, work); for (;;) { spin_lock_irqsave(&mf_cpu->lock, proc_flags); gotten = kfifo_get(&mf_cpu->fifo, &entry); spin_unlock_irqrestore(&mf_cpu->lock, proc_flags); if (!gotten) break; if (entry.flags & MF_SOFT_OFFLINE) soft_offline_page(entry.pfn, entry.flags); else memory_failure(entry.pfn, entry.flags); } } /* * Process memory_failure work queued on the specified CPU. * Used to avoid return-to-userspace racing with the memory_failure workqueue. */ void memory_failure_queue_kick(int cpu) { struct memory_failure_cpu *mf_cpu; mf_cpu = &per_cpu(memory_failure_cpu, cpu); cancel_work_sync(&mf_cpu->work); memory_failure_work_func(&mf_cpu->work); } static int __init memory_failure_init(void) { struct memory_failure_cpu *mf_cpu; int cpu; for_each_possible_cpu(cpu) { mf_cpu = &per_cpu(memory_failure_cpu, cpu); spin_lock_init(&mf_cpu->lock); INIT_KFIFO(mf_cpu->fifo); INIT_WORK(&mf_cpu->work, memory_failure_work_func); } return 0; } core_initcall(memory_failure_init); #define unpoison_pr_info(fmt, pfn, rs) \ ({ \ if (__ratelimit(rs)) \ pr_info(fmt, pfn); \ }) /** * unpoison_memory - Unpoison a previously poisoned page * @pfn: Page number of the to be unpoisoned page * * Software-unpoison a page that has been poisoned by * memory_failure() earlier. * * This is only done on the software-level, so it only works * for linux injected failures, not real hardware failures * * Returns 0 for success, otherwise -errno. */ int unpoison_memory(unsigned long pfn) { struct page *page; struct page *p; int freeit = 0; unsigned long flags = 0; static DEFINE_RATELIMIT_STATE(unpoison_rs, DEFAULT_RATELIMIT_INTERVAL, DEFAULT_RATELIMIT_BURST); if (!pfn_valid(pfn)) return -ENXIO; p = pfn_to_page(pfn); page = compound_head(p); if (!PageHWPoison(p)) { unpoison_pr_info("Unpoison: Page was already unpoisoned %#lx\n", pfn, &unpoison_rs); return 0; } if (page_count(page) > 1) { unpoison_pr_info("Unpoison: Someone grabs the hwpoison page %#lx\n", pfn, &unpoison_rs); return 0; } if (page_mapped(page)) { unpoison_pr_info("Unpoison: Someone maps the hwpoison page %#lx\n", pfn, &unpoison_rs); return 0; } if (page_mapping(page)) { unpoison_pr_info("Unpoison: the hwpoison page has non-NULL mapping %#lx\n", pfn, &unpoison_rs); return 0; } /* * unpoison_memory() can encounter thp only when the thp is being * worked by memory_failure() and the page lock is not held yet. * In such case, we yield to memory_failure() and make unpoison fail. */ if (!PageHuge(page) && PageTransHuge(page)) { unpoison_pr_info("Unpoison: Memory failure is now running on %#lx\n", pfn, &unpoison_rs); return 0; } if (!get_hwpoison_page(p, flags, 0)) { if (TestClearPageHWPoison(p)) num_poisoned_pages_dec(); unpoison_pr_info("Unpoison: Software-unpoisoned free page %#lx\n", pfn, &unpoison_rs); return 0; } lock_page(page); /* * This test is racy because PG_hwpoison is set outside of page lock. * That's acceptable because that won't trigger kernel panic. Instead, * the PG_hwpoison page will be caught and isolated on the entrance to * the free buddy page pool. */ if (TestClearPageHWPoison(page)) { unpoison_pr_info("Unpoison: Software-unpoisoned page %#lx\n", pfn, &unpoison_rs); num_poisoned_pages_dec(); freeit = 1; } unlock_page(page); put_page(page); if (freeit && !(pfn == my_zero_pfn(0) && page_count(p) == 1)) put_page(page); return 0; } EXPORT_SYMBOL(unpoison_memory); static bool isolate_page(struct page *page, struct list_head *pagelist) { bool isolated = false; bool lru = PageLRU(page); if (PageHuge(page)) { isolated = isolate_huge_page(page, pagelist); } else { if (lru) isolated = !isolate_lru_page(page); else isolated = !isolate_movable_page(page, ISOLATE_UNEVICTABLE); if (isolated) list_add(&page->lru, pagelist); } if (isolated && lru) inc_node_page_state(page, NR_ISOLATED_ANON + page_is_file_lru(page)); /* * If we succeed to isolate the page, we grabbed another refcount on * the page, so we can safely drop the one we got from get_any_pages(). * If we failed to isolate the page, it means that we cannot go further * and we will return an error, so drop the reference we got from * get_any_pages() as well. */ put_page(page); return isolated; } /* * __soft_offline_page handles hugetlb-pages and non-hugetlb pages. * If the page is a non-dirty unmapped page-cache page, it simply invalidates. * If the page is mapped, it migrates the contents over. */ static int __soft_offline_page(struct page *page) { int ret = 0; unsigned long pfn = page_to_pfn(page); struct page *hpage = compound_head(page); char const *msg_page[] = {"page", "hugepage"}; bool huge = PageHuge(page); LIST_HEAD(pagelist); struct migration_target_control mtc = { .nid = NUMA_NO_NODE, .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL, }; /* * Check PageHWPoison again inside page lock because PageHWPoison * is set by memory_failure() outside page lock. Note that * memory_failure() also double-checks PageHWPoison inside page lock, * so there's no race between soft_offline_page() and memory_failure(). */ lock_page(page); if (!PageHuge(page)) wait_on_page_writeback(page); if (PageHWPoison(page)) { unlock_page(page); put_page(page); pr_info("soft offline: %#lx page already poisoned\n", pfn); return 0; } if (!PageHuge(page)) /* * Try to invalidate first. This should work for * non dirty unmapped page cache pages. */ ret = invalidate_inode_page(page); unlock_page(page); /* * RED-PEN would be better to keep it isolated here, but we * would need to fix isolation locking first. */ if (ret) { pr_info("soft_offline: %#lx: invalidated\n", pfn); page_handle_poison(page, false, true); return 0; } if (isolate_page(hpage, &pagelist)) { ret = migrate_pages(&pagelist, alloc_migration_target, NULL, (unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_FAILURE); if (!ret) { bool release = !huge; if (!page_handle_poison(page, huge, release)) ret = -EBUSY; } else { if (!list_empty(&pagelist)) putback_movable_pages(&pagelist); pr_info("soft offline: %#lx: %s migration failed %d, type %lx (%pGp)\n", pfn, msg_page[huge], ret, page->flags, &page->flags); if (ret > 0) ret = -EBUSY; } } else { pr_info("soft offline: %#lx: %s isolation failed, page count %d, type %lx (%pGp)\n", pfn, msg_page[huge], page_count(page), page->flags, &page->flags); ret = -EBUSY; } return ret; } static int soft_offline_in_use_page(struct page *page) { struct page *hpage = compound_head(page); if (!PageHuge(page) && PageTransHuge(hpage)) if (try_to_split_thp_page(page, "soft offline") < 0) return -EBUSY; return __soft_offline_page(page); } static int soft_offline_free_page(struct page *page) { int rc = 0; if (!page_handle_poison(page, true, false)) rc = -EBUSY; return rc; } static void put_ref_page(struct page *page) { if (page) put_page(page); } /** * soft_offline_page - Soft offline a page. * @pfn: pfn to soft-offline * @flags: flags. Same as memory_failure(). * * Returns 0 on success, otherwise negated errno. * * Soft offline a page, by migration or invalidation, * without killing anything. This is for the case when * a page is not corrupted yet (so it's still valid to access), * but has had a number of corrected errors and is better taken * out. * * The actual policy on when to do that is maintained by * user space. * * This should never impact any application or cause data loss, * however it might take some time. * * This is not a 100% solution for all memory, but tries to be * ``good enough'' for the majority of memory. */ int soft_offline_page(unsigned long pfn, int flags) { int ret; bool try_again = true; struct page *page, *ref_page = NULL; WARN_ON_ONCE(!pfn_valid(pfn) && (flags & MF_COUNT_INCREASED)); if (!pfn_valid(pfn)) return -ENXIO; if (flags & MF_COUNT_INCREASED) ref_page = pfn_to_page(pfn); /* Only online pages can be soft-offlined (esp., not ZONE_DEVICE). */ page = pfn_to_online_page(pfn); if (!page) { put_ref_page(ref_page); return -EIO; } if (PageHWPoison(page)) { pr_info("%s: %#lx page already poisoned\n", __func__, pfn); put_ref_page(ref_page); return 0; } retry: get_online_mems(); ret = get_hwpoison_page(page, flags, MF_SOFT_OFFLINE); put_online_mems(); if (ret > 0) { ret = soft_offline_in_use_page(page); } else if (ret == 0) { if (soft_offline_free_page(page) && try_again) { try_again = false; goto retry; } } else if (ret == -EIO) { pr_info("%s: %#lx: unknown page type: %lx (%pGp)\n", __func__, pfn, page->flags, &page->flags); } return ret; }
Broadcom/linux-rdma-nxt
mm/memory-failure.c
C
gpl-2.0
55,032
/* atomic.c -- implement atomic routines for Go. Copyright 2011 The Go 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 "runtime.h" int32_t SwapInt32 (int32_t *, int32_t) __asm__ (GOSYM_PREFIX "sync_atomic.SwapInt32") __attribute__ ((no_split_stack)); int32_t SwapInt32 (int32_t *addr, int32_t new) { return __atomic_exchange_n (addr, new, __ATOMIC_SEQ_CST); } int64_t SwapInt64 (int64_t *, int64_t) __asm__ (GOSYM_PREFIX "sync_atomic.SwapInt64") __attribute__ ((no_split_stack)); int64_t SwapInt64 (int64_t *addr, int64_t new) { if (((uintptr_t) addr & 7) != 0) addr = NULL; return __atomic_exchange_n (addr, new, __ATOMIC_SEQ_CST); } uint32_t SwapUint32 (uint32_t *, uint32_t) __asm__ (GOSYM_PREFIX "sync_atomic.SwapUint32") __attribute__ ((no_split_stack)); uint32_t SwapUint32 (uint32_t *addr, uint32_t new) { return __atomic_exchange_n (addr, new, __ATOMIC_SEQ_CST); } uint64_t SwapUint64 (uint64_t *, uint64_t) __asm__ (GOSYM_PREFIX "sync_atomic.SwapUint64") __attribute__ ((no_split_stack)); uint64_t SwapUint64 (uint64_t *addr, uint64_t new) { if (((uintptr_t) addr & 7) != 0) addr = NULL; return __atomic_exchange_n (addr, new, __ATOMIC_SEQ_CST); } uintptr_t SwapUintptr (uintptr_t *, uintptr_t) __asm__ (GOSYM_PREFIX "sync_atomic.SwapUintptr") __attribute__ ((no_split_stack)); uintptr_t SwapUintptr (uintptr_t *addr, uintptr_t new) { return __atomic_exchange_n (addr, new, __ATOMIC_SEQ_CST); } void *SwapPointer (void **, void *) __asm__ (GOSYM_PREFIX "sync_atomic.SwapPointer") __attribute__ ((no_split_stack)); void * SwapPointer (void **addr, void *new) { return __atomic_exchange_n (addr, new, __ATOMIC_SEQ_CST); } _Bool CompareAndSwapInt32 (int32_t *, int32_t, int32_t) __asm__ (GOSYM_PREFIX "sync_atomic.CompareAndSwapInt32") __attribute__ ((no_split_stack)); _Bool CompareAndSwapInt32 (int32_t *val, int32_t old, int32_t new) { return __sync_bool_compare_and_swap (val, old, new); } _Bool CompareAndSwapInt64 (int64_t *, int64_t, int64_t) __asm__ (GOSYM_PREFIX "sync_atomic.CompareAndSwapInt64") __attribute__ ((no_split_stack)); _Bool CompareAndSwapInt64 (int64_t *val, int64_t old, int64_t new) { if (((uintptr_t) val & 7) != 0) val = NULL; return __sync_bool_compare_and_swap (val, old, new); } _Bool CompareAndSwapUint32 (uint32_t *, uint32_t, uint32_t) __asm__ (GOSYM_PREFIX "sync_atomic.CompareAndSwapUint32") __attribute__ ((no_split_stack)); _Bool CompareAndSwapUint32 (uint32_t *val, uint32_t old, uint32_t new) { return __sync_bool_compare_and_swap (val, old, new); } _Bool CompareAndSwapUint64 (uint64_t *, uint64_t, uint64_t) __asm__ (GOSYM_PREFIX "sync_atomic.CompareAndSwapUint64") __attribute__ ((no_split_stack)); _Bool CompareAndSwapUint64 (uint64_t *val, uint64_t old, uint64_t new) { if (((uintptr_t) val & 7) != 0) val = NULL; return __sync_bool_compare_and_swap (val, old, new); } _Bool CompareAndSwapUintptr (uintptr_t *, uintptr_t, uintptr_t) __asm__ (GOSYM_PREFIX "sync_atomic.CompareAndSwapUintptr") __attribute__ ((no_split_stack)); _Bool CompareAndSwapUintptr (uintptr_t *val, uintptr_t old, uintptr_t new) { return __sync_bool_compare_and_swap (val, old, new); } _Bool CompareAndSwapPointer (void **, void *, void *) __asm__ (GOSYM_PREFIX "sync_atomic.CompareAndSwapPointer") __attribute__ ((no_split_stack)); _Bool CompareAndSwapPointer (void **val, void *old, void *new) { return __sync_bool_compare_and_swap (val, old, new); } int32_t AddInt32 (int32_t *, int32_t) __asm__ (GOSYM_PREFIX "sync_atomic.AddInt32") __attribute__ ((no_split_stack)); int32_t AddInt32 (int32_t *val, int32_t delta) { return __sync_add_and_fetch (val, delta); } uint32_t AddUint32 (uint32_t *, uint32_t) __asm__ (GOSYM_PREFIX "sync_atomic.AddUint32") __attribute__ ((no_split_stack)); uint32_t AddUint32 (uint32_t *val, uint32_t delta) { return __sync_add_and_fetch (val, delta); } int64_t AddInt64 (int64_t *, int64_t) __asm__ (GOSYM_PREFIX "sync_atomic.AddInt64") __attribute__ ((no_split_stack)); int64_t AddInt64 (int64_t *val, int64_t delta) { if (((uintptr_t) val & 7) != 0) val = NULL; return __sync_add_and_fetch (val, delta); } uint64_t AddUint64 (uint64_t *, uint64_t) __asm__ (GOSYM_PREFIX "sync_atomic.AddUint64") __attribute__ ((no_split_stack)); uint64_t AddUint64 (uint64_t *val, uint64_t delta) { if (((uintptr_t) val & 7) != 0) val = NULL; return __sync_add_and_fetch (val, delta); } uintptr_t AddUintptr (uintptr_t *, uintptr_t) __asm__ (GOSYM_PREFIX "sync_atomic.AddUintptr") __attribute__ ((no_split_stack)); uintptr_t AddUintptr (uintptr_t *val, uintptr_t delta) { return __sync_add_and_fetch (val, delta); } int32_t LoadInt32 (int32_t *addr) __asm__ (GOSYM_PREFIX "sync_atomic.LoadInt32") __attribute__ ((no_split_stack)); int32_t LoadInt32 (int32_t *addr) { int32_t v; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, v)) v = *addr; return v; } int64_t LoadInt64 (int64_t *addr) __asm__ (GOSYM_PREFIX "sync_atomic.LoadInt64") __attribute__ ((no_split_stack)); int64_t LoadInt64 (int64_t *addr) { int64_t v; if (((uintptr_t) addr & 7) != 0) addr = NULL; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, v)) v = *addr; return v; } uint32_t LoadUint32 (uint32_t *addr) __asm__ (GOSYM_PREFIX "sync_atomic.LoadUint32") __attribute__ ((no_split_stack)); uint32_t LoadUint32 (uint32_t *addr) { uint32_t v; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, v)) v = *addr; return v; } uint64_t LoadUint64 (uint64_t *addr) __asm__ (GOSYM_PREFIX "sync_atomic.LoadUint64") __attribute__ ((no_split_stack)); uint64_t LoadUint64 (uint64_t *addr) { uint64_t v; if (((uintptr_t) addr & 7) != 0) addr = NULL; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, v)) v = *addr; return v; } uintptr_t LoadUintptr (uintptr_t *addr) __asm__ (GOSYM_PREFIX "sync_atomic.LoadUintptr") __attribute__ ((no_split_stack)); uintptr_t LoadUintptr (uintptr_t *addr) { uintptr_t v; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, v)) v = *addr; return v; } void *LoadPointer (void **addr) __asm__ (GOSYM_PREFIX "sync_atomic.LoadPointer") __attribute__ ((no_split_stack)); void * LoadPointer (void **addr) { void *v; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, v)) v = *addr; return v; } void StoreInt32 (int32_t *addr, int32_t val) __asm__ (GOSYM_PREFIX "sync_atomic.StoreInt32") __attribute__ ((no_split_stack)); void StoreInt32 (int32_t *addr, int32_t val) { int32_t v; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, val)) v = *addr; } void StoreInt64 (int64_t *addr, int64_t val) __asm__ (GOSYM_PREFIX "sync_atomic.StoreInt64") __attribute__ ((no_split_stack)); void StoreInt64 (int64_t *addr, int64_t val) { int64_t v; if (((uintptr_t) addr & 7) != 0) addr = NULL; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, val)) v = *addr; } void StoreUint32 (uint32_t *addr, uint32_t val) __asm__ (GOSYM_PREFIX "sync_atomic.StoreUint32") __attribute__ ((no_split_stack)); void StoreUint32 (uint32_t *addr, uint32_t val) { uint32_t v; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, val)) v = *addr; } void StoreUint64 (uint64_t *addr, uint64_t val) __asm__ (GOSYM_PREFIX "sync_atomic.StoreUint64") __attribute__ ((no_split_stack)); void StoreUint64 (uint64_t *addr, uint64_t val) { uint64_t v; if (((uintptr_t) addr & 7) != 0) addr = NULL; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, val)) v = *addr; } void StoreUintptr (uintptr_t *addr, uintptr_t val) __asm__ (GOSYM_PREFIX "sync_atomic.StoreUintptr") __attribute__ ((no_split_stack)); void StoreUintptr (uintptr_t *addr, uintptr_t val) { uintptr_t v; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, val)) v = *addr; } void StorePointer (void **addr, void *val) __asm__ (GOSYM_PREFIX "sync_atomic.StorePointer") __attribute__ ((no_split_stack)); void StorePointer (void **addr, void *val) { void *v; v = *addr; while (! __sync_bool_compare_and_swap (addr, v, val)) v = *addr; }
mickael-guene/gcc
libgo/go/sync/atomic/atomic.c
C
gpl-2.0
8,398
// license:GPL-2.0+ // copyright-holders:Juergen Buchmueller /*************************************************************************** vtech2.c machine driver Juergen Buchmueller <[email protected]> MESS driver, Jan 2000 Davide Moretti <[email protected]> ROM dump and hardware description TODO: RS232 support. Check if the FDC is really the same as in the Laser 210/310 (aka VZ200/300) series. ****************************************************************************/ #include "emu.h" #include "includes/vtech2.h" /* public */ /* static */ #define TRKSIZE_VZ 0x9a0 /* arbitrary (actually from analyzing format) */ static const uint8_t laser_fdc_wrprot[2] = {0x80, 0x80}; void vtech2_state::init_laser() { init_waitstates(); uint8_t *gfx = memregion("gfx2")->base(); int i; m_laser_track_x2[0] = m_laser_track_x2[1] = 80; m_laser_fdc_bits = 8; m_laser_drive = -1; m_cart_size = 0; for (i = 0; i < 256; i++) gfx[i] = i; m_laser_latch = -1; // check ROM expansion std::string region_tag; m_cart_rom = memregion(region_tag.assign(m_cart->tag()).append(GENERIC_ROM_REGION_TAG).c_str()); } DEVICE_IMAGE_LOAD_MEMBER( vtech2_state::cart_load ) { m_cart_size = m_cart->common_get_size("rom"); if (m_cart_size > 0x10000) { image.seterror(IMAGE_ERROR_UNSPECIFIED, "Cartridge bigger than 64k"); m_cart_size = 0; return image_init_result::FAIL; } m_cart->rom_alloc(m_cart_size, GENERIC_ROM8_WIDTH, ENDIANNESS_LITTLE); m_cart->common_load_rom(m_cart->get_rom_base(), m_cart_size, "rom"); return image_init_result::PASS; } void vtech2_state::machine_reset() { m_language = m_io_keyboard[5]->read() & 0x30; } void vtech2_state::machine_start() { save_item(NAME(m_laser_frame_message)); save_item(NAME(m_laser_frame_time)); save_item(NAME(m_laser_latch)); save_item(NAME(m_laser_track_x2)); save_item(NAME(m_laser_fdc_status)); save_item(NAME(m_laser_fdc_data)); save_item(NAME(m_laser_data)); save_item(NAME(m_laser_fdc_edge)); save_item(NAME(m_laser_fdc_bits)); save_item(NAME(m_laser_drive)); save_item(NAME(m_laser_fdc_start)); save_item(NAME(m_laser_fdc_write)); save_item(NAME(m_laser_fdc_offs)); save_item(NAME(m_laser_fdc_latch)); save_item(NAME(m_level_old)); save_item(NAME(m_cassette_bit)); save_item(NAME(m_laser_bg_mode)); save_item(NAME(m_laser_two_color)); save_item(NAME(m_language)); save_item(NAME(m_cart_size)); } uint8_t vtech2_state::cart_r(offs_t offset) { if (offset >= m_cart_size) return 0xff; return m_cart->read_rom(offset); } // The ULA inserts one waitstate for every read and write in each space (MT 07094, MT 07141) void vtech2_state::init_waitstates() { address_space &mem = m_maincpu->space(AS_PROGRAM); address_space &io = m_maincpu->space(AS_IO); mem.install_read_tap(0x0000, 0xffff, "mem_wait_r", [this](offs_t offset, u8 &data, u8 mem_mask) { if (!machine().side_effects_disabled()) m_maincpu->adjust_icount(-1); return data; }); mem.install_write_tap(0x0000, 0xffff, "mem_wait_w", [this](offs_t offset, u8 &data, u8 mem_mask) { if (!machine().side_effects_disabled()) m_maincpu->adjust_icount(-1); return data; }); io.install_read_tap(0x00, 0xff, "io_wait_r", [this](offs_t offset, u8 &data, u8 mem_mask) { if (!machine().side_effects_disabled()) m_maincpu->adjust_icount(-1); return data; }); io.install_write_tap(0x00, 0xff, "io_wait_w", [this](offs_t offset, u8 &data, u8 mem_mask) { if (!machine().side_effects_disabled()) m_maincpu->adjust_icount(-1); return data; }); } /************************************************* * memory mapped I/O read * bit function * 7 not assigned * 6 column 6 * 5 column 5 * 4 column 4 * 3 column 3 * 2 column 2 * 1 column 1 * 0 column 0 ************************************************/ uint8_t vtech2_state::mmio_r(offs_t offset) { u8 data = 0x7f; offset = ~offset & 0x7ff; if (BIT(offset, 10)) data &= m_io_keyboard[BIT(offset,8,2) + 8]->read(); // ROW A-D else for (u8 i = 0; i < 8; i++) if (BIT(offset, i)) data &= m_io_keyboard[i]->read(); // ROW 0-7 /* BIT 7 - tape input */ data |= (m_cassette->input() > +0.02) ? 0x80 : 0; return data; } /************************************************* * memory mapped I/O write * bit function * 7-6 not assigned * 5 speaker B ??? * 4 ??? * 3 mode: 1 graphics, 0 text * 2 cassette out (MSB) * 1 cassette out (LSB) * 0 speaker A ************************************************/ void vtech2_state::mmio_w(uint8_t data) { m_speaker->level_w(data & 1); m_laser_latch = data; m_cassette->output( BIT(data, 2) ? -1.0 : +1.0); } void vtech2_state::laser_get_track() { sprintf(m_laser_frame_message, "#%d get track %02d", m_laser_drive, m_laser_track_x2[m_laser_drive]/2); m_laser_frame_time = 30; /* drive selected or and image file ok? */ if( m_laser_drive >= 0 && m_laser_file[m_laser_drive].found() ) { device_image_interface &image = *m_laser_file[m_laser_drive]; int size = TRKSIZE_VZ; int offs = TRKSIZE_VZ * m_laser_track_x2[m_laser_drive]/2; image.fseek(offs, SEEK_SET); size = image.fread(m_laser_fdc_data, size); logerror("get track @$%05x $%04x bytes\n", offs, size); } m_laser_fdc_offs = 0; m_laser_fdc_write = 0; } void vtech2_state::laser_put_track() { /* drive selected and image file ok? */ if( m_laser_drive >= 0 && m_laser_file[m_laser_drive].found() ) { device_image_interface &image = *m_laser_file[m_laser_drive]; int offs = TRKSIZE_VZ * m_laser_track_x2[m_laser_drive]/2; image.fseek(offs + m_laser_fdc_start, SEEK_SET); int size = image.fwrite(&m_laser_fdc_data[m_laser_fdc_start], m_laser_fdc_write); logerror("put track @$%05X+$%X $%04X/$%04X bytes\n", offs, m_laser_fdc_start, size, m_laser_fdc_write); } } #define PHI0(n) (((n)>>0)&1) #define PHI1(n) (((n)>>1)&1) #define PHI2(n) (((n)>>2)&1) #define PHI3(n) (((n)>>3)&1) uint8_t vtech2_state::laser_fdc_r(offs_t offset) { int data = 0xff; switch( offset ) { case 1: /* data (read-only) */ if( m_laser_fdc_bits > 0 ) { if( m_laser_fdc_status & 0x80 ) m_laser_fdc_bits--; data = (m_laser_data >> m_laser_fdc_bits) & 0xff; #if 0 logerror("laser_fdc_r bits %d%d%d%d%d%d%d%d\n", (data>>7)&1,(data>>6)&1,(data>>5)&1,(data>>4)&1, (data>>3)&1,(data>>2)&1,(data>>1)&1,(data>>0)&1 ); #endif } if( m_laser_fdc_bits == 0 ) { m_laser_data = m_laser_fdc_data[m_laser_fdc_offs]; logerror("laser_fdc_r %d : data ($%04X) $%02X\n", offset, m_laser_fdc_offs, m_laser_data); if( m_laser_fdc_status & 0x80 ) { m_laser_fdc_bits = 8; m_laser_fdc_offs = (m_laser_fdc_offs + 1) % TRKSIZE_FM; } m_laser_fdc_status &= ~0x80; } break; case 2: /* polling (read-only) */ /* fake */ if( m_laser_drive >= 0 ) m_laser_fdc_status |= 0x80; data = m_laser_fdc_status; break; case 3: /* write protect status (read-only) */ if( m_laser_drive >= 0 ) data = laser_fdc_wrprot[m_laser_drive]; logerror("laser_fdc_r %d : write_protect $%02X\n", offset, data); break; } return data; } void vtech2_state::laser_fdc_w(offs_t offset, uint8_t data) { int drive; switch( offset ) { case 0: /* latch (write-only) */ drive = (data & 0x10) ? 0 : (data & 0x80) ? 1 : -1; if( drive != m_laser_drive ) { m_laser_drive = drive; if( m_laser_drive >= 0 ) laser_get_track(); } if( m_laser_drive >= 0 ) { if( (PHI0(data) && !(PHI1(data) || PHI2(data) || PHI3(data)) && PHI1(m_laser_fdc_latch)) || (PHI1(data) && !(PHI0(data) || PHI2(data) || PHI3(data)) && PHI2(m_laser_fdc_latch)) || (PHI2(data) && !(PHI0(data) || PHI1(data) || PHI3(data)) && PHI3(m_laser_fdc_latch)) || (PHI3(data) && !(PHI0(data) || PHI1(data) || PHI2(data)) && PHI0(m_laser_fdc_latch)) ) { if( m_laser_track_x2[m_laser_drive] > 0 ) m_laser_track_x2[m_laser_drive]--; logerror("laser_fdc_w(%d) $%02X drive %d: stepout track #%2d.%d\n", offset, data, m_laser_drive, m_laser_track_x2[m_laser_drive]/2,5*(m_laser_track_x2[m_laser_drive]&1)); if( (m_laser_track_x2[m_laser_drive] & 1) == 0 ) laser_get_track(); } else if( (PHI0(data) && !(PHI1(data) || PHI2(data) || PHI3(data)) && PHI3(m_laser_fdc_latch)) || (PHI1(data) && !(PHI0(data) || PHI2(data) || PHI3(data)) && PHI0(m_laser_fdc_latch)) || (PHI2(data) && !(PHI0(data) || PHI1(data) || PHI3(data)) && PHI1(m_laser_fdc_latch)) || (PHI3(data) && !(PHI0(data) || PHI1(data) || PHI2(data)) && PHI2(m_laser_fdc_latch)) ) { if( m_laser_track_x2[m_laser_drive] < 2*40 ) m_laser_track_x2[m_laser_drive]++; logerror("laser_fdc_w(%d) $%02X drive %d: stepin track #%2d.%d\n", offset, data, m_laser_drive, m_laser_track_x2[m_laser_drive]/2,5*(m_laser_track_x2[m_laser_drive]&1)); if( (m_laser_track_x2[m_laser_drive] & 1) == 0 ) laser_get_track(); } if( (data & 0x40) == 0 ) { m_laser_data <<= 1; if( (m_laser_fdc_latch ^ data) & 0x20 ) m_laser_data |= 1; if( (m_laser_fdc_edge ^= 1) == 0 ) { if( --m_laser_fdc_bits == 0 ) { uint8_t value = 0; m_laser_data &= 0xffff; if( m_laser_data & 0x4000 ) value |= 0x80; if( m_laser_data & 0x1000 ) value |= 0x40; if( m_laser_data & 0x0400 ) value |= 0x20; if( m_laser_data & 0x0100 ) value |= 0x10; if( m_laser_data & 0x0040 ) value |= 0x08; if( m_laser_data & 0x0010 ) value |= 0x04; if( m_laser_data & 0x0004 ) value |= 0x02; if( m_laser_data & 0x0001 ) value |= 0x01; logerror("laser_fdc_w(%d) data($%04X) $%02X <- $%02X ($%04X)\n", offset, m_laser_fdc_offs, m_laser_fdc_data[m_laser_fdc_offs], value, m_laser_data); m_laser_fdc_data[m_laser_fdc_offs] = value; m_laser_fdc_offs = (m_laser_fdc_offs + 1) % TRKSIZE_FM; m_laser_fdc_write++; m_laser_fdc_bits = 8; } } } /* change of write signal? */ if( (m_laser_fdc_latch ^ data) & 0x40 ) { /* falling edge? */ if ( m_laser_fdc_latch & 0x40 ) { sprintf(m_laser_frame_message, "#%d put track %02d", m_laser_drive, m_laser_track_x2[m_laser_drive]/2); m_laser_frame_time = 30; m_laser_fdc_start = m_laser_fdc_offs; m_laser_fdc_edge = 0; } else { /* data written to track before? */ if( m_laser_fdc_write ) laser_put_track(); } m_laser_fdc_bits = 8; m_laser_fdc_write = 0; } } m_laser_fdc_latch = data; break; } }
johnparker007/mame
src/mame/machine/vtech2.cpp
C++
gpl-2.0
10,474
/* * Intel IXP4xx Ethernet driver for Linux * * Copyright (C) 2007 Krzysztof Halasa <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation. * * Ethernet port config (0x00 is not present on IXP42X): * * logical port 0x00 0x10 0x20 * NPE 0 (NPE-A) 1 (NPE-B) 2 (NPE-C) * physical PortId 2 0 1 * TX queue 23 24 25 * RX-free queue 26 27 28 * TX-done queue is always 31, per-port RX and TX-ready queues are configurable * * * Queue entries: * bits 0 -> 1 - NPE ID (RX and TX-done) * bits 0 -> 2 - priority (TX, per 802.1D) * bits 3 -> 4 - port ID (user-set?) * bits 5 -> 31 - physical descriptor address */ #include <linux/delay.h> #include <linux/dma-mapping.h> #include <linux/dmapool.h> #include <linux/etherdevice.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/net_tstamp.h> #include <linux/phy.h> #include <linux/platform_device.h> #include <linux/ptp_classify.h> #include <linux/slab.h> #include <linux/module.h> #include <mach/ixp46x_ts.h> #include <mach/npe.h> #include <mach/qmgr.h> #define DEBUG_DESC 0 #define DEBUG_RX 0 #define DEBUG_TX 0 #define DEBUG_PKT_BYTES 0 #define DEBUG_MDIO 0 #define DEBUG_CLOSE 0 #define DRV_NAME "ixp4xx_eth" #define MAX_NPES 3 #define RX_DESCS 64 /* */ #define TX_DESCS 16 /* */ #define TXDONE_QUEUE_LEN 64 /* */ #define POOL_ALLOC_SIZE (sizeof(struct desc) * (RX_DESCS + TX_DESCS)) #define REGS_SIZE 0x1000 #define MAX_MRU 1536 /* */ #define RX_BUFF_SIZE ALIGN((NET_IP_ALIGN) + MAX_MRU, 4) #define NAPI_WEIGHT 16 #define MDIO_INTERVAL (3 * HZ) #define MAX_MDIO_RETRIES 100 /* */ #define MAX_CLOSE_WAIT 1000 /* */ #define NPE_ID(port_id) ((port_id) >> 4) #define PHYSICAL_ID(port_id) ((NPE_ID(port_id) + 2) % 3) #define TX_QUEUE(port_id) (NPE_ID(port_id) + 23) #define RXFREE_QUEUE(port_id) (NPE_ID(port_id) + 26) #define TXDONE_QUEUE 31 #define PTP_SLAVE_MODE 1 #define PTP_MASTER_MODE 2 #define PORT2CHANNEL(p) NPE_ID(p->id) /* */ #define TX_CNTRL0_TX_EN 0x01 #define TX_CNTRL0_HALFDUPLEX 0x02 #define TX_CNTRL0_RETRY 0x04 #define TX_CNTRL0_PAD_EN 0x08 #define TX_CNTRL0_APPEND_FCS 0x10 #define TX_CNTRL0_2DEFER 0x20 #define TX_CNTRL0_RMII 0x40 /* */ #define TX_CNTRL1_RETRIES 0x0F /* */ /* */ #define RX_CNTRL0_RX_EN 0x01 #define RX_CNTRL0_PADSTRIP_EN 0x02 #define RX_CNTRL0_SEND_FCS 0x04 #define RX_CNTRL0_PAUSE_EN 0x08 #define RX_CNTRL0_LOOP_EN 0x10 #define RX_CNTRL0_ADDR_FLTR_EN 0x20 #define RX_CNTRL0_RX_RUNT_EN 0x40 #define RX_CNTRL0_BCAST_DIS 0x80 #define RX_CNTRL1_DEFER_EN 0x01 /* */ #define CORE_RESET 0x01 #define CORE_RX_FIFO_FLUSH 0x02 #define CORE_TX_FIFO_FLUSH 0x04 #define CORE_SEND_JAM 0x08 #define CORE_MDC_EN 0x10 /* */ #define DEFAULT_TX_CNTRL0 (TX_CNTRL0_TX_EN | TX_CNTRL0_RETRY | \ TX_CNTRL0_PAD_EN | TX_CNTRL0_APPEND_FCS | \ TX_CNTRL0_2DEFER) #define DEFAULT_RX_CNTRL0 RX_CNTRL0_RX_EN #define DEFAULT_CORE_CNTRL CORE_MDC_EN /* */ #define NPE_GETSTATUS 0x00 #define NPE_EDB_SETPORTADDRESS 0x01 #define NPE_EDB_GETMACADDRESSDATABASE 0x02 #define NPE_EDB_SETMACADDRESSSDATABASE 0x03 #define NPE_GETSTATS 0x04 #define NPE_RESETSTATS 0x05 #define NPE_SETMAXFRAMELENGTHS 0x06 #define NPE_VLAN_SETRXTAGMODE 0x07 #define NPE_VLAN_SETDEFAULTRXVID 0x08 #define NPE_VLAN_SETPORTVLANTABLEENTRY 0x09 #define NPE_VLAN_SETPORTVLANTABLERANGE 0x0A #define NPE_VLAN_SETRXQOSENTRY 0x0B #define NPE_VLAN_SETPORTIDEXTRACTIONMODE 0x0C #define NPE_STP_SETBLOCKINGSTATE 0x0D #define NPE_FW_SETFIREWALLMODE 0x0E #define NPE_PC_SETFRAMECONTROLDURATIONID 0x0F #define NPE_PC_SETAPMACTABLE 0x11 #define NPE_SETLOOPBACK_MODE 0x12 #define NPE_PC_SETBSSIDTABLE 0x13 #define NPE_ADDRESS_FILTER_CONFIG 0x14 #define NPE_APPENDFCSCONFIG 0x15 #define NPE_NOTIFY_MAC_RECOVERY_DONE 0x16 #define NPE_MAC_RECOVERY_START 0x17 #ifdef __ARMEB__ typedef struct sk_buff buffer_t; #define free_buffer dev_kfree_skb #define free_buffer_irq dev_kfree_skb_irq #else typedef void buffer_t; #define free_buffer kfree #define free_buffer_irq kfree #endif struct eth_regs { u32 tx_control[2], __res1[2]; /* */ u32 rx_control[2], __res2[2]; /* */ u32 random_seed, __res3[3]; /* */ u32 partial_empty_threshold, __res4; /* */ u32 partial_full_threshold, __res5; /* */ u32 tx_start_bytes, __res6[3]; /* */ u32 tx_deferral, rx_deferral, __res7[2];/* */ u32 tx_2part_deferral[2], __res8[2]; /* */ u32 slot_time, __res9[3]; /* */ u32 mdio_command[4]; /* */ u32 mdio_status[4]; /* */ u32 mcast_mask[6], __res10[2]; /* */ u32 mcast_addr[6], __res11[2]; /* */ u32 int_clock_threshold, __res12[3]; /* */ u32 hw_addr[6], __res13[61]; /* */ u32 core_control; /* */ }; struct port { struct resource *mem_res; struct eth_regs __iomem *regs; struct npe *npe; struct net_device *netdev; struct napi_struct napi; struct phy_device *phydev; struct eth_plat_info *plat; buffer_t *rx_buff_tab[RX_DESCS], *tx_buff_tab[TX_DESCS]; struct desc *desc_tab; /* */ u32 desc_tab_phys; int id; /* */ int speed, duplex; u8 firmware[4]; int hwts_tx_en; int hwts_rx_en; }; /* */ struct msg { #ifdef __ARMEB__ u8 cmd, eth_id, byte2, byte3; u8 byte4, byte5, byte6, byte7; #else u8 byte3, byte2, eth_id, cmd; u8 byte7, byte6, byte5, byte4; #endif }; /* */ struct desc { u32 next; /* */ #ifdef __ARMEB__ u16 buf_len; /* */ u16 pkt_len; /* */ u32 data; /* */ u8 dest_id; u8 src_id; u16 flags; u8 qos; u8 padlen; u16 vlan_tci; #else u16 pkt_len; /* */ u16 buf_len; /* */ u32 data; /* */ u16 flags; u8 src_id; u8 dest_id; u16 vlan_tci; u8 padlen; u8 qos; #endif #ifdef __ARMEB__ u8 dst_mac_0, dst_mac_1, dst_mac_2, dst_mac_3; u8 dst_mac_4, dst_mac_5, src_mac_0, src_mac_1; u8 src_mac_2, src_mac_3, src_mac_4, src_mac_5; #else u8 dst_mac_3, dst_mac_2, dst_mac_1, dst_mac_0; u8 src_mac_1, src_mac_0, dst_mac_5, dst_mac_4; u8 src_mac_5, src_mac_4, src_mac_3, src_mac_2; #endif }; #define rx_desc_phys(port, n) ((port)->desc_tab_phys + \ (n) * sizeof(struct desc)) #define rx_desc_ptr(port, n) (&(port)->desc_tab[n]) #define tx_desc_phys(port, n) ((port)->desc_tab_phys + \ ((n) + RX_DESCS) * sizeof(struct desc)) #define tx_desc_ptr(port, n) (&(port)->desc_tab[(n) + RX_DESCS]) #ifndef __ARMEB__ static inline void memcpy_swab32(u32 *dest, u32 *src, int cnt) { int i; for (i = 0; i < cnt; i++) dest[i] = swab32(src[i]); } #endif static spinlock_t mdio_lock; static struct eth_regs __iomem *mdio_regs; /* */ static struct mii_bus *mdio_bus; static int ports_open; static struct port *npe_port_tab[MAX_NPES]; static struct dma_pool *dma_pool; static struct sock_filter ptp_filter[] = { PTP_FILTER }; static int ixp_ptp_match(struct sk_buff *skb, u16 uid_hi, u32 uid_lo, u16 seqid) { u8 *data = skb->data; unsigned int offset; u16 *hi, *id; u32 lo; if (sk_run_filter(skb, ptp_filter) != PTP_CLASS_V1_IPV4) return 0; offset = ETH_HLEN + IPV4_HLEN(data) + UDP_HLEN; if (skb->len < offset + OFF_PTP_SEQUENCE_ID + sizeof(seqid)) return 0; hi = (u16 *)(data + offset + OFF_PTP_SOURCE_UUID); id = (u16 *)(data + offset + OFF_PTP_SEQUENCE_ID); memcpy(&lo, &hi[1], sizeof(lo)); return (uid_hi == ntohs(*hi) && uid_lo == ntohl(lo) && seqid == ntohs(*id)); } static void ixp_rx_timestamp(struct port *port, struct sk_buff *skb) { struct skb_shared_hwtstamps *shhwtstamps; struct ixp46x_ts_regs *regs; u64 ns; u32 ch, hi, lo, val; u16 uid, seq; if (!port->hwts_rx_en) return; ch = PORT2CHANNEL(port); regs = (struct ixp46x_ts_regs __iomem *) IXP4XX_TIMESYNC_BASE_VIRT; val = __raw_readl(&regs->channel[ch].ch_event); if (!(val & RX_SNAPSHOT_LOCKED)) return; lo = __raw_readl(&regs->channel[ch].src_uuid_lo); hi = __raw_readl(&regs->channel[ch].src_uuid_hi); uid = hi & 0xffff; seq = (hi >> 16) & 0xffff; if (!ixp_ptp_match(skb, htons(uid), htonl(lo), htons(seq))) goto out; lo = __raw_readl(&regs->channel[ch].rx_snap_lo); hi = __raw_readl(&regs->channel[ch].rx_snap_hi); ns = ((u64) hi) << 32; ns |= lo; ns <<= TICKS_NS_SHIFT; shhwtstamps = skb_hwtstamps(skb); memset(shhwtstamps, 0, sizeof(*shhwtstamps)); shhwtstamps->hwtstamp = ns_to_ktime(ns); out: __raw_writel(RX_SNAPSHOT_LOCKED, &regs->channel[ch].ch_event); } static void ixp_tx_timestamp(struct port *port, struct sk_buff *skb) { struct skb_shared_hwtstamps shhwtstamps; struct ixp46x_ts_regs *regs; struct skb_shared_info *shtx; u64 ns; u32 ch, cnt, hi, lo, val; shtx = skb_shinfo(skb); if (unlikely(shtx->tx_flags & SKBTX_HW_TSTAMP && port->hwts_tx_en)) shtx->tx_flags |= SKBTX_IN_PROGRESS; else return; ch = PORT2CHANNEL(port); regs = (struct ixp46x_ts_regs __iomem *) IXP4XX_TIMESYNC_BASE_VIRT; /* */ for (cnt = 0; cnt < 100; cnt++) { val = __raw_readl(&regs->channel[ch].ch_event); if (val & TX_SNAPSHOT_LOCKED) break; udelay(1); } if (!(val & TX_SNAPSHOT_LOCKED)) { shtx->tx_flags &= ~SKBTX_IN_PROGRESS; return; } lo = __raw_readl(&regs->channel[ch].tx_snap_lo); hi = __raw_readl(&regs->channel[ch].tx_snap_hi); ns = ((u64) hi) << 32; ns |= lo; ns <<= TICKS_NS_SHIFT; memset(&shhwtstamps, 0, sizeof(shhwtstamps)); shhwtstamps.hwtstamp = ns_to_ktime(ns); skb_tstamp_tx(skb, &shhwtstamps); __raw_writel(TX_SNAPSHOT_LOCKED, &regs->channel[ch].ch_event); } static int hwtstamp_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd) { struct hwtstamp_config cfg; struct ixp46x_ts_regs *regs; struct port *port = netdev_priv(netdev); int ch; if (copy_from_user(&cfg, ifr->ifr_data, sizeof(cfg))) return -EFAULT; if (cfg.flags) /* */ return -EINVAL; ch = PORT2CHANNEL(port); regs = (struct ixp46x_ts_regs __iomem *) IXP4XX_TIMESYNC_BASE_VIRT; switch (cfg.tx_type) { case HWTSTAMP_TX_OFF: port->hwts_tx_en = 0; break; case HWTSTAMP_TX_ON: port->hwts_tx_en = 1; break; default: return -ERANGE; } switch (cfg.rx_filter) { case HWTSTAMP_FILTER_NONE: port->hwts_rx_en = 0; break; case HWTSTAMP_FILTER_PTP_V1_L4_SYNC: port->hwts_rx_en = PTP_SLAVE_MODE; __raw_writel(0, &regs->channel[ch].ch_control); break; case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ: port->hwts_rx_en = PTP_MASTER_MODE; __raw_writel(MASTER_MODE, &regs->channel[ch].ch_control); break; default: return -ERANGE; } /* */ __raw_writel(TX_SNAPSHOT_LOCKED | RX_SNAPSHOT_LOCKED, &regs->channel[ch].ch_event); return copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)) ? -EFAULT : 0; } static int ixp4xx_mdio_cmd(struct mii_bus *bus, int phy_id, int location, int write, u16 cmd) { int cycles = 0; if (__raw_readl(&mdio_regs->mdio_command[3]) & 0x80) { printk(KERN_ERR "%s: MII not ready to transmit\n", bus->name); return -1; } if (write) { __raw_writel(cmd & 0xFF, &mdio_regs->mdio_command[0]); __raw_writel(cmd >> 8, &mdio_regs->mdio_command[1]); } __raw_writel(((phy_id << 5) | location) & 0xFF, &mdio_regs->mdio_command[2]); __raw_writel((phy_id >> 3) | (write << 2) | 0x80 /* */, &mdio_regs->mdio_command[3]); while ((cycles < MAX_MDIO_RETRIES) && (__raw_readl(&mdio_regs->mdio_command[3]) & 0x80)) { udelay(1); cycles++; } if (cycles == MAX_MDIO_RETRIES) { printk(KERN_ERR "%s #%i: MII write failed\n", bus->name, phy_id); return -1; } #if DEBUG_MDIO printk(KERN_DEBUG "%s #%i: mdio_%s() took %i cycles\n", bus->name, phy_id, write ? "write" : "read", cycles); #endif if (write) return 0; if (__raw_readl(&mdio_regs->mdio_status[3]) & 0x80) { #if DEBUG_MDIO printk(KERN_DEBUG "%s #%i: MII read failed\n", bus->name, phy_id); #endif return 0xFFFF; /* */ } return (__raw_readl(&mdio_regs->mdio_status[0]) & 0xFF) | ((__raw_readl(&mdio_regs->mdio_status[1]) & 0xFF) << 8); } static int ixp4xx_mdio_read(struct mii_bus *bus, int phy_id, int location) { unsigned long flags; int ret; spin_lock_irqsave(&mdio_lock, flags); ret = ixp4xx_mdio_cmd(bus, phy_id, location, 0, 0); spin_unlock_irqrestore(&mdio_lock, flags); #if DEBUG_MDIO printk(KERN_DEBUG "%s #%i: MII read [%i] -> 0x%X\n", bus->name, phy_id, location, ret); #endif return ret; } static int ixp4xx_mdio_write(struct mii_bus *bus, int phy_id, int location, u16 val) { unsigned long flags; int ret; spin_lock_irqsave(&mdio_lock, flags); ret = ixp4xx_mdio_cmd(bus, phy_id, location, 1, val); spin_unlock_irqrestore(&mdio_lock, flags); #if DEBUG_MDIO printk(KERN_DEBUG "%s #%i: MII write [%i] <- 0x%X, err = %i\n", bus->name, phy_id, location, val, ret); #endif return ret; } static int ixp4xx_mdio_register(void) { int err; if (!(mdio_bus = mdiobus_alloc())) return -ENOMEM; if (cpu_is_ixp43x()) { /* */ if (!(ixp4xx_read_feature_bits() & IXP4XX_FEATURE_NPEC_ETH)) return -ENODEV; mdio_regs = (struct eth_regs __iomem *)IXP4XX_EthC_BASE_VIRT; } else { /* */ if (!(ixp4xx_read_feature_bits() & IXP4XX_FEATURE_NPEB_ETH0)) return -ENODEV; mdio_regs = (struct eth_regs __iomem *)IXP4XX_EthB_BASE_VIRT; } __raw_writel(DEFAULT_CORE_CNTRL, &mdio_regs->core_control); spin_lock_init(&mdio_lock); mdio_bus->name = "IXP4xx MII Bus"; mdio_bus->read = &ixp4xx_mdio_read; mdio_bus->write = &ixp4xx_mdio_write; snprintf(mdio_bus->id, MII_BUS_ID_SIZE, "ixp4xx-eth-0"); if ((err = mdiobus_register(mdio_bus))) mdiobus_free(mdio_bus); return err; } static void ixp4xx_mdio_remove(void) { mdiobus_unregister(mdio_bus); mdiobus_free(mdio_bus); } static void ixp4xx_adjust_link(struct net_device *dev) { struct port *port = netdev_priv(dev); struct phy_device *phydev = port->phydev; if (!phydev->link) { if (port->speed) { port->speed = 0; printk(KERN_INFO "%s: link down\n", dev->name); } return; } if (port->speed == phydev->speed && port->duplex == phydev->duplex) return; port->speed = phydev->speed; port->duplex = phydev->duplex; if (port->duplex) __raw_writel(DEFAULT_TX_CNTRL0 & ~TX_CNTRL0_HALFDUPLEX, &port->regs->tx_control[0]); else __raw_writel(DEFAULT_TX_CNTRL0 | TX_CNTRL0_HALFDUPLEX, &port->regs->tx_control[0]); printk(KERN_INFO "%s: link up, speed %u Mb/s, %s duplex\n", dev->name, port->speed, port->duplex ? "full" : "half"); } static inline void debug_pkt(struct net_device *dev, const char *func, u8 *data, int len) { #if DEBUG_PKT_BYTES int i; printk(KERN_DEBUG "%s: %s(%i) ", dev->name, func, len); for (i = 0; i < len; i++) { if (i >= DEBUG_PKT_BYTES) break; printk("%s%02X", ((i == 6) || (i == 12) || (i >= 14)) ? " " : "", data[i]); } printk("\n"); #endif } static inline void debug_desc(u32 phys, struct desc *desc) { #if DEBUG_DESC printk(KERN_DEBUG "%X: %X %3X %3X %08X %2X < %2X %4X %X" " %X %X %02X%02X%02X%02X%02X%02X < %02X%02X%02X%02X%02X%02X\n", phys, desc->next, desc->buf_len, desc->pkt_len, desc->data, desc->dest_id, desc->src_id, desc->flags, desc->qos, desc->padlen, desc->vlan_tci, desc->dst_mac_0, desc->dst_mac_1, desc->dst_mac_2, desc->dst_mac_3, desc->dst_mac_4, desc->dst_mac_5, desc->src_mac_0, desc->src_mac_1, desc->src_mac_2, desc->src_mac_3, desc->src_mac_4, desc->src_mac_5); #endif } static inline int queue_get_desc(unsigned int queue, struct port *port, int is_tx) { u32 phys, tab_phys, n_desc; struct desc *tab; if (!(phys = qmgr_get_entry(queue))) return -1; phys &= ~0x1F; /* */ tab_phys = is_tx ? tx_desc_phys(port, 0) : rx_desc_phys(port, 0); tab = is_tx ? tx_desc_ptr(port, 0) : rx_desc_ptr(port, 0); n_desc = (phys - tab_phys) / sizeof(struct desc); BUG_ON(n_desc >= (is_tx ? TX_DESCS : RX_DESCS)); debug_desc(phys, &tab[n_desc]); BUG_ON(tab[n_desc].next); return n_desc; } static inline void queue_put_desc(unsigned int queue, u32 phys, struct desc *desc) { debug_desc(phys, desc); BUG_ON(phys & 0x1F); qmgr_put_entry(queue, phys); /* */ } static inline void dma_unmap_tx(struct port *port, struct desc *desc) { #ifdef __ARMEB__ dma_unmap_single(&port->netdev->dev, desc->data, desc->buf_len, DMA_TO_DEVICE); #else dma_unmap_single(&port->netdev->dev, desc->data & ~3, ALIGN((desc->data & 3) + desc->buf_len, 4), DMA_TO_DEVICE); #endif } static void eth_rx_irq(void *pdev) { struct net_device *dev = pdev; struct port *port = netdev_priv(dev); #if DEBUG_RX printk(KERN_DEBUG "%s: eth_rx_irq\n", dev->name); #endif qmgr_disable_irq(port->plat->rxq); napi_schedule(&port->napi); } static int eth_poll(struct napi_struct *napi, int budget) { struct port *port = container_of(napi, struct port, napi); struct net_device *dev = port->netdev; unsigned int rxq = port->plat->rxq, rxfreeq = RXFREE_QUEUE(port->id); int received = 0; #if DEBUG_RX printk(KERN_DEBUG "%s: eth_poll\n", dev->name); #endif while (received < budget) { struct sk_buff *skb; struct desc *desc; int n; #ifdef __ARMEB__ struct sk_buff *temp; u32 phys; #endif if ((n = queue_get_desc(rxq, port, 0)) < 0) { #if DEBUG_RX printk(KERN_DEBUG "%s: eth_poll napi_complete\n", dev->name); #endif napi_complete(napi); qmgr_enable_irq(rxq); if (!qmgr_stat_below_low_watermark(rxq) && napi_reschedule(napi)) { /* */ #if DEBUG_RX printk(KERN_DEBUG "%s: eth_poll" " napi_reschedule successed\n", dev->name); #endif qmgr_disable_irq(rxq); continue; } #if DEBUG_RX printk(KERN_DEBUG "%s: eth_poll all done\n", dev->name); #endif return received; /* */ } desc = rx_desc_ptr(port, n); #ifdef __ARMEB__ if ((skb = netdev_alloc_skb(dev, RX_BUFF_SIZE))) { phys = dma_map_single(&dev->dev, skb->data, RX_BUFF_SIZE, DMA_FROM_DEVICE); if (dma_mapping_error(&dev->dev, phys)) { dev_kfree_skb(skb); skb = NULL; } } #else skb = netdev_alloc_skb(dev, ALIGN(NET_IP_ALIGN + desc->pkt_len, 4)); #endif if (!skb) { dev->stats.rx_dropped++; /* */ desc->buf_len = MAX_MRU; desc->pkt_len = 0; queue_put_desc(rxfreeq, rx_desc_phys(port, n), desc); continue; } /* */ #ifdef __ARMEB__ temp = skb; skb = port->rx_buff_tab[n]; dma_unmap_single(&dev->dev, desc->data - NET_IP_ALIGN, RX_BUFF_SIZE, DMA_FROM_DEVICE); #else dma_sync_single_for_cpu(&dev->dev, desc->data - NET_IP_ALIGN, RX_BUFF_SIZE, DMA_FROM_DEVICE); memcpy_swab32((u32 *)skb->data, (u32 *)port->rx_buff_tab[n], ALIGN(NET_IP_ALIGN + desc->pkt_len, 4) / 4); #endif skb_reserve(skb, NET_IP_ALIGN); skb_put(skb, desc->pkt_len); debug_pkt(dev, "eth_poll", skb->data, skb->len); ixp_rx_timestamp(port, skb); skb->protocol = eth_type_trans(skb, dev); dev->stats.rx_packets++; dev->stats.rx_bytes += skb->len; netif_receive_skb(skb); /* */ #ifdef __ARMEB__ port->rx_buff_tab[n] = temp; desc->data = phys + NET_IP_ALIGN; #endif desc->buf_len = MAX_MRU; desc->pkt_len = 0; queue_put_desc(rxfreeq, rx_desc_phys(port, n), desc); received++; } #if DEBUG_RX printk(KERN_DEBUG "eth_poll(): end, not all work done\n"); #endif return received; /* */ } static void eth_txdone_irq(void *unused) { u32 phys; #if DEBUG_TX printk(KERN_DEBUG DRV_NAME ": eth_txdone_irq\n"); #endif while ((phys = qmgr_get_entry(TXDONE_QUEUE)) != 0) { u32 npe_id, n_desc; struct port *port; struct desc *desc; int start; npe_id = phys & 3; BUG_ON(npe_id >= MAX_NPES); port = npe_port_tab[npe_id]; BUG_ON(!port); phys &= ~0x1F; /* */ n_desc = (phys - tx_desc_phys(port, 0)) / sizeof(struct desc); BUG_ON(n_desc >= TX_DESCS); desc = tx_desc_ptr(port, n_desc); debug_desc(phys, desc); if (port->tx_buff_tab[n_desc]) { /* */ port->netdev->stats.tx_packets++; port->netdev->stats.tx_bytes += desc->pkt_len; dma_unmap_tx(port, desc); #if DEBUG_TX printk(KERN_DEBUG "%s: eth_txdone_irq free %p\n", port->netdev->name, port->tx_buff_tab[n_desc]); #endif free_buffer_irq(port->tx_buff_tab[n_desc]); port->tx_buff_tab[n_desc] = NULL; } start = qmgr_stat_below_low_watermark(port->plat->txreadyq); queue_put_desc(port->plat->txreadyq, phys, desc); if (start) { /* */ #if DEBUG_TX printk(KERN_DEBUG "%s: eth_txdone_irq xmit ready\n", port->netdev->name); #endif netif_wake_queue(port->netdev); } } } static int eth_xmit(struct sk_buff *skb, struct net_device *dev) { struct port *port = netdev_priv(dev); unsigned int txreadyq = port->plat->txreadyq; int len, offset, bytes, n; void *mem; u32 phys; struct desc *desc; #if DEBUG_TX printk(KERN_DEBUG "%s: eth_xmit\n", dev->name); #endif if (unlikely(skb->len > MAX_MRU)) { dev_kfree_skb(skb); dev->stats.tx_errors++; return NETDEV_TX_OK; } debug_pkt(dev, "eth_xmit", skb->data, skb->len); len = skb->len; #ifdef __ARMEB__ offset = 0; /* */ bytes = len; mem = skb->data; #else offset = (int)skb->data & 3; /* */ bytes = ALIGN(offset + len, 4); if (!(mem = kmalloc(bytes, GFP_ATOMIC))) { dev_kfree_skb(skb); dev->stats.tx_dropped++; return NETDEV_TX_OK; } memcpy_swab32(mem, (u32 *)((int)skb->data & ~3), bytes / 4); #endif phys = dma_map_single(&dev->dev, mem, bytes, DMA_TO_DEVICE); if (dma_mapping_error(&dev->dev, phys)) { dev_kfree_skb(skb); #ifndef __ARMEB__ kfree(mem); #endif dev->stats.tx_dropped++; return NETDEV_TX_OK; } n = queue_get_desc(txreadyq, port, 1); BUG_ON(n < 0); desc = tx_desc_ptr(port, n); #ifdef __ARMEB__ port->tx_buff_tab[n] = skb; #else port->tx_buff_tab[n] = mem; #endif desc->data = phys + offset; desc->buf_len = desc->pkt_len = len; /* */ wmb(); queue_put_desc(TX_QUEUE(port->id), tx_desc_phys(port, n), desc); if (qmgr_stat_below_low_watermark(txreadyq)) { /* */ #if DEBUG_TX printk(KERN_DEBUG "%s: eth_xmit queue full\n", dev->name); #endif netif_stop_queue(dev); /* */ /* */ if (!qmgr_stat_below_low_watermark(txreadyq)) { #if DEBUG_TX printk(KERN_DEBUG "%s: eth_xmit ready again\n", dev->name); #endif netif_wake_queue(dev); } } #if DEBUG_TX printk(KERN_DEBUG "%s: eth_xmit end\n", dev->name); #endif ixp_tx_timestamp(port, skb); skb_tx_timestamp(skb); #ifndef __ARMEB__ dev_kfree_skb(skb); #endif return NETDEV_TX_OK; } static void eth_set_mcast_list(struct net_device *dev) { struct port *port = netdev_priv(dev); struct netdev_hw_addr *ha; u8 diffs[ETH_ALEN], *addr; int i; static const u8 allmulti[] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (dev->flags & IFF_ALLMULTI) { for (i = 0; i < ETH_ALEN; i++) { __raw_writel(allmulti[i], &port->regs->mcast_addr[i]); __raw_writel(allmulti[i], &port->regs->mcast_mask[i]); } __raw_writel(DEFAULT_RX_CNTRL0 | RX_CNTRL0_ADDR_FLTR_EN, &port->regs->rx_control[0]); return; } if ((dev->flags & IFF_PROMISC) || netdev_mc_empty(dev)) { __raw_writel(DEFAULT_RX_CNTRL0 & ~RX_CNTRL0_ADDR_FLTR_EN, &port->regs->rx_control[0]); return; } memset(diffs, 0, ETH_ALEN); addr = NULL; netdev_for_each_mc_addr(ha, dev) { if (!addr) addr = ha->addr; /* */ for (i = 0; i < ETH_ALEN; i++) diffs[i] |= addr[i] ^ ha->addr[i]; } for (i = 0; i < ETH_ALEN; i++) { __raw_writel(addr[i], &port->regs->mcast_addr[i]); __raw_writel(~diffs[i], &port->regs->mcast_mask[i]); } __raw_writel(DEFAULT_RX_CNTRL0 | RX_CNTRL0_ADDR_FLTR_EN, &port->regs->rx_control[0]); } static int eth_ioctl(struct net_device *dev, struct ifreq *req, int cmd) { struct port *port = netdev_priv(dev); if (!netif_running(dev)) return -EINVAL; if (cpu_is_ixp46x() && cmd == SIOCSHWTSTAMP) return hwtstamp_ioctl(dev, req, cmd); return phy_mii_ioctl(port->phydev, req, cmd); } /* */ static void ixp4xx_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct port *port = netdev_priv(dev); strcpy(info->driver, DRV_NAME); snprintf(info->fw_version, sizeof(info->fw_version), "%u:%u:%u:%u", port->firmware[0], port->firmware[1], port->firmware[2], port->firmware[3]); strcpy(info->bus_info, "internal"); } static int ixp4xx_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct port *port = netdev_priv(dev); return phy_ethtool_gset(port->phydev, cmd); } static int ixp4xx_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct port *port = netdev_priv(dev); return phy_ethtool_sset(port->phydev, cmd); } static int ixp4xx_nway_reset(struct net_device *dev) { struct port *port = netdev_priv(dev); return phy_start_aneg(port->phydev); } static const struct ethtool_ops ixp4xx_ethtool_ops = { .get_drvinfo = ixp4xx_get_drvinfo, .get_settings = ixp4xx_get_settings, .set_settings = ixp4xx_set_settings, .nway_reset = ixp4xx_nway_reset, .get_link = ethtool_op_get_link, }; static int request_queues(struct port *port) { int err; err = qmgr_request_queue(RXFREE_QUEUE(port->id), RX_DESCS, 0, 0, "%s:RX-free", port->netdev->name); if (err) return err; err = qmgr_request_queue(port->plat->rxq, RX_DESCS, 0, 0, "%s:RX", port->netdev->name); if (err) goto rel_rxfree; err = qmgr_request_queue(TX_QUEUE(port->id), TX_DESCS, 0, 0, "%s:TX", port->netdev->name); if (err) goto rel_rx; err = qmgr_request_queue(port->plat->txreadyq, TX_DESCS, 0, 0, "%s:TX-ready", port->netdev->name); if (err) goto rel_tx; /* */ if (!ports_open) { err = qmgr_request_queue(TXDONE_QUEUE, TXDONE_QUEUE_LEN, 0, 0, "%s:TX-done", DRV_NAME); if (err) goto rel_txready; } return 0; rel_txready: qmgr_release_queue(port->plat->txreadyq); rel_tx: qmgr_release_queue(TX_QUEUE(port->id)); rel_rx: qmgr_release_queue(port->plat->rxq); rel_rxfree: qmgr_release_queue(RXFREE_QUEUE(port->id)); printk(KERN_DEBUG "%s: unable to request hardware queues\n", port->netdev->name); return err; } static void release_queues(struct port *port) { qmgr_release_queue(RXFREE_QUEUE(port->id)); qmgr_release_queue(port->plat->rxq); qmgr_release_queue(TX_QUEUE(port->id)); qmgr_release_queue(port->plat->txreadyq); if (!ports_open) qmgr_release_queue(TXDONE_QUEUE); } static int init_queues(struct port *port) { int i; if (!ports_open) if (!(dma_pool = dma_pool_create(DRV_NAME, NULL, POOL_ALLOC_SIZE, 32, 0))) return -ENOMEM; if (!(port->desc_tab = dma_pool_alloc(dma_pool, GFP_KERNEL, &port->desc_tab_phys))) return -ENOMEM; memset(port->desc_tab, 0, POOL_ALLOC_SIZE); memset(port->rx_buff_tab, 0, sizeof(port->rx_buff_tab)); /* */ memset(port->tx_buff_tab, 0, sizeof(port->tx_buff_tab)); /* */ for (i = 0; i < RX_DESCS; i++) { struct desc *desc = rx_desc_ptr(port, i); buffer_t *buff; /* */ void *data; #ifdef __ARMEB__ if (!(buff = netdev_alloc_skb(port->netdev, RX_BUFF_SIZE))) return -ENOMEM; data = buff->data; #else if (!(buff = kmalloc(RX_BUFF_SIZE, GFP_KERNEL))) return -ENOMEM; data = buff; #endif desc->buf_len = MAX_MRU; desc->data = dma_map_single(&port->netdev->dev, data, RX_BUFF_SIZE, DMA_FROM_DEVICE); if (dma_mapping_error(&port->netdev->dev, desc->data)) { free_buffer(buff); return -EIO; } desc->data += NET_IP_ALIGN; port->rx_buff_tab[i] = buff; } return 0; } static void destroy_queues(struct port *port) { int i; if (port->desc_tab) { for (i = 0; i < RX_DESCS; i++) { struct desc *desc = rx_desc_ptr(port, i); buffer_t *buff = port->rx_buff_tab[i]; if (buff) { dma_unmap_single(&port->netdev->dev, desc->data - NET_IP_ALIGN, RX_BUFF_SIZE, DMA_FROM_DEVICE); free_buffer(buff); } } for (i = 0; i < TX_DESCS; i++) { struct desc *desc = tx_desc_ptr(port, i); buffer_t *buff = port->tx_buff_tab[i]; if (buff) { dma_unmap_tx(port, desc); free_buffer(buff); } } dma_pool_free(dma_pool, port->desc_tab, port->desc_tab_phys); port->desc_tab = NULL; } if (!ports_open && dma_pool) { dma_pool_destroy(dma_pool); dma_pool = NULL; } } static int eth_open(struct net_device *dev) { struct port *port = netdev_priv(dev); struct npe *npe = port->npe; struct msg msg; int i, err; if (!npe_running(npe)) { err = npe_load_firmware(npe, npe_name(npe), &dev->dev); if (err) return err; if (npe_recv_message(npe, &msg, "ETH_GET_STATUS")) { printk(KERN_ERR "%s: %s not responding\n", dev->name, npe_name(npe)); return -EIO; } port->firmware[0] = msg.byte4; port->firmware[1] = msg.byte5; port->firmware[2] = msg.byte6; port->firmware[3] = msg.byte7; } memset(&msg, 0, sizeof(msg)); msg.cmd = NPE_VLAN_SETRXQOSENTRY; msg.eth_id = port->id; msg.byte5 = port->plat->rxq | 0x80; msg.byte7 = port->plat->rxq << 4; for (i = 0; i < 8; i++) { msg.byte3 = i; if (npe_send_recv_message(port->npe, &msg, "ETH_SET_RXQ")) return -EIO; } msg.cmd = NPE_EDB_SETPORTADDRESS; msg.eth_id = PHYSICAL_ID(port->id); msg.byte2 = dev->dev_addr[0]; msg.byte3 = dev->dev_addr[1]; msg.byte4 = dev->dev_addr[2]; msg.byte5 = dev->dev_addr[3]; msg.byte6 = dev->dev_addr[4]; msg.byte7 = dev->dev_addr[5]; if (npe_send_recv_message(port->npe, &msg, "ETH_SET_MAC")) return -EIO; memset(&msg, 0, sizeof(msg)); msg.cmd = NPE_FW_SETFIREWALLMODE; msg.eth_id = port->id; if (npe_send_recv_message(port->npe, &msg, "ETH_SET_FIREWALL_MODE")) return -EIO; if ((err = request_queues(port)) != 0) return err; if ((err = init_queues(port)) != 0) { destroy_queues(port); release_queues(port); return err; } port->speed = 0; /* */ phy_start(port->phydev); for (i = 0; i < ETH_ALEN; i++) __raw_writel(dev->dev_addr[i], &port->regs->hw_addr[i]); __raw_writel(0x08, &port->regs->random_seed); __raw_writel(0x12, &port->regs->partial_empty_threshold); __raw_writel(0x30, &port->regs->partial_full_threshold); __raw_writel(0x08, &port->regs->tx_start_bytes); __raw_writel(0x15, &port->regs->tx_deferral); __raw_writel(0x08, &port->regs->tx_2part_deferral[0]); __raw_writel(0x07, &port->regs->tx_2part_deferral[1]); __raw_writel(0x80, &port->regs->slot_time); __raw_writel(0x01, &port->regs->int_clock_threshold); /* */ for (i = 0; i < TX_DESCS; i++) queue_put_desc(port->plat->txreadyq, tx_desc_phys(port, i), tx_desc_ptr(port, i)); for (i = 0; i < RX_DESCS; i++) queue_put_desc(RXFREE_QUEUE(port->id), rx_desc_phys(port, i), rx_desc_ptr(port, i)); __raw_writel(TX_CNTRL1_RETRIES, &port->regs->tx_control[1]); __raw_writel(DEFAULT_TX_CNTRL0, &port->regs->tx_control[0]); __raw_writel(0, &port->regs->rx_control[1]); __raw_writel(DEFAULT_RX_CNTRL0, &port->regs->rx_control[0]); napi_enable(&port->napi); eth_set_mcast_list(dev); netif_start_queue(dev); qmgr_set_irq(port->plat->rxq, QUEUE_IRQ_SRC_NOT_EMPTY, eth_rx_irq, dev); if (!ports_open) { qmgr_set_irq(TXDONE_QUEUE, QUEUE_IRQ_SRC_NOT_EMPTY, eth_txdone_irq, NULL); qmgr_enable_irq(TXDONE_QUEUE); } ports_open++; /* */ napi_schedule(&port->napi); return 0; } static int eth_close(struct net_device *dev) { struct port *port = netdev_priv(dev); struct msg msg; int buffs = RX_DESCS; /* */ int i; ports_open--; qmgr_disable_irq(port->plat->rxq); napi_disable(&port->napi); netif_stop_queue(dev); while (queue_get_desc(RXFREE_QUEUE(port->id), port, 0) >= 0) buffs--; memset(&msg, 0, sizeof(msg)); msg.cmd = NPE_SETLOOPBACK_MODE; msg.eth_id = port->id; msg.byte3 = 1; if (npe_send_recv_message(port->npe, &msg, "ETH_ENABLE_LOOPBACK")) printk(KERN_CRIT "%s: unable to enable loopback\n", dev->name); i = 0; do { /* */ while (queue_get_desc(port->plat->rxq, port, 0) >= 0) buffs--; if (!buffs) break; if (qmgr_stat_empty(TX_QUEUE(port->id))) { /* */ struct desc *desc; u32 phys; int n = queue_get_desc(port->plat->txreadyq, port, 1); BUG_ON(n < 0); desc = tx_desc_ptr(port, n); phys = tx_desc_phys(port, n); desc->buf_len = desc->pkt_len = 1; wmb(); queue_put_desc(TX_QUEUE(port->id), phys, desc); } udelay(1); } while (++i < MAX_CLOSE_WAIT); if (buffs) printk(KERN_CRIT "%s: unable to drain RX queue, %i buffer(s)" " left in NPE\n", dev->name, buffs); #if DEBUG_CLOSE if (!buffs) printk(KERN_DEBUG "Draining RX queue took %i cycles\n", i); #endif buffs = TX_DESCS; while (queue_get_desc(TX_QUEUE(port->id), port, 1) >= 0) buffs--; /* */ i = 0; do { while (queue_get_desc(port->plat->txreadyq, port, 1) >= 0) buffs--; if (!buffs) break; } while (++i < MAX_CLOSE_WAIT); if (buffs) printk(KERN_CRIT "%s: unable to drain TX queue, %i buffer(s) " "left in NPE\n", dev->name, buffs); #if DEBUG_CLOSE if (!buffs) printk(KERN_DEBUG "Draining TX queues took %i cycles\n", i); #endif msg.byte3 = 0; if (npe_send_recv_message(port->npe, &msg, "ETH_DISABLE_LOOPBACK")) printk(KERN_CRIT "%s: unable to disable loopback\n", dev->name); phy_stop(port->phydev); if (!ports_open) qmgr_disable_irq(TXDONE_QUEUE); destroy_queues(port); release_queues(port); return 0; } static const struct net_device_ops ixp4xx_netdev_ops = { .ndo_open = eth_open, .ndo_stop = eth_close, .ndo_start_xmit = eth_xmit, .ndo_set_rx_mode = eth_set_mcast_list, .ndo_do_ioctl = eth_ioctl, .ndo_change_mtu = eth_change_mtu, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static int __devinit eth_init_one(struct platform_device *pdev) { struct port *port; struct net_device *dev; struct eth_plat_info *plat = pdev->dev.platform_data; u32 regs_phys; char phy_id[MII_BUS_ID_SIZE + 3]; int err; if (ptp_filter_init(ptp_filter, ARRAY_SIZE(ptp_filter))) { pr_err("ixp4xx_eth: bad ptp filter\n"); return -EINVAL; } if (!(dev = alloc_etherdev(sizeof(struct port)))) return -ENOMEM; SET_NETDEV_DEV(dev, &pdev->dev); port = netdev_priv(dev); port->netdev = dev; port->id = pdev->id; switch (port->id) { case IXP4XX_ETH_NPEA: port->regs = (struct eth_regs __iomem *)IXP4XX_EthA_BASE_VIRT; regs_phys = IXP4XX_EthA_BASE_PHYS; break; case IXP4XX_ETH_NPEB: port->regs = (struct eth_regs __iomem *)IXP4XX_EthB_BASE_VIRT; regs_phys = IXP4XX_EthB_BASE_PHYS; break; case IXP4XX_ETH_NPEC: port->regs = (struct eth_regs __iomem *)IXP4XX_EthC_BASE_VIRT; regs_phys = IXP4XX_EthC_BASE_PHYS; break; default: err = -ENODEV; goto err_free; } dev->netdev_ops = &ixp4xx_netdev_ops; dev->ethtool_ops = &ixp4xx_ethtool_ops; dev->tx_queue_len = 100; netif_napi_add(dev, &port->napi, eth_poll, NAPI_WEIGHT); if (!(port->npe = npe_request(NPE_ID(port->id)))) { err = -EIO; goto err_free; } port->mem_res = request_mem_region(regs_phys, REGS_SIZE, dev->name); if (!port->mem_res) { err = -EBUSY; goto err_npe_rel; } port->plat = plat; npe_port_tab[NPE_ID(port->id)] = port; memcpy(dev->dev_addr, plat->hwaddr, ETH_ALEN); platform_set_drvdata(pdev, dev); __raw_writel(DEFAULT_CORE_CNTRL | CORE_RESET, &port->regs->core_control); udelay(50); __raw_writel(DEFAULT_CORE_CNTRL, &port->regs->core_control); udelay(50); snprintf(phy_id, MII_BUS_ID_SIZE + 3, PHY_ID_FMT, mdio_bus->id, plat->phy); port->phydev = phy_connect(dev, phy_id, &ixp4xx_adjust_link, 0, PHY_INTERFACE_MODE_MII); if (IS_ERR(port->phydev)) { err = PTR_ERR(port->phydev); goto err_free_mem; } port->phydev->irq = PHY_POLL; if ((err = register_netdev(dev))) goto err_phy_dis; printk(KERN_INFO "%s: MII PHY %i on %s\n", dev->name, plat->phy, npe_name(port->npe)); return 0; err_phy_dis: phy_disconnect(port->phydev); err_free_mem: npe_port_tab[NPE_ID(port->id)] = NULL; platform_set_drvdata(pdev, NULL); release_resource(port->mem_res); err_npe_rel: npe_release(port->npe); err_free: free_netdev(dev); return err; } static int __devexit eth_remove_one(struct platform_device *pdev) { struct net_device *dev = platform_get_drvdata(pdev); struct port *port = netdev_priv(dev); unregister_netdev(dev); phy_disconnect(port->phydev); npe_port_tab[NPE_ID(port->id)] = NULL; platform_set_drvdata(pdev, NULL); npe_release(port->npe); release_resource(port->mem_res); free_netdev(dev); return 0; } static struct platform_driver ixp4xx_eth_driver = { .driver.name = DRV_NAME, .probe = eth_init_one, .remove = eth_remove_one, }; static int __init eth_init_module(void) { int err; if ((err = ixp4xx_mdio_register())) return err; return platform_driver_register(&ixp4xx_eth_driver); } static void __exit eth_cleanup_module(void) { platform_driver_unregister(&ixp4xx_eth_driver); ixp4xx_mdio_remove(); } MODULE_AUTHOR("Krzysztof Halasa"); MODULE_DESCRIPTION("Intel IXP4xx Ethernet driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:ixp4xx_eth"); module_init(eth_init_module); module_exit(eth_cleanup_module);
holyangel/LGE_G3
drivers/net/ethernet/xscale/ixp4xx_eth.c
C
gpl-2.0
38,452
#! /bin/bash # Haven't managed to have Android.mk put my static libraries in front of # libgcc.a and libgnustl_static.a so that I had to resort to this manual # build script. rm -rf obj ./cplibs-static.py ARCH=armeabi NDK=${HOME}/android-ndk-r7 HOSTOS=`uname -s` case ${HOSTOS} in 'Darwin') HOSTOS="darwin" ;; *) HOSTOS="linux" ;; esac TOOLCHAIN=${NDK}/toolchains/arm-linux-androideabi-4.4.3/prebuilt/${HOSTOS}-x86 CXX=${TOOLCHAIN}/bin/arm-linux-androideabi-g++ STRIP=${TOOLCHAIN}/bin/arm-linux-androideabi-strip PLATFORM=android-8 TARGETDIR=./obj/local/${ARCH} INSTALLDIR=./libs/${ARCH} INCLUDES=" -I../encfs/encfs-1.7.4 -I../encfs/encfs-1.7.4/encfs -I../encfs/encfs-1.7.4/intl -I../fuse/fuse-android/jni/include -I../boost/boost_1_46_1 -I../rlog/rlog-1.4/armeabi/include -I${NDK}/sources/cxx-stl/gnu-libstdc++/include -I${NDK}/sources/cxx-stl/gnu-libstdc++/libs/armeabi/include -Ijni -I${NDK}/platforms/${PLATFORM}/arch-arm/usr/include" DEFINES=" -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ -DANDROID -D_FILE_OFFSET_BITS=64 -DRLOG_COMPONENT=\"encfs\" -DFUSE_USE_VERSION=26 -D__STDC_FORMAT_MACROS -D__MULTI_THREAD -DOPENSSL_NO_ENGINE -DHAVE_EVP_AES -DHAVE_EVP_BF -DNDEBUG" CXXFLAGS="${DEFINES} -fpic -ffunction-sections -funwind-tables -fstack-protector -Wno-psabi -march=armv5te -mtune=xscale -msoft-float -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 ${INCLUDES} -Wa,--noexecstack -fexceptions -frtti -O2 -g" SRC=cryptonite.cpp LDFLAGS="-Wl,-soname,libcryptonite.so -shared --sysroot=${NDK}/platforms/${PLATFORM}/arch-arm" STATIC_LIBS=" ${TARGETDIR}/libencfs.a ${TARGETDIR}/libfuse.a ${TARGETDIR}/libboost_serialization.a ${TARGETDIR}/librlog.a ${TARGETDIR}/libboost_filesystem.a ${TARGETDIR}/libboost_system.a ${TARGETDIR}/libstdc++.a ${TARGETDIR}/libgcc.a" SHARED_LIBS="-L../openssl/openssl-android/libs/armeabi/ -lssl -lcrypto" mkdir -p ${TARGETDIR}/cryptonite/cryptonite mkdir -p ${TARGETDIR}/objs/cryptonite ${CXX} -MMD -MP -MF ${TARGETDIR}/cryptonite/cryptonite.o.d ${CXXFLAGS} -c jni/${SRC} -o ${TARGETDIR}/objs/cryptonite/cryptonite.o ${CXX} ${LDFLAGS} ${TARGETDIR}/objs/cryptonite/cryptonite.o ${STATIC_LIBS} -Wl,--no-undefined -Wl,-z,noexecstack ${SHARED_LIBS} -lc -lm -o ${TARGETDIR}/libcryptonite.so mkdir -p ${INSTALLDIR} install -p ${TARGETDIR}/libcryptonite.so ${INSTALLDIR}/libcryptonite.so ${STRIP} --strip-unneeded ${INSTALLDIR}/libcryptonite.so
xdggplus/cryptonite
cryptonite/manual_make.sh
Shell
gpl-2.0
2,583
/* * drivers/media/video/tegra/tegra_camera.c * * Copyright (C) 2010 Google, Inc. * Copyright (C) 2012 Nvidia Corp * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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/miscdevice.h> #include <linux/platform_device.h> #include <linux/ioctl.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/regulator/consumer.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/uaccess.h> #include <linux/delay.h> #include <mach/iomap.h> #include <mach/clk.h> #include <mach/powergate.h> #include <media/tegra_camera.h> /* Eventually this should handle all clock and reset calls for the isp, vi, * vi_sensor, and csi modules, replacing nvrm and nvos completely for camera */ #define TEGRA_CAMERA_NAME "tegra_camera" struct tegra_camera_dev { struct device *dev; struct miscdevice misc_dev; struct clk *isp_clk; struct clk *vi_clk; struct clk *vi_sensor_clk; struct clk *csus_clk; struct clk *csi_clk; struct clk *emc_clk; struct regulator *reg; struct tegra_camera_clk_info info; struct mutex tegra_camera_lock; atomic_t in_use; int power_on; }; struct tegra_camera_block { int (*enable) (struct tegra_camera_dev *dev); int (*disable) (struct tegra_camera_dev *dev); bool is_enabled; }; static int tegra_camera_enable_clk(struct tegra_camera_dev *dev) { clk_enable(dev->vi_clk); clk_enable(dev->vi_sensor_clk); clk_enable(dev->csus_clk); tegra_periph_reset_assert(dev->vi_clk); udelay(2); tegra_periph_reset_deassert(dev->vi_clk); clk_enable(dev->isp_clk); tegra_periph_reset_assert(dev->isp_clk); udelay(2); tegra_periph_reset_deassert(dev->isp_clk); clk_enable(dev->csi_clk); tegra_periph_reset_assert(dev->csi_clk); udelay(2); tegra_periph_reset_deassert(dev->csi_clk); return 0; } static int tegra_camera_disable_clk(struct tegra_camera_dev *dev) { clk_disable(dev->csi_clk); tegra_periph_reset_assert(dev->csi_clk); clk_disable(dev->isp_clk); tegra_periph_reset_assert(dev->isp_clk); clk_disable(dev->csus_clk); clk_disable(dev->vi_sensor_clk); clk_disable(dev->vi_clk); tegra_periph_reset_assert(dev->vi_clk); return 0; } static int tegra_camera_enable_emc(struct tegra_camera_dev *dev) { int ret = tegra_emc_disable_eack(); clk_enable(dev->emc_clk); #ifdef CONFIG_ARCH_TEGRA_2x_SOC clk_set_rate(dev->emc_clk, 300000000); #endif return ret; } static int tegra_camera_disable_emc(struct tegra_camera_dev *dev) { clk_disable(dev->emc_clk); return tegra_emc_enable_eack(); } static int tegra_camera_clk_set_rate(struct tegra_camera_dev *dev) { struct clk *clk, *clk_parent; struct tegra_camera_clk_info *info = &dev->info; unsigned long parent_rate, parent_div_rate, parent_div_rate_pre; if (!info) { dev_err(dev->dev, "%s: no clock info %d\n", __func__, info->id); return -EINVAL; } if (info->id != TEGRA_CAMERA_MODULE_VI && info->id != TEGRA_CAMERA_MODULE_EMC) { dev_err(dev->dev, "%s: set rate only aplies to vi module %d\n", __func__, info->id); return -EINVAL; } switch (info->clk_id) { case TEGRA_CAMERA_VI_CLK: clk = dev->vi_clk; break; case TEGRA_CAMERA_VI_SENSOR_CLK: clk = dev->vi_sensor_clk; break; case TEGRA_CAMERA_EMC_CLK: clk = dev->emc_clk; #ifndef CONFIG_ARCH_TEGRA_2x_SOC dev_dbg(dev->dev, "%s: emc_clk rate=%lu\n", __func__, info->rate); clk_set_rate(dev->emc_clk, info->rate); #endif goto set_rate_end; default: dev_err(dev->dev, "%s: invalid clk id for set rate %d\n", __func__, info->clk_id); return -EINVAL; } clk_parent = clk_get_parent(clk); parent_rate = clk_get_rate(clk_parent); dev_dbg(dev->dev, "%s: clk_id=%d, parent_rate=%lu, clk_rate=%lu\n", __func__, info->clk_id, parent_rate, info->rate); parent_div_rate = parent_rate; parent_div_rate_pre = parent_rate; /* * The requested clock rate from user space should be respected. * This loop is to search the clock rate that is higher than requested * clock. */ while (parent_div_rate >= info->rate) { parent_div_rate_pre = parent_div_rate; parent_div_rate = clk_round_rate(clk, parent_div_rate-1); } dev_dbg(dev->dev, "%s: set_rate=%lu", __func__, parent_div_rate_pre); clk_set_rate(clk, parent_div_rate_pre); if (info->clk_id == TEGRA_CAMERA_VI_CLK) { /* * bit 25: 0 = pd2vi_Clk, 1 = vi_sensor_clk * bit 24: 0 = internal clock, 1 = external clock(pd2vi_clk) */ if (info->flag == TEGRA_CAMERA_ENABLE_PD2VI_CLK) tegra_clk_cfg_ex(clk, TEGRA_CLK_VI_INP_SEL, 2); #ifdef CONFIG_ARCH_TEGRA_2x_SOC { u32 val; void __iomem *apb_misc = IO_ADDRESS(TEGRA_APB_MISC_BASE); val = readl(apb_misc + 0x42c); writel(val | 0x1, apb_misc + 0x42c); } #endif } set_rate_end: info->rate = clk_get_rate(clk); dev_dbg(dev->dev, "%s: get_rate=%lu", __func__, info->rate); return 0; } static int tegra_camera_power_on(struct tegra_camera_dev *dev) { int ret = 0; dev_dbg(dev->dev, "%s++\n", __func__); /* Enable external power */ if (dev->reg) { ret = regulator_enable(dev->reg); if (ret) { dev_err(dev->dev, "%s: enable csi regulator failed.\n", __func__); return ret; } } #ifndef CONFIG_ARCH_TEGRA_2x_SOC /* Unpowergate VE */ ret = tegra_unpowergate_partition(TEGRA_POWERGATE_VENC); if (ret) dev_err(dev->dev, "%s: unpowergate failed.\n", __func__); #endif dev->power_on = 1; return ret; } static int tegra_camera_power_off(struct tegra_camera_dev *dev) { int ret = 0; dev_dbg(dev->dev, "%s++\n", __func__); #ifndef CONFIG_ARCH_TEGRA_2x_SOC /* Powergate VE */ ret = tegra_powergate_partition(TEGRA_POWERGATE_VENC); if (ret) dev_err(dev->dev, "%s: powergate failed.\n", __func__); #endif /* Disable external power */ if (dev->reg) { ret = regulator_disable(dev->reg); if (ret) { dev_err(dev->dev, "%s: disable csi regulator failed.\n", __func__); return ret; } } dev->power_on = 0; return ret; } static long tegra_camera_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { uint id; struct tegra_camera_dev *dev = file->private_data; /* first element of arg must be u32 with id of module to talk to */ if (copy_from_user(&id, (const void __user *)arg, sizeof(uint))) { dev_err(dev->dev, "%s: Failed to copy arg from user", __func__); return -EFAULT; } if (id >= TEGRA_CAMERA_MODULE_MAX) { dev_err(dev->dev, "%s: Invalid id to tegra isp ioctl%d\n", __func__, id); return -EINVAL; } switch (cmd) { /* * Clock enable/disable and reset should be handled in kernel. * In order to support legacy code in user space, we don't remove * these IOCTL. */ case TEGRA_CAMERA_IOCTL_ENABLE: case TEGRA_CAMERA_IOCTL_DISABLE: case TEGRA_CAMERA_IOCTL_RESET: return 0; case TEGRA_CAMERA_IOCTL_CLK_SET_RATE: { int ret; if (copy_from_user(&dev->info, (const void __user *)arg, sizeof(struct tegra_camera_clk_info))) { dev_err(dev->dev, "%s: Failed to copy arg from user\n", __func__); return -EFAULT; } ret = tegra_camera_clk_set_rate(dev); if (ret) return ret; if (copy_to_user((void __user *)arg, &dev->info, sizeof(struct tegra_camera_clk_info))) { dev_err(dev->dev, "%s: Failed to copy arg to user\n", __func__); return -EFAULT; } return 0; } default: dev_err(dev->dev, "%s: Unknown tegra_camera ioctl.\n", __func__); return -EINVAL; } return 0; } static int tegra_camera_open(struct inode *inode, struct file *file) { struct miscdevice *miscdev = file->private_data; struct tegra_camera_dev *dev = container_of(miscdev, struct tegra_camera_dev, misc_dev); int ret = 0; dev_info(dev->dev, "%s\n", __func__); if (atomic_xchg(&dev->in_use, 1)) return -EBUSY; file->private_data = dev; mutex_lock(&dev->tegra_camera_lock); /* turn on CSI regulator */ ret = tegra_camera_power_on(dev); if (ret) goto open_exit; /* set EMC request */ ret = tegra_camera_enable_emc(dev); if (ret) goto open_exit; /* enable camera HW clock */ ret = tegra_camera_enable_clk(dev); if (ret) goto open_exit; open_exit: mutex_unlock(&dev->tegra_camera_lock); return ret; } static int tegra_camera_release(struct inode *inode, struct file *file) { int ret = 0; struct tegra_camera_dev *dev = file->private_data; dev_info(dev->dev, "%s\n", __func__); mutex_lock(&dev->tegra_camera_lock); /* disable HW clock */ ret = tegra_camera_disable_clk(dev); if (ret) goto release_exit; /* nullify EMC request */ ret = tegra_camera_disable_emc(dev); if (ret) goto release_exit; /* turn off CSI regulator */ tegra_camera_power_off(dev); if (ret) goto release_exit; release_exit: mutex_unlock(&dev->tegra_camera_lock); WARN_ON(!atomic_xchg(&dev->in_use, 0)); return 0; } static const struct file_operations tegra_camera_fops = { .owner = THIS_MODULE, .open = tegra_camera_open, .unlocked_ioctl = tegra_camera_ioctl, .release = tegra_camera_release, }; static int tegra_camera_clk_get(struct platform_device *pdev, const char *name, struct clk **clk) { *clk = clk_get(&pdev->dev, name); if (IS_ERR_OR_NULL(*clk)) { dev_err(&pdev->dev, "%s: unable to get clock for %s\n", __func__, name); *clk = NULL; return PTR_ERR(*clk); } return 0; } static int tegra_camera_probe(struct platform_device *pdev) { int err; struct tegra_camera_dev *dev; dev_info(&pdev->dev, "%s\n", __func__); dev = devm_kzalloc(&pdev->dev, sizeof(struct tegra_camera_dev), GFP_KERNEL); if (!dev) { err = -ENOMEM; dev_err(&pdev->dev, "%s: unable to allocate memory\n", __func__); goto alloc_err; } mutex_init(&dev->tegra_camera_lock); /* Powergate VE when boot */ mutex_lock(&dev->tegra_camera_lock); #ifndef CONFIG_ARCH_TEGRA_2x_SOC err = tegra_powergate_partition(TEGRA_POWERGATE_VENC); if (err) dev_err(&pdev->dev, "%s: powergate failed.\n", __func__); #endif mutex_unlock(&dev->tegra_camera_lock); dev->dev = &pdev->dev; /* Get regulator pointer */ #ifdef CONFIG_ARCH_TEGRA_2x_SOC dev->reg = regulator_get(&pdev->dev, "vcsi"); #else dev->reg = regulator_get(&pdev->dev, "avdd_dsi_csi"); #endif if (IS_ERR_OR_NULL(dev->reg)) { if (dev->reg == ERR_PTR(-ENODEV)) { dev->reg = NULL; dev_info(&pdev->dev, "%s: no regulator device, overriding\n", __func__); } else { dev_err(&pdev->dev, "%s: couldn't get regulator\n", __func__); return PTR_ERR(dev->reg); } } dev->misc_dev.minor = MISC_DYNAMIC_MINOR; dev->misc_dev.name = TEGRA_CAMERA_NAME; dev->misc_dev.fops = &tegra_camera_fops; dev->misc_dev.parent = &pdev->dev; err = misc_register(&dev->misc_dev); if (err) { dev_err(&pdev->dev, "%s: Unable to register misc device!\n", TEGRA_CAMERA_NAME); goto misc_register_err; } err = tegra_camera_clk_get(pdev, "isp", &dev->isp_clk); if (err) goto misc_register_err; err = tegra_camera_clk_get(pdev, "vi", &dev->vi_clk); if (err) goto vi_clk_get_err; err = tegra_camera_clk_get(pdev, "vi_sensor", &dev->vi_sensor_clk); if (err) goto vi_sensor_clk_get_err; err = tegra_camera_clk_get(pdev, "csus", &dev->csus_clk); if (err) goto csus_clk_get_err; err = tegra_camera_clk_get(pdev, "csi", &dev->csi_clk); if (err) goto csi_clk_get_err; err = tegra_camera_clk_get(pdev, "emc", &dev->emc_clk); if (err) goto emc_clk_get_err; /* dev is set in order to restore in _remove */ platform_set_drvdata(pdev, dev); return 0; emc_clk_get_err: clk_put(dev->emc_clk); csi_clk_get_err: clk_put(dev->csus_clk); csus_clk_get_err: clk_put(dev->vi_sensor_clk); vi_sensor_clk_get_err: clk_put(dev->vi_clk); vi_clk_get_err: clk_put(dev->isp_clk); misc_register_err: regulator_put(dev->reg); alloc_err: return err; } static int tegra_camera_remove(struct platform_device *pdev) { struct tegra_camera_dev *dev = platform_get_drvdata(pdev); clk_put(dev->isp_clk); clk_put(dev->vi_clk); clk_put(dev->vi_sensor_clk); clk_put(dev->csus_clk); clk_put(dev->csi_clk); misc_deregister(&dev->misc_dev); regulator_put(dev->reg); mutex_destroy(&dev->tegra_camera_lock); return 0; } static int tegra_camera_suspend(struct platform_device *pdev, pm_message_t state) { struct tegra_camera_dev *dev = platform_get_drvdata(pdev); int ret = 0; mutex_lock(&dev->tegra_camera_lock); if (dev->power_on) { ret = -EBUSY; dev_err(&pdev->dev, "tegra_camera cannot suspend, " "application is holding on to camera. \n"); } mutex_unlock(&dev->tegra_camera_lock); return ret; } static int tegra_camera_resume(struct platform_device *pdev) { return 0; } static struct platform_driver tegra_camera_driver = { .probe = tegra_camera_probe, .remove = tegra_camera_remove, .suspend = tegra_camera_suspend, .resume = tegra_camera_resume, .driver = { .name = TEGRA_CAMERA_NAME } }; static int __init tegra_camera_init(void) { return platform_driver_register(&tegra_camera_driver); } static void __exit tegra_camera_exit(void) { platform_driver_unregister(&tegra_camera_driver); } module_init(tegra_camera_init); module_exit(tegra_camera_exit);
wooshy1/kernel-olympus-3.1
drivers/media/video/tegra/tegra_camera.c
C
gpl-2.0
13,379
/* drivers/video/msm/msm_fb.c * * Core MSM framebuffer driver. * * Copyright (C) 2007 Google Incorporated * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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/platform_device.h> #include <linux/module.h> #include <linux/fb.h> #include <linux/delay.h> #include <linux/freezer.h> #include <linux/wait.h> #include <linux/wakelock.h> #include <linux/earlysuspend.h> #include <linux/msm_mdp.h> #include <linux/io.h> #include <linux/uaccess.h> #include <mach/msm_fb.h> #include <mach/board.h> #include <linux/workqueue.h> #include <linux/clk.h> #include <linux/debugfs.h> #include <linux/dma-mapping.h> #include <linux/android_pmem.h> #include "mdp_hw.h" extern void start_drawing_late_resume(struct early_suspend *h); static void msmfb_resume_handler(struct early_suspend *h); static void msmfb_resume(struct work_struct *work); #ifdef CONFIG_MSM_HDMI void hdmi_DoBlit(int offset); int hdmi_usePanelSync(void); #endif #define MSMFB_DEBUG 1 #ifdef CONFIG_FB_MSM_LOGO #define INIT_IMAGE_FILE "/logo.rle" extern int load_565rle_image(char *filename); #endif #define PRINT_FPS 0 #define PRINT_BLIT_TIME 0 #define SLEEPING 0x4 #define UPDATING 0x3 #define FULL_UPDATE_DONE 0x2 #define WAKING 0x1 #define AWAKE 0x0 #define NONE 0 #define SUSPEND_RESUME 0x1 #define FPS 0x2 #define BLIT_TIME 0x4 #define SHOW_UPDATES 0x8 #ifdef CONFIG_PANEL_SELF_REFRESH extern struct panel_icm_info *panel_icm; extern wait_queue_head_t panel_update_wait_queue; #endif #define DLOG(mask, fmt, args...) \ do { \ if ((msmfb_debug_mask | SUSPEND_RESUME) & mask) \ printk(KERN_INFO "msmfb: "fmt, ##args); \ } while (0) #define BITS_PER_PIXEL(info) (info->fb->var.bits_per_pixel) #define BYTES_PER_PIXEL(info) (info->fb->var.bits_per_pixel >> 3) static int msmfb_debug_mask; module_param_named(msmfb_debug_mask, msmfb_debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP); struct mdp_device *mdp; static atomic_t mdpclk_on = ATOMIC_INIT(1); struct msmfb_info { struct fb_info *fb; struct msm_panel_data *panel; int xres; int yres; unsigned output_format; unsigned yoffset; unsigned frame_requested; unsigned frame_done; int sleeping; unsigned update_frame; struct { int left; int top; int eright; /* exclusive */ int ebottom; /* exclusive */ } update_info; char *black; #ifdef CONFIG_HTC_ONMODE_CHARGING struct early_suspend onchg_earlier_suspend; struct early_suspend onchg_suspend; #endif struct early_suspend earlier_suspend; struct early_suspend early_suspend; struct wake_lock idle_lock; spinlock_t update_lock; struct mutex panel_init_lock; wait_queue_head_t frame_wq; struct workqueue_struct *resume_workqueue; struct work_struct resume_work; struct work_struct msmfb_resume_work; struct msmfb_callback dma_callback; struct msmfb_callback vsync_callback; struct hrtimer fake_vsync; ktime_t vsync_request_time; unsigned fb_resumed; }; #ifdef CONFIG_FB_MSM_OVERLAY #define USE_OVERLAY 1 struct overlay_waitevent{ uint32_t waked_up; wait_queue_head_t event_wait; }; static struct overlay_waitevent overlay_event; DEFINE_MUTEX(overlay_event_lock); #endif #if (defined(CONFIG_USB_FUNCTION_PROJECTOR) || defined(CONFIG_USB_ANDROID_PROJECTOR)) static spinlock_t fb_data_lock = SPIN_LOCK_UNLOCKED; static struct msm_fb_info msm_fb_data; int msmfb_get_var(struct msm_fb_info *tmp) { unsigned long flags; spin_lock_irqsave(&fb_data_lock, flags); memcpy(tmp, &msm_fb_data, sizeof(msm_fb_data)); spin_unlock_irqrestore(&fb_data_lock, flags); return 0; } /* projector need this, and very much */ int msmfb_get_fb_area(void) { int area; unsigned long flags; spin_lock_irqsave(&fb_data_lock, flags); area = msm_fb_data.msmfb_area; spin_unlock_irqrestore(&fb_data_lock, flags); return area; } static void msmfb_set_var(unsigned char *addr, int area) { unsigned long flags; spin_lock_irqsave(&fb_data_lock, flags); msm_fb_data.fb_addr = addr; msm_fb_data.msmfb_area = area; spin_unlock_irqrestore(&fb_data_lock, flags); } #endif static int msmfb_open(struct fb_info *info, int user) { return 0; } static int msmfb_release(struct fb_info *info, int user) { return 0; } /* Called from dma interrupt handler, must not sleep */ static void msmfb_handle_dma_interrupt(struct msmfb_callback *callback) { unsigned long irq_flags=0; struct msmfb_info *msmfb = container_of(callback, struct msmfb_info, dma_callback); #if PRINT_FPS int64_t dt; ktime_t now; static int64_t frame_count; static ktime_t last_sec; #endif spin_lock_irqsave(&msmfb->update_lock, irq_flags); msmfb->frame_done = msmfb->frame_requested; if (msmfb->sleeping == UPDATING && msmfb->frame_done == msmfb->update_frame) { DLOG(SUSPEND_RESUME, "full update completed\n"); queue_work(msmfb->resume_workqueue, &msmfb->resume_work); } #if PRINT_FPS now = ktime_get(); dt = ktime_to_ns(ktime_sub(now, last_sec)); frame_count++; if (dt > NSEC_PER_SEC) { int64_t fps = frame_count * NSEC_PER_SEC * 100; frame_count = 0; last_sec = ktime_get(); do_div(fps, dt); DLOG(FPS, "fps * 100: %llu\n", fps); } #endif spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); wake_up(&msmfb->frame_wq); } static int msmfb_start_dma(struct msmfb_info *msmfb) { uint32_t x, y, w, h; unsigned addr; unsigned long irq_flags=0; uint32_t yoffset; s64 time_since_request; struct msm_panel_data *panel = msmfb->panel; spin_lock_irqsave(&msmfb->update_lock, irq_flags); time_since_request = ktime_to_ns(ktime_sub(ktime_get(), msmfb->vsync_request_time)); if (time_since_request > 20 * NSEC_PER_MSEC) { uint32_t us; us = do_div(time_since_request, NSEC_PER_MSEC) / NSEC_PER_USEC; printk(KERN_WARNING "msmfb_start_dma %lld.%03u ms after vsync " "request\n", time_since_request, us); } if (msmfb->frame_done == msmfb->frame_requested) { spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); return -1; } if (msmfb->sleeping == SLEEPING) { DLOG(SUSPEND_RESUME, "tried to start dma while asleep\n"); spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); return -1; } x = msmfb->update_info.left; y = msmfb->update_info.top; w = msmfb->update_info.eright - x; h = msmfb->update_info.ebottom - y; #if 0 /* zeusk: */ ;;;;;;ASD #if defined(CONFIG_FRAMEBUFFER_CONSOLE) x = 0; y = 0; w = msmfb->xres; h = msmfb->yres; #endif ASD;;;;;; #endif yoffset = msmfb->yoffset; msmfb->update_info.left = msmfb->xres + 1; msmfb->update_info.top = msmfb->yres + 1; msmfb->update_info.eright = 0; msmfb->update_info.ebottom = 0; if (unlikely(w > msmfb->xres || h > msmfb->yres || w == 0 || h == 0)) { printk(KERN_INFO "invalid update: %d %d %d " "%d\n", x, y, w, h); msmfb->frame_done = msmfb->frame_requested; goto error; } spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); addr = ((msmfb->xres * (yoffset + y) + x) * BYTES_PER_PIXEL(msmfb)); mdp->dma(mdp, addr + msmfb->fb->fix.smem_start, msmfb->xres * BYTES_PER_PIXEL(msmfb), w, h, x, y, &msmfb->dma_callback, panel->interface_type); return 0; error: spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); /* some clients need to clear their vsync interrupt */ if (panel->clear_vsync) panel->clear_vsync(panel); wake_up(&msmfb->frame_wq); return 0; } /* Called from esync interrupt handler, must not sleep */ static void msmfb_handle_vsync_interrupt(struct msmfb_callback *callback) { struct msmfb_info *msmfb = container_of(callback, struct msmfb_info, vsync_callback); wake_unlock(&msmfb->idle_lock); msmfb_start_dma(msmfb); } static enum hrtimer_restart msmfb_fake_vsync(struct hrtimer *timer) { struct msmfb_info *msmfb = container_of(timer, struct msmfb_info, fake_vsync); msmfb_start_dma(msmfb); return HRTIMER_NORESTART; } static void msmfb_pan_update(struct fb_info *info, uint32_t left, uint32_t top, uint32_t eright, uint32_t ebottom, uint32_t yoffset, int pan_display) { struct msmfb_info *msmfb = info->par; struct msm_panel_data *panel = msmfb->panel; #ifdef CONFIG_PANEL_SELF_REFRESH struct mdp_lcdc_info *lcdc = panel_to_lcdc(panel); #endif unsigned long irq_flags=0; int sleeping; int retry = 1; #if PRINT_FPS ktime_t t1, t2; static uint64_t pans; static uint64_t dt; t1 = ktime_get(); #endif DLOG(SHOW_UPDATES, "update %d %d %d %d %d %d\n", left, top, eright, ebottom, yoffset, pan_display); #ifdef CONFIG_PANEL_SELF_REFRESH if (lcdc->mdp->mdp_dev.overrides & MSM_MDP_RGB_PANEL_SELE_REFRESH) { spin_lock_irqsave(&panel_icm->lock, irq_flags); panel_icm->panel_update = 1; spin_unlock_irqrestore(&panel_icm->lock, irq_flags); wake_up(&panel_update_wait_queue); } #endif #if (defined(CONFIG_USB_FUNCTION_PROJECTOR) || defined(CONFIG_USB_ANDROID_PROJECTOR)) /* Jay, 8/1/09' */ msmfb_set_var(msmfb->fb->screen_base, yoffset); #endif if (msmfb->sleeping != AWAKE) DLOG(SUSPEND_RESUME, "pan_update in state(%d)\n", msmfb->sleeping); restart: spin_lock_irqsave(&msmfb->update_lock, irq_flags); /* if we are sleeping, on a pan_display wait 10ms (to throttle back * drawing otherwise return */ if (msmfb->sleeping == SLEEPING) { DLOG(SUSPEND_RESUME, "drawing while asleep\n"); spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); if (pan_display) wait_event_interruptible_timeout(msmfb->frame_wq, msmfb->sleeping != SLEEPING, HZ/10); return; } sleeping = msmfb->sleeping; /* on a full update, if the last frame has not completed, wait for it */ if (pan_display && (msmfb->frame_requested != msmfb->frame_done || sleeping == UPDATING)) { int ret; spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); ret = wait_event_interruptible_timeout(msmfb->frame_wq, msmfb->frame_done == msmfb->frame_requested && msmfb->sleeping != UPDATING, 5 * HZ); if (ret <= 0 && (msmfb->frame_requested != msmfb->frame_done || msmfb->sleeping == UPDATING)) { if (retry && panel->request_vsync && (sleeping == AWAKE)) { wake_lock_timeout(&msmfb->idle_lock, HZ/4); panel->request_vsync(panel, &msmfb->vsync_callback); retry = 0; printk(KERN_WARNING "msmfb_pan_display timeout " "rerequest vsync\n"); } else { printk(KERN_WARNING "msmfb_pan_display timeout " "waiting for frame start, %d %d\n", msmfb->frame_requested, msmfb->frame_done); return; } } goto restart; } #if PRINT_FPS t2 = ktime_get(); if (pan_display) { uint64_t temp = ktime_to_ns(ktime_sub(t2, t1)); do_div(temp, 1000); dt += temp; pans++; if (pans > 1000) { do_div(dt, pans); DLOG(FPS, "ave_wait_time: %lld\n", dt); dt = 0; pans = 0; } } #endif msmfb->frame_requested++; /* if necessary, update the y offset, if this is the * first full update on resume, set the sleeping state */ if (pan_display) { msmfb->yoffset = yoffset; if (left == 0 && top == 0 && eright == info->var.xres && ebottom == info->var.yres) { if (sleeping == WAKING) { msmfb->update_frame = msmfb->frame_requested; DLOG(SUSPEND_RESUME, "full update starting\n"); msmfb->sleeping = UPDATING; } } } /* set the update request */ if (left < msmfb->update_info.left) msmfb->update_info.left = left; if (top < msmfb->update_info.top) msmfb->update_info.top = top; if (eright > msmfb->update_info.eright) msmfb->update_info.eright = eright; if (ebottom > msmfb->update_info.ebottom) msmfb->update_info.ebottom = ebottom; DLOG(SHOW_UPDATES, "update queued %d %d %d %d %d\n", msmfb->update_info.left, msmfb->update_info.top, msmfb->update_info.eright, msmfb->update_info.ebottom, msmfb->yoffset); spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); #ifdef CONFIG_MSM_HDMI if (!hdmi_usePanelSync()) { msmfb->vsync_request_time = ktime_get(); msmfb_start_dma(msmfb); } else { #endif /* if the panel is all the way on wait for vsync, otherwise sleep * for 16 ms (long enough for the dma to panel) and then begin dma */ msmfb->vsync_request_time = ktime_get(); if (panel->request_vsync && (sleeping == AWAKE)) { wake_lock_timeout(&msmfb->idle_lock, HZ/4); panel->request_vsync(panel, &msmfb->vsync_callback); } else { if (!hrtimer_active(&msmfb->fake_vsync)) { hrtimer_start(&msmfb->fake_vsync, ktime_set(0, NSEC_PER_SEC/60), HRTIMER_MODE_REL); } } #ifdef CONFIG_MSM_HDMI } /* We did the DMA, now blit the data to the other display */ hdmi_DoBlit(msmfb->xres * msmfb->yoffset * BYTES_PER_PIXEL(msmfb)); #endif return; } static void msmfb_update(struct fb_info *info, uint32_t left, uint32_t top, uint32_t eright, uint32_t ebottom) { msmfb_pan_update(info, left, top, eright, ebottom, 0, 0); } static void power_on_panel(struct work_struct *work) { struct msmfb_info *msmfb = container_of(work, struct msmfb_info, resume_work); struct msm_panel_data *panel = msmfb->panel; unsigned long irq_flags=0; mutex_lock(&msmfb->panel_init_lock); DLOG(SUSPEND_RESUME, "turning on panel\n"); if (msmfb->sleeping == UPDATING) { wake_lock_timeout(&msmfb->idle_lock, HZ); if (panel->unblank(panel)) { printk(KERN_INFO "msmfb: panel unblank failed," "not starting drawing\n"); goto error; } wake_unlock(&msmfb->idle_lock); spin_lock_irqsave(&msmfb->update_lock, irq_flags); msmfb->sleeping = AWAKE; wake_up(&msmfb->frame_wq); spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); } error: mutex_unlock(&msmfb->panel_init_lock); } static BLOCKING_NOTIFIER_HEAD(display_chain_head); int register_display_notifier(struct notifier_block *nb) { return blocking_notifier_chain_register(&display_chain_head, nb); } static int display_notifier_callback(struct notifier_block *nfb, unsigned long action, void *ignored) { //struct msmfb_info *msm_fb = (struct msmfb_info *)ignored; switch (action) { case NOTIFY_MSM_FB: printk(KERN_DEBUG "NOTIFY_MSM_FB\n"); //msmfb_resume(&msm_fb->early_suspend); break; case NOTIFY_POWER: /* nothing to do */ break; default: printk(KERN_ERR "%s: unknown action in 0x%lx\n", __func__, action); return NOTIFY_BAD; } return NOTIFY_OK; } #ifdef CONFIG_HAS_EARLYSUSPEND /* turn off the panel */ static void msmfb_earlier_suspend(struct early_suspend *h) { struct msmfb_info *msmfb = container_of(h, struct msmfb_info, earlier_suspend); struct msm_panel_data *panel = msmfb->panel; unsigned long irq_flags=0; mutex_lock(&msmfb->panel_init_lock); msmfb->sleeping = SLEEPING; wake_up(&msmfb->frame_wq); spin_lock_irqsave(&msmfb->update_lock, irq_flags); spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); wait_event_timeout(msmfb->frame_wq, msmfb->frame_requested == msmfb->frame_done, HZ/10); #ifndef CONFIG_MSM_MDP40 mdp->dma(mdp, virt_to_phys(msmfb->black), 0, msmfb->fb->var.xres, msmfb->fb->var.yres, 0, 0, NULL, panel->interface_type); mdp->dma_wait(mdp, panel->interface_type); #endif /* turn off the panel */ panel->blank(panel); } static void msmfb_suspend(struct early_suspend *h) { struct msmfb_info *msmfb = container_of(h, struct msmfb_info, early_suspend); struct msm_panel_data *panel = msmfb->panel; /* suspend the panel */ #ifdef CONFIG_FB_MSM_OVERLAY /*check whether overlay done*/ wait_event_interruptible_timeout( overlay_event.event_wait, (overlay_event.waked_up == ~USE_OVERLAY), 10*HZ); /*wait until USE_OVERLAY flag is off and set mdpclk_on as off*/ atomic_set(&mdpclk_on, 0); pr_info("wait event : %X\n", overlay_event.waked_up); #endif panel->suspend(panel); msmfb->fb_resumed = 0; mutex_unlock(&msmfb->panel_init_lock); } static void msmfb_resume_handler(struct early_suspend *h) { struct msmfb_info *msmfb = container_of(h, struct msmfb_info, early_suspend); #ifdef CONFIG_HTC_ONMODE_CHARGING if (msmfb->fb_resumed == 1) { DLOG(SUSPEND_RESUME, "fb is resumed by onchg. skip resume\n"); return; } #endif queue_work(msmfb->resume_workqueue, &msmfb->msmfb_resume_work); wait_event_interruptible_timeout(msmfb->frame_wq, msmfb->fb_resumed==1,HZ/2); } #ifdef CONFIG_HTC_ONMODE_CHARGING static void msmfb_onchg_earlier_suspend(struct early_suspend *h) { struct msmfb_info *msmfb = container_of(h, struct msmfb_info, onchg_earlier_suspend); struct msm_panel_data *panel = msmfb->panel; unsigned long irq_flags=0; mutex_lock(&msmfb->panel_init_lock); msmfb->sleeping = SLEEPING; wake_up(&msmfb->frame_wq); spin_lock_irqsave(&msmfb->update_lock, irq_flags); spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); #ifndef CONFIG_MSM_MDP40 mdp->dma(mdp, virt_to_phys(msmfb->black), 0, msmfb->fb->var.xres, msmfb->fb->var.yres, 0, 0, NULL, panel->interface_type); mdp->dma_wait(mdp, panel->interface_type); #endif wait_event_timeout(msmfb->frame_wq, msmfb->frame_requested == msmfb->frame_done, HZ/10); /* turn off the panel */ panel->blank(panel); } static void msmfb_onchg_suspend(struct early_suspend *h) { struct msmfb_info *msmfb = container_of(h, struct msmfb_info, onchg_suspend); struct msm_panel_data *panel = msmfb->panel; /* suspend the panel */ #ifdef CONFIG_FB_MSM_OVERLAY /*check whether overlay done*/ wait_event_interruptible_timeout( overlay_event.event_wait, (overlay_event.waked_up == ~USE_OVERLAY), 10*HZ); /*wait until USE_OVERLAY flag is off and set mdpclk_on as off*/ atomic_set(&mdpclk_on, 0); pr_info("wait event : %X\n", overlay_event.waked_up); #endif panel->suspend(panel); msmfb->fb_resumed = 0; mutex_unlock(&msmfb->panel_init_lock); } static void msmfb_onchg_resume_handler(struct early_suspend *h) { struct msmfb_info *msmfb = container_of(h, struct msmfb_info, onchg_suspend); queue_work(msmfb->resume_workqueue, &msmfb->msmfb_resume_work); wait_event_interruptible_timeout(msmfb->frame_wq, msmfb->fb_resumed == 1, HZ/2); } #endif static void msmfb_resume(struct work_struct *work) { struct msmfb_info *msmfb = container_of(work, struct msmfb_info, msmfb_resume_work); struct msm_panel_data *panel = msmfb->panel; unsigned long irq_flags=0; if (panel->resume(panel)) { printk(KERN_INFO "msmfb: panel resume failed, not resuming " "fb\n"); return; } spin_lock_irqsave(&msmfb->update_lock, irq_flags); msmfb->frame_requested = msmfb->frame_done = msmfb->update_frame = 0; msmfb->sleeping = WAKING; DLOG(SUSPEND_RESUME, "ready, waiting for full update\n"); spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); msmfb->fb_resumed = 1; wake_up(&msmfb->frame_wq); atomic_set(&mdpclk_on, 1); } #endif static int msmfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { uint32_t size; if ((var->xres != info->var.xres) || (var->yres != info->var.yres) || (var->xoffset != info->var.xoffset) || (mdp->check_output_format(mdp, var->bits_per_pixel)) || (var->grayscale != info->var.grayscale)) return -EINVAL; size = var->xres_virtual * var->yres_virtual * (var->bits_per_pixel >> 3); if (size > info->fix.smem_len) return -EINVAL; return 0; } static int msmfb_set_par(struct fb_info *info) { struct fb_var_screeninfo *var = &info->var; struct fb_fix_screeninfo *fix = &info->fix; /* we only support RGB ordering for now */ if (var->bits_per_pixel == 32 || var->bits_per_pixel == 24) { var->red.offset = 0; var->red.length = 8; var->green.offset = 8; var->green.length = 8; var->blue.offset = 16; var->blue.length = 8; } else if (var->bits_per_pixel == 16) { var->red.offset = 11; var->red.length = 5; var->green.offset = 5; var->green.length = 6; var->blue.offset = 0; var->blue.length = 5; } else return -1; mdp->set_output_format(mdp, var->bits_per_pixel); fix->line_length = var->xres * var->bits_per_pixel / 8; return 0; } int msmfb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) { struct msmfb_info *msmfb = info->par; struct msm_panel_data *panel = msmfb->panel; /* "UPDT" */ if ((panel->caps & MSMFB_CAP_PARTIAL_UPDATES) && (var->reserved[0] == 0x54445055)) { #if 0 printk(KERN_INFO "pan frame %d-%d, rect %d %d %d %d\n", msmfb->frame_requested, msmfb->frame_done, var->reserved[1] & 0xffff, var->reserved[1] >> 16, var->reserved[2] & 0xffff, var->reserved[2] >> 16); #endif msmfb_pan_update(info, var->reserved[1] & 0xffff, var->reserved[1] >> 16, var->reserved[2] & 0xffff, var->reserved[2] >> 16, var->yoffset, 1); } else { msmfb_pan_update(info, 0, 0, info->var.xres, info->var.yres, var->yoffset, 1); } return 0; } static void msmfb_fillrect(struct fb_info *p, const struct fb_fillrect *rect) { cfb_fillrect(p, rect); msmfb_update(p, rect->dx, rect->dy, rect->dx + rect->width, rect->dy + rect->height); } static void msmfb_copyarea(struct fb_info *p, const struct fb_copyarea *area) { cfb_copyarea(p, area); msmfb_update(p, area->dx, area->dy, area->dx + area->width, area->dy + area->height); } static void msmfb_imageblit(struct fb_info *p, const struct fb_image *image) { cfb_imageblit(p, image); msmfb_update(p, image->dx, image->dy, image->dx + image->width, image->dy + image->height); } static int msmfb_blit(struct fb_info *info, void __user *p) { struct mdp_blit_req req; struct mdp_blit_req_list req_list; int i; int ret; if (copy_from_user(&req_list, p, sizeof(req_list))) return -EFAULT; for (i = 0; i < req_list.count; i++) { struct mdp_blit_req_list *list = (struct mdp_blit_req_list *)p; if (copy_from_user(&req, &list->req[i], sizeof(req))) return -EFAULT; ret = mdp->blit(mdp, info, &req); if (ret) return ret; } return 0; } #ifdef CONFIG_FB_MSM_OVERLAY static int msmfb_overlay_get(struct fb_info *info, void __user *p) { struct mdp_overlay req; int ret; if (copy_from_user(&req, p, sizeof(req))) return -EFAULT; ret = mdp->overlay_get(mdp, info, &req); if (ret) { printk(KERN_ERR "%s: ioctl failed \n", __func__); return ret; } if (copy_to_user(p, &req, sizeof(req))) { printk(KERN_ERR "%s: copy2user failed \n", __func__); return -EFAULT; } return 0; } static int msmfb_overlay_set(struct fb_info *info, void __user *p) { struct mdp_overlay req; int ret; if (copy_from_user(&req, p, sizeof(req))) return -EFAULT; printk(KERN_INFO "%s(%d) dst rect info w=%d h=%d x=%d y=%d rotator=%d\n", __func__, __LINE__, req.dst_rect.w, req.dst_rect.h, req.dst_rect.x, req.dst_rect.y, req.user_data[0]); ret = mdp->overlay_set(mdp, info, &req); if (ret) { printk(KERN_ERR "%s:ioctl failed \n", __func__); return ret; } if (copy_to_user(p, &req, sizeof(req))) { printk(KERN_ERR "%s: copy2user failed \n", __func__); return -EFAULT; } return 0; } static int msmfb_overlay_unset(struct fb_info *info, unsigned long *argp) { int ret, ndx; ret = copy_from_user(&ndx, argp, sizeof(ndx)); if (ret) { printk(KERN_ERR "%s:msmfb_overlay_unset ioctl failed \n", __func__); return ret; } return mdp->overlay_unset(mdp, info, ndx); } static int msmfb_overlay_play(struct fb_info *info, unsigned long *argp) { int ret; struct msmfb_overlay_data req; struct file *p_src_file = 0; ret = copy_from_user(&req, argp, sizeof(req)); if (ret) { printk(KERN_ERR "%s:msmfb_overlay_play ioctl failed \n", __func__); return ret; } ret = mdp->overlay_play(mdp, info, &req, &p_src_file); if (p_src_file) put_pmem_file(p_src_file); return ret; } #endif DEFINE_MUTEX(mdp_ppp_lock); static int msmfb_ioctl(struct fb_info *p, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int ret = 0; #if PRINT_BLIT_TIME ktime_t t1, t2; #endif switch (cmd) { case MSMFB_GRP_DISP: mdp->set_grp_disp(mdp, arg); break; case MSMFB_BLIT: #if PRINT_BLIT_TIME t1 = ktime_get(); #endif ret = msmfb_blit(p, argp); if (ret) return ret; #if PRINT_BLIT_TIME t2 = ktime_get(); DLOG(BLIT_TIME, "total %lld\n", ktime_to_ns(t2) - ktime_to_ns(t1)); #endif break; #ifdef CONFIG_FB_MSM_OVERLAY case MSMFB_OVERLAY_GET: ret = msmfb_overlay_get(p, argp); break; case MSMFB_OVERLAY_SET: if(!atomic_read(&mdpclk_on)) { printk(KERN_ERR "MSMFB_OVERLAY_SET during suspend\n"); ret = -EINVAL; } else { mutex_lock(&overlay_event_lock); overlay_event.waked_up = USE_OVERLAY; mutex_unlock(&overlay_event_lock); ret = msmfb_overlay_set(p, argp); } printk(KERN_INFO "MSMFB_OVERLAY_SET ret=%d\n", ret); break; case MSMFB_OVERLAY_UNSET: ret = msmfb_overlay_unset(p, argp); mutex_lock(&overlay_event_lock); overlay_event.waked_up = ~USE_OVERLAY; wake_up(&overlay_event.event_wait); mutex_unlock(&overlay_event_lock); printk(KERN_INFO "MSMFB_OVERLAY_UNSET ret=%d\n", ret); break; case MSMFB_OVERLAY_PLAY: if(!atomic_read(&mdpclk_on)) { printk(KERN_ERR "MSMFB_OVERLAY_PLAY during suspend\n"); ret = -EINVAL; } else ret = msmfb_overlay_play(p, argp); break; #endif default: printk(KERN_INFO "msmfb unknown ioctl: %d\n", cmd); return -EINVAL; } return ret; } static struct fb_ops msmfb_ops = { .owner = THIS_MODULE, .fb_open = msmfb_open, .fb_release = msmfb_release, .fb_check_var = msmfb_check_var, .fb_set_par = msmfb_set_par, .fb_pan_display = msmfb_pan_display, .fb_fillrect = msmfb_fillrect, .fb_copyarea = msmfb_copyarea, .fb_imageblit = msmfb_imageblit, .fb_ioctl = msmfb_ioctl, }; static unsigned PP[16]; #if MSMFB_DEBUG static ssize_t debug_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static ssize_t debug_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { const int debug_bufmax = 4096; static char buffer[4096]; int n = 0; struct msmfb_info *msmfb = (struct msmfb_info *)file->private_data; unsigned long irq_flags=0; spin_lock_irqsave(&msmfb->update_lock, irq_flags); n = scnprintf(buffer, debug_bufmax, "yoffset %d\n", msmfb->yoffset); n += scnprintf(buffer + n, debug_bufmax, "frame_requested %d\n", msmfb->frame_requested); n += scnprintf(buffer + n, debug_bufmax, "frame_done %d\n", msmfb->frame_done); n += scnprintf(buffer + n, debug_bufmax, "sleeping %d\n", msmfb->sleeping); n += scnprintf(buffer + n, debug_bufmax, "update_frame %d\n", msmfb->update_frame); spin_unlock_irqrestore(&msmfb->update_lock, irq_flags); n++; buffer[n] = 0; return simple_read_from_buffer(buf, count, ppos, buffer, n); } static struct file_operations debug_fops = { .read = debug_read, .open = debug_open, }; #endif #define BITS_PER_PIXEL_DEF 32 static void setup_fb_info(struct msmfb_info *msmfb) { struct fb_info *fb_info = msmfb->fb; int r; /* finish setting up the fb_info struct */ strncpy(fb_info->fix.id, "msmfb31_0", 16); fb_info->fix.ypanstep = 1; fb_info->fbops = &msmfb_ops; fb_info->flags = FBINFO_DEFAULT; fb_info->fix.type = FB_TYPE_PACKED_PIXELS; fb_info->fix.visual = FB_VISUAL_TRUECOLOR; fb_info->fix.line_length = msmfb->xres * 2; fb_info->var.xres = msmfb->xres; fb_info->var.yres = msmfb->yres; fb_info->var.width = msmfb->panel->fb_data->width; fb_info->var.height = msmfb->panel->fb_data->height; fb_info->var.xres_virtual = msmfb->xres; fb_info->var.yres_virtual = msmfb->yres * 2; fb_info->var.bits_per_pixel = BITS_PER_PIXEL_DEF; fb_info->var.accel_flags = 0; fb_info->var.reserved[4] = 60; fb_info->var.yoffset = 0; if (msmfb->panel->caps & MSMFB_CAP_PARTIAL_UPDATES) { /* set the param in the fixed screen, so userspace can't * change it. This will be used to check for the * capability. */ /* FIX ME: every panel support partial update? fb_info->fix.reserved[0] = 0x5444; fb_info->fix.reserved[1] = 0x5055; */ /* This preloads the value so that if userspace doesn't * change it, it will be a full update */ fb_info->var.reserved[0] = 0x54445055; fb_info->var.reserved[1] = 0; fb_info->var.reserved[2] = (uint16_t)msmfb->xres | ((uint32_t)msmfb->yres << 16); } fb_info->var.red.offset = 11; fb_info->var.red.length = 5; fb_info->var.red.msb_right = 0; fb_info->var.green.offset = 5; fb_info->var.green.length = 6; fb_info->var.green.msb_right = 0; fb_info->var.blue.offset = 0; fb_info->var.blue.length = 5; fb_info->var.blue.msb_right = 0; mdp->set_output_format(mdp, fb_info->var.bits_per_pixel); mdp->set_panel_size(mdp, msmfb->xres, msmfb->yres); r = fb_alloc_cmap(&fb_info->cmap, 16, 0); fb_info->pseudo_palette = PP; PP[0] = 0; for (r = 1; r < 16; r++) PP[r] = 0xffffffff; /* Jay add, 7/1/09' */ #if (defined(CONFIG_USB_FUNCTION_PROJECTOR) || defined(CONFIG_USB_ANDROID_PROJECTOR)) msm_fb_data.xres = msmfb->xres; msm_fb_data.yres = msmfb->yres; printk(KERN_INFO "setup_fb_info msmfb->xres %d, msmfb->yres %d\n", msmfb->xres,msmfb->yres); #endif } static int setup_fbmem(struct msmfb_info *msmfb, struct platform_device *pdev) { struct fb_info *fb = msmfb->fb; struct resource *resource; unsigned long size = msmfb->xres * msmfb->yres * BYTES_PER_PIXEL(msmfb) * 2; unsigned long resource_size; unsigned char *fbram; /* board file might have attached a resource describing an fb */ resource = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!resource) return -EINVAL; resource_size = resource->end - resource->start + 1; /* check the resource is large enough to fit the fb */ if (resource_size < size) { printk(KERN_ERR "msmfb: allocated resource is too small for " "fb\n"); return -ENOMEM; } fb->fix.smem_start = resource->start; fb->fix.smem_len = resource_size; fbram = ioremap(resource->start, resource_size); if (fbram == 0) { printk(KERN_ERR "msmfb: cannot allocate fbram!\n"); return -ENOMEM; } fb->screen_base = fbram; return 0; } static int msmfb_probe(struct platform_device *pdev) { struct fb_info *fb; struct msmfb_info *msmfb; struct msm_panel_data *panel = pdev->dev.platform_data; int ret; if (!panel) { pr_err("msmfb_probe: no platform data\n"); return -EINVAL; } if (!panel->fb_data) { pr_err("msmfb_probe: no fb_data\n"); return -EINVAL; } fb = framebuffer_alloc(sizeof(struct msmfb_info), &pdev->dev); if (!fb) return -ENOMEM; msmfb = fb->par; msmfb->fb = fb; msmfb->panel = panel; msmfb->xres = panel->fb_data->xres; msmfb->yres = panel->fb_data->yres; ret = setup_fbmem(msmfb, pdev); if (ret) goto error_setup_fbmem; #if (defined(CONFIG_USB_FUNCTION_PROJECTOR) || defined(CONFIG_USB_ANDROID_PROJECTOR)) /* Jay, 8/1/09' */ msmfb_set_var(msmfb->fb->screen_base, 0); #endif setup_fb_info(msmfb); spin_lock_init(&msmfb->update_lock); mutex_init(&msmfb->panel_init_lock); init_waitqueue_head(&msmfb->frame_wq); msmfb->resume_workqueue = create_workqueue("panel_on"); if (msmfb->resume_workqueue == NULL) { printk(KERN_ERR "failed to create panel_on workqueue\n"); ret = -ENOMEM; goto error_create_workqueue; } INIT_WORK(&msmfb->resume_work, power_on_panel); msmfb->black = kzalloc(msmfb->fb->var.bits_per_pixel*msmfb->xres, GFP_KERNEL); wake_lock_init(&msmfb->idle_lock, WAKE_LOCK_IDLE, "msmfb_idle_lock"); #ifdef CONFIG_HAS_EARLYSUSPEND INIT_WORK(&msmfb->msmfb_resume_work, msmfb_resume); msmfb->early_suspend.suspend = msmfb_suspend; msmfb->early_suspend.resume = msmfb_resume_handler; msmfb->early_suspend.level = EARLY_SUSPEND_LEVEL_DISABLE_FB; register_early_suspend(&msmfb->early_suspend); msmfb->earlier_suspend.suspend = msmfb_earlier_suspend; msmfb->earlier_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN; register_early_suspend(&msmfb->earlier_suspend); #ifdef CONFIG_HTC_ONMODE_CHARGING msmfb->onchg_suspend.suspend = msmfb_onchg_suspend; msmfb->onchg_suspend.resume = msmfb_onchg_resume_handler; msmfb->onchg_suspend.level = EARLY_SUSPEND_LEVEL_DISABLE_FB; register_onchg_suspend(&msmfb->onchg_suspend); msmfb->onchg_earlier_suspend.suspend = msmfb_onchg_earlier_suspend; msmfb->onchg_earlier_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN; register_onchg_suspend(&msmfb->onchg_earlier_suspend); #endif #endif #if MSMFB_DEBUG debugfs_create_file("msm_fb", S_IFREG | S_IRUGO, NULL, (void *)fb->par, &debug_fops); #endif printk(KERN_INFO "msmfb_probe() installing %d x %d panel\n", msmfb->xres, msmfb->yres); msmfb->dma_callback.func = msmfb_handle_dma_interrupt; msmfb->vsync_callback.func = msmfb_handle_vsync_interrupt; hrtimer_init(&msmfb->fake_vsync, CLOCK_MONOTONIC, HRTIMER_MODE_REL); msmfb->fake_vsync.function = msmfb_fake_vsync; ret = register_framebuffer(fb); if (ret) goto error_register_framebuffer; msmfb->sleeping = WAKING; #ifdef CONFIG_FB_MSM_OVERLAY /*init wait event*/ init_waitqueue_head(&overlay_event.event_wait); /*init waked_up value*/ overlay_event.waked_up = ~USE_OVERLAY; #endif #ifdef CONFIG_FB_MSM_LOGO if (!load_565rle_image(INIT_IMAGE_FILE)) { /* Flip buffer */ msmfb->update_info.left = 0; msmfb->update_info.top = 0; msmfb->update_info.eright = msmfb->xres; msmfb->update_info.ebottom = msmfb->yres; msmfb_pan_update(msmfb->fb, 0, 0, msmfb->xres, msmfb->yres, 0, 1); } #endif /* Jay, 29/12/08' */ display_notifier(display_notifier_callback, NOTIFY_MSM_FB); return 0; error_register_framebuffer: wake_lock_destroy(&msmfb->idle_lock); destroy_workqueue(msmfb->resume_workqueue); error_create_workqueue: iounmap(fb->screen_base); error_setup_fbmem: framebuffer_release(msmfb->fb); return ret; } static void msmfb_shutdown(struct platform_device *pdev) { struct msm_panel_data *panel = pdev->dev.platform_data; struct fb_info *fb; struct msmfb_info *msmfb; printk(KERN_INFO "%s\n", __func__); fb = registered_fb[0]; if (!fb) { printk(KERN_ERR "fb0 unavailable.\n"); return; } msmfb = fb->par; mdp->dma(mdp, virt_to_phys(msmfb->black), 0, msmfb->fb->var.xres, msmfb->fb->var.yres, 0, 0, NULL, panel->interface_type); if (panel->blank) panel->blank(panel); if (panel->shutdown) panel->shutdown(panel); } static struct platform_driver msm_panel_driver = { /* need to write remove */ .probe = msmfb_probe, .shutdown = msmfb_shutdown, .driver = {.name = "msm_panel"}, }; static int msmfb_add_mdp_device(struct device *dev, struct class_interface *class_intf) { /* might need locking if mulitple mdp devices */ if (mdp) return 0; mdp = container_of(dev, struct mdp_device, dev); return platform_driver_register(&msm_panel_driver); } static void msmfb_remove_mdp_device(struct device *dev, struct class_interface *class_intf) { /* might need locking if mulitple mdp devices */ if (dev != &mdp->dev) return; platform_driver_unregister(&msm_panel_driver); mdp = NULL; } static struct class_interface msm_fb_interface = { .add_dev = &msmfb_add_mdp_device, .remove_dev = &msmfb_remove_mdp_device, }; static int __init msmfb_init(void) { return register_mdp_client(&msm_fb_interface); } module_init(msmfb_init);
NooNameR/k3_bravo
drivers3/video/msm/msm_fb.c
C
gpl-2.0
35,380
/* * Copyright(C) NXP Semiconductors, 2012 * All rights reserved. * * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * LPC products. This software is supplied "AS IS" without any warranties of * any kind, and NXP Semiconductors and its licensor disclaim any and * all warranties, express or implied, including all implied warranties of * merchantability, fitness for a particular purpose and non-infringement of * intellectual property rights. NXP Semiconductors assumes no responsibility * or liability for the use of the software, conveys no license or rights under any * patent, copyright, mask work right, or any other intellectual property rights in * or to any products. NXP Semiconductors reserves the right to make changes * in the software without notification. NXP Semiconductors also makes no * representation or warranty that such application will be suitable for the * specified use without further testing or modification. * * Permission to use, copy, modify, and distribute this software and its * documentation is hereby granted, under NXP Semiconductors' and its * licensor's relevant copyrights in the software, without fee, provided that it * is used in conjunction with NXP Semiconductors microcontrollers. This * copyright, permission, and disclaimer notice must appear in all copies of * this code. */ #include "board.h" #include "string.h" #include "lpc_phy_smsc87x0.c" #include "retarget.c" /** @ingroup BOARD_NGX_XPLORER_18304330 * @{ */ void Board_UART_Init(LPC_USART_Type *UARTx) { if (UARTx == LPC_USART0) { Chip_SCU_PinMux(0x6, 4, MD_PDN, FUNC2); /* P6.5 : UART0_TXD */ Chip_SCU_PinMux(0x6, 5, MD_PLN | MD_EZI | MD_ZI, FUNC2);/* P6.4 : UART0_RXD */ } else if (UARTx == LPC_UART1) { Chip_SCU_PinMux(0x1, 13, MD_PDN, FUNC2); /* P1.13 : UART1_TXD */ Chip_SCU_PinMux(0x1, 14, MD_PLN | MD_EZI | MD_ZI, FUNC2);/* P1.14 : UART1_RX */ } } /* Initialize debug output via UART for board */ void Board_Debug_Init(void) { #if defined(DEBUG_UART) Board_UART_Init(DEBUG_UART); Chip_UART_Init(DEBUG_UART); Chip_UART_SetBaud(DEBUG_UART, 115200); Chip_UART_ConfigData(DEBUG_UART, UART_DATABIT_8, UART_PARITY_NONE, UART_STOPBIT_1); /* Enable UART Transmit */ Chip_UART_TxCmd(DEBUG_UART, ENABLE); #endif } /* Sends a character on the UART */ void Board_UARTPutChar(char ch) { #if defined(DEBUG_UART) while (Chip_UART_SendByte(DEBUG_UART, (uint8_t) ch) == ERROR) {} #endif } /* Gets a character from the UART, returns EOF if no character is ready */ int Board_UARTGetChar(void) { #if defined(DEBUG_UART) uint8_t data; if (Chip_UART_ReceiveByte(DEBUG_UART, &data) == SUCCESS) { return (int) data; } #endif return EOF; } /* Outputs a string on the debug UART */ void Board_UARTPutSTR(char *str) { #if defined(DEBUG_UART) while (*str != '\0') { Board_UARTPutChar(*str++); } #endif } void Board_LED_Init() { /* P2.12 : LED D2 as output */ Chip_GPIO_WriteDirBit(1, 12, true); /* P2.11 : LED D3 as output */ Chip_GPIO_WriteDirBit(1, 11, true); /* Set initial states to off (true to disable) */ Chip_GPIO_WritePortBit(1, 12, (bool) true); Chip_GPIO_WritePortBit(1, 11, (bool) true); } void Board_LED_Set(uint8_t LEDNumber, bool On) { if (LEDNumber == 0) { Chip_GPIO_WritePortBit(1, 12, (bool) !On); } else if (LEDNumber == 1) { Chip_GPIO_WritePortBit(1, 11, (bool) !On); } } bool Board_LED_Test(uint8_t LEDNumber) { if (LEDNumber == 0) { return (bool) !Chip_GPIO_ReadPortBit(1, 12); } else if (LEDNumber == 1) { return (bool) !Chip_GPIO_ReadPortBit(1, 11); } return false; } void Board_Buttons_Init(void) // FIXME not functional ATM { Chip_SCU_PinMux(0x2, 7, MD_PUP | MD_EZI | MD_ZI, FUNC0); // P2_7 as GPIO0[7] Chip_GPIO_WriteDirBit(BUTTONS_BUTTON1_GPIO_PORT_NUM, (1 << BUTTONS_BUTTON1_GPIO_BIT_NUM), false); // input } uint32_t Buttons_GetStatus(void) { uint8_t ret = NO_BUTTON_PRESSED; if (Chip_GPIO_ReadPortBit(BUTTONS_BUTTON1_GPIO_PORT_NUM, BUTTONS_BUTTON1_GPIO_BIT_NUM) == 0) { ret |= BUTTONS_BUTTON1; } return ret; } void Board_Joystick_Init(void) {} uint8_t Joystick_GetStatus(void) { return NO_BUTTON_PRESSED; } /*!< System Clock Frequency (Core Clock)*/ uint32_t SystemCoreClock; /* Update system core clock rate, should be called if the system has a clock rate change */ void SystemCoreClockUpdate(void) { /* CPU core speed */ SystemCoreClock = Chip_Clock_GetRate(CLK_MX_MXCORE); } /* Returns the MAC address assigned to this board */ void Board_ENET_GetMacADDR(uint8_t *mcaddr) { uint8_t boardmac[] = {0x00, 0x60, 0x37, 0x12, 0x34, 0x56}; memcpy(mcaddr, boardmac, 6); } /* Set up and initialize all required blocks and functions related to the board hardware */ void Board_Init(void) { /* Sets up DEBUG UART */ DEBUGINIT(); /* Updates SystemCoreClock global var with current clock speed */ SystemCoreClockUpdate(); /* Initializes GPIO */ Chip_GPIO_Init(); /* Setup GPIOs for USB demos */ Chip_SCU_PinMux(0x2, 6, (MD_PUP | MD_EZI), FUNC4); /* P2_6 USB1_PWR_EN, USB1 VBus function */ Chip_SCU_PinMux(0x2, 5, (MD_PLN | MD_EZI | MD_ZI), FUNC2); /* P2_5 USB1_VBUS, MUST CONFIGURE THIS SIGNAL FOR USB1 NORMAL OPERATION */ Chip_SCU_PinMux(0x1, 7, (MD_PUP | MD_EZI), FUNC4); /* P1_7 USB0_PWR_EN, USB0 VBus function Xplorer */ Chip_GPIO_WriteDirBit(5, 6, true); /* GPIO5[6] = USB1_PWR_EN */ Chip_GPIO_WritePortBit(5, 6, true); /* GPIO5[6] output high */ } void Board_I2C_Init(LPC_I2C_Type *I2Cx) { if (I2Cx == LPC_I2C1) { /* Configure pin function for I2C1*/ Chip_SCU_PinMux(0x2, 3, MD_ZI | MD_EZI, FUNC1); /* P2.3 : I2C1_SDA */ Chip_SCU_PinMux(0x2, 4, MD_ZI | MD_EZI, FUNC1); /* P2.4 : I2C1_SCL */ } } void GPIO0_IRQHandler(void) { static bool On; if (Chip_GPIO_IntGetStatus(0, 0, 0)) { Chip_GPIO_IntClear(0, 0); On = (bool) !On; Board_LED_Set(1, On); } } void Board_GPIO_Int_Init() { Chip_SCU_PinMux(0xF, 9, (MD_PLN | MD_EZI | MD_ZI), FUNC0); /* PF.9 : POTI button */ Chip_GPIO_WriteDirBit(7, 23, false); /* PF.9 -> GPIO7[23] : input */ Chip_SCU_GPIOIntPinSel(0, 7, 23); Chip_GPIO_IntCmd(0, 0, IP_GPIOPININT_FALLING_EDGE); /* Configure GPIO0[7] to interrupt pin (SW2 switch) */ NVIC_EnableIRQ(PIN_INT0_IRQn); /* enable GPIO interrupt 0 */ } void Board_SDMMC_Init(void) { Chip_SCU_PinMux(0x1, 9, MD_PLN_FAST, FUNC7); /* P1.9 connected to SDIO_D0 */ Chip_SCU_PinMux(0x1, 10, MD_PLN_FAST, FUNC7); /* P1.10 connected to SDIO_D1 */ Chip_SCU_PinMux(0x1, 11, MD_PLN_FAST, FUNC7); /* P1.11 connected to SDIO_D2 */ Chip_SCU_PinMux(0x1, 12, MD_PLN_FAST, FUNC7); /* P1.12 connected to SDIO_D3 */ Chip_SCU_PinMux(PINMUX_CLK, 2, MD_PLN | MD_EZI, FUNC4); /* CLK2 connected to SDIO_CLK */ Chip_SCU_PinMux(0x1, 6, MD_PLN_FAST, FUNC7); /* P1.6 connected to SDIO_CMD */ } void Board_SSP_Init(LPC_SSP_Type *SSPx) { if (SSPx == LPC_SSP1) { /* Set up clock and power for SSP1 module */ /* Configure SSP1 pins*/ /* SCLK comes out pin CLK0 */ Chip_SCU_PinMux(PINMUX_CLK, 0, MD_PLN_FAST, FUNC6); /* CLK0 connected to CLK func6=SSP1 CLK1 */ Chip_SCU_PinMux(0x1, 5, MD_PLN_FAST, FUNC5); /* P1.5 connected to nCS func5=SSP1 SSEL1 */ Chip_SCU_PinMux(0x1, 3, MD_PLN | MD_EZI | MD_ZI, FUNC5);/* P1.3 connected to SO func5=SSP1 MISO1 */ Chip_SCU_PinMux(0x1, 4, MD_PLN | MD_EZI | MD_ZI, FUNC5);/* P1.4 connected to nSI func5=SSP1 MOSI1 */ Chip_Clock_EnableOpts(CLK_MX_SSP1, true, true, 1); } else { return; } } /* System Register Data Set */ uint16_t UDA_sys_regs_dat[] = { UDA1380_REG_EVALCLK_DEFAULT_VALUE, UDA1380_REG_I2S_DEFAULT_VALUE, UDA1380_REG_PWRCTRL_DEFAULT_VALUE, UDA1380_REG_ANAMIX_DEFAULT_VALUE, UDA1380_REG_HEADAMP_DEFAULT_VALUE }; /* System Register Data Set */ uint16_t UDA_interfil_regs_dat[] = { UDA1380_REG_MSTRVOL_DEFAULT_VALUE, UDA1380_REG_MIXVOL_DEFAULT_VALUE, UDA1380_REG_MODEBBT_DEFAULT_VALUE, UDA1380_REG_MSTRMUTE_DEFAULT_VALUE, UDA1380_REG_MIXSDO_DEFAULT_VALUE }; /* decimator Register Data Set */ uint16_t UDA_decimator_regs_dat[] = { UDA1380_REG_DECVOL_DEFAULT_VALUE, UDA1380_REG_PGA_DEFAULT_VALUE, UDA1380_REG_ADC_DEFAULT_VALUE, UDA1380_REG_AGC_DEFAULT_VALUE }; static void delay(uint32_t i) { while (i--) {} } static void UDA_Reg_write(UDA1380_REG reg, unsigned short value, I2C_M_SETUP_Type *I2C_Config) { I2C_Config->tx_data[0] = reg; I2C_Config->tx_data[1] = value >> 8; I2C_Config->tx_data[2] = value & 0xFF; Chip_I2C_MasterTransmitData(LPC_I2C0, I2C_Config, I2C_TRANSFER_POLLING); delay(10000); } static uint16_t UDA_Reg_read(UDA1380_REG reg) { uint8_t rx_data[2]; Chip_I2C_MasterReadReg(LPC_I2C0, I2CDEV_UDA1380_ADDR, reg, rx_data, 2); return rx_data[0] << 8 | rx_data[1]; } static Status UDA1380_init(I2C_M_SETUP_Type *I2C_Config, Board_Audio_Input_Sel_Type audio_in_sel) { uint16_t temp; uint8_t i; /* Reset UDA1380 on board NGX Xplorer */ Chip_SCU_PinMux(0x2, 10, MD_PUP, FUNC0); Chip_GPIO_WriteDirBit(0, 14, true); Chip_GPIO_WritePortBit(0, 14, true); // delay 1us delay(100000); Chip_GPIO_WritePortBit(0, 14, false); delay(100000); for (i = 0; i < 5; i++) { UDA_Reg_write((UDA1380_REG) (UDA_EVALM_CLK + i), UDA_sys_regs_dat[i], I2C_Config); temp = UDA_Reg_read((UDA1380_REG) (UDA_EVALM_CLK + i)); if (temp != UDA_sys_regs_dat[i]) { return ERROR; } } /* interfilter regs init */ for (i = 0; i < 5; i++) { UDA_Reg_write((UDA1380_REG) (UDA_MASTER_VOL_CTRL + i), UDA_interfil_regs_dat[i], I2C_Config); temp = UDA_Reg_read((UDA1380_REG) (UDA_MASTER_VOL_CTRL + i)); if (temp != UDA_interfil_regs_dat[i]) { return ERROR; } } /* decimator regs init */ for (i = 0; i < 4; i++) { UDA_Reg_write((UDA1380_REG) (UDA_DEC_VOL_CTRL + i), UDA_decimator_regs_dat[i], I2C_Config); temp = UDA_Reg_read((UDA1380_REG) (UDA_DEC_VOL_CTRL + i)); if (temp != UDA_decimator_regs_dat[i]) { return ERROR; } } if (audio_in_sel == MCB_18XX_AUDIO_MIC_SELECT) { /* Disable Power On for ADCR, PGAR, PGAL to get mic sound more clearly */ UDA_Reg_write((UDA1380_REG) (UDA_POWER_CTRL), UDA1380_REG_PWRCTRL_DEFAULT_VALUE & (~(0x0B)), I2C_Config); temp = UDA_Reg_read((UDA1380_REG) (UDA_ADC_CTRL)); if (temp != (UDA1380_REG_ADC_DEFAULT_VALUE | MCB_18XX_AUDIO_MIC_SELECT)) { return ERROR; } UDA_Reg_write((UDA1380_REG) (UDA_ADC_CTRL), UDA1380_REG_ADC_DEFAULT_VALUE | MCB_18XX_AUDIO_MIC_SELECT, I2C_Config); temp = UDA_Reg_read((UDA1380_REG) (UDA_ADC_CTRL)); if (temp != (UDA1380_REG_ADC_DEFAULT_VALUE | MCB_18XX_AUDIO_MIC_SELECT)) { return ERROR; } } return SUCCESS; } void Board_Audio_Init(LPC_I2S_Type *I2Sx, Board_Audio_Input_Sel_Type audio_in_sel) { uint8_t uda1380_tx_data_buf[3]; Chip_I2S_Audio_Format_Type I2S_Config; I2C_M_SETUP_Type I2C_Config; I2C_Config.sl_addr7bit = I2CDEV_UDA1380_ADDR; I2C_Config.retransmissions_max = 5; I2C_Config.tx_length = 3; I2C_Config.tx_data = uda1380_tx_data_buf; I2C_Config.rx_length = 0; I2C_Config.rx_data = NULL; /* Initialize I2C peripheral ------------------------------------*/ /* Init I2C */ Chip_I2C_Init(LPC_I2C0); Chip_I2C_SetClockRate(LPC_I2C0, 100000); I2S_Config.SampleRate = 48000; I2S_Config.ChannelNumber = 2; /* 1 is mono, 2 is stereo */ I2S_Config.WordWidth = 16; /* 8, 16 or 32 bits */ Chip_I2S_Init(LPC_I2S0); Chip_I2S_Config(LPC_I2S0, I2S_TX_MODE, &I2S_Config); /* Enable Slave I2C operation */ Chip_I2C_Cmd(LPC_I2C0, I2C_MASTER_MODE, ENABLE); /* Init UDA1380 CODEC */ while (UDA1380_init(&I2C_Config, audio_in_sel) != SUCCESS) {} } /* FIXME Should we remove this function? */ void Serial_CreateStream(void *Stream) {} /** * @} */
poranmeloge/test-github
stm32_rtt_wifi/bsp/xplorer4330/libraries/lpc_board/boards_18xx_43xx/ngx_xplorer_18304330/board_ngx_xplorer_18304330.c
C
gpl-2.0
11,657
/* Copyright (C) 1991, 1997 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <sgtty.h> /* Set the terminal parameters associated with FD to *PARAMS. */ int stty (fd, params) int fd; const struct sgttyb *params; { return ioctl (fd, TIOCSETP, (void *) params); }
pirix/glibc-pirix
sysdeps/unix/bsd/stty.c
C
gpl-2.0
1,016
/****************************************************************************** * * Name: actables.h - ACPI table management * $Revision: 32 $ * *****************************************************************************/ /* * Copyright (C) 2000, 2001 R. Byron Moore * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __ACTABLES_H__ #define __ACTABLES_H__ /* Used in Acpi_tb_map_acpi_table for size parameter if table header is to be used */ #define SIZE_IN_HEADER 0 acpi_status acpi_tb_handle_to_object ( u16 table_id, acpi_table_desc **table_desc); /* * tbconvrt - Table conversion routines */ acpi_status acpi_tb_convert_to_xsdt ( acpi_table_desc *table_info, u32 *number_of_tables); acpi_status acpi_tb_convert_table_fadt ( void); acpi_status acpi_tb_build_common_facs ( acpi_table_desc *table_info); u32 acpi_tb_get_table_count ( RSDP_DESCRIPTOR *RSDP, acpi_table_header *RSDT); /* * tbget - Table "get" routines */ acpi_status acpi_tb_get_table_ptr ( acpi_table_type table_type, u32 instance, acpi_table_header **table_ptr_loc); acpi_status acpi_tb_get_table ( ACPI_PHYSICAL_ADDRESS physical_address, acpi_table_header *buffer_ptr, acpi_table_desc *table_info); acpi_status acpi_tb_verify_rsdp ( ACPI_PHYSICAL_ADDRESS RSDP_physical_address); acpi_status acpi_tb_get_table_facs ( acpi_table_header *buffer_ptr, acpi_table_desc *table_info); ACPI_PHYSICAL_ADDRESS acpi_tb_get_rsdt_address ( void); acpi_status acpi_tb_validate_rsdt ( acpi_table_header *table_ptr); acpi_status acpi_tb_get_table_pointer ( ACPI_PHYSICAL_ADDRESS physical_address, u32 flags, u32 *size, acpi_table_header **table_ptr); /* * tbgetall - Get all firmware ACPI tables */ acpi_status acpi_tb_get_all_tables ( u32 number_of_tables, acpi_table_header *buffer_ptr); /* * tbinstall - Table installation */ acpi_status acpi_tb_install_table ( acpi_table_header *table_ptr, acpi_table_desc *table_info); acpi_status acpi_tb_recognize_table ( acpi_table_header *table_ptr, acpi_table_desc *table_info); acpi_status acpi_tb_init_table_descriptor ( acpi_table_type table_type, acpi_table_desc *table_info); /* * tbremove - Table removal and deletion */ void acpi_tb_delete_acpi_tables ( void); void acpi_tb_delete_acpi_table ( acpi_table_type type); void acpi_tb_delete_single_table ( acpi_table_desc *table_desc); acpi_table_desc * acpi_tb_uninstall_table ( acpi_table_desc *table_desc); void acpi_tb_free_acpi_tables_of_type ( acpi_table_desc *table_info); /* * tbrsd - RSDP, RSDT utilities */ acpi_status acpi_tb_get_table_rsdt ( u32 *number_of_tables); u8 * acpi_tb_scan_memory_for_rsdp ( u8 *start_address, u32 length); acpi_status acpi_tb_find_rsdp ( acpi_table_desc *table_info, u32 flags); /* * tbutils - common table utilities */ acpi_status acpi_tb_map_acpi_table ( ACPI_PHYSICAL_ADDRESS physical_address, u32 *size, acpi_table_header **logical_address); acpi_status acpi_tb_verify_table_checksum ( acpi_table_header *table_header); u8 acpi_tb_checksum ( void *buffer, u32 length); acpi_status acpi_tb_validate_table_header ( acpi_table_header *table_header); #endif /* __ACTABLES_H__ */
robacklin/celinux
drivers/acpi/include/actables.h
C
gpl-2.0
4,357
<div class="slider-parent"> <div class="slider-wrapper theme-default container"> <div class="ribbon"></div> <div id="slider" class="nivoSlider"> <a href='#'><img src='<?php echo get_template_directory_uri()."/defaults/images/dimg9.jpg"; ?>' title='#caption_1'></a> <a href='#'><img src='<?php echo get_template_directory_uri()."/defaults/images/dimg8.jpg"; ?>' title='#caption_2'></a> </div><!--#slider--> <div id='caption_1' class='nivo-html-caption'><div class='nivocapper'> <a href='#'><div class='slide-title'><span>Fully Responsive Theme</span></div></a> <div class='slide-description'>Resize your Browser to see the Effect</div> </div></div> <div id='caption_2' class='nivo-html-caption'><div class='nivocapper'> <a href='#'><div class='slide-title'><span>Parallax Effect</span></div></a> <div class='slide-description'>Scroll and Notice the Header Image</div> </div></div> </div> </div>
Yacenko/Solaris
wp-content/themes/tmp/defaults/slider.php
PHP
gpl-2.0
980
/****************************************************************************** * * Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ #ifndef __RTL8712_DEBUGCTRL_BITDEF_H__ #define __RTL8712_DEBUGCTRL_BITDEF_H__ /* */ #define _BIST_RST BIT(0) /* */ #define _LMS_MSK 0x03 /* */ #define _OVSEL_MSK 0x0600 #define _OVSEL_SHT 9 #define _WDGCLR BIT(8) #define _WDGEN_MSK 0x00FF #define _WDGEN_SHT 0 /* */ #define _TXTIMER_MSK 0xF000 #define _TXTIMER_SHT 12 #define _TXNUM_MSK 0x0F00 #define _TXNUM_SHT 8 #define _RXTIMER_MSK 0x00F0 #define _RXTIMER_SHT 4 #define _RXNUM_MSK 0x000F #define _RXNUM_SHT 0 /* */ /* */ #define _TURN1 BIT(0) /* */ /* */ #define _LOCKFLAG1_MSK 0x03 #endif /* */
holyangel/LGE_G3
drivers/staging/rtl8712/rtl8712_debugctrl_bitdef.h
C
gpl-2.0
1,567
#.rst: # FindFLTK2 # --------- # # Find the native FLTK2 includes and library # # The following settings are defined # # :: # # FLTK2_FLUID_EXECUTABLE, where to find the Fluid tool # FLTK2_WRAP_UI, This enables the FLTK2_WRAP_UI command # FLTK2_INCLUDE_DIR, where to find include files # FLTK2_LIBRARIES, list of fltk2 libraries # FLTK2_FOUND, Don't use FLTK2 if false. # # The following settings should not be used in general. # # :: # # FLTK2_BASE_LIBRARY = the full path to fltk2.lib # FLTK2_GL_LIBRARY = the full path to fltk2_gl.lib # FLTK2_IMAGES_LIBRARY = the full path to fltk2_images.lib #============================================================================= # Copyright 2007-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) set (FLTK2_DIR $ENV{FLTK2_DIR} ) # Platform dependent libraries required by FLTK2 if(WIN32) if(NOT CYGWIN) if(BORLAND) set( FLTK2_PLATFORM_DEPENDENT_LIBS import32 ) else() set( FLTK2_PLATFORM_DEPENDENT_LIBS wsock32 comctl32 ) endif() endif() endif() if(UNIX) include(${CMAKE_ROOT}/Modules/FindX11.cmake) set( FLTK2_PLATFORM_DEPENDENT_LIBS ${X11_LIBRARIES} -lm) endif() if(APPLE) set( FLTK2_PLATFORM_DEPENDENT_LIBS "-framework Carbon -framework Cocoa -framework ApplicationServices -lz") endif() # If FLTK2_INCLUDE_DIR is already defined we assign its value to FLTK2_DIR if(FLTK2_INCLUDE_DIR) set(FLTK2_DIR ${FLTK2_INCLUDE_DIR}) else() set(FLTK2_INCLUDE_DIR ${FLTK2_DIR}) endif() # If FLTK2 has been built using CMake we try to find everything directly set(FLTK2_DIR_STRING "directory containing FLTK2Config.cmake. This is either the root of the build tree, or PREFIX/lib/fltk for an installation.") # Search only if the location is not already known. if(NOT FLTK2_DIR) # Get the system search path as a list. file(TO_CMAKE_PATH "$ENV{PATH}" FLTK2_DIR_SEARCH2) # Construct a set of paths relative to the system search path. set(FLTK2_DIR_SEARCH "") foreach(dir ${FLTK2_DIR_SEARCH2}) set(FLTK2_DIR_SEARCH ${FLTK2_DIR_SEARCH} "${dir}/../lib/fltk") endforeach() string(REPLACE "//" "/" FLTK2_DIR_SEARCH "${FLTK2_DIR_SEARCH}") # # Look for an installation or build tree. # find_path(FLTK2_DIR FLTK2Config.cmake # Look for an environment variable FLTK2_DIR. ENV FLTK2_DIR # Look in places relative to the system executable search path. ${FLTK2_DIR_SEARCH} # Look in standard UNIX install locations. /usr/local/lib/fltk2 /usr/lib/fltk2 /usr/local/fltk2 /usr/X11R6/include # Help the user find it if we cannot. DOC "The ${FLTK2_DIR_STRING}" ) if(NOT FLTK2_DIR) find_path(FLTK2_DIR fltk/run.h ${FLTK2_INCLUDE_SEARCH_PATH}) endif() endif() # If FLTK2 was found, load the configuration file to get the rest of the # settings. if(FLTK2_DIR) # Check if FLTK2 was built using CMake if(EXISTS ${FLTK2_DIR}/FLTK2Config.cmake) set(FLTK2_BUILT_WITH_CMAKE 1) endif() if(FLTK2_BUILT_WITH_CMAKE) set(FLTK2_FOUND 1) include(${FLTK2_DIR}/FLTK2Config.cmake) # Fluid if(FLUID_COMMAND) set(FLTK2_FLUID_EXECUTABLE ${FLUID_COMMAND} CACHE FILEPATH "Fluid executable") else() find_program(FLTK2_FLUID_EXECUTABLE fluid2 PATHS ${FLTK2_EXECUTABLE_DIRS} ${FLTK2_EXECUTABLE_DIRS}/RelWithDebInfo ${FLTK2_EXECUTABLE_DIRS}/Debug ${FLTK2_EXECUTABLE_DIRS}/Release NO_SYSTEM_PATH) endif() mark_as_advanced(FLTK2_FLUID_EXECUTABLE) set( FLTK_FLUID_EXECUTABLE ${FLTK2_FLUID_EXECUTABLE} ) set(FLTK2_INCLUDE_DIR ${FLTK2_DIR}) link_directories(${FLTK2_LIBRARY_DIRS}) set(FLTK2_BASE_LIBRARY fltk2) set(FLTK2_GL_LIBRARY fltk2_gl) set(FLTK2_IMAGES_LIBRARY fltk2_images) # Add the extra libraries load_cache(${FLTK2_DIR} READ_WITH_PREFIX FL FLTK2_USE_SYSTEM_JPEG FL FLTK2_USE_SYSTEM_PNG FL FLTK2_USE_SYSTEM_ZLIB ) set(FLTK2_IMAGES_LIBS "") if(FLFLTK2_USE_SYSTEM_JPEG) set(FLTK2_IMAGES_LIBS ${FLTK2_IMAGES_LIBS} fltk2_jpeg) endif() if(FLFLTK2_USE_SYSTEM_PNG) set(FLTK2_IMAGES_LIBS ${FLTK2_IMAGES_LIBS} fltk2_png) endif() if(FLFLTK2_USE_SYSTEM_ZLIB) set(FLTK2_IMAGES_LIBS ${FLTK2_IMAGES_LIBS} fltk2_zlib) endif() set(FLTK2_IMAGES_LIBS "${FLTK2_IMAGES_LIBS}" CACHE INTERNAL "Extra libraries for fltk2_images library.") else() # if FLTK2 was not built using CMake # Find fluid executable. find_program(FLTK2_FLUID_EXECUTABLE fluid2 ${FLTK2_INCLUDE_DIR}/fluid) # Use location of fluid to help find everything else. set(FLTK2_INCLUDE_SEARCH_PATH "") set(FLTK2_LIBRARY_SEARCH_PATH "") if(FLTK2_FLUID_EXECUTABLE) set( FLTK_FLUID_EXECUTABLE ${FLTK2_FLUID_EXECUTABLE} ) get_filename_component(FLTK2_BIN_DIR "${FLTK2_FLUID_EXECUTABLE}" PATH) set(FLTK2_INCLUDE_SEARCH_PATH ${FLTK2_INCLUDE_SEARCH_PATH} ${FLTK2_BIN_DIR}/../include ${FLTK2_BIN_DIR}/..) set(FLTK2_LIBRARY_SEARCH_PATH ${FLTK2_LIBRARY_SEARCH_PATH} ${FLTK2_BIN_DIR}/../lib) set(FLTK2_WRAP_UI 1) endif() set(FLTK2_INCLUDE_SEARCH_PATH ${FLTK2_INCLUDE_SEARCH_PATH} /usr/local/fltk2 /usr/X11R6/include ) find_path(FLTK2_INCLUDE_DIR fltk/run.h ${FLTK2_INCLUDE_SEARCH_PATH}) set(FLTK2_LIBRARY_SEARCH_PATH ${FLTK2_LIBRARY_SEARCH_PATH} /usr/local/fltk2/lib /usr/X11R6/lib ${FLTK2_INCLUDE_DIR}/lib ) find_library(FLTK2_BASE_LIBRARY NAMES fltk2 PATHS ${FLTK2_LIBRARY_SEARCH_PATH}) find_library(FLTK2_GL_LIBRARY NAMES fltk2_gl PATHS ${FLTK2_LIBRARY_SEARCH_PATH}) find_library(FLTK2_IMAGES_LIBRARY NAMES fltk2_images PATHS ${FLTK2_LIBRARY_SEARCH_PATH}) # Find the extra libraries needed for the fltk_images library. if(UNIX) find_program(FLTK2_CONFIG_SCRIPT fltk2-config PATHS ${FLTK2_BIN_DIR}) if(FLTK2_CONFIG_SCRIPT) exec_program(${FLTK2_CONFIG_SCRIPT} ARGS --use-images --ldflags OUTPUT_VARIABLE FLTK2_IMAGES_LDFLAGS) set(FLTK2_LIBS_EXTRACT_REGEX ".*-lfltk2_images (.*) -lfltk2.*") if("${FLTK2_IMAGES_LDFLAGS}" MATCHES "${FLTK2_LIBS_EXTRACT_REGEX}") string(REGEX REPLACE " +" ";" FLTK2_IMAGES_LIBS "${CMAKE_MATCH_1}") # The EXEC_PROGRAM will not be inherited into subdirectories from # the file that originally included this module. Save the answer. set(FLTK2_IMAGES_LIBS "${FLTK2_IMAGES_LIBS}" CACHE INTERNAL "Extra libraries for fltk_images library.") endif() endif() endif() endif() endif() set(FLTK2_FOUND 1) foreach(var FLTK2_FLUID_EXECUTABLE FLTK2_INCLUDE_DIR FLTK2_BASE_LIBRARY FLTK2_GL_LIBRARY FLTK2_IMAGES_LIBRARY) if(NOT ${var}) message( STATUS "${var} not found" ) set(FLTK2_FOUND 0) endif() endforeach() if(FLTK2_FOUND) set(FLTK2_LIBRARIES ${FLTK2_IMAGES_LIBRARY} ${FLTK2_IMAGES_LIBS} ${FLTK2_BASE_LIBRARY} ${FLTK2_GL_LIBRARY} ) if(APPLE) set(FLTK2_LIBRARIES ${FLTK2_PLATFORM_DEPENDENT_LIBS} ${FLTK2_LIBRARIES}) else() set(FLTK2_LIBRARIES ${FLTK2_LIBRARIES} ${FLTK2_PLATFORM_DEPENDENT_LIBS}) endif() # The following deprecated settings are for compatibility with CMake 1.4 set (HAS_FLTK2 ${FLTK2_FOUND}) set (FLTK2_INCLUDE_PATH ${FLTK2_INCLUDE_DIR}) set (FLTK2_FLUID_EXE ${FLTK2_FLUID_EXECUTABLE}) set (FLTK2_LIBRARY ${FLTK2_LIBRARIES}) else() # make FIND_PACKAGE friendly if(NOT FLTK2_FIND_QUIETLY) if(FLTK2_FIND_REQUIRED) message(FATAL_ERROR "FLTK2 required, please specify its location with FLTK2_DIR.") else() message(STATUS "FLTK2 was not found.") endif() endif() endif()
xiaohaidao007/pandoraBox-SDK-mt7620
staging_dir/host/share/cmake-3.6/Modules/FindFLTK2.cmake
CMake
gpl-2.0
8,162
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.hotspot.aarch64; import org.graalvm.compiler.core.aarch64.AArch64LIRKindTool; import org.graalvm.compiler.core.common.LIRKind; import org.graalvm.compiler.hotspot.nodes.type.HotSpotLIRKindTool; import jdk.vm.ci.aarch64.AArch64Kind; public class AArch64HotSpotLIRKindTool extends AArch64LIRKindTool implements HotSpotLIRKindTool { @Override public LIRKind getNarrowOopKind() { return LIRKind.reference(AArch64Kind.DWORD); } @Override public LIRKind getNarrowPointerKind() { return LIRKind.value(AArch64Kind.DWORD); } }
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot.aarch64/src/org/graalvm/compiler/hotspot/aarch64/AArch64HotSpotLIRKindTool.java
Java
gpl-2.0
1,643
/* sched.c - SPU scheduler. * * Copyright (C) IBM 2005 * Author: Mark Nutter <[email protected]> * * 2006-03-31 NUMA domains added. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #undef DEBUG #include <linux/errno.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/completion.h> #include <linux/vmalloc.h> #include <linux/smp.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/numa.h> #include <linux/mutex.h> #include <linux/notifier.h> #include <linux/kthread.h> #include <linux/pid_namespace.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <asm/io.h> #include <asm/mmu_context.h> #include <asm/spu.h> #include <asm/spu_csa.h> #include <asm/spu_priv1.h> #include "spufs.h" #define CREATE_TRACE_POINTS #include "sputrace.h" struct spu_prio_array { DECLARE_BITMAP(bitmap, MAX_PRIO); struct list_head runq[MAX_PRIO]; spinlock_t runq_lock; int nr_waiting; }; static unsigned long spu_avenrun[3]; static struct spu_prio_array *spu_prio; static struct task_struct *spusched_task; static struct timer_list spusched_timer; static struct timer_list spuloadavg_timer; /* */ #define NORMAL_PRIO 120 /* */ #define SPUSCHED_TICK (10) /* */ #define MIN_SPU_TIMESLICE max(5 * HZ / (1000 * SPUSCHED_TICK), 1) #define DEF_SPU_TIMESLICE (100 * HZ / (1000 * SPUSCHED_TICK)) #define MAX_USER_PRIO (MAX_PRIO - MAX_RT_PRIO) #define SCALE_PRIO(x, prio) \ max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_SPU_TIMESLICE) /* */ void spu_set_timeslice(struct spu_context *ctx) { if (ctx->prio < NORMAL_PRIO) ctx->time_slice = SCALE_PRIO(DEF_SPU_TIMESLICE * 4, ctx->prio); else ctx->time_slice = SCALE_PRIO(DEF_SPU_TIMESLICE, ctx->prio); } /* */ void __spu_update_sched_info(struct spu_context *ctx) { /* */ BUG_ON(!list_empty(&ctx->rq)); /* */ ctx->tid = current->pid; /* */ if (rt_prio(current->prio)) ctx->prio = current->prio; else ctx->prio = current->static_prio; ctx->policy = current->policy; /* */ cpumask_copy(&ctx->cpus_allowed, tsk_cpus_allowed(current)); /* */ ctx->last_ran = raw_smp_processor_id(); } void spu_update_sched_info(struct spu_context *ctx) { int node; if (ctx->state == SPU_STATE_RUNNABLE) { node = ctx->spu->node; /* */ mutex_lock(&cbe_spu_info[node].list_mutex); __spu_update_sched_info(ctx); mutex_unlock(&cbe_spu_info[node].list_mutex); } else { __spu_update_sched_info(ctx); } } static int __node_allowed(struct spu_context *ctx, int node) { if (nr_cpus_node(node)) { const struct cpumask *mask = cpumask_of_node(node); if (cpumask_intersects(mask, &ctx->cpus_allowed)) return 1; } return 0; } static int node_allowed(struct spu_context *ctx, int node) { int rval; spin_lock(&spu_prio->runq_lock); rval = __node_allowed(ctx, node); spin_unlock(&spu_prio->runq_lock); return rval; } void do_notify_spus_active(void) { int node; /* */ for_each_online_node(node) { struct spu *spu; mutex_lock(&cbe_spu_info[node].list_mutex); list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) { if (spu->alloc_state != SPU_FREE) { struct spu_context *ctx = spu->ctx; set_bit(SPU_SCHED_NOTIFY_ACTIVE, &ctx->sched_flags); mb(); wake_up_all(&ctx->stop_wq); } } mutex_unlock(&cbe_spu_info[node].list_mutex); } } /* */ static void spu_bind_context(struct spu *spu, struct spu_context *ctx) { spu_context_trace(spu_bind_context__enter, ctx, spu); spuctx_switch_state(ctx, SPU_UTIL_SYSTEM); if (ctx->flags & SPU_CREATE_NOSCHED) atomic_inc(&cbe_spu_info[spu->node].reserved_spus); ctx->stats.slb_flt_base = spu->stats.slb_flt; ctx->stats.class2_intr_base = spu->stats.class2_intr; spu_associate_mm(spu, ctx->owner); spin_lock_irq(&spu->register_lock); spu->ctx = ctx; spu->flags = 0; ctx->spu = spu; ctx->ops = &spu_hw_ops; spu->pid = current->pid; spu->tgid = current->tgid; spu->ibox_callback = spufs_ibox_callback; spu->wbox_callback = spufs_wbox_callback; spu->stop_callback = spufs_stop_callback; spu->mfc_callback = spufs_mfc_callback; spin_unlock_irq(&spu->register_lock); spu_unmap_mappings(ctx); spu_switch_log_notify(spu, ctx, SWITCH_LOG_START, 0); spu_restore(&ctx->csa, spu); spu->timestamp = jiffies; spu_switch_notify(spu, ctx); ctx->state = SPU_STATE_RUNNABLE; spuctx_switch_state(ctx, SPU_UTIL_USER); } /* */ static inline int sched_spu(struct spu *spu) { BUG_ON(!mutex_is_locked(&cbe_spu_info[spu->node].list_mutex)); return (!spu->ctx || !(spu->ctx->flags & SPU_CREATE_NOSCHED)); } static void aff_merge_remaining_ctxs(struct spu_gang *gang) { struct spu_context *ctx; list_for_each_entry(ctx, &gang->aff_list_head, aff_list) { if (list_empty(&ctx->aff_list)) list_add(&ctx->aff_list, &gang->aff_list_head); } gang->aff_flags |= AFF_MERGED; } static void aff_set_offsets(struct spu_gang *gang) { struct spu_context *ctx; int offset; offset = -1; list_for_each_entry_reverse(ctx, &gang->aff_ref_ctx->aff_list, aff_list) { if (&ctx->aff_list == &gang->aff_list_head) break; ctx->aff_offset = offset--; } offset = 0; list_for_each_entry(ctx, gang->aff_ref_ctx->aff_list.prev, aff_list) { if (&ctx->aff_list == &gang->aff_list_head) break; ctx->aff_offset = offset++; } gang->aff_flags |= AFF_OFFSETS_SET; } static struct spu *aff_ref_location(struct spu_context *ctx, int mem_aff, int group_size, int lowest_offset) { struct spu *spu; int node, n; /* */ node = cpu_to_node(raw_smp_processor_id()); for (n = 0; n < MAX_NUMNODES; n++, node++) { /* */ int available_spus; node = (node < MAX_NUMNODES) ? node : 0; if (!node_allowed(ctx, node)) continue; available_spus = 0; mutex_lock(&cbe_spu_info[node].list_mutex); list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) { if (spu->ctx && spu->ctx->gang && !spu->ctx->aff_offset && spu->ctx->gang->aff_ref_spu) available_spus -= spu->ctx->gang->contexts; available_spus++; } if (available_spus < ctx->gang->contexts) { mutex_unlock(&cbe_spu_info[node].list_mutex); continue; } list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) { if ((!mem_aff || spu->has_mem_affinity) && sched_spu(spu)) { mutex_unlock(&cbe_spu_info[node].list_mutex); return spu; } } mutex_unlock(&cbe_spu_info[node].list_mutex); } return NULL; } static void aff_set_ref_point_location(struct spu_gang *gang) { int mem_aff, gs, lowest_offset; struct spu_context *ctx; struct spu *tmp; mem_aff = gang->aff_ref_ctx->flags & SPU_CREATE_AFFINITY_MEM; lowest_offset = 0; gs = 0; list_for_each_entry(tmp, &gang->aff_list_head, aff_list) gs++; list_for_each_entry_reverse(ctx, &gang->aff_ref_ctx->aff_list, aff_list) { if (&ctx->aff_list == &gang->aff_list_head) break; lowest_offset = ctx->aff_offset; } gang->aff_ref_spu = aff_ref_location(gang->aff_ref_ctx, mem_aff, gs, lowest_offset); } static struct spu *ctx_location(struct spu *ref, int offset, int node) { struct spu *spu; spu = NULL; if (offset >= 0) { list_for_each_entry(spu, ref->aff_list.prev, aff_list) { BUG_ON(spu->node != node); if (offset == 0) break; if (sched_spu(spu)) offset--; } } else { list_for_each_entry_reverse(spu, ref->aff_list.next, aff_list) { BUG_ON(spu->node != node); if (offset == 0) break; if (sched_spu(spu)) offset++; } } return spu; } /* */ static int has_affinity(struct spu_context *ctx) { struct spu_gang *gang = ctx->gang; if (list_empty(&ctx->aff_list)) return 0; if (atomic_read(&ctx->gang->aff_sched_count) == 0) ctx->gang->aff_ref_spu = NULL; if (!gang->aff_ref_spu) { if (!(gang->aff_flags & AFF_MERGED)) aff_merge_remaining_ctxs(gang); if (!(gang->aff_flags & AFF_OFFSETS_SET)) aff_set_offsets(gang); aff_set_ref_point_location(gang); } return gang->aff_ref_spu != NULL; } /* */ static void spu_unbind_context(struct spu *spu, struct spu_context *ctx) { u32 status; spu_context_trace(spu_unbind_context__enter, ctx, spu); spuctx_switch_state(ctx, SPU_UTIL_SYSTEM); if (spu->ctx->flags & SPU_CREATE_NOSCHED) atomic_dec(&cbe_spu_info[spu->node].reserved_spus); if (ctx->gang) /* */ atomic_dec_if_positive(&ctx->gang->aff_sched_count); spu_switch_notify(spu, NULL); spu_unmap_mappings(ctx); spu_save(&ctx->csa, spu); spu_switch_log_notify(spu, ctx, SWITCH_LOG_STOP, 0); spin_lock_irq(&spu->register_lock); spu->timestamp = jiffies; ctx->state = SPU_STATE_SAVED; spu->ibox_callback = NULL; spu->wbox_callback = NULL; spu->stop_callback = NULL; spu->mfc_callback = NULL; spu->pid = 0; spu->tgid = 0; ctx->ops = &spu_backing_ops; spu->flags = 0; spu->ctx = NULL; spin_unlock_irq(&spu->register_lock); spu_associate_mm(spu, NULL); ctx->stats.slb_flt += (spu->stats.slb_flt - ctx->stats.slb_flt_base); ctx->stats.class2_intr += (spu->stats.class2_intr - ctx->stats.class2_intr_base); /* */ spuctx_switch_state(ctx, SPU_UTIL_IDLE_LOADED); ctx->spu = NULL; if (spu_stopped(ctx, &status)) wake_up_all(&ctx->stop_wq); } /* */ static void __spu_add_to_rq(struct spu_context *ctx) { /* */ if (list_empty(&ctx->rq)) { list_add_tail(&ctx->rq, &spu_prio->runq[ctx->prio]); set_bit(ctx->prio, spu_prio->bitmap); if (!spu_prio->nr_waiting++) mod_timer(&spusched_timer, jiffies + SPUSCHED_TICK); } } static void spu_add_to_rq(struct spu_context *ctx) { spin_lock(&spu_prio->runq_lock); __spu_add_to_rq(ctx); spin_unlock(&spu_prio->runq_lock); } static void __spu_del_from_rq(struct spu_context *ctx) { int prio = ctx->prio; if (!list_empty(&ctx->rq)) { if (!--spu_prio->nr_waiting) del_timer(&spusched_timer); list_del_init(&ctx->rq); if (list_empty(&spu_prio->runq[prio])) clear_bit(prio, spu_prio->bitmap); } } void spu_del_from_rq(struct spu_context *ctx) { spin_lock(&spu_prio->runq_lock); __spu_del_from_rq(ctx); spin_unlock(&spu_prio->runq_lock); } static void spu_prio_wait(struct spu_context *ctx) { DEFINE_WAIT(wait); /* */ BUG_ON(!(ctx->flags & SPU_CREATE_NOSCHED)); spin_lock(&spu_prio->runq_lock); prepare_to_wait_exclusive(&ctx->stop_wq, &wait, TASK_INTERRUPTIBLE); if (!signal_pending(current)) { __spu_add_to_rq(ctx); spin_unlock(&spu_prio->runq_lock); mutex_unlock(&ctx->state_mutex); schedule(); mutex_lock(&ctx->state_mutex); spin_lock(&spu_prio->runq_lock); __spu_del_from_rq(ctx); } spin_unlock(&spu_prio->runq_lock); __set_current_state(TASK_RUNNING); remove_wait_queue(&ctx->stop_wq, &wait); } static struct spu *spu_get_idle(struct spu_context *ctx) { struct spu *spu, *aff_ref_spu; int node, n; spu_context_nospu_trace(spu_get_idle__enter, ctx); if (ctx->gang) { mutex_lock(&ctx->gang->aff_mutex); if (has_affinity(ctx)) { aff_ref_spu = ctx->gang->aff_ref_spu; atomic_inc(&ctx->gang->aff_sched_count); mutex_unlock(&ctx->gang->aff_mutex); node = aff_ref_spu->node; mutex_lock(&cbe_spu_info[node].list_mutex); spu = ctx_location(aff_ref_spu, ctx->aff_offset, node); if (spu && spu->alloc_state == SPU_FREE) goto found; mutex_unlock(&cbe_spu_info[node].list_mutex); atomic_dec(&ctx->gang->aff_sched_count); goto not_found; } mutex_unlock(&ctx->gang->aff_mutex); } node = cpu_to_node(raw_smp_processor_id()); for (n = 0; n < MAX_NUMNODES; n++, node++) { node = (node < MAX_NUMNODES) ? node : 0; if (!node_allowed(ctx, node)) continue; mutex_lock(&cbe_spu_info[node].list_mutex); list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) { if (spu->alloc_state == SPU_FREE) goto found; } mutex_unlock(&cbe_spu_info[node].list_mutex); } not_found: spu_context_nospu_trace(spu_get_idle__not_found, ctx); return NULL; found: spu->alloc_state = SPU_USED; mutex_unlock(&cbe_spu_info[node].list_mutex); spu_context_trace(spu_get_idle__found, ctx, spu); spu_init_channels(spu); return spu; } /* */ static struct spu *find_victim(struct spu_context *ctx) { struct spu_context *victim = NULL; struct spu *spu; int node, n; spu_context_nospu_trace(spu_find_victim__enter, ctx); /* */ restart: node = cpu_to_node(raw_smp_processor_id()); for (n = 0; n < MAX_NUMNODES; n++, node++) { node = (node < MAX_NUMNODES) ? node : 0; if (!node_allowed(ctx, node)) continue; mutex_lock(&cbe_spu_info[node].list_mutex); list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) { struct spu_context *tmp = spu->ctx; if (tmp && tmp->prio > ctx->prio && !(tmp->flags & SPU_CREATE_NOSCHED) && (!victim || tmp->prio > victim->prio)) { victim = spu->ctx; } } if (victim) get_spu_context(victim); mutex_unlock(&cbe_spu_info[node].list_mutex); if (victim) { /* */ if (!mutex_trylock(&victim->state_mutex)) { put_spu_context(victim); victim = NULL; goto restart; } spu = victim->spu; if (!spu || victim->prio <= ctx->prio) { /* */ mutex_unlock(&victim->state_mutex); put_spu_context(victim); victim = NULL; goto restart; } spu_context_trace(__spu_deactivate__unload, ctx, spu); mutex_lock(&cbe_spu_info[node].list_mutex); cbe_spu_info[node].nr_active--; spu_unbind_context(spu, victim); mutex_unlock(&cbe_spu_info[node].list_mutex); victim->stats.invol_ctx_switch++; spu->stats.invol_ctx_switch++; if (test_bit(SPU_SCHED_SPU_RUN, &victim->sched_flags)) spu_add_to_rq(victim); mutex_unlock(&victim->state_mutex); put_spu_context(victim); return spu; } } return NULL; } static void __spu_schedule(struct spu *spu, struct spu_context *ctx) { int node = spu->node; int success = 0; spu_set_timeslice(ctx); mutex_lock(&cbe_spu_info[node].list_mutex); if (spu->ctx == NULL) { spu_bind_context(spu, ctx); cbe_spu_info[node].nr_active++; spu->alloc_state = SPU_USED; success = 1; } mutex_unlock(&cbe_spu_info[node].list_mutex); if (success) wake_up_all(&ctx->run_wq); else spu_add_to_rq(ctx); } static void spu_schedule(struct spu *spu, struct spu_context *ctx) { /* */ mutex_lock(&ctx->state_mutex); if (ctx->state == SPU_STATE_SAVED) __spu_schedule(spu, ctx); spu_release(ctx); } /* */ static void spu_unschedule(struct spu *spu, struct spu_context *ctx, int free_spu) { int node = spu->node; mutex_lock(&cbe_spu_info[node].list_mutex); cbe_spu_info[node].nr_active--; if (free_spu) spu->alloc_state = SPU_FREE; spu_unbind_context(spu, ctx); ctx->stats.invol_ctx_switch++; spu->stats.invol_ctx_switch++; mutex_unlock(&cbe_spu_info[node].list_mutex); } /* */ int spu_activate(struct spu_context *ctx, unsigned long flags) { struct spu *spu; /* */ if (ctx->spu) return 0; spu_activate_top: if (signal_pending(current)) return -ERESTARTSYS; spu = spu_get_idle(ctx); /* */ if (!spu && rt_prio(ctx->prio)) spu = find_victim(ctx); if (spu) { unsigned long runcntl; runcntl = ctx->ops->runcntl_read(ctx); __spu_schedule(spu, ctx); if (runcntl & SPU_RUNCNTL_RUNNABLE) spuctx_switch_state(ctx, SPU_UTIL_USER); return 0; } if (ctx->flags & SPU_CREATE_NOSCHED) { spu_prio_wait(ctx); goto spu_activate_top; } spu_add_to_rq(ctx); return 0; } /* */ static struct spu_context *grab_runnable_context(int prio, int node) { struct spu_context *ctx; int best; spin_lock(&spu_prio->runq_lock); best = find_first_bit(spu_prio->bitmap, prio); while (best < prio) { struct list_head *rq = &spu_prio->runq[best]; list_for_each_entry(ctx, rq, rq) { /* */ if (__node_allowed(ctx, node)) { __spu_del_from_rq(ctx); goto found; } } best++; } ctx = NULL; found: spin_unlock(&spu_prio->runq_lock); return ctx; } static int __spu_deactivate(struct spu_context *ctx, int force, int max_prio) { struct spu *spu = ctx->spu; struct spu_context *new = NULL; if (spu) { new = grab_runnable_context(max_prio, spu->node); if (new || force) { spu_unschedule(spu, ctx, new == NULL); if (new) { if (new->flags & SPU_CREATE_NOSCHED) wake_up(&new->stop_wq); else { spu_release(ctx); spu_schedule(spu, new); /* */ mutex_lock(&ctx->state_mutex); } } } } return new != NULL; } /* */ void spu_deactivate(struct spu_context *ctx) { spu_context_nospu_trace(spu_deactivate__enter, ctx); __spu_deactivate(ctx, 1, MAX_PRIO); } /* */ void spu_yield(struct spu_context *ctx) { spu_context_nospu_trace(spu_yield__enter, ctx); if (!(ctx->flags & SPU_CREATE_NOSCHED)) { mutex_lock(&ctx->state_mutex); __spu_deactivate(ctx, 0, MAX_PRIO); mutex_unlock(&ctx->state_mutex); } } static noinline void spusched_tick(struct spu_context *ctx) { struct spu_context *new = NULL; struct spu *spu = NULL; if (spu_acquire(ctx)) BUG(); /* */ if (ctx->state != SPU_STATE_RUNNABLE) goto out; if (ctx->flags & SPU_CREATE_NOSCHED) goto out; if (ctx->policy == SCHED_FIFO) goto out; if (--ctx->time_slice && test_bit(SPU_SCHED_SPU_RUN, &ctx->sched_flags)) goto out; spu = ctx->spu; spu_context_trace(spusched_tick__preempt, ctx, spu); new = grab_runnable_context(ctx->prio + 1, spu->node); if (new) { spu_unschedule(spu, ctx, 0); if (test_bit(SPU_SCHED_SPU_RUN, &ctx->sched_flags)) spu_add_to_rq(ctx); } else { spu_context_nospu_trace(spusched_tick__newslice, ctx); if (!ctx->time_slice) ctx->time_slice++; } out: spu_release(ctx); if (new) spu_schedule(spu, new); } /* */ static unsigned long count_active_contexts(void) { int nr_active = 0, node; for (node = 0; node < MAX_NUMNODES; node++) nr_active += cbe_spu_info[node].nr_active; nr_active += spu_prio->nr_waiting; return nr_active; } /* */ static void spu_calc_load(void) { unsigned long active_tasks; /* */ active_tasks = count_active_contexts() * FIXED_1; CALC_LOAD(spu_avenrun[0], EXP_1, active_tasks); CALC_LOAD(spu_avenrun[1], EXP_5, active_tasks); CALC_LOAD(spu_avenrun[2], EXP_15, active_tasks); } static void spusched_wake(unsigned long data) { mod_timer(&spusched_timer, jiffies + SPUSCHED_TICK); wake_up_process(spusched_task); } static void spuloadavg_wake(unsigned long data) { mod_timer(&spuloadavg_timer, jiffies + LOAD_FREQ); spu_calc_load(); } static int spusched_thread(void *unused) { struct spu *spu; int node; while (!kthread_should_stop()) { set_current_state(TASK_INTERRUPTIBLE); schedule(); for (node = 0; node < MAX_NUMNODES; node++) { struct mutex *mtx = &cbe_spu_info[node].list_mutex; mutex_lock(mtx); list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) { struct spu_context *ctx = spu->ctx; if (ctx) { get_spu_context(ctx); mutex_unlock(mtx); spusched_tick(ctx); mutex_lock(mtx); put_spu_context(ctx); } } mutex_unlock(mtx); } } return 0; } void spuctx_switch_state(struct spu_context *ctx, enum spu_utilization_state new_state) { unsigned long long curtime; signed long long delta; struct timespec ts; struct spu *spu; enum spu_utilization_state old_state; int node; ktime_get_ts(&ts); curtime = timespec_to_ns(&ts); delta = curtime - ctx->stats.tstamp; WARN_ON(!mutex_is_locked(&ctx->state_mutex)); WARN_ON(delta < 0); spu = ctx->spu; old_state = ctx->stats.util_state; ctx->stats.util_state = new_state; ctx->stats.tstamp = curtime; /* */ if (spu) { ctx->stats.times[old_state] += delta; spu->stats.times[old_state] += delta; spu->stats.util_state = new_state; spu->stats.tstamp = curtime; node = spu->node; if (old_state == SPU_UTIL_USER) atomic_dec(&cbe_spu_info[node].busy_spus); if (new_state == SPU_UTIL_USER) atomic_inc(&cbe_spu_info[node].busy_spus); } } #define LOAD_INT(x) ((x) >> FSHIFT) #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100) static int show_spu_loadavg(struct seq_file *s, void *private) { int a, b, c; a = spu_avenrun[0] + (FIXED_1/200); b = spu_avenrun[1] + (FIXED_1/200); c = spu_avenrun[2] + (FIXED_1/200); /* */ seq_printf(s, "%d.%02d %d.%02d %d.%02d %ld/%d %d\n", LOAD_INT(a), LOAD_FRAC(a), LOAD_INT(b), LOAD_FRAC(b), LOAD_INT(c), LOAD_FRAC(c), count_active_contexts(), atomic_read(&nr_spu_contexts), current->nsproxy->pid_ns->last_pid); return 0; } static int spu_loadavg_open(struct inode *inode, struct file *file) { return single_open(file, show_spu_loadavg, NULL); } static const struct file_operations spu_loadavg_fops = { .open = spu_loadavg_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; int __init spu_sched_init(void) { struct proc_dir_entry *entry; int err = -ENOMEM, i; spu_prio = kzalloc(sizeof(struct spu_prio_array), GFP_KERNEL); if (!spu_prio) goto out; for (i = 0; i < MAX_PRIO; i++) { INIT_LIST_HEAD(&spu_prio->runq[i]); __clear_bit(i, spu_prio->bitmap); } spin_lock_init(&spu_prio->runq_lock); setup_timer(&spusched_timer, spusched_wake, 0); setup_timer(&spuloadavg_timer, spuloadavg_wake, 0); spusched_task = kthread_run(spusched_thread, NULL, "spusched"); if (IS_ERR(spusched_task)) { err = PTR_ERR(spusched_task); goto out_free_spu_prio; } mod_timer(&spuloadavg_timer, 0); entry = proc_create("spu_loadavg", 0, NULL, &spu_loadavg_fops); if (!entry) goto out_stop_kthread; pr_debug("spusched: tick: %d, min ticks: %d, default ticks: %d\n", SPUSCHED_TICK, MIN_SPU_TIMESLICE, DEF_SPU_TIMESLICE); return 0; out_stop_kthread: kthread_stop(spusched_task); out_free_spu_prio: kfree(spu_prio); out: return err; } void spu_sched_exit(void) { struct spu *spu; int node; remove_proc_entry("spu_loadavg", NULL); del_timer_sync(&spusched_timer); del_timer_sync(&spuloadavg_timer); kthread_stop(spusched_task); for (node = 0; node < MAX_NUMNODES; node++) { mutex_lock(&cbe_spu_info[node].list_mutex); list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) if (spu->alloc_state != SPU_FREE) spu->alloc_state = SPU_FREE; mutex_unlock(&cbe_spu_info[node].list_mutex); } kfree(spu_prio); }
holyangel/LGE_G3
arch/powerpc/platforms/cell/spufs/sched.c
C
gpl-2.0
30,242
<?php if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' ); mm_showMyFileName(__FILE__); ?> <?php if(!@is_object( $pagenav)) return; ?> <!-- BEGIN PAGE NAVIGATION --> <div align="center"> <?php $pagenav->writePagesLinks( $search_string ); ?> <?php if( $show_limitbox ) { ?> <br/><br/> <form action="<?php echo $search_string ?>" method="post"> <?php echo $VM_LANG->_('PN_DISPLAY_NR') ?>&nbsp;&nbsp; <?php $pagenav->writeLimitBox( $search_string ); ?> <noscript><input class="button" type="submit" value="<?php echo $VM_LANG->_('PHPSHOP_SUBMIT') ?>" /></noscript> </form> <?php } $pagenav->writePagesCounter(); ?> </div> <!-- END PAGE NAVIGATION -->
dreamriks/gift
components/original_com_virtuemart/themes/default/templates/browse/includes/browse_pagenav.tpl.php
PHP
gpl-2.0
767
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef AVC_DECODER_H_ #define AVC_DECODER_H_ #include <media/stagefright/MediaBuffer.h> #include <media/stagefright/MediaSource.h> #include <utils/Vector.h> struct tagAVCHandle; namespace android { struct AVCDecoder : public MediaSource, public MediaBufferObserver { AVCDecoder(const sp<MediaSource> &source); virtual status_t start(MetaData *params); virtual status_t stop(); virtual sp<MetaData> getFormat(); virtual status_t read( MediaBuffer **buffer, const ReadOptions *options); virtual void signalBufferReturned(MediaBuffer *buffer); protected: virtual ~AVCDecoder(); private: sp<MediaSource> mSource; bool mStarted; sp<MetaData> mFormat; Vector<MediaBuffer *> mCodecSpecificData; tagAVCHandle *mHandle; Vector<MediaBuffer *> mFrames; MediaBuffer *mInputBuffer; int64_t mAnchorTimeUs; int64_t mNumSamplesOutput; int64_t mPendingSeekTimeUs; MediaSource::ReadOptions::SeekMode mPendingSeekMode; int64_t mTargetTimeUs; bool mSPSSeen; bool mPPSSeen; void addCodecSpecificData(const uint8_t *data, size_t size); static int32_t ActivateSPSWrapper( void *userData, unsigned int sizeInMbs, unsigned int numBuffers); static int32_t BindFrameWrapper( void *userData, int32_t index, uint8_t **yuv); static void UnbindFrame(void *userData, int32_t index); int32_t activateSPS( unsigned int sizeInMbs, unsigned int numBuffers); int32_t bindFrame(int32_t index, uint8_t **yuv); void releaseFrames(); MediaBuffer *drainOutputBuffer(); AVCDecoder(const AVCDecoder &); AVCDecoder &operator=(const AVCDecoder &); }; } // namespace android #endif // AVC_DECODER_H_
luquanhong/MyCodec
projects/stagefright/jni/src/codec/decoder/video/sw_opencore/OEM/jni/media/frameworks/base/media/libstagefright/include/AVCDecoder.h
C
gpl-2.0
2,397
// Hungarian // from Google Translate -- please help improve this translation if (typeof FlexibleMap != "undefined") { FlexibleMap.prototype.i18n["hu"] = { "Click for details" : "Kattintson a rรฉszletekรฉrt", "Directions" : "Tรฉrkรฉp irรกnyban", "From" : "Indulรกs helye", "Get directions" : "Tรฉrkรฉp irรกnyban" }; }
mathewhtc/cats-old
wp-content/plugins/wp-flexible-map/i18n/hu.js
JavaScript
gpl-2.0
331
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML ><HEAD ><TITLE >รฒร…ร‡ร‰ร“ร”ร’รรƒร‰ร‘ รรร‰ร“ร‹รร—ร™รˆ รšรรร’รร“รร— </TITLE ><META NAME="GENERATOR" CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK REL="HOME" TITLE="DataparkSearch Engine 4.54" HREF="index.ru.html"><LINK REL="UP" TITLE="รฐรร‰ร“ร‹ ร„รร‹ร•รร…รŽร”รร—" HREF="dpsearch-doingsearch.ru.html"><LINK REL="PREVIOUS" TITLE="รฒร…รŒร…ร—รรŽร”รŽรร“ร”ร˜ " HREF="dpsearch-rel.ru.html"><LINK REL="NEXT" TITLE="รซรœร› ร’ร…รšร•รŒร˜ร”รร”รร— รรร‰ร“ร‹ร " HREF="dpsearch-srcache.ru.html"><LINK REL="STYLESHEET" TYPE="text/css" HREF="datapark.css"><META NAME="Description" CONTENT="DataparkSearch - รฐรรŒรŽรร†ร•รŽร‹รƒร‰รรŽรรŒร˜รŽรร‘ รรร‰ร“ร‹รร—รร‘ รรร›ร‰รŽร ร„รŒร‘ รฉรŽร”ร…ร’รŽร…ร”ร ร‰ รฉรŽร”ร’รรŽร…ร”ร ร“ รร”ร‹ร’ร™ร”ร™ร ร‰ร“รˆรร„รŽร™ร ร‹รร„รร. รฒรร“รร’รร“ร”ร’รรŽร‘ร…ร”ร“ร‘ รร รŒร‰รƒร…รŽรšร‰ร‰ GNU."><META NAME="Keywords" CONTENT="shareware, freeware, ร‰รŽร”ร…ร’รŽร…ร”, unix, รรร‰ร“ร‹รร—ร‰ร‹, รรร‰ร“ร‹รร—รร‘ รรร›ร‰รŽร, รรร‰ร“ร‹, รรร‰ร“ร‹ ร‰รŽร†รร’รรรƒร‰ร‰, ร‰รŽร”ร’รรŽร…ร”, open source, opensource, search, searching, software, udmsearch, engine, indexing, system, web, ftp, http, cgi, php, SQL, MySQL, database, php3, FreeBSD, Linux, Unix, DataparkSearch, MacOS X, Mac OS X, Windows, 2000, NT, 95, 98, GNU, GPL, url, grabbing"></HEAD ><BODY CLASS="SECT1" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000C4" VLINK="#1200B2" ALINK="#C40000" ><!--#include virtual="body-before.html"--><DIV CLASS="NAVHEADER" ><TABLE SUMMARY="Header navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TH COLSPAN="3" ALIGN="center" >DataparkSearch Engine 4.54: รณรร’รร—รรžรŽรร… ร’ร•ร‹รร—รร„ร“ร”ร—ร</TH ></TR ><TR ><TD WIDTH="10%" ALIGN="left" VALIGN="bottom" ><A HREF="dpsearch-rel.ru.html" ACCESSKEY="P" >&#1055;&#1088;&#1077;&#1076;.</A ></TD ><TD WIDTH="80%" ALIGN="center" VALIGN="bottom" >&#1043;&#1083;&#1072;&#1074;&#1072; 8. รฐรร‰ร“ร‹ ร„รร‹ร•รร…รŽร”รร—</TD ><TD WIDTH="10%" ALIGN="right" VALIGN="bottom" ><A HREF="dpsearch-srcache.ru.html" ACCESSKEY="N" >&#1057;&#1083;&#1077;&#1076;.</A ></TD ></TR ></TABLE ><HR ALIGN="LEFT" WIDTH="100%"></DIV ><DIV CLASS="SECT1" ><H1 CLASS="SECT1" ><A NAME="TRACK" >8.6. รฒร…ร‡ร‰ร“ร”ร’รรƒร‰ร‘ รรร‰ร“ร‹รร—ร™รˆ รšรรร’รร“รร— <A NAME="AEN6358" ></A ></A ></H1 ><P ><SPAN CLASS="APPLICATION" >DataparkSearch</SPAN > รรร„ร„ร…ร’ร–ร‰ร—รร…ร” ร’ร…ร‡ร‰ร“ร”ร’รรƒร‰ร€ รรร‰ร“ร‹รร—ร™รˆ รšรรร’รร“รร—.</P ><P >รฐร’ร‰ ร—ร™รรรŒรŽร…รŽร‰ร‰ รรร‰ร“ร‹รร—ร™รˆ รšรรร’รร“รร—, <SPAN CLASS="APPLICATION" >DataparkSearch</SPAN > ร‰ร“รรรŒร˜รšร•ร…ร” ร”รร‚รŒร‰รƒร• <TT CLASS="LITERAL" >qtrack</TT > ร„รŒร‘ รšรรร‰ร“ร‰ รรร‰ร“ร‹รร—รร‡ร รšรรร’รร“ร, IP รร„ร’ร…ร“ร ร‹รŒร‰ร…รŽร”ร, รžร‰ร“รŒร รŽรรŠร„ร…รŽรŽร™รˆ ร„รร‹ร•รร…รŽร”รร— ร‰ ร”ร…ร‹ร•รร…ร‡ร ร—ร’ร…รร…รŽร‰ ร— <SPAN CLASS="APPLICATION" >UNIX</SPAN > ร†รรรร”ร…, ร ร”รร‹ร–ร… ร”รร‚รŒร‰รƒร• <TT CLASS="LITERAL" >qinfo</TT > ร„รŒร‘ รšรรร‰ร“ร‰ ร—ร“ร…รˆ รรร’รรร…ร”ร’รร— รšรรร’รร“ร.</P ><P >รครŒร‘ ร”รร‡ร, รžร”รร‚ร™ ร—ร‹รŒร€รžร‰ร”ร˜ ร’ร…ร‡ร‰ร“ร”ร’รรƒร‰ร€ รšรรร’รร“รร—, ร„รร‚รร—ร˜ร”ร… รรร’รรร…ร”ร…ร’ <TT CLASS="LITERAL" >trackquery</TT > ร„รŒร‘ ร“รรร”ร—ร…ร”ร“ร—ร•ร€รร…รŠ ร‹รรรรŽร„ร™ <B CLASS="COMMAND" >DBAddr</B > (ร“ร. <A HREF="dpsearch-indexcmd.ru.html#DBADDR_CMD" >&#1056;&#1072;&#1079;&#1076;. 3.10.2</A >&#62;) ร—รร›ร…ร‡ร ร›รร‚รŒรรŽร รรร‰ร“ร‹ร <TT CLASS="FILENAME" >search.htm</TT >. รฎรรร’ร‰รร…ร’: <PRE CLASS="PROGRAMLISTING" >DBAddr pgsql://user:pass@localhost/search/?dbmode=cache&amp;trackquery</PRE ></P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >&#1047;&#1072;&#1084;&#1077;&#1095;&#1072;&#1085;&#1080;&#1077;: </B > รฅร“รŒร‰ ร‰ร“รรรŒร˜รšร•ร…ร”ร“ร‘ <B CLASS="COMMAND" >searchd</B >, รœร”รร” รรร’รรร…ร”ร’ รŽร…รร‚รˆรร„ร‰รร ร„รร‚รร—ร‰ร”ร˜ ร”รรŒร˜ร‹ร ร— ร‹รรรรŽร„ร•<B CLASS="COMMAND" >DBAddr</B > ร‰รš ร†รรŠรŒร <TT CLASS="FILENAME" >searchd.conf</TT >. </P ><P ><A NAME="AEN6379" ></A > รทร™ รรร–ร…ร”ร… ร‰ร“รรรŒร˜รšรร—รร”ร˜ ร‹รรรรŽร„ร• <B CLASS="COMMAND" >TrackDBAddr</B > ร„รŒร‘ ร•ร‹รรšรรŽร‰ร‘ ร„ร’ร•ร‡รรŠ SQL-ร‚รรšร™ ร„รŒร‘ ร“รรˆร’รรŽร…รŽร‰ร‘ รรร’รรร…ร”ร’รร— รรร‰ร“ร‹รร—ร™รˆ รšรรร’รร“รร—. รผร”ร SQL-ร‚รรšร ร„รรŒร–รŽร ร“รร„ร…ร’ร–รร”ร˜ ร”ร…ร–ร… ร”รร‚รŒร‰รƒร™ <TT CLASS="LITERAL" >qtrack</TT > ร‰ <TT CLASS="LITERAL" >qinfo</TT >, รžร”ร ร‰ ร‚รรšร DataparkSearch. </P ></BLOCKQUOTE ></DIV ><P >รฒร…ร‡ร‰ร“ร”ร’รรƒร‰ร‘ รšรรร’รร“รร— รรร‰ร“ร‹ร รรรŒร…รšรŽร ร„รŒร‘ รรรŒร•รžร…รŽร‰ร‘ ร“ร”รร”ร‰ร“ร”ร‰ร‹ร‰ ร‰ร“รรรŒร˜รšรร—รรŽร‰ร‘ ร—รร›ร…ร‡ร รรร‰ร“ร‹รร—รร‡ร ร“ร…ร’ร—ร…ร’ร. รครŒร‘ ร“รร“ร”รร—รŒร…รŽร‰ร‘ รร”รžยฃร”ร, ร—ร™ รรร–ร…ร”ร…, รŽรรร’ร‰รร…ร’, ร‰ร“รรรŒร˜รšรร—รร”ร˜ ร“รŒร…ร„ร•ร€รร‰รŠ SQL-รšรรร’รร“: <PRE CLASS="PROGRAMLISTING" >SELECT qwords,count(*),sum(found),avg(found) FROM qtrack GROUP BY qwords;</PRE > </P ></DIV ><DIV CLASS="NAVFOOTER" ><HR ALIGN="LEFT" WIDTH="100%"><TABLE SUMMARY="Footer navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" ><A HREF="dpsearch-rel.ru.html" ACCESSKEY="P" >&#1055;&#1088;&#1077;&#1076;.</A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="index.ru.html" ACCESSKEY="H" >&#1053;&#1072;&#1095;&#1072;&#1083;&#1086;</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" ><A HREF="dpsearch-srcache.ru.html" ACCESSKEY="N" >&#1057;&#1083;&#1077;&#1076;.</A ></TD ></TR ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" >รฒร…รŒร…ร—รรŽร”รŽรร“ร”ร˜ <A NAME="AEN6107" ></A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="dpsearch-doingsearch.ru.html" ACCESSKEY="U" >&#1059;&#1088;&#1086;&#1074;&#1077;&#1085;&#1100; &#1074;&#1099;&#1096;&#1077;</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" >รซรœร› ร’ร…รšร•รŒร˜ร”รร”รร— รรร‰ร“ร‹ร <A NAME="AEN6389" ></A ></TD ></TR ></TABLE ></DIV ><!--#include virtual="body-after.html"--></BODY ></HTML >
Letractively/dataparksearch
doc/dpsearch-track.ru.html
HTML
gpl-2.0
5,018
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * 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: * * Copyright (C) 2012 Google, Inc. */ #include <string.h> #include "mm-errors-types.h" #include "mm-bearer-ip-config.h" /** * SECTION: mm-bearer-ip-config * @title: MMBearerIpConfig * @short_description: Helper object to handle IP configuration. * * The #MMBearerIpConfig is an object handling the IP configuration required by * the bearer to finish the connection. * * This object is retrieved with either mm_bearer_get_ipv4_config(), * mm_bearer_peek_ipv4_config(), mm_bearer_get_ipv6_config() or * mm_bearer_peek_ipv6_config(). */ G_DEFINE_TYPE (MMBearerIpConfig, mm_bearer_ip_config, G_TYPE_OBJECT); #define PROPERTY_METHOD "method" #define PROPERTY_ADDRESS "address" #define PROPERTY_PREFIX "prefix" #define PROPERTY_DNS1 "dns1" #define PROPERTY_DNS2 "dns2" #define PROPERTY_DNS3 "dns3" #define PROPERTY_GATEWAY "gateway" #define PROPERTY_MTU "mtu" struct _MMBearerIpConfigPrivate { MMBearerIpMethod method; gchar *address; guint prefix; gchar **dns; gchar *gateway; guint mtu; }; /*****************************************************************************/ /** * mm_bearer_ip_config_get_method: * @self: a #MMBearerIpConfig. * * Gets the IP method to be used with this bearer. * * Returns: a #MMBearerIpMethod. */ MMBearerIpMethod mm_bearer_ip_config_get_method (MMBearerIpConfig *self) { g_return_val_if_fail (MM_IS_BEARER_IP_CONFIG (self), MM_BEARER_IP_METHOD_UNKNOWN); return self->priv->method; } void mm_bearer_ip_config_set_method (MMBearerIpConfig *self, MMBearerIpMethod method) { g_return_if_fail (MM_IS_BEARER_IP_CONFIG (self)); self->priv->method = method; } /*****************************************************************************/ /** * mm_bearer_ip_config_get_address: * @self: a #MMBearerIpConfig. * * Gets the IP address to be used with this bearer. * * Returns: a string with the IP address, or #NULL if unknown. Do not free the returned value, it is owned by @self. */ const gchar * mm_bearer_ip_config_get_address (MMBearerIpConfig *self) { g_return_val_if_fail (MM_IS_BEARER_IP_CONFIG (self), NULL); return self->priv->address; } void mm_bearer_ip_config_set_address (MMBearerIpConfig *self, const gchar *address) { g_return_if_fail (MM_IS_BEARER_IP_CONFIG (self)); g_free (self->priv->address); self->priv->address = g_strdup (address); } /*****************************************************************************/ /** * mm_bearer_ip_config_get_prefix: * @self: a #MMBearerIpConfig. * * Gets the network prefix to be used with this bearer. * * Returns: the network prefix. */ guint mm_bearer_ip_config_get_prefix (MMBearerIpConfig *self) { g_return_val_if_fail (MM_IS_BEARER_IP_CONFIG (self), 0); return self->priv->prefix; } void mm_bearer_ip_config_set_prefix (MMBearerIpConfig *self, guint prefix) { g_return_if_fail (MM_IS_BEARER_IP_CONFIG (self)); self->priv->prefix = prefix; } /*****************************************************************************/ /** * mm_bearer_ip_config_get_dns: * @self: a #MMBearerIpConfig. * * Gets the list of IP addresses of DNS servers to be used with this bearer. * * Returns: (transfer none) (array zero-terminated=1): a NULL-terminated array of strings. Do not free the returned value, it is owned by @self. */ const gchar ** mm_bearer_ip_config_get_dns (MMBearerIpConfig *self) { g_return_val_if_fail (MM_IS_BEARER_IP_CONFIG (self), NULL); return (const gchar **)self->priv->dns; } void mm_bearer_ip_config_set_dns (MMBearerIpConfig *self, const gchar **dns) { g_return_if_fail (MM_IS_BEARER_IP_CONFIG (self)); g_strfreev (self->priv->dns); self->priv->dns = g_strdupv ((gchar **)dns); } /*****************************************************************************/ /** * mm_bearer_ip_config_get_gateway: * @self: a #MMBearerIpConfig. * * Gets the IP address of the gateway to be used with this bearer. * * Returns: a string with the IP address, or #NULL if unknown. Do not free the returned value, it is owned by @self. */ const gchar * mm_bearer_ip_config_get_gateway (MMBearerIpConfig *self) { g_return_val_if_fail (MM_IS_BEARER_IP_CONFIG (self), NULL); return self->priv->gateway; } void mm_bearer_ip_config_set_gateway (MMBearerIpConfig *self, const gchar *gateway) { g_return_if_fail (MM_IS_BEARER_IP_CONFIG (self)); g_free (self->priv->gateway); self->priv->gateway = g_strdup (gateway); } /*****************************************************************************/ /** * mm_bearer_ip_config_get_mtu: * @self: a #MMBearerIpConfig. * * Gets the MTU to be used with this bearer. * * Returns: the MTU. */ guint mm_bearer_ip_config_get_mtu (MMBearerIpConfig *self) { g_return_val_if_fail (MM_IS_BEARER_IP_CONFIG (self), 0); return self->priv->mtu; } void mm_bearer_ip_config_set_mtu (MMBearerIpConfig *self, guint mtu) { g_return_if_fail (MM_IS_BEARER_IP_CONFIG (self)); self->priv->mtu = mtu; } /*****************************************************************************/ GVariant * mm_bearer_ip_config_get_dictionary (MMBearerIpConfig *self) { GVariantBuilder builder; /* We do allow self==NULL. We'll just report method=unknown in this case */ if (self) g_return_val_if_fail (MM_IS_BEARER_IP_CONFIG (self), NULL); g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); g_variant_builder_add (&builder, "{sv}", PROPERTY_METHOD, g_variant_new_uint32 (self ? self->priv->method : MM_BEARER_IP_METHOD_UNKNOWN)); if (self) { if (self->priv->address) g_variant_builder_add (&builder, "{sv}", PROPERTY_ADDRESS, g_variant_new_string (self->priv->address)); if (self->priv->prefix) g_variant_builder_add (&builder, "{sv}", PROPERTY_PREFIX, g_variant_new_uint32 (self->priv->prefix)); if (self->priv->dns && self->priv->dns[0]) { g_variant_builder_add (&builder, "{sv}", PROPERTY_DNS1, g_variant_new_string (self->priv->dns[0])); if (self->priv->dns[1]) { g_variant_builder_add (&builder, "{sv}", PROPERTY_DNS2, g_variant_new_string (self->priv->dns[1])); if (self->priv->dns[2]) { g_variant_builder_add (&builder, "{sv}", PROPERTY_DNS3, g_variant_new_string (self->priv->dns[2])); } } } if (self->priv->gateway) g_variant_builder_add (&builder, "{sv}", PROPERTY_GATEWAY, g_variant_new_string (self->priv->gateway)); if (self->priv->mtu) g_variant_builder_add (&builder, "{sv}", PROPERTY_MTU, g_variant_new_uint32 (self->priv->mtu)); } return g_variant_builder_end (&builder); } /*****************************************************************************/ MMBearerIpConfig * mm_bearer_ip_config_new_from_dictionary (GVariant *dictionary, GError **error) { GVariantIter iter; gchar *key; GVariant *value; MMBearerIpConfig *self; gchar *dns_array[4] = { 0 }; gboolean method_received = FALSE; self = mm_bearer_ip_config_new (); if (!dictionary) return self; if (!g_variant_is_of_type (dictionary, G_VARIANT_TYPE ("a{sv}"))) { g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_INVALID_ARGS, "Cannot create IP config from dictionary: " "invalid variant type received"); g_object_unref (self); return NULL; } g_variant_iter_init (&iter, dictionary); while (g_variant_iter_next (&iter, "{sv}", &key, &value)) { if (g_str_equal (key, PROPERTY_METHOD)) { method_received = TRUE; mm_bearer_ip_config_set_method ( self, (MMBearerIpMethod) g_variant_get_uint32 (value)); } else if (g_str_equal (key, PROPERTY_ADDRESS)) mm_bearer_ip_config_set_address ( self, g_variant_get_string (value, NULL)); else if (g_str_equal (key, PROPERTY_PREFIX)) mm_bearer_ip_config_set_prefix ( self, g_variant_get_uint32 (value)); else if (g_str_equal (key, PROPERTY_DNS1)) { g_free (dns_array[0]); dns_array[0] = g_variant_dup_string (value, NULL); } else if (g_str_equal (key, PROPERTY_DNS2)) { g_free (dns_array[1]); dns_array[1] = g_variant_dup_string (value, NULL); } else if (g_str_equal (key, PROPERTY_DNS3)) { g_free (dns_array[2]); dns_array[2] = g_variant_dup_string (value, NULL); } else if (g_str_equal (key, PROPERTY_GATEWAY)) mm_bearer_ip_config_set_gateway ( self, g_variant_get_string (value, NULL)); else if (g_str_equal (key, PROPERTY_MTU)) mm_bearer_ip_config_set_mtu ( self, g_variant_get_uint32 (value)); g_free (key); g_variant_unref (value); } if (dns_array[0]) mm_bearer_ip_config_set_dns (self, (const gchar **)dns_array); if (!method_received) { g_set_error (error, MM_CORE_ERROR, MM_CORE_ERROR_INVALID_ARGS, "Couldn't create IP config from dictionary: 'method not given'"); g_clear_object (&self); } g_free (dns_array[0]); g_free (dns_array[1]); g_free (dns_array[2]); return self; } /*****************************************************************************/ /** * mm_bearer_ip_config_dup: * @orig: a #MMBearerIpConfig * * Creates a copy of @orig. * * Returns: (transfer full): a newly created #MMBearerIpConfig */ MMBearerIpConfig * mm_bearer_ip_config_dup (MMBearerIpConfig *orig) { GVariant *dict; MMBearerIpConfig *copy; GError *error = NULL; g_return_val_if_fail (MM_IS_BEARER_IP_CONFIG (orig), NULL); dict = mm_bearer_ip_config_get_dictionary (orig); copy = mm_bearer_ip_config_new_from_dictionary (dict, &error); g_assert_no_error (error); g_variant_unref (dict); return copy; } /*****************************************************************************/ MMBearerIpConfig * mm_bearer_ip_config_new (void) { return (MM_BEARER_IP_CONFIG ( g_object_new (MM_TYPE_BEARER_IP_CONFIG, NULL))); } static void mm_bearer_ip_config_init (MMBearerIpConfig *self) { self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), MM_TYPE_BEARER_IP_CONFIG, MMBearerIpConfigPrivate); /* Some defaults */ self->priv->method = MM_BEARER_IP_METHOD_UNKNOWN; } static void finalize (GObject *object) { MMBearerIpConfig *self = MM_BEARER_IP_CONFIG (object); g_free (self->priv->address); g_free (self->priv->gateway); g_strfreev (self->priv->dns); G_OBJECT_CLASS (mm_bearer_ip_config_parent_class)->finalize (object); } static void mm_bearer_ip_config_class_init (MMBearerIpConfigClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); g_type_class_add_private (object_class, sizeof (MMBearerIpConfigPrivate)); object_class->finalize = finalize; }
mkotsbak/modemmanager-debian
libmm-glib/mm-bearer-ip-config.c
C
gpl-2.0
13,113
/* * Copyright 2008 Christian Franke <[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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #include "sourcehighlighter.h" #include <qpalette.h> SourceHighlighter::SourceHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { QPalette palette; QColor foreground = palette.text().color(); QColor background = palette.base().color(); QTextCharFormat entityFormat; QColor entityColor; entityColor.setRed((foreground.red() + background.red()) / 2); entityColor.setGreen( (foreground.green() + background.green()) / 2); entityColor.setBlue( (foreground.blue() + background.blue()) / 2); if (abs(entityColor.red() - background.red()) > 80) entityColor.setRed(foreground.red()); else if (abs(entityColor.green()-background.green()) > 80) entityColor.setGreen(foreground.green()); else entityColor.setBlue(foreground.blue()); entityFormat.setForeground(entityColor); entityFormat.setFontWeight(QFont::Normal); setFormatFor(Entity, entityFormat); QTextCharFormat tagFormat; QColor tagColor; tagColor.setRed(foreground.red() + (background.red() - foreground.red()) / 4); tagColor.setGreen( foreground.green() + (background.green() - foreground.green()) / 4); tagColor.setBlue( foreground.blue() + (background.blue() - foreground.blue()) / 4); tagFormat.setForeground(tagColor); tagFormat.setFontWeight(QFont::Bold); setFormatFor(Tag, tagFormat); QTextCharFormat commentFormat; QColor commentColor; commentColor.setRed(background.red() + (foreground.red() - background.red()) / 3); commentColor.setGreen( background.green() + (foreground.green() - background.green()) / 3); commentColor.setBlue( background.blue() + (foreground.blue() - background.blue()) / 3); commentFormat.setForeground(commentColor); commentFormat.setFontWeight(QFont::Normal); setFormatFor(Comment, commentFormat); QTextCharFormat attributeFormat; QColor attributeColor; attributeColor.setRed((foreground.red() + background.red()) / 2); attributeColor.setGreen( (foreground.green() + background.green()) / 2); attributeColor.setBlue( (foreground.blue() + background.blue()) / 2); if (abs(attributeColor.red() - background.red()) > 80) attributeColor.setRed(background.red()); else if (abs(attributeColor.green() - background.green()) > 80) attributeColor.setGreen(background.green()); else attributeColor.setBlue(background.blue()); attributeFormat.setForeground(attributeColor); attributeFormat.setFontWeight(QFont::Normal); setFormatFor(Attribute, attributeFormat); } QTextCharFormat SourceHighlighter::getFormatFor(Construct construct) { return formats[construct]; } void SourceHighlighter::setFormatFor(Construct construct, QTextCharFormat &format) { formats[construct] = format; } void SourceHighlighter::highlightBlock(const QString &text) { int state = previousBlockState(); int len = text.length(); int start = 0; int pos = 0; QRegExp regex; while (pos >= 0 && pos < len && len > 0) { switch (state) { default: case Normal: regex.setPattern(QLatin1String("[<&]")); pos = regex.indexIn(text, pos); if (pos >= 0) { if (text.at(pos) == QLatin1Char('<')) { start = pos; if (text.mid(pos, 4) == QLatin1String("<!--")) { state = InComment; } else { state = InTag; } ++pos; } else if (text.at(pos) == QLatin1Char('&')) { regex.setPattern(QLatin1String("&[a-zA-Z0-9]+;")); if (regex.indexIn(text, pos) == pos) { setFormat(pos, regex.matchedLength(), formats[Entity]); } ++pos; } } break; case InComment: regex.setPattern(QLatin1String("-->")); pos = regex.indexIn(text, pos); if (pos >= 0) { state = Normal; pos += 3; setFormat(start, pos - start, formats[Comment]); ++pos; } else { setFormat(start, len - start, formats[Comment]); } break; case InTag: regex.setPattern(QLatin1String("[>\"]")); pos = regex.indexIn(text, pos); if (pos >= 0) { if (text.at(pos) == QLatin1Char('>')) { state = Normal; ++pos; setFormat(start, pos - start, formats[Tag]); } else if (text.at(pos) == QLatin1Char('"')) { setFormat(start, pos - start, formats[Tag]); start = pos; state = InAttribute; ++pos; } } else { setFormat(start, len-start, formats[Tag]); } break; case InAttribute: regex.setPattern(QLatin1String("\"")); pos = regex.indexIn(text, pos); if (pos >= 0) { setFormat(start, pos - start, formats[Attribute]); state = InTag; start = ++pos; } else { setFormat(start, len - start, formats[Attribute]); } break; } } setCurrentBlockState(state); }
cfra/arora
src/sourcehighlighter.cpp
C++
gpl-2.0
6,364
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Function template extract_or_throw</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../index.html" title="Chapter&#160;1.&#160;Boost.Log v2"> <link rel="up" href="../../attributes.html#header.boost.log.attributes.value_extraction_hpp" title="Header &lt;boost/log/attributes/value_extraction.hpp&gt;"> <link rel="prev" href="extract_or_thr_idp42387536.html" title="Function template extract_or_throw"> <link rel="next" href="extract_or_thr_idp42403440.html" title="Function template extract_or_throw"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="extract_or_thr_idp42387536.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../attributes.html#header.boost.log.attributes.value_extraction_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="extract_or_thr_idp42403440.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.log.extract_or_thr_idp42395488"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Function template extract_or_throw</span></h2> <p>boost::log::extract_or_throw</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../attributes.html#header.boost.log.attributes.value_extraction_hpp" title="Header &lt;boost/log/attributes/value_extraction.hpp&gt;">boost/log/attributes/value_extraction.hpp</a>&gt; </span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> T<span class="special">,</span> <span class="keyword">typename</span> TagT <span class="special">=</span> <span class="keyword">void</span><span class="special">&gt;</span> <a class="link" href="result_of/extract_or_throw.html" title="Struct template extract_or_throw">result_of::extract_or_throw</a><span class="special">&lt;</span> <span class="identifier">T</span><span class="special">,</span> <span class="identifier">TagT</span> <span class="special">&gt;</span><span class="special">::</span><span class="identifier">type</span> <span class="identifier">extract_or_throw</span><span class="special">(</span><a class="link" href="attribute_name.html" title="Class attribute_name">attribute_name</a> <span class="keyword">const</span> <span class="special">&amp;</span> name<span class="special">,</span> <span class="identifier">record_view</span> <span class="keyword">const</span> <span class="special">&amp;</span> rec<span class="special">)</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp109962608"></a><h2>Description</h2> <p>The function extracts an attribute value from the view. The user has to explicitly specify the type or set of possible types of the attribute value to be extracted.</p> <p> </p> <div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term">Parameters:</span></p></td> <td><div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term"><code class="computeroutput">name</code></span></p></td> <td><p>The name of the attribute value to extract. </p></td> </tr> <tr> <td><p><span class="term"><code class="computeroutput">rec</code></span></p></td> <td><p>A log record view. The attribute value will be sought among those associated with the record. </p></td> </tr> </tbody> </table></div></td> </tr> <tr> <td><p><span class="term">Returns:</span></p></td> <td><p>The extracted value or a non-empty <code class="computeroutput">value_ref</code> that refers to the value. </p></td> </tr> <tr> <td><p><span class="term">Throws:</span></p></td> <td>An exception is thrown if the requested value cannot be extracted. </td> </tr> </tbody> </table></div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2007-2015 Andrey Semashev<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>). </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="extract_or_thr_idp42387536.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../attributes.html#header.boost.log.attributes.value_extraction_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="extract_or_thr_idp42403440.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
rprata/boost
libs/log/doc/html/boost/log/extract_or_thr_idp42395488.html
HTML
gpl-2.0
5,805
#ifndef OF_CONSTANTS #define OF_CONSTANTS //------------------------------- #define OF_VERSION 6 //------------------------------- //------------------------------- // find the system type -------- //------------------------------- // helpful: // http://www.ogre3d.org/docs/api/html/OgrePlatform_8h-source.html #if defined( __WIN32__ ) || defined( _WIN32 ) #define TARGET_WIN32 #elif defined( __APPLE_CC__) #include <TargetConditionals.h> #if (TARGET_OF_IPHONE_SIMULATOR) || (TARGET_OS_IPHONE) || (TARGET_IPHONE) #define TARGET_OF_IPHONE #define TARGET_OPENGLES #else #define TARGET_OSX #endif #else #define TARGET_LINUX #endif //------------------------------- // then the the platform specific includes: #ifdef TARGET_WIN32 //this is for TryEnterCriticalSection //http://www.zeroc.com/forums/help-center/351-ice-1-2-tryentercriticalsection-problem.html #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x400 #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include "GLee.h" #include "glu.h" #define __WINDOWS_DS__ #define __WINDOWS_MM__ #if (_MSC_VER) // microsoft visual studio #pragma warning(disable : 4996) // disable all deprecation warnings #pragma warning(disable : 4068) // unknown pragmas #pragma warning(disable : 4101) // unreferenced local variable #pragma warning(disable : 4312) // type cast conversion (in qt vp) #pragma warning(disable : 4311) // type cast pointer truncation (qt vp) #pragma warning(disable : 4018) // signed/unsigned mismatch (since vector.size() is a size_t) #pragma warning(disable : 4267) // conversion from size_t to Size warning... possible loss of data #pragma warning(disable : 4800) // 'Boolean' : forcing value to bool 'true' or 'false' #pragma warning(disable : 4099) // for debug, PDB 'vc80.pdb' was not found with... #endif #define TARGET_LITTLE_ENDIAN // intel cpu // some gl.h files, like dev-c++, are old - this is pretty universal #ifndef GL_BGR_EXT #define GL_BGR_EXT 0x80E0 #endif // #define WIN32_HIGH_RES_TIMING // note: this is experimental! // uncomment to turn this on (only for windows machines) // if you want to try setting the timer to be high resolution // this could make camera grabbing and other low level // operations quicker, but you must quit the app normally, // ie, using "esc", rather than killing the process or closing // the console window in order to set the timer resolution back // to normal (since the high res timer might give the OS // problems) // info: http://www.geisswerks.com/ryan/FAQS/timing.html #endif #ifdef TARGET_OSX #ifndef __MACOSX_CORE__ #define __MACOSX_CORE__ #endif #include <unistd.h> #include "GLee.h" #include <OpenGL/glu.h> #include <ApplicationServices/ApplicationServices.h> #if defined(__LITTLE_ENDIAN__) #define TARGET_LITTLE_ENDIAN // intel cpu #endif #endif #ifdef TARGET_LINUX #include <unistd.h> #include "GLee.h" #include <GL/glu.h> // for some reason, this isn't defined at compile time, // so this hack let's us work // for 99% of the linux folks that are on intel // everyone one else will have RGB / BGR issues. //#if defined(__LITTLE_ENDIAN__) #define TARGET_LITTLE_ENDIAN // intel cpu //#endif // some things for serial compilation: #define B14400 14400 #define B28800 28800 #endif #ifdef TARGET_OF_IPHONE #import <OpenGLES/ES1/gl.h> #import <OpenGLES/ES1/glext.h> #endif #ifndef __MWERKS__ #define OF_EXIT_APP(val) std::exit(val); #else #define OF_EXIT_APP(val) std::exit(val); #endif //------------------------------------------------ capture // if are linux #ifdef TARGET_LINUX // some cameras don't seem to work in unicap, so we keep // V4l code here. comment out this next line, to switch to the older // V4l code... // (if you change this, you might need to clean and rebuild, in CB build->rebuild) #define OF_SWITCH_TO_UNICAP_FOR_LINUX_VIDCAP #ifdef OF_SWITCH_TO_UNICAP_FOR_LINUX_VIDCAP #define OF_VIDEO_CAPTURE_UNICAP #else #define OF_VIDEO_CAPTURE_V4L #endif #else // non - linux, pc or osx // comment out this following line, if you'd like to use the // quicktime capture interface on windows // if not, we default to videoInput library for // direct show capture... #define OF_SWITCH_TO_DSHOW_FOR_WIN_VIDCAP #ifdef OF_SWITCH_TO_DSHOW_FOR_WIN_VIDCAP #ifdef TARGET_OSX #define OF_VIDEO_CAPTURE_QUICKTIME #else #define OF_VIDEO_CAPTURE_DIRECTSHOW #endif #else // all quicktime, all the time #define OF_VIDEO_CAPTURE_QUICKTIME #endif #endif #ifdef TARGET_LINUX #define OF_VIDEO_PLAYER_GSTREAMER #else #define OF_VIDEO_PLAYER_QUICKTIME #endif // comment out this line to disable all poco related code #ifndef TARGET_OF_IPHONE #define OF_USING_POCO #endif //we don't want to break old code that uses ofSimpleApp //so we forward declare ofBaseApp and make ofSimpleApp mean the same thing class ofBaseApp; typedef ofBaseApp ofSimpleApp; enum ofLogLevel{ OF_LOG_VERBOSE, OF_LOG_NOTICE, OF_LOG_WARNING, OF_LOG_ERROR, OF_LOG_FATAL_ERROR, OF_LOG_SILENT //this one is special and should always be last - set ofSetLogLevel to OF_SILENT to not recieve any messages }; #define OF_DEFAULT_LOG_LEVEL OF_LOG_WARNING; // serial error codes #define OF_SERIAL_NO_DATA -2 #define OF_SERIAL_ERROR -1 // core: --------------------------- #include <stdio.h> #include <stdarg.h> #include <math.h> #include <time.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <vector> #include <string> #include <sstream> //for ostringsream #include <iomanip> //for setprecision using namespace std; #ifndef PI #define PI 3.14159265358979323846 #endif #ifndef TWO_PI #define TWO_PI 6.28318530717958647693 #endif #ifndef M_TWO_PI #define M_TWO_PI 6.28318530717958647693 #endif #ifndef FOUR_PI #define FOUR_PI 12.56637061435917295385 #endif #ifndef HALF_PI #define HALF_PI 1.57079632679489661923 #endif #ifndef DEG_TO_RAD #define DEG_TO_RAD (PI/180.0) #endif #ifndef RAD_TO_DEG #define RAD_TO_DEG (180.0/PI) #endif #ifndef MIN #define MIN(x,y) (((x) < (y)) ? (x) : (y)) #endif #ifndef MAX #define MAX(x,y) (((x) > (y)) ? (x) : (y)) #endif #ifndef CLAMP #define CLAMP(val,min,max) (MAX(MIN(val,max),min)) #endif #ifndef ABS #define ABS(x) (((x) < 0) ? -(x) : (x)) #endif #define OF_FILLED 0x01 #define OF_OUTLINE 0x02 #define OF_WINDOW 0 #define OF_FULLSCREEN 1 #define OF_GAME_MODE 2 #define OF_RECTMODE_CORNER 0 #define OF_RECTMODE_CENTER 1 #define OF_IMAGE_GRAYSCALE 0x00 #define OF_IMAGE_COLOR 0x01 #define OF_IMAGE_COLOR_ALPHA 0x02 #define OF_IMAGE_UNDEFINED 0x03 #define OF_MAX_STYLE_HISTORY 32 #define OF_MAX_CIRCLE_PTS 1024 // these are straight out of glu, but renamed and included here // for convenience // // we don't mean to wrap the whole glu library (or any other library for that matter) // but these defines are useful to give people flexability over the polygonizer // // some info: // http://glprogramming.com/red/images/Image128.gif // // also: http://glprogramming.com/red/chapter11.html // (CSG ideas) #define OF_POLY_WINDING_ODD 100130 #define OF_POLY_WINDING_NONZERO 100131 #define OF_POLY_WINDING_POSITIVE 100132 #define OF_POLY_WINDING_NEGATIVE 100133 #define OF_POLY_WINDING_ABS_GEQ_TWO 100134 #define OF_CLOSE (true) //-------------------------------------------- // // Keyboard definitions // // ok -- why this? // glut key commands have some annoying features, // in that some normal keys have the same value as special keys, // but we want ONE key routine, so we need to redefine several, // so that we get some normalacy across keys routines // // (everything that comes through "glutSpecialKeyFunc" will get 256 added to it, // to avoid conflicts, before, values like "left, right up down" (ie, 104, 105, 106) were conflicting with // letters.. now they will be 256 + 104, 256 + 105....) #define OF_KEY_MODIFIER 0x0100 #define OF_KEY_RETURN 13 #define OF_KEY_ESC 27 // http://www.openframeworks.cc/forum/viewtopic.php?t=494 // some issues with keys across platforms: #ifdef TARGET_OSX #define OF_KEY_BACKSPACE 127 #define OF_KEY_DEL 8 #else #define OF_KEY_BACKSPACE 8 #define OF_KEY_DEL 127 #endif // zach - there are more of these keys, we can add them here... // these are keys that are not coming through "special keys" // via glut, but just other keys on your keyboard like #define OF_KEY_F1 (1 | OF_KEY_MODIFIER) #define OF_KEY_F2 (2 | OF_KEY_MODIFIER) #define OF_KEY_F3 (3 | OF_KEY_MODIFIER) #define OF_KEY_F4 (4 | OF_KEY_MODIFIER) #define OF_KEY_F5 (5 | OF_KEY_MODIFIER) #define OF_KEY_F6 (6 | OF_KEY_MODIFIER) #define OF_KEY_F7 (7 | OF_KEY_MODIFIER) #define OF_KEY_F8 (8 | OF_KEY_MODIFIER) #define OF_KEY_F9 (9 | OF_KEY_MODIFIER) #define OF_KEY_F10 (10 | OF_KEY_MODIFIER) #define OF_KEY_F11 (11 | OF_KEY_MODIFIER) #define OF_KEY_F12 (12 | OF_KEY_MODIFIER) #define OF_KEY_LEFT (100 | OF_KEY_MODIFIER) #define OF_KEY_UP (101 | OF_KEY_MODIFIER) #define OF_KEY_RIGHT (102 | OF_KEY_MODIFIER) #define OF_KEY_DOWN (103 | OF_KEY_MODIFIER) #define OF_KEY_PAGE_UP (104 | OF_KEY_MODIFIER) #define OF_KEY_PAGE_DOWN (105 | OF_KEY_MODIFIER) #define OF_KEY_HOME (106 | OF_KEY_MODIFIER) #define OF_KEY_END (107 | OF_KEY_MODIFIER) #define OF_KEY_INSERT (108 | OF_KEY_MODIFIER) // not sure what to do in the case of non-glut apps.... //-------------------------------------------- //console colors for our logger - shame this doesn't work with the xcode console #ifdef TARGET_WIN32 #define OF_CONSOLE_COLOR_RESTORE (0 | (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE) ) #define OF_CONSOLE_COLOR_BLACK (0) #define OF_CONSOLE_COLOR_RED (FOREGROUND_RED) #define OF_CONSOLE_COLOR_GREEN (FOREGROUND_GREEN) #define OF_CONSOLE_COLOR_YELLOW (FOREGROUND_RED|FOREGROUND_GREEN) #define OF_CONSOLE_COLOR_BLUE (FOREGROUND_BLUE) #define OF_CONSOLE_COLOR_PURPLE (FOREGROUND_RED | FOREGROUND_BLUE ) #define OF_CONSOLE_COLOR_CYAN (FOREGROUND_GREEN | FOREGROUND_BLUE) #define OF_CONSOLE_COLOR_WHITE (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE) #else #define OF_CONSOLE_COLOR_RESTORE (0) #define OF_CONSOLE_COLOR_BLACK (30) #define OF_CONSOLE_COLOR_RED (31) #define OF_CONSOLE_COLOR_GREEN (32) #define OF_CONSOLE_COLOR_YELLOW (33) #define OF_CONSOLE_COLOR_BLUE (34) #define OF_CONSOLE_COLOR_PURPLE (35) #define OF_CONSOLE_COLOR_CYAN (36) #define OF_CONSOLE_COLOR_WHITE (37) #endif //-------------------------------------------- #endif
ehsan108190/ccv-hand
CCV-HAND_Windows/libs/openFrameworks/utils/ofConstants.h
C
gpl-2.0
11,186
/* LUFA Library Copyright (C) Dean Camera, 2014. dean [at] fourwalledcubicle [dot] com www.lufa-lib.org */ /* Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com) Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaims all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /** \file * * Header file for ConfigDescriptor.c. */ #ifndef _CONFIGDESCRIPTOR_H_ #define _CONFIGDESCRIPTOR_H_ /* Includes: */ #include <LUFA/Drivers/USB/USB.h> #include "HIDReport.h" /* Macros: */ /** Pipe address for the keyboard report data IN pipe. */ #define KEYBOARD_DATA_IN_PIPE (PIPE_DIR_IN | 1) /* Enums: */ /** Enum for the possible return codes of the \ref ProcessConfigurationDescriptor() function. */ enum KeyboardHostWithParser_GetConfigDescriptorDataCodes_t { SuccessfulConfigRead = 0, /**< Configuration Descriptor was processed successfully */ ControlError = 1, /**< A control request to the device failed to complete successfully */ DescriptorTooLarge = 2, /**< The device's Configuration Descriptor is too large to process */ InvalidConfigDataReturned = 3, /**< The device returned an invalid Configuration Descriptor */ NoCompatibleInterfaceFound = 4, /**< A compatible interface with the required endpoints was not found */ }; /* Function Prototypes: */ uint8_t ProcessConfigurationDescriptor(void); uint8_t DComp_NextKeyboardInterface(void* CurrentDescriptor); uint8_t DComp_NextKeyboardInterfaceDataEndpoint(void* CurrentDescriptor); uint8_t DComp_NextHID(void* CurrentDescriptor); #endif
ruriwo/ErgoThumb072_firmware
tmk_core/protocol/lufa/LUFA-git/Demos/Host/LowLevel/KeyboardHostWithParser/ConfigDescriptor.h
C
gpl-2.0
2,509
///////////////////////////////////////////////////////////////////////////// // Name: src/msw/textctrl.cpp // Purpose: wxTextCtrl // Author: Julian Smart // Modified by: // Created: 04/01/98 // RCS-ID: $Id: textctrl.cpp 60394 2009-04-26 18:41:02Z VZ $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_TEXTCTRL && !(defined(__SMARTPHONE__) && defined(__WXWINCE__)) #ifndef WX_PRECOMP #include "wx/textctrl.h" #include "wx/settings.h" #include "wx/brush.h" #include "wx/utils.h" #include "wx/intl.h" #include "wx/log.h" #include "wx/app.h" #include "wx/menu.h" #include "wx/math.h" #include "wx/module.h" #endif #include "wx/sysopt.h" #if wxUSE_CLIPBOARD #include "wx/clipbrd.h" #endif #include "wx/textfile.h" #include <windowsx.h> #include "wx/msw/private.h" #include "wx/msw/winundef.h" #include "wx/msw/mslu.h" #include <string.h> #include <stdlib.h> #ifndef __WXWINCE__ #include <sys/types.h> #endif #if wxUSE_RICHEDIT #if wxUSE_INKEDIT #include "wx/dynlib.h" #endif // old mingw32 has richedit stuff directly in windows.h and doesn't have // richedit.h at all #if !defined(__GNUWIN32_OLD__) || defined(__CYGWIN10__) #include <richedit.h> #endif #endif // wxUSE_RICHEDIT #include "wx/msw/missing.h" // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- #if wxUSE_RICHEDIT // this module initializes RichEdit DLL(s) if needed class wxRichEditModule : public wxModule { public: enum Version { Version_1, // riched32.dll Version_2or3, // both use riched20.dll Version_41, // msftedit.dll (XP SP1 and Windows 2003) Version_Max }; virtual bool OnInit(); virtual void OnExit(); // load the richedit DLL for the specified version of rich edit static bool Load(Version version); #if wxUSE_INKEDIT // load the InkEdit library static bool LoadInkEdit(); #endif private: // the handles to richedit 1.0 and 2.0 (or 3.0) DLLs static HINSTANCE ms_hRichEdit[Version_Max]; #if wxUSE_INKEDIT static wxDynamicLibrary ms_inkEditLib; static bool ms_inkEditLibLoadAttemped; #endif DECLARE_DYNAMIC_CLASS(wxRichEditModule) }; HINSTANCE wxRichEditModule::ms_hRichEdit[Version_Max] = { NULL, NULL, NULL }; #if wxUSE_INKEDIT wxDynamicLibrary wxRichEditModule::ms_inkEditLib; bool wxRichEditModule::ms_inkEditLibLoadAttemped = false; #endif IMPLEMENT_DYNAMIC_CLASS(wxRichEditModule, wxModule) #endif // wxUSE_RICHEDIT // a small class used to set m_updatesCount to 0 (to filter duplicate events if // necessary) and to reset it back to -1 afterwards class UpdatesCountFilter { public: UpdatesCountFilter(int& count) : m_count(count) { wxASSERT_MSG( m_count == -1 || m_count == -2, _T("wrong initial m_updatesCount value") ); if (m_count != -2) m_count = 0; //else: we don't want to count how many update events we get as we're going // to ignore all of them } ~UpdatesCountFilter() { m_count = -1; } // return true if an event has been received bool GotUpdate() const { return m_count == 1; } private: int& m_count; DECLARE_NO_COPY_CLASS(UpdatesCountFilter) }; // ---------------------------------------------------------------------------- // event tables and other macros // ---------------------------------------------------------------------------- #if wxUSE_EXTENDED_RTTI WX_DEFINE_FLAGS( wxTextCtrlStyle ) wxBEGIN_FLAGS( wxTextCtrlStyle ) // new style border flags, we put them first to // use them for streaming out wxFLAGS_MEMBER(wxBORDER_SIMPLE) wxFLAGS_MEMBER(wxBORDER_SUNKEN) wxFLAGS_MEMBER(wxBORDER_DOUBLE) wxFLAGS_MEMBER(wxBORDER_RAISED) wxFLAGS_MEMBER(wxBORDER_STATIC) wxFLAGS_MEMBER(wxBORDER_NONE) // old style border flags wxFLAGS_MEMBER(wxSIMPLE_BORDER) wxFLAGS_MEMBER(wxSUNKEN_BORDER) wxFLAGS_MEMBER(wxDOUBLE_BORDER) wxFLAGS_MEMBER(wxRAISED_BORDER) wxFLAGS_MEMBER(wxSTATIC_BORDER) wxFLAGS_MEMBER(wxBORDER) // standard window styles wxFLAGS_MEMBER(wxTAB_TRAVERSAL) wxFLAGS_MEMBER(wxCLIP_CHILDREN) wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW) wxFLAGS_MEMBER(wxWANTS_CHARS) wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE) wxFLAGS_MEMBER(wxALWAYS_SHOW_SB ) wxFLAGS_MEMBER(wxVSCROLL) wxFLAGS_MEMBER(wxHSCROLL) wxFLAGS_MEMBER(wxTE_PROCESS_ENTER) wxFLAGS_MEMBER(wxTE_PROCESS_TAB) wxFLAGS_MEMBER(wxTE_MULTILINE) wxFLAGS_MEMBER(wxTE_PASSWORD) wxFLAGS_MEMBER(wxTE_READONLY) wxFLAGS_MEMBER(wxHSCROLL) wxFLAGS_MEMBER(wxTE_RICH) wxFLAGS_MEMBER(wxTE_RICH2) wxFLAGS_MEMBER(wxTE_AUTO_URL) wxFLAGS_MEMBER(wxTE_NOHIDESEL) wxFLAGS_MEMBER(wxTE_LEFT) wxFLAGS_MEMBER(wxTE_CENTRE) wxFLAGS_MEMBER(wxTE_RIGHT) wxFLAGS_MEMBER(wxTE_DONTWRAP) wxFLAGS_MEMBER(wxTE_CHARWRAP) wxFLAGS_MEMBER(wxTE_WORDWRAP) wxEND_FLAGS( wxTextCtrlStyle ) IMPLEMENT_DYNAMIC_CLASS_XTI(wxTextCtrl, wxControl,"wx/textctrl.h") wxBEGIN_PROPERTIES_TABLE(wxTextCtrl) wxEVENT_PROPERTY( TextUpdated , wxEVT_COMMAND_TEXT_UPDATED , wxCommandEvent ) wxEVENT_PROPERTY( TextEnter , wxEVT_COMMAND_TEXT_ENTER , wxCommandEvent ) wxPROPERTY( Font , wxFont , SetFont , GetFont , EMPTY_MACROVALUE, 0 /*flags*/ , wxT("Helpstring") , wxT("group") ) wxPROPERTY( Value , wxString , SetValue, GetValue, wxString() , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) wxPROPERTY_FLAGS( WindowStyle , wxTextCtrlStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style wxEND_PROPERTIES_TABLE() wxBEGIN_HANDLERS_TABLE(wxTextCtrl) wxEND_HANDLERS_TABLE() wxCONSTRUCTOR_6( wxTextCtrl , wxWindow* , Parent , wxWindowID , Id , wxString , Value , wxPoint , Position , wxSize , Size , long , WindowStyle) #else IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxTextCtrlBase) #endif BEGIN_EVENT_TABLE(wxTextCtrl, wxTextCtrlBase) EVT_CHAR(wxTextCtrl::OnChar) EVT_KEY_DOWN(wxTextCtrl::OnKeyDown) EVT_DROP_FILES(wxTextCtrl::OnDropFiles) #if wxUSE_RICHEDIT EVT_CONTEXT_MENU(wxTextCtrl::OnContextMenu) #endif EVT_MENU(wxID_CUT, wxTextCtrl::OnCut) EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy) EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste) EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo) EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo) EVT_MENU(wxID_CLEAR, wxTextCtrl::OnDelete) EVT_MENU(wxID_SELECTALL, wxTextCtrl::OnSelectAll) EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut) EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy) EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste) EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo) EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo) EVT_UPDATE_UI(wxID_CLEAR, wxTextCtrl::OnUpdateDelete) EVT_UPDATE_UI(wxID_SELECTALL, wxTextCtrl::OnUpdateSelectAll) EVT_SET_FOCUS(wxTextCtrl::OnSetFocus) END_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // creation // ---------------------------------------------------------------------------- void wxTextCtrl::Init() { #if wxUSE_RICHEDIT m_verRichEdit = 0; #endif // wxUSE_RICHEDIT #if wxUSE_INKEDIT && wxUSE_RICHEDIT m_isInkEdit = 0; #endif m_privateContextMenu = NULL; m_updatesCount = -1; m_isNativeCaretShown = true; } wxTextCtrl::~wxTextCtrl() { delete m_privateContextMenu; } bool wxTextCtrl::Create(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) { #ifdef __WXWINCE__ if ((style & wxBORDER_MASK) == 0) style |= wxBORDER_SIMPLE; #else // Standard text control already handles theming if ((style & (wxTE_RICH|wxTE_RICH2)) && ((style & wxBORDER_MASK) == wxBORDER_DEFAULT)) style |= wxBORDER_THEME; #endif // base initialization if ( !CreateControl(parent, id, pos, size, style, validator, name) ) return false; if ( !MSWCreateText(value, pos, size) ) return false; return true; } bool wxTextCtrl::MSWCreateText(const wxString& value, const wxPoint& pos, const wxSize& size) { // translate wxWin style flags to MSW ones WXDWORD msStyle = MSWGetCreateWindowFlags(); // do create the control - either an EDIT or RICHEDIT wxString windowClass = wxT("EDIT"); #if defined(__POCKETPC__) || defined(__SMARTPHONE__) // A control that capitalizes the first letter if ( HasFlag(wxTE_CAPITALIZE) ) windowClass = wxT("CAPEDIT"); #endif #if wxUSE_RICHEDIT if ( m_windowStyle & wxTE_AUTO_URL ) { // automatic URL detection only works in RichEdit 2.0+ m_windowStyle |= wxTE_RICH2; } if ( m_windowStyle & wxTE_RICH2 ) { // using richedit 2.0 implies using wxTE_RICH m_windowStyle |= wxTE_RICH; } // we need to load the richedit DLL before creating the rich edit control if ( m_windowStyle & wxTE_RICH ) { // versions 2.0, 3.0 and 4.1 of rich edit are mostly compatible with // each other but not with version 1.0, so we have separate flags for // the version 1.0 and the others (and so m_verRichEdit may be 0 (plain // EDIT control), 1 for version 1.0 or 2 for any higher version) // // notice that 1.0 has no Unicode support at all so in Unicode build we // must use another version #if wxUSE_UNICODE m_verRichEdit = 2; #else // !wxUSE_UNICODE m_verRichEdit = m_windowStyle & wxTE_RICH2 ? 2 : 1; #endif // wxUSE_UNICODE/!wxUSE_UNICODE #if wxUSE_INKEDIT // First test if we can load an ink edit control. Normally, all edit // controls will be made ink edit controls if a tablet environment is // found (or if msw.inkedit != 0 and the InkEd.dll is present). // However, an application can veto ink edit controls by either specifying // msw.inkedit = 0 or by removing wxTE_RICH[2] from the style. // if ((wxSystemSettings::HasFeature(wxSYS_TABLET_PRESENT) || wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) != 0) && !(wxSystemOptions::HasOption(wxT("msw.inkedit")) && wxSystemOptions::GetOptionInt(wxT("msw.inkedit")) == 0)) { if (wxRichEditModule::LoadInkEdit()) { windowClass = INKEDIT_CLASS; #if wxUSE_INKEDIT && wxUSE_RICHEDIT m_isInkEdit = 1; #endif // Fake rich text version for other calls m_verRichEdit = 2; } } #endif if (!IsInkEdit()) { if ( m_verRichEdit == 2 ) { if ( wxRichEditModule::Load(wxRichEditModule::Version_41) ) { // yes, class name for version 4.1 really is 5.0 windowClass = _T("RICHEDIT50W"); } else if ( wxRichEditModule::Load(wxRichEditModule::Version_2or3) ) { windowClass = _T("RichEdit20") #if wxUSE_UNICODE _T("W"); #else // ANSI _T("A"); #endif // Unicode/ANSI } else // failed to load msftedit.dll and riched20.dll { m_verRichEdit = 1; } } if ( m_verRichEdit == 1 ) { if ( wxRichEditModule::Load(wxRichEditModule::Version_1) ) { windowClass = _T("RICHEDIT"); } else // failed to load any richedit control DLL { // only give the error msg once if the DLL can't be loaded static bool s_errorGiven = false; // MT ok as only used by GUI if ( !s_errorGiven ) { wxLogError(_("Impossible to create a rich edit control, using simple text control instead. Please reinstall riched32.dll")); s_errorGiven = true; } m_verRichEdit = 0; } } } // !useInkEdit } #endif // wxUSE_RICHEDIT // we need to turn '\n's into "\r\n"s for the multiline controls wxString valueWin; if ( m_windowStyle & wxTE_MULTILINE ) { valueWin = wxTextFile::Translate(value, wxTextFileType_Dos); } else // single line { valueWin = value; } if ( !MSWCreateControl(windowClass, msStyle, pos, size, valueWin) ) return false; #if wxUSE_RICHEDIT if (IsRich()) { #if wxUSE_INKEDIT if (IsInkEdit()) { // Pass IEM_InsertText (0) as wParam, in order to have the ink always // converted to text. ::SendMessage(GetHwnd(), EM_SETINKINSERTMODE, 0, 0); // Make sure the mouse can be used for input ::SendMessage(GetHwnd(), EM_SETUSEMOUSEFORINPUT, 1, 0); } #endif // enable the events we're interested in: we want to get EN_CHANGE as // for the normal controls LPARAM mask = ENM_CHANGE; if (GetRichVersion() == 1 && !IsInkEdit()) { // we also need EN_MSGFILTER for richedit 1.0 for the reasons // explained in its handler mask |= ENM_MOUSEEVENTS; // we also need to force the appearance of the vertical scrollbar // initially as otherwise the control doesn't refresh correctly // after resize: but once the vertical scrollbar had been shown // (even if it's subsequently hidden) it does // // this is clearly a bug and for now it has been only noticed under // Windows XP, so if we're sure it works correctly under other // systems we could do this only for XP SetSize(-1, 1); // 1 is small enough to force vert scrollbar SetInitialSize(size); } else if ( m_windowStyle & wxTE_AUTO_URL ) { mask |= ENM_LINK; ::SendMessage(GetHwnd(), EM_AUTOURLDETECT, TRUE, 0); } ::SendMessage(GetHwnd(), EM_SETEVENTMASK, 0, mask); } #endif // wxUSE_RICHEDIT #ifndef __WXWINCE__ // Without this, if we pass the size in the constructor and then don't change it, // the themed borders will be drawn incorrectly. SetWindowPos(GetHwnd(), NULL, 0, 0, 0, 0, SWP_NOZORDER|SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE| SWP_FRAMECHANGED); #endif return true; } // Make sure the window style (etc.) reflects the HWND style (roughly) void wxTextCtrl::AdoptAttributesFromHWND() { wxWindow::AdoptAttributesFromHWND(); HWND hWnd = GetHwnd(); long style = ::GetWindowLong(hWnd, GWL_STYLE); // retrieve the style to see whether this is an edit or richedit ctrl #if wxUSE_RICHEDIT wxString classname = wxGetWindowClass(GetHWND()); if ( classname.IsSameAs(_T("EDIT"), false /* no case */) ) { m_verRichEdit = 0; } else // rich edit? { wxChar c; if ( wxSscanf(classname, _T("RichEdit%d0%c"), &m_verRichEdit, &c) != 2 ) { wxLogDebug(_T("Unknown edit control '%s'."), classname.c_str()); m_verRichEdit = 0; } } #endif // wxUSE_RICHEDIT if (style & ES_MULTILINE) m_windowStyle |= wxTE_MULTILINE; if (style & ES_PASSWORD) m_windowStyle |= wxTE_PASSWORD; if (style & ES_READONLY) m_windowStyle |= wxTE_READONLY; if (style & ES_WANTRETURN) m_windowStyle |= wxTE_PROCESS_ENTER; if (style & ES_CENTER) m_windowStyle |= wxTE_CENTRE; if (style & ES_RIGHT) m_windowStyle |= wxTE_RIGHT; } WXDWORD wxTextCtrl::MSWGetStyle(long style, WXDWORD *exstyle) const { long msStyle = wxControl::MSWGetStyle(style, exstyle); // styles which we alaways add by default if ( style & wxTE_MULTILINE ) { msStyle |= ES_MULTILINE | ES_WANTRETURN; if ( !(style & wxTE_NO_VSCROLL) ) { // always adjust the vertical scrollbar automatically if we have it msStyle |= WS_VSCROLL | ES_AUTOVSCROLL; #if wxUSE_RICHEDIT // we have to use this style for the rich edit controls because // without it the vertical scrollbar never appears at all in // richedit 3.0 because of our ECO_NOHIDESEL hack (search for it) if ( style & wxTE_RICH2 ) { msStyle |= ES_DISABLENOSCROLL; } #endif // wxUSE_RICHEDIT } style |= wxTE_PROCESS_ENTER; } else // !multiline { // there is really no reason to not have this style for single line // text controls msStyle |= ES_AUTOHSCROLL; } // note that wxTE_DONTWRAP is the same as wxHSCROLL so if we have a horz // scrollbar, there is no wrapping -- which makes sense if ( style & wxTE_DONTWRAP ) { // automatically scroll the control horizontally as necessary // // NB: ES_AUTOHSCROLL is needed for richedit controls or they don't // show horz scrollbar at all, even in spite of WS_HSCROLL, and as // it doesn't seem to do any harm for plain edit controls, add it // always msStyle |= WS_HSCROLL | ES_AUTOHSCROLL; } if ( style & wxTE_READONLY ) msStyle |= ES_READONLY; if ( style & wxTE_PASSWORD ) msStyle |= ES_PASSWORD; if ( style & wxTE_NOHIDESEL ) msStyle |= ES_NOHIDESEL; // note that we can't do do "& wxTE_LEFT" as wxTE_LEFT == 0 if ( style & wxTE_CENTRE ) msStyle |= ES_CENTER; else if ( style & wxTE_RIGHT ) msStyle |= ES_RIGHT; else msStyle |= ES_LEFT; // ES_LEFT is 0 as well but for consistency... return msStyle; } void wxTextCtrl::SetWindowStyleFlag(long style) { // changing the alignment of the control dynamically works under Win2003 // (but not older Windows version: it seems to work under some versions of // XP but not other ones, and we have no way to determine it so be // conservative here) and only for plain EDIT controls (not RICH ones) and // we have to recreate the control to make it always work if ( IsRich() || wxGetWinVersion() < wxWinVersion_2003 ) { const long alignMask = wxTE_LEFT | wxTE_CENTRE | wxTE_RIGHT; if ( (style & alignMask) != (GetWindowStyle() & alignMask) ) { const wxString value = GetValue(); const wxPoint pos = GetPosition(); const wxSize size = GetSize(); // delete the old window HWND hwnd = GetHwnd(); DissociateHandle(); ::DestroyWindow(hwnd); // create the new one with the updated flags m_windowStyle = style; MSWCreateText(value, pos, size); // and make sure it has the same attributes as before if ( m_hasFont ) { // calling SetFont(m_font) would do nothing as the code would // notice that the font didn't change, so force it to believe // that it did wxFont font = m_font; m_font = wxNullFont; SetFont(font); } if ( m_hasFgCol ) { wxColour colFg = m_foregroundColour; m_foregroundColour = wxNullColour; SetForegroundColour(colFg); } if ( m_hasBgCol ) { wxColour colBg = m_backgroundColour; m_backgroundColour = wxNullColour; SetBackgroundColour(colBg); } // note that text styles are lost but this is probably not a big // problem: if you use styles, you probably don't use nor change // alignment flags anyhow return; } } #if wxUSE_RICHEDIT // we have to deal with some styles separately because they can't be // changed by simply calling SetWindowLong(GWL_STYLE) but can be changed // using richedit-specific EM_SETOPTIONS if ( IsRich() && ((style & wxTE_NOHIDESEL) != (GetWindowStyle() & wxTE_NOHIDESEL)) ) { bool set = (style & wxTE_NOHIDESEL) != 0; ::SendMessage(GetHwnd(), EM_SETOPTIONS, set ? ECOOP_OR : ECOOP_AND, set ? ECO_NOHIDESEL : ~ECO_NOHIDESEL); } #endif // wxUSE_RICHEDIT wxControl::SetWindowStyleFlag(style); } // ---------------------------------------------------------------------------- // set/get the controls text // ---------------------------------------------------------------------------- bool wxTextCtrl::IsEmpty() const { // this is an optimization for multiline controls containing a lot of text if ( IsMultiLine() && GetNumberOfLines() != 1 ) return false; return wxTextCtrlBase::IsEmpty(); } wxString wxTextCtrl::GetValue() const { // range 0..-1 is special for GetRange() and means to retrieve all text return GetRange(0, -1); } wxString wxTextCtrl::GetRange(long from, long to) const { wxString str; if ( from >= to && to != -1 ) { // nothing to retrieve return str; } #if wxUSE_RICHEDIT if ( IsRich() ) { int len = GetWindowTextLength(GetHwnd()); if ( len > from ) { if ( to == -1 ) to = len; #if !wxUSE_UNICODE // we must use EM_STREAMOUT if we don't want to lose all characters // not representable in the current character set (EM_GETTEXTRANGE // simply replaces them with question marks...) if ( GetRichVersion() > 1 ) { // we must have some encoding, otherwise any 8bit chars in the // control are simply *lost* (replaced by '?') wxFontEncoding encoding = wxFONTENCODING_SYSTEM; wxFont font = m_defaultStyle.GetFont(); if ( !font.Ok() ) font = GetFont(); if ( font.Ok() ) { encoding = font.GetEncoding(); } #if wxUSE_INTL if ( encoding == wxFONTENCODING_SYSTEM ) { encoding = wxLocale::GetSystemEncoding(); } #endif // wxUSE_INTL if ( encoding == wxFONTENCODING_SYSTEM ) { encoding = wxFONTENCODING_ISO8859_1; } str = StreamOut(encoding); if ( !str.empty() ) { // we have to manually extract the required part, luckily // this is easy in this case as EOL characters in str are // just LFs because we remove CRs in wxRichEditStreamOut str = str.Mid(from, to - from); } } // StreamOut() wasn't used or failed, try to do it in normal way if ( str.empty() ) #endif // !wxUSE_UNICODE { // alloc one extra WORD as needed by the control wxStringBuffer tmp(str, ++len); wxChar *p = tmp; TEXTRANGE textRange; textRange.chrg.cpMin = from; textRange.chrg.cpMax = to; textRange.lpstrText = p; (void)::SendMessage(GetHwnd(), EM_GETTEXTRANGE, 0, (LPARAM)&textRange); if ( m_verRichEdit > 1 ) { // RichEdit 2.0 uses just CR ('\r') for the // newlines which is neither Unix nor Windows // style - convert it to something reasonable for ( ; *p; p++ ) { if ( *p == _T('\r') ) *p = _T('\n'); } } } if ( m_verRichEdit == 1 ) { // convert to the canonical form - see comment below str = wxTextFile::Translate(str, wxTextFileType_Unix); } } //else: no text at all, leave the string empty } else #endif // wxUSE_RICHEDIT { // retrieve all text str = wxGetWindowText(GetHWND()); // need only a range? if ( from < to ) { str = str.Mid(from, to - from); } // WM_GETTEXT uses standard DOS CR+LF (\r\n) convention - convert to the // canonical one (same one as above) for consistency with the other kinds // of controls and, more importantly, with the other ports str = wxTextFile::Translate(str, wxTextFileType_Unix); } return str; } void wxTextCtrl::DoSetValue(const wxString& value, int flags) { // if the text is long enough, it's faster to just set it instead of first // comparing it with the old one (chances are that it will be different // anyhow, this comparison is there to avoid flicker for small single-line // edit controls mostly) if ( (value.length() > 0x400) || (value != GetValue()) ) { DoWriteText(value, flags /* doesn't include SelectionOnly here */); // mark the control as being not dirty - we changed its text, not the // user DiscardEdits(); // for compatibility, don't move the cursor when doing SetValue() SetInsertionPoint(0); } else // same text { // still reset the modified flag even if the value didn't really change // because now it comes from the program and not the user (and do it // before generating the event so that the event handler could get the // expected value from IsModified()) DiscardEdits(); // still send an event for consistency if (flags & SetValue_SendEvent) SendUpdateEvent(); } } #if wxUSE_RICHEDIT && (!wxUSE_UNICODE || wxUSE_UNICODE_MSLU) // TODO: using memcpy() would improve performance a lot for big amounts of text DWORD CALLBACK wxRichEditStreamIn(DWORD dwCookie, BYTE *buf, LONG cb, LONG *pcb) { *pcb = 0; const wchar_t ** const ppws = (const wchar_t **)dwCookie; wchar_t *wbuf = (wchar_t *)buf; const wchar_t *wpc = *ppws; while ( cb && *wpc ) { *wbuf++ = *wpc++; cb -= sizeof(wchar_t); (*pcb) += sizeof(wchar_t); } *ppws = wpc; return 0; } // helper struct used to pass parameters from wxTextCtrl to wxRichEditStreamOut struct wxStreamOutData { wchar_t *wpc; size_t len; }; DWORD CALLBACK wxRichEditStreamOut(DWORD_PTR dwCookie, BYTE *buf, LONG cb, LONG *pcb) { *pcb = 0; wxStreamOutData *data = (wxStreamOutData *)dwCookie; const wchar_t *wbuf = (const wchar_t *)buf; wchar_t *wpc = data->wpc; while ( cb ) { wchar_t wch = *wbuf++; // turn "\r\n" into "\n" on the fly if ( wch != L'\r' ) *wpc++ = wch; else data->len--; cb -= sizeof(wchar_t); (*pcb) += sizeof(wchar_t); } data->wpc = wpc; return 0; } #if wxUSE_UNICODE_MSLU #define UNUSED_IF_MSLU(param) #else #define UNUSED_IF_MSLU(param) param #endif bool wxTextCtrl::StreamIn(const wxString& value, wxFontEncoding UNUSED_IF_MSLU(encoding), bool selectionOnly) { #if wxUSE_UNICODE_MSLU const wchar_t *wpc = value.c_str(); #else // !wxUSE_UNICODE_MSLU wxCSConv conv(encoding); const size_t len = conv.MB2WC(NULL, value, value.length()); if (len == wxCONV_FAILED) return false; #if wxUSE_WCHAR_T wxWCharBuffer wchBuf(len); // allocates one extra character wchar_t *wpc = wchBuf.data(); #else wchar_t *wchBuf = (wchar_t *)malloc((len + 1)*sizeof(wchar_t)); wchar_t *wpc = wchBuf; #endif conv.MB2WC(wpc, value, len + 1); #endif // wxUSE_UNICODE_MSLU // finally, stream it in the control EDITSTREAM eds; wxZeroMemory(eds); eds.dwCookie = (DWORD)&wpc; // the cast below is needed for broken (very) old mingw32 headers eds.pfnCallback = (EDITSTREAMCALLBACK)wxRichEditStreamIn; // same problem as in DoWriteText(): we can get multiple events here UpdatesCountFilter ucf(m_updatesCount); ::SendMessage(GetHwnd(), EM_STREAMIN, SF_TEXT | SF_UNICODE | (selectionOnly ? SFF_SELECTION : 0), (LPARAM)&eds); // It's okay for EN_UPDATE to not be sent if the selection is empty and // the text is empty, otherwise warn the programmer about it. wxASSERT_MSG( ucf.GotUpdate() || ( !HasSelection() && value.empty() ), _T("EM_STREAMIN didn't send EN_UPDATE?") ); if ( eds.dwError ) { wxLogLastError(_T("EM_STREAMIN")); } #if !wxUSE_WCHAR_T free(wchBuf); #endif // !wxUSE_WCHAR_T return true; } #if !wxUSE_UNICODE_MSLU wxString wxTextCtrl::StreamOut(wxFontEncoding encoding, bool selectionOnly) const { wxString out; const int len = GetWindowTextLength(GetHwnd()); #if wxUSE_WCHAR_T wxWCharBuffer wchBuf(len); wchar_t *wpc = wchBuf.data(); #else wchar_t *wchBuf = (wchar_t *)malloc((len + 1)*sizeof(wchar_t)); wchar_t *wpc = wchBuf; #endif wxStreamOutData data; data.wpc = wpc; data.len = len; EDITSTREAM eds; wxZeroMemory(eds); eds.dwCookie = (DWORD)&data; eds.pfnCallback = wxRichEditStreamOut; ::SendMessage ( GetHwnd(), EM_STREAMOUT, SF_TEXT | SF_UNICODE | (selectionOnly ? SFF_SELECTION : 0), (LPARAM)&eds ); if ( eds.dwError ) { wxLogLastError(_T("EM_STREAMOUT")); } else // streamed out ok { // NUL-terminate the string because its length could have been // decreased by wxRichEditStreamOut *(wchBuf.data() + data.len) = L'\0'; // now convert to the given encoding (this is a possibly lossful // conversion but what else can we do) wxCSConv conv(encoding); size_t lenNeeded = conv.WC2MB(NULL, wchBuf, 0); if ( lenNeeded != wxCONV_FAILED && lenNeeded++ ) { conv.WC2MB(wxStringBuffer(out, lenNeeded), wchBuf, lenNeeded); } } #if !wxUSE_WCHAR_T free(wchBuf); #endif // !wxUSE_WCHAR_T return out; } #endif // !wxUSE_UNICODE_MSLU #endif // wxUSE_RICHEDIT void wxTextCtrl::WriteText(const wxString& value) { DoWriteText(value); } void wxTextCtrl::DoWriteText(const wxString& value, int flags) { bool selectionOnly = (flags & SetValue_SelectionOnly) != 0; wxString valueDos; if ( m_windowStyle & wxTE_MULTILINE ) valueDos = wxTextFile::Translate(value, wxTextFileType_Dos); else valueDos = value; #if wxUSE_RICHEDIT // there are several complications with the rich edit controls here bool done = false; if ( IsRich() ) { // first, ensure that the new text will be in the default style if ( !m_defaultStyle.IsDefault() ) { long start, end; GetSelection(&start, &end); SetStyle(start, end, m_defaultStyle); } #if wxUSE_UNICODE_MSLU // RichEdit doesn't have Unicode version of EM_REPLACESEL on Win9x, // but EM_STREAMIN works if ( wxUsingUnicowsDll() && GetRichVersion() > 1 ) { done = StreamIn(valueDos, wxFONTENCODING_SYSTEM, selectionOnly); } #endif // wxUSE_UNICODE_MSLU #if !wxUSE_UNICODE // next check if the text we're inserting must be shown in a non // default charset -- this only works for RichEdit > 1.0 if ( GetRichVersion() > 1 ) { wxFont font = m_defaultStyle.GetFont(); if ( !font.Ok() ) font = GetFont(); if ( font.Ok() ) { wxFontEncoding encoding = font.GetEncoding(); if ( encoding != wxFONTENCODING_SYSTEM ) { // we have to use EM_STREAMIN to force richedit control 2.0+ // to show any text in the non default charset -- otherwise // it thinks it knows better than we do and always shows it // in the default one done = StreamIn(valueDos, encoding, selectionOnly); } } } #endif // !wxUSE_UNICODE } if ( !done ) #endif // wxUSE_RICHEDIT { // in some cases we get 2 EN_CHANGE notifications after the SendMessage // call (this happens for plain EDITs with EM_REPLACESEL and under some // -- undetermined -- conditions with rich edit) and sometimes we don't // get any events at all (plain EDIT with WM_SETTEXT), so ensure that // we generate exactly one of them by ignoring all but the first one in // SendUpdateEvent() and generating one ourselves if we hadn't got any // notifications from Windows if ( !(flags & SetValue_SendEvent) ) m_updatesCount = -2; // suppress any update event UpdatesCountFilter ucf(m_updatesCount); ::SendMessage(GetHwnd(), selectionOnly ? EM_REPLACESEL : WM_SETTEXT, // EM_REPLACESEL takes 1 to indicate the operation should be redoable selectionOnly ? 1 : 0, (LPARAM)valueDos.c_str()); if ( !ucf.GotUpdate() && (flags & SetValue_SendEvent) ) { SendUpdateEvent(); } } } void wxTextCtrl::AppendText(const wxString& text) { SetInsertionPointEnd(); WriteText(text); #if wxUSE_RICHEDIT // don't do this if we're frozen, saves some time if ( !IsFrozen() && IsMultiLine() && GetRichVersion() > 1 ) { // setting the caret to the end and showing it simply doesn't work for // RichEdit 2.0 -- force it to still do what we want ::SendMessage(GetHwnd(), EM_LINESCROLL, 0, GetNumberOfLines()); } #endif // wxUSE_RICHEDIT } void wxTextCtrl::Clear() { ::SetWindowText(GetHwnd(), wxEmptyString); #if wxUSE_RICHEDIT if ( !IsRich() ) #endif // wxUSE_RICHEDIT { // rich edit controls send EN_UPDATE from WM_SETTEXT handler themselves // but the normal ones don't -- make Clear() behaviour consistent by // always sending this event // Windows already sends an update event for single-line // controls. if ( m_windowStyle & wxTE_MULTILINE ) SendUpdateEvent(); } } #ifdef __WIN32__ bool wxTextCtrl::EmulateKeyPress(const wxKeyEvent& event) { SetFocus(); size_t lenOld = GetValue().length(); wxUint32 code = event.GetRawKeyCode(); ::keybd_event((BYTE)code, 0, 0 /* key press */, 0); ::keybd_event((BYTE)code, 0, KEYEVENTF_KEYUP, 0); // assume that any alphanumeric key changes the total number of characters // in the control - this should work in 99% of cases return GetValue().length() != lenOld; } #endif // __WIN32__ // ---------------------------------------------------------------------------- // Clipboard operations // ---------------------------------------------------------------------------- void wxTextCtrl::Copy() { if (CanCopy()) { ::SendMessage(GetHwnd(), WM_COPY, 0, 0L); } } void wxTextCtrl::Cut() { if (CanCut()) { ::SendMessage(GetHwnd(), WM_CUT, 0, 0L); } } void wxTextCtrl::Paste() { if (CanPaste()) { ::SendMessage(GetHwnd(), WM_PASTE, 0, 0L); } } bool wxTextCtrl::HasSelection() const { long from, to; GetSelection(&from, &to); return from != to; } bool wxTextCtrl::CanCopy() const { // Can copy if there's a selection return HasSelection(); } bool wxTextCtrl::CanCut() const { return CanCopy() && IsEditable(); } bool wxTextCtrl::CanPaste() const { if ( !IsEditable() ) return false; #if wxUSE_RICHEDIT if ( IsRich() ) { UINT cf = 0; // 0 == any format return ::SendMessage(GetHwnd(), EM_CANPASTE, cf, 0) != 0; } #endif // wxUSE_RICHEDIT // Standard edit control: check for straight text on clipboard if ( !::OpenClipboard(GetHwndOf(wxTheApp->GetTopWindow())) ) return false; bool isTextAvailable = ::IsClipboardFormatAvailable(CF_TEXT) != 0; ::CloseClipboard(); return isTextAvailable; } // ---------------------------------------------------------------------------- // Accessors // ---------------------------------------------------------------------------- void wxTextCtrl::SetEditable(bool editable) { HWND hWnd = GetHwnd(); ::SendMessage(hWnd, EM_SETREADONLY, (WPARAM)!editable, (LPARAM)0L); } void wxTextCtrl::SetInsertionPoint(long pos) { DoSetSelection(pos, pos); } void wxTextCtrl::SetInsertionPointEnd() { // we must not do anything if the caret is already there because calling // SetInsertionPoint() thaws the controls if Freeze() had been called even // if it doesn't actually move the caret anywhere and so the simple fact of // doing it results in horrible flicker when appending big amounts of text // to the control in a few chunks (see DoAddText() test in the text sample) const wxTextPos lastPosition = GetLastPosition(); if ( GetInsertionPoint() == lastPosition ) { return; } long pos; #if wxUSE_RICHEDIT if ( m_verRichEdit == 1 ) { // we don't have to waste time calling GetLastPosition() in this case pos = -1; } else // !RichEdit 1.0 #endif // wxUSE_RICHEDIT { pos = lastPosition; } SetInsertionPoint(pos); } long wxTextCtrl::GetInsertionPoint() const { #if wxUSE_RICHEDIT if ( IsRich() ) { CHARRANGE range; range.cpMin = 0; range.cpMax = 0; ::SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &range); return range.cpMin; } #endif // wxUSE_RICHEDIT DWORD Pos = (DWORD)::SendMessage(GetHwnd(), EM_GETSEL, 0, 0L); return Pos & 0xFFFF; } wxTextPos wxTextCtrl::GetLastPosition() const { int numLines = GetNumberOfLines(); long posStartLastLine = XYToPosition(0, numLines - 1); long lenLastLine = GetLengthOfLineContainingPos(posStartLastLine); return posStartLastLine + lenLastLine; } // If the return values from and to are the same, there is no // selection. void wxTextCtrl::GetSelection(long* from, long* to) const { #if wxUSE_RICHEDIT if ( IsRich() ) { CHARRANGE charRange; ::SendMessage(GetHwnd(), EM_EXGETSEL, 0, (LPARAM) &charRange); *from = charRange.cpMin; *to = charRange.cpMax; } else #endif // !wxUSE_RICHEDIT { DWORD dwStart, dwEnd; ::SendMessage(GetHwnd(), EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd); *from = dwStart; *to = dwEnd; } } bool wxTextCtrl::IsEditable() const { // strangely enough, we may be called before the control is created: our // own Create() calls MSWGetStyle() which calls AcceptsFocus() which calls // us if ( !m_hWnd ) return true; long style = ::GetWindowLong(GetHwnd(), GWL_STYLE); return (style & ES_READONLY) == 0; } // ---------------------------------------------------------------------------- // selection // ---------------------------------------------------------------------------- void wxTextCtrl::SetSelection(long from, long to) { // if from and to are both -1, it means (in wxWidgets) that all text should // be selected - translate into Windows convention if ( (from == -1) && (to == -1) ) { from = 0; to = -1; } DoSetSelection(from, to); } void wxTextCtrl::DoSetSelection(long from, long to, bool scrollCaret) { HWND hWnd = GetHwnd(); #if wxUSE_RICHEDIT if ( IsRich() ) { CHARRANGE range; range.cpMin = from; range.cpMax = to; ::SendMessage(hWnd, EM_EXSETSEL, 0, (LPARAM) &range); } else #endif // wxUSE_RICHEDIT { ::SendMessage(hWnd, EM_SETSEL, (WPARAM)from, (LPARAM)to); } if ( scrollCaret && !IsFrozen() ) { #if wxUSE_RICHEDIT // richedit 3.0 (i.e. the version living in riched20.dll distributed // with Windows 2000 and beyond) doesn't honour EM_SCROLLCARET when // emulating richedit 2.0 unless the control has focus or ECO_NOHIDESEL // option is set (but it does work ok in richedit 1.0 mode...) // // so to make it work we either need to give focus to it here which // will probably create many problems (dummy focus events; window // containing the text control being brought to foreground // unexpectedly; ...) or to temporarily set ECO_NOHIDESEL which may // create other problems too -- and in fact it does because if we turn // on/off this style while appending the text to the control, the // vertical scrollbar never appears in it even if we append tons of // text and to work around this the only solution I found was to use // ES_DISABLENOSCROLL // // this is very ugly but I don't see any other way to make this work long style = 0; if ( GetRichVersion() > 1 ) { if ( !HasFlag(wxTE_NOHIDESEL) ) { // setting ECO_NOHIDESEL also sets WS_VISIBLE and possibly // others, remember the style so we can reset it later if needed style = ::GetWindowLong(GetHwnd(), GWL_STYLE); ::SendMessage(GetHwnd(), EM_SETOPTIONS, ECOOP_OR, ECO_NOHIDESEL); } //else: everything is already ok } #endif // wxUSE_RICHEDIT ::SendMessage(hWnd, EM_SCROLLCARET, (WPARAM)0, (LPARAM)0); #if wxUSE_RICHEDIT // restore ECO_NOHIDESEL if we changed it if ( GetRichVersion() > 1 && !HasFlag(wxTE_NOHIDESEL) ) { ::SendMessage(GetHwnd(), EM_SETOPTIONS, ECOOP_AND, ~ECO_NOHIDESEL); if ( style != ::GetWindowLong(GetHwnd(), GWL_STYLE) ) ::SetWindowLong(GetHwnd(), GWL_STYLE, style); } #endif // wxUSE_RICHEDIT } } // ---------------------------------------------------------------------------- // Working with files // ---------------------------------------------------------------------------- bool wxTextCtrl::DoLoadFile(const wxString& file, int fileType) { if ( wxTextCtrlBase::DoLoadFile(file, fileType) ) { // update the size limit if needed AdjustSpaceLimit(); return true; } return false; } // ---------------------------------------------------------------------------- // Editing // ---------------------------------------------------------------------------- void wxTextCtrl::Replace(long from, long to, const wxString& value) { // Set selection and remove it DoSetSelection(from, to, false /* don't scroll caret into view */); DoWriteText(value); } void wxTextCtrl::Remove(long from, long to) { Replace(from, to, wxEmptyString); } bool wxTextCtrl::IsModified() const { return ::SendMessage(GetHwnd(), EM_GETMODIFY, 0, 0) != 0; } void wxTextCtrl::MarkDirty() { ::SendMessage(GetHwnd(), EM_SETMODIFY, TRUE, 0L); } void wxTextCtrl::DiscardEdits() { ::SendMessage(GetHwnd(), EM_SETMODIFY, FALSE, 0L); } int wxTextCtrl::GetNumberOfLines() const { return (int)::SendMessage(GetHwnd(), EM_GETLINECOUNT, (WPARAM)0, (LPARAM)0); } // ---------------------------------------------------------------------------- // Positions <-> coords // ---------------------------------------------------------------------------- long wxTextCtrl::XYToPosition(long x, long y) const { // This gets the char index for the _beginning_ of this line long charIndex = ::SendMessage(GetHwnd(), EM_LINEINDEX, (WPARAM)y, (LPARAM)0); return charIndex + x; } bool wxTextCtrl::PositionToXY(long pos, long *x, long *y) const { HWND hWnd = GetHwnd(); // This gets the line number containing the character long lineNo; #if wxUSE_RICHEDIT if ( IsRich() ) { lineNo = ::SendMessage(hWnd, EM_EXLINEFROMCHAR, 0, (LPARAM)pos); } else #endif // wxUSE_RICHEDIT { lineNo = ::SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, 0); } if ( lineNo == -1 ) { // no such line return false; } // This gets the char index for the _beginning_ of this line long charIndex = ::SendMessage(hWnd, EM_LINEINDEX, (WPARAM)lineNo, (LPARAM)0); if ( charIndex == -1 ) { return false; } // The X position must therefore be the different between pos and charIndex if ( x ) *x = pos - charIndex; if ( y ) *y = lineNo; return true; } wxTextCtrlHitTestResult wxTextCtrl::HitTest(const wxPoint& pt, long *posOut) const { // first get the position from Windows LPARAM lParam; #if wxUSE_RICHEDIT POINTL ptl; if ( IsRich() ) { // for rich edit controls the position is passed iva the struct fields ptl.x = pt.x; ptl.y = pt.y; lParam = (LPARAM)&ptl; } else #endif // wxUSE_RICHEDIT { // for the plain ones, we are limited to 16 bit positions which are // combined in a single 32 bit value lParam = MAKELPARAM(pt.x, pt.y); } LRESULT pos = ::SendMessage(GetHwnd(), EM_CHARFROMPOS, 0, lParam); if ( pos == -1 ) { // this seems to indicate an error... return wxTE_HT_UNKNOWN; } #if wxUSE_RICHEDIT if ( !IsRich() ) #endif // wxUSE_RICHEDIT { // for plain EDIT controls the higher word contains something else pos = LOWORD(pos); } // next determine where it is relatively to our point: EM_CHARFROMPOS // always returns the closest character but we need to be more precise, so // double check that we really are where it pretends POINTL ptReal; #if wxUSE_RICHEDIT // FIXME: we need to distinguish between richedit 2 and 3 here somehow but // we don't know how to do it if ( IsRich() ) { ::SendMessage(GetHwnd(), EM_POSFROMCHAR, (WPARAM)&ptReal, pos); } else #endif // wxUSE_RICHEDIT { LRESULT lRc = ::SendMessage(GetHwnd(), EM_POSFROMCHAR, pos, 0); if ( lRc == -1 ) { // this is apparently returned when pos corresponds to the last // position ptReal.x = ptReal.y = 0; } else { ptReal.x = LOWORD(lRc); ptReal.y = HIWORD(lRc); } } wxTextCtrlHitTestResult rc; if ( pt.y > ptReal.y + GetCharHeight() ) rc = wxTE_HT_BELOW; else if ( pt.x > ptReal.x + GetCharWidth() ) rc = wxTE_HT_BEYOND; else rc = wxTE_HT_ON_TEXT; if ( posOut ) *posOut = pos; return rc; } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- void wxTextCtrl::ShowPosition(long pos) { HWND hWnd = GetHwnd(); // To scroll to a position, we pass the number of lines and characters // to scroll *by*. This means that we need to: // (1) Find the line position of the current line. // (2) Find the line position of pos. // (3) Scroll by (pos - current). // For now, ignore the horizontal scrolling. // Is this where scrolling is relative to - the line containing the caret? // Or is the first visible line??? Try first visible line. // int currentLineLineNo1 = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)-1, (LPARAM)0L); int currentLineLineNo = (int)::SendMessage(hWnd, EM_GETFIRSTVISIBLELINE, (WPARAM)0, (LPARAM)0L); int specifiedLineLineNo = (int)::SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)pos, (LPARAM)0L); int linesToScroll = specifiedLineLineNo - currentLineLineNo; if (linesToScroll != 0) (void)::SendMessage(hWnd, EM_LINESCROLL, (WPARAM)0, (LPARAM)linesToScroll); } long wxTextCtrl::GetLengthOfLineContainingPos(long pos) const { return ::SendMessage(GetHwnd(), EM_LINELENGTH, (WPARAM)pos, 0); } int wxTextCtrl::GetLineLength(long lineNo) const { long pos = XYToPosition(0, lineNo); return GetLengthOfLineContainingPos(pos); } wxString wxTextCtrl::GetLineText(long lineNo) const { size_t len = (size_t)GetLineLength(lineNo) + 1; // there must be at least enough place for the length WORD in the // buffer len += sizeof(WORD); wxString str; { wxStringBufferLength tmp(str, len); wxChar *buf = tmp; *(WORD *)buf = (WORD)len; len = (size_t)::SendMessage(GetHwnd(), EM_GETLINE, lineNo, (LPARAM)buf); #if wxUSE_RICHEDIT if ( IsRich() ) { // remove the '\r' returned by the rich edit control, the user code // should never see it if ( buf[len - 2] == _T('\r') && buf[len - 1] == _T('\n') ) { // richedit 1.0 uses "\r\n" as line terminator, so remove "\r" // here and "\n" below buf[len - 2] = _T('\n'); len--; } else if ( buf[len - 1] == _T('\r') ) { // richedit 2.0+ uses only "\r", replace it with "\n" buf[len - 1] = _T('\n'); } } #endif // wxUSE_RICHEDIT // remove the '\n' at the end, if any (this is how this function is // supposed to work according to the docs) if ( buf[len - 1] == _T('\n') ) { len--; } buf[len] = 0; tmp.SetLength(len); } return str; } void wxTextCtrl::SetMaxLength(unsigned long len) { #if wxUSE_RICHEDIT if ( IsRich() ) { ::SendMessage(GetHwnd(), EM_EXLIMITTEXT, 0, len ? len : 0x7fffffff); } else #endif // wxUSE_RICHEDIT { if ( len >= 0xffff ) { // this will set it to a platform-dependent maximum (much more // than 64Kb under NT) len = 0; } ::SendMessage(GetHwnd(), EM_LIMITTEXT, len, 0); } } // ---------------------------------------------------------------------------- // Undo/redo // ---------------------------------------------------------------------------- void wxTextCtrl::Undo() { if (CanUndo()) { ::SendMessage(GetHwnd(), EM_UNDO, 0, 0); } } void wxTextCtrl::Redo() { if (CanRedo()) { #if wxUSE_RICHEDIT if (GetRichVersion() > 1) ::SendMessage(GetHwnd(), EM_REDO, 0, 0); else #endif // Same as Undo, since Undo undoes the undo, i.e. a redo. ::SendMessage(GetHwnd(), EM_UNDO, 0, 0); } } bool wxTextCtrl::CanUndo() const { return ::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0; } bool wxTextCtrl::CanRedo() const { #if wxUSE_RICHEDIT if (GetRichVersion() > 1) return ::SendMessage(GetHwnd(), EM_CANREDO, 0, 0) != 0; else #endif return ::SendMessage(GetHwnd(), EM_CANUNDO, 0, 0) != 0; } // ---------------------------------------------------------------------------- // caret handling (Windows only) // ---------------------------------------------------------------------------- bool wxTextCtrl::ShowNativeCaret(bool show) { if ( show != m_isNativeCaretShown ) { if ( !(show ? ::ShowCaret(GetHwnd()) : ::HideCaret(GetHwnd())) ) { // not an error, may simply indicate that it's not shown/hidden // yet (i.e. it had been hidden/showh 2 times before) return false; } m_isNativeCaretShown = show; } return true; } // ---------------------------------------------------------------------------- // implemenation details // ---------------------------------------------------------------------------- void wxTextCtrl::Command(wxCommandEvent & event) { SetValue(event.GetString()); ProcessCommand (event); } void wxTextCtrl::OnDropFiles(wxDropFilesEvent& event) { // By default, load the first file into the text window. if (event.GetNumberOfFiles() > 0) { LoadFile(event.GetFiles()[0]); } } // ---------------------------------------------------------------------------- // kbd input processing // ---------------------------------------------------------------------------- bool wxTextCtrl::MSWShouldPreProcessMessage(WXMSG* msg) { // check for our special keys here: if we don't do it and the parent frame // uses them as accelerators, they wouldn't work at all, so we disable // usual preprocessing for them if ( msg->message == WM_KEYDOWN ) { const WPARAM vkey = msg->wParam; if ( HIWORD(msg->lParam) & KF_ALTDOWN ) { // Alt-Backspace is accelerator for "Undo" if ( vkey == VK_BACK ) return false; } else // no Alt { // we want to process some Ctrl-foo and Shift-bar but no key // combinations without either Ctrl or Shift nor with both of them // pressed const int ctrl = wxIsCtrlDown(), shift = wxIsShiftDown(); switch ( ctrl + shift ) { default: wxFAIL_MSG( _T("how many modifiers have we got?") ); // fall through case 0: if ( IsMultiLine() && vkey == VK_RETURN ) return false; // fall through case 2: break; case 1: // either Ctrl or Shift pressed if ( ctrl ) { switch ( vkey ) { case 'C': case 'V': case 'X': case VK_INSERT: case VK_DELETE: case VK_HOME: case VK_END: return false; } } else // Shift is pressed { if ( vkey == VK_INSERT || vkey == VK_DELETE ) return false; } } } } return wxControl::MSWShouldPreProcessMessage(msg); } void wxTextCtrl::OnChar(wxKeyEvent& event) { switch ( event.GetKeyCode() ) { case WXK_RETURN: { wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId); InitCommandEvent(event); event.SetString(GetValue()); if ( GetEventHandler()->ProcessEvent(event) ) if ( !HasFlag(wxTE_MULTILINE) ) return; //else: multiline controls need Enter for themselves } break; case WXK_TAB: // ok, so this is getting absolutely ridiculous but I don't see // any other way to fix this bug: when a multiline text control is // inside a wxFrame, we need to generate the navigation event as // otherwise nothing happens at all, but when the same control is // created inside a dialog, IsDialogMessage() *does* switch focus // all by itself and so if we do it here as well, it is advanced // twice and goes to the next control... to prevent this from // happening we're doing this ugly check, the logic being that if // we don't have focus then it had been already changed to the next // control // // the right thing to do would, of course, be to understand what // the hell is IsDialogMessage() doing but this is beyond my feeble // forces at the moment unfortunately if ( !(m_windowStyle & wxTE_PROCESS_TAB)) { if ( FindFocus() == this ) { int flags = 0; if (!event.ShiftDown()) flags |= wxNavigationKeyEvent::IsForward ; if (event.ControlDown()) flags |= wxNavigationKeyEvent::WinChange ; if (Navigate(flags)) return; } } else { // Insert tab since calling the default Windows handler // doesn't seem to do it WriteText(wxT("\t")); return; } break; } // no, we didn't process it event.Skip(); } void wxTextCtrl::OnKeyDown(wxKeyEvent& event) { // richedit control doesn't send WM_PASTE, WM_CUT and WM_COPY messages // when Ctrl-V, X or C is pressed and this prevents wxClipboardTextEvent // from working. So we work around it by intercepting these shortcuts // ourselves and emitting clipboard events (which richedit will handle, // so everything works as before, including pasting of rich text): if ( event.GetModifiers() == wxMOD_CONTROL && IsRich() ) { switch ( event.GetKeyCode() ) { case 'C': Copy(); return; case 'X': Cut(); return; case 'V': Paste(); return; default: break; } } // no, we didn't process it event.Skip(); } WXLRESULT wxTextCtrl::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) { // we must handle clipboard events before calling MSWWindowProc, otherwise // the event would be handled twice if there's a handler for it in user // code: switch ( nMsg ) { case WM_CUT: case WM_COPY: case WM_PASTE: if ( HandleClipboardEvent(nMsg) ) return 0; break; } WXLRESULT lRc = wxTextCtrlBase::MSWWindowProc(nMsg, wParam, lParam); switch ( nMsg ) { case WM_GETDLGCODE: { // we always want the chars and the arrows: the arrows for // navigation and the chars because we want Ctrl-C to work even // in a read only control long lDlgCode = DLGC_WANTCHARS | DLGC_WANTARROWS; if ( IsEditable() ) { // we may have several different cases: // 1. normal: both TAB and ENTER are used for navigation // 2. ctrl wants TAB for itself: ENTER is used to pass to // the next control in the dialog // 3. ctrl wants ENTER for itself: TAB is used for dialog // navigation // 4. ctrl wants both TAB and ENTER: Ctrl-ENTER is used to // go to the next control (we need some way to do it) // multiline controls should always get ENTER for themselves if ( HasFlag(wxTE_PROCESS_ENTER) || HasFlag(wxTE_MULTILINE) ) lDlgCode |= DLGC_WANTMESSAGE; if ( HasFlag(wxTE_PROCESS_TAB) ) lDlgCode |= DLGC_WANTTAB; lRc |= lDlgCode; } else // !editable { // NB: use "=", not "|=" as the base class version returns // the same flags is this state as usual (i.e. // including DLGC_WANTMESSAGE). This is strange (how // does it work in the native Win32 apps?) but for now // live with it. lRc = lDlgCode; } } break; } return lRc; } // ---------------------------------------------------------------------------- // text control event processing // ---------------------------------------------------------------------------- bool wxTextCtrl::SendUpdateEvent() { switch ( m_updatesCount ) { case 0: // remember that we've got an update m_updatesCount++; break; case 1: // we had already sent one event since the last control modification return false; default: wxFAIL_MSG( _T("unexpected wxTextCtrl::m_updatesCount value") ); // fall through case -1: // we hadn't updated the control ourselves, this event comes from // the user, don't need to ignore it nor update the count break; case -2: // the control was updated programmatically and we do NOT want to // send events return false; } wxCommandEvent event(wxEVT_COMMAND_TEXT_UPDATED, GetId()); InitCommandEvent(event); return ProcessCommand(event); } bool wxTextCtrl::MSWCommand(WXUINT param, WXWORD WXUNUSED(id)) { switch ( param ) { case EN_SETFOCUS: case EN_KILLFOCUS: { wxFocusEvent event(param == EN_KILLFOCUS ? wxEVT_KILL_FOCUS : wxEVT_SET_FOCUS, m_windowId); event.SetEventObject(this); GetEventHandler()->ProcessEvent(event); } break; case EN_CHANGE: SendUpdateEvent(); break; case EN_MAXTEXT: // the text size limit has been hit -- try to increase it if ( !AdjustSpaceLimit() ) { wxCommandEvent event(wxEVT_COMMAND_TEXT_MAXLEN, m_windowId); InitCommandEvent(event); event.SetString(GetValue()); ProcessCommand(event); } break; // the other edit notification messages are not processed default: return false; } // processed return true; } WXHBRUSH wxTextCtrl::MSWControlColor(WXHDC hDC, WXHWND hWnd) { if ( !IsEnabled() && !HasFlag(wxTE_MULTILINE) ) return MSWControlColorDisabled(hDC); return wxTextCtrlBase::MSWControlColor(hDC, hWnd); } bool wxTextCtrl::HasSpaceLimit(unsigned int *len) const { // HACK: we try to automatically extend the limit for the amount of text // to allow (interactively) entering more than 64Kb of text under // Win9x but we shouldn't reset the text limit which was previously // set explicitly with SetMaxLength() // // Unfortunately there is no EM_GETLIMITTEXTSETBYUSER and so we don't // know the limit we set (if any). We could solve this by storing the // limit we set in wxTextCtrl but to save space we prefer to simply // test here the actual limit value: we consider that SetMaxLength() // can only be called for small values while EN_MAXTEXT is only sent // for large values (in practice the default limit seems to be 30000 // but make it smaller just to be on the safe side) *len = ::SendMessage(GetHwnd(), EM_GETLIMITTEXT, 0, 0); return *len < 10001; } bool wxTextCtrl::AdjustSpaceLimit() { unsigned int limit; if ( HasSpaceLimit(&limit) ) return false; unsigned int len = ::GetWindowTextLength(GetHwnd()); if ( len >= limit ) { // increment in 32Kb chunks SetMaxLength(len + 0x8000); } // we changed the limit return true; } bool wxTextCtrl::AcceptsFocus() const { // we don't want focus if we can't be edited unless we're a multiline // control because then it might be still nice to get focus from keyboard // to be able to scroll it without mouse return (IsEditable() || IsMultiLine()) && wxControl::AcceptsFocus(); } wxSize wxTextCtrl::DoGetBestSize() const { int cx, cy; wxGetCharSize(GetHWND(), &cx, &cy, GetFont()); int wText = DEFAULT_ITEM_WIDTH; int hText = cy; if ( m_windowStyle & wxTE_MULTILINE ) { hText *= wxMax(wxMin(GetNumberOfLines(), 10), 2); } //else: for single line control everything is ok // we have to add the adjustments for the control height only once, not // once per line, so do it after multiplication above hText += EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy) - cy; return wxSize(wText, hText); } // ---------------------------------------------------------------------------- // standard handlers for standard edit menu events // ---------------------------------------------------------------------------- void wxTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event)) { Cut(); } void wxTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event)) { Copy(); } void wxTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event)) { Paste(); } void wxTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event)) { Undo(); } void wxTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event)) { Redo(); } void wxTextCtrl::OnDelete(wxCommandEvent& WXUNUSED(event)) { long from, to; GetSelection(& from, & to); if (from != -1 && to != -1) Remove(from, to); } void wxTextCtrl::OnSelectAll(wxCommandEvent& WXUNUSED(event)) { SetSelection(-1, -1); } void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event) { event.Enable( CanCut() ); } void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event) { event.Enable( CanCopy() ); } void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event) { event.Enable( CanPaste() ); } void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event) { event.Enable( CanUndo() ); } void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event) { event.Enable( CanRedo() ); } void wxTextCtrl::OnUpdateDelete(wxUpdateUIEvent& event) { long from, to; GetSelection(& from, & to); event.Enable(from != -1 && to != -1 && from != to && IsEditable()) ; } void wxTextCtrl::OnUpdateSelectAll(wxUpdateUIEvent& event) { event.Enable(GetLastPosition() > 0); } void wxTextCtrl::OnContextMenu(wxContextMenuEvent& event) { #if wxUSE_RICHEDIT if (IsRich()) { if (!m_privateContextMenu) { m_privateContextMenu = new wxMenu; m_privateContextMenu->Append(wxID_UNDO, _("&Undo")); m_privateContextMenu->Append(wxID_REDO, _("&Redo")); m_privateContextMenu->AppendSeparator(); m_privateContextMenu->Append(wxID_CUT, _("Cu&t")); m_privateContextMenu->Append(wxID_COPY, _("&Copy")); m_privateContextMenu->Append(wxID_PASTE, _("&Paste")); m_privateContextMenu->Append(wxID_CLEAR, _("&Delete")); m_privateContextMenu->AppendSeparator(); m_privateContextMenu->Append(wxID_SELECTALL, _("Select &All")); } PopupMenu(m_privateContextMenu); return; } else #endif event.Skip(); } void wxTextCtrl::OnSetFocus(wxFocusEvent& event) { // be sure the caret remains invisible if the user had hidden it if ( !m_isNativeCaretShown ) { ::HideCaret(GetHwnd()); } event.Skip(); } // ---------------------------------------------------------------------------- // Default colors for MSW text control // // Set default background color to the native white instead of // the default wxSYS_COLOUR_BTNFACE (is triggered with wxNullColour). // ---------------------------------------------------------------------------- wxVisualAttributes wxTextCtrl::GetDefaultAttributes() const { wxVisualAttributes attrs; attrs.font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); attrs.colFg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT); attrs.colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW); //white return attrs; } // the rest of the file only deals with the rich edit controls #if wxUSE_RICHEDIT // ---------------------------------------------------------------------------- // EN_LINK processing // ---------------------------------------------------------------------------- bool wxTextCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result) { NMHDR *hdr = (NMHDR* )lParam; switch ( hdr->code ) { case EN_MSGFILTER: { const MSGFILTER *msgf = (MSGFILTER *)lParam; UINT msg = msgf->msg; // this is a bit crazy but richedit 1.0 sends us all mouse // events _except_ WM_LBUTTONUP (don't ask me why) so we have // generate the wxWin events for this message manually // // NB: in fact, this is still not totally correct as it does // send us WM_LBUTTONUP if the selection was cleared by the // last click -- so currently we get 2 events in this case, // but as I don't see any obvious way to check for this I // leave this code in place because it's still better than // not getting left up events at all if ( msg == WM_LBUTTONUP ) { WXUINT flags = msgf->wParam; int x = GET_X_LPARAM(msgf->lParam), y = GET_Y_LPARAM(msgf->lParam); HandleMouseEvent(msg, x, y, flags); } } // return true to process the event (and false to ignore it) return true; case EN_LINK: { const ENLINK *enlink = (ENLINK *)hdr; switch ( enlink->msg ) { case WM_SETCURSOR: // ok, so it is hardcoded - do we really nee to // customize it? { wxCursor cur(wxCURSOR_HAND); ::SetCursor(GetHcursorOf(cur)); *result = TRUE; break; } case WM_MOUSEMOVE: case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_RBUTTONDBLCLK: // send a mouse event { static const wxEventType eventsMouse[] = { wxEVT_MOTION, wxEVT_LEFT_DOWN, wxEVT_LEFT_UP, wxEVT_LEFT_DCLICK, wxEVT_RIGHT_DOWN, wxEVT_RIGHT_UP, wxEVT_RIGHT_DCLICK, }; // the event ids are consecutive wxMouseEvent evtMouse(eventsMouse[enlink->msg - WM_MOUSEMOVE]); InitMouseEvent(evtMouse, GET_X_LPARAM(enlink->lParam), GET_Y_LPARAM(enlink->lParam), enlink->wParam); wxTextUrlEvent event(m_windowId, evtMouse, enlink->chrg.cpMin, enlink->chrg.cpMax); InitCommandEvent(event); *result = ProcessCommand(event); } break; } } return true; } // not processed, leave it to the base class return wxTextCtrlBase::MSWOnNotify(idCtrl, lParam, result); } // ---------------------------------------------------------------------------- // colour setting for the rich edit controls // ---------------------------------------------------------------------------- bool wxTextCtrl::SetBackgroundColour(const wxColour& colour) { if ( !wxTextCtrlBase::SetBackgroundColour(colour) ) { // colour didn't really change return false; } if ( IsRich() ) { // rich edit doesn't use WM_CTLCOLOR, hence we need to send // EM_SETBKGNDCOLOR additionally ::SendMessage(GetHwnd(), EM_SETBKGNDCOLOR, 0, wxColourToRGB(colour)); } return true; } bool wxTextCtrl::SetForegroundColour(const wxColour& colour) { if ( !wxTextCtrlBase::SetForegroundColour(colour) ) { // colour didn't really change return false; } if ( IsRich() ) { // change the colour of everything CHARFORMAT cf; wxZeroMemory(cf); cf.cbSize = sizeof(cf); cf.dwMask = CFM_COLOR; cf.crTextColor = wxColourToRGB(colour); ::SendMessage(GetHwnd(), EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf); } return true; } // ---------------------------------------------------------------------------- // styling support for rich edit controls // ---------------------------------------------------------------------------- #if wxUSE_RICHEDIT bool wxTextCtrl::SetStyle(long start, long end, const wxTextAttr& style) { if ( !IsRich() ) { // can't do it with normal text control return false; } // the richedit 1.0 doesn't handle setting background colour, so don't // even try to do anything if it's the only thing we want to change if ( m_verRichEdit == 1 && !style.HasFont() && !style.HasTextColour() && !style.HasLeftIndent() && !style.HasRightIndent() && !style.HasAlignment() && !style.HasTabs() ) { // nothing to do: return true if there was really nothing to do and // false if we failed to set bg colour return !style.HasBackgroundColour(); } // order the range if needed if ( start > end ) { long tmp = start; start = end; end = tmp; } // we can only change the format of the selection, so select the range we // want and restore the old selection later long startOld, endOld; GetSelection(&startOld, &endOld); // but do we really have to change the selection? bool changeSel = start != startOld || end != endOld; if ( changeSel ) { DoSetSelection(start, end, false /* don't scroll caret into view */); } // initialize CHARFORMAT struct #if wxUSE_RICHEDIT2 CHARFORMAT2 cf; #else CHARFORMAT cf; #endif wxZeroMemory(cf); // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple // CHARFORMAT in that case #if wxUSE_RICHEDIT2 if ( m_verRichEdit == 1 ) { // this is the only thing the control is going to grok cf.cbSize = sizeof(CHARFORMAT); } else #endif { // CHARFORMAT or CHARFORMAT2 cf.cbSize = sizeof(cf); } if ( style.HasFont() ) { // VZ: CFM_CHARSET doesn't seem to do anything at all in RichEdit 2.0 // but using it doesn't seem to hurt neither so leaving it for now cf.dwMask |= CFM_FACE | CFM_SIZE | CFM_CHARSET | CFM_ITALIC | CFM_BOLD | CFM_UNDERLINE; // fill in data from LOGFONT but recalculate lfHeight because we need // the real height in twips and not the negative number which // wxFillLogFont() returns (this is correct in general and works with // the Windows font mapper, but not here) LOGFONT lf; wxFillLogFont(&lf, &style.GetFont()); cf.yHeight = 20*style.GetFont().GetPointSize(); // 1 pt = 20 twips cf.bCharSet = lf.lfCharSet; cf.bPitchAndFamily = lf.lfPitchAndFamily; wxStrncpy( cf.szFaceName, lf.lfFaceName, WXSIZEOF(cf.szFaceName) ); // also deal with underline/italic/bold attributes: note that we must // always set CFM_ITALIC &c bits in dwMask, even if we don't set the // style to allow clearing it if ( lf.lfItalic ) { cf.dwEffects |= CFE_ITALIC; } if ( lf.lfWeight == FW_BOLD ) { cf.dwEffects |= CFE_BOLD; } if ( lf.lfUnderline ) { cf.dwEffects |= CFE_UNDERLINE; } // strikeout fonts are not supported by wxWidgets } if ( style.HasTextColour() ) { cf.dwMask |= CFM_COLOR; cf.crTextColor = wxColourToRGB(style.GetTextColour()); } #if wxUSE_RICHEDIT2 if ( m_verRichEdit != 1 && style.HasBackgroundColour() ) { cf.dwMask |= CFM_BACKCOLOR; cf.crBackColor = wxColourToRGB(style.GetBackgroundColour()); } #endif // wxUSE_RICHEDIT2 // do format the selection bool ok = ::SendMessage(GetHwnd(), EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf) != 0; if ( !ok ) { wxLogDebug(_T("SendMessage(EM_SETCHARFORMAT, SCF_SELECTION) failed")); } // now do the paragraph formatting PARAFORMAT2 pf; wxZeroMemory(pf); // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple // PARAFORMAT in that case #if wxUSE_RICHEDIT2 if ( m_verRichEdit == 1 ) { // this is the only thing the control is going to grok pf.cbSize = sizeof(PARAFORMAT); } else #endif { // PARAFORMAT or PARAFORMAT2 pf.cbSize = sizeof(pf); } if (style.HasAlignment()) { pf.dwMask |= PFM_ALIGNMENT; if (style.GetAlignment() == wxTEXT_ALIGNMENT_RIGHT) pf.wAlignment = PFA_RIGHT; else if (style.GetAlignment() == wxTEXT_ALIGNMENT_CENTRE) pf.wAlignment = PFA_CENTER; else if (style.GetAlignment() == wxTEXT_ALIGNMENT_JUSTIFIED) pf.wAlignment = PFA_JUSTIFY; else pf.wAlignment = PFA_LEFT; } if (style.HasLeftIndent()) { pf.dwMask |= PFM_STARTINDENT | PFM_OFFSET; // Convert from 1/10 mm to TWIPS pf.dxStartIndent = (int) (((double) style.GetLeftIndent()) * mm2twips / 10.0) ; pf.dxOffset = (int) (((double) style.GetLeftSubIndent()) * mm2twips / 10.0) ; } if (style.HasRightIndent()) { pf.dwMask |= PFM_RIGHTINDENT; // Convert from 1/10 mm to TWIPS pf.dxRightIndent = (int) (((double) style.GetRightIndent()) * mm2twips / 10.0) ; } if (style.HasTabs()) { pf.dwMask |= PFM_TABSTOPS; const wxArrayInt& tabs = style.GetTabs(); pf.cTabCount = (SHORT)wxMin(tabs.GetCount(), MAX_TAB_STOPS); size_t i; for (i = 0; i < (size_t) pf.cTabCount; i++) { // Convert from 1/10 mm to TWIPS pf.rgxTabs[i] = (int) (((double) tabs[i]) * mm2twips / 10.0) ; } } #if wxUSE_RICHEDIT2 if ( m_verRichEdit > 1 ) { if ( wxTheApp->GetLayoutDirection() == wxLayout_RightToLeft ) { // Use RTL paragraphs in RTL mode to get proper layout pf.dwMask |= PFM_RTLPARA; pf.wEffects |= PFE_RTLPARA; } } #endif // wxUSE_RICHEDIT2 if ( pf.dwMask ) { // do format the selection bool ok = ::SendMessage(GetHwnd(), EM_SETPARAFORMAT, 0, (LPARAM) &pf) != 0; if ( !ok ) { wxLogDebug(_T("SendMessage(EM_SETPARAFORMAT, 0) failed")); } } if ( changeSel ) { // restore the original selection DoSetSelection(startOld, endOld, false); } return ok; } bool wxTextCtrl::SetDefaultStyle(const wxTextAttr& style) { if ( !wxTextCtrlBase::SetDefaultStyle(style) ) return false; if ( IsEditable() ) { // we have to do this or the style wouldn't apply for the text typed by // the user wxTextPos posLast = GetLastPosition(); SetStyle(posLast, posLast, m_defaultStyle); } return true; } bool wxTextCtrl::GetStyle(long position, wxTextAttr& style) { if ( !IsRich() ) { // can't do it with normal text control return false; } // initialize CHARFORMAT struct #if wxUSE_RICHEDIT2 CHARFORMAT2 cf; #else CHARFORMAT cf; #endif wxZeroMemory(cf); // we can't use CHARFORMAT2 with RichEdit 1.0, so pretend it is a simple // CHARFORMAT in that case #if wxUSE_RICHEDIT2 if ( m_verRichEdit == 1 ) { // this is the only thing the control is going to grok cf.cbSize = sizeof(CHARFORMAT); } else #endif { // CHARFORMAT or CHARFORMAT2 cf.cbSize = sizeof(cf); } // we can only change the format of the selection, so select the range we // want and restore the old selection later long startOld, endOld; GetSelection(&startOld, &endOld); // but do we really have to change the selection? bool changeSel = position != startOld || position != endOld; if ( changeSel ) { DoSetSelection(position, position+1, false /* don't scroll caret into view */); } // get the selection formatting (void) ::SendMessage(GetHwnd(), EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf) ; LOGFONT lf; lf.lfHeight = cf.yHeight; lf.lfWidth = 0; lf.lfCharSet = ANSI_CHARSET; // FIXME: how to get correct charset? lf.lfClipPrecision = 0; lf.lfEscapement = 0; wxStrcpy(lf.lfFaceName, cf.szFaceName); //NOTE: we _MUST_ set each of these values to _something_ since we //do not call wxZeroMemory on the LOGFONT lf if (cf.dwEffects & CFE_ITALIC) lf.lfItalic = TRUE; else lf.lfItalic = FALSE; lf.lfOrientation = 0; lf.lfPitchAndFamily = cf.bPitchAndFamily; lf.lfQuality = 0; if (cf.dwEffects & CFE_STRIKEOUT) lf.lfStrikeOut = TRUE; else lf.lfStrikeOut = FALSE; if (cf.dwEffects & CFE_UNDERLINE) lf.lfUnderline = TRUE; else lf.lfUnderline = FALSE; if (cf.dwEffects & CFE_BOLD) lf.lfWeight = FW_BOLD; else lf.lfWeight = FW_NORMAL; wxFont font = wxCreateFontFromLogFont(& lf); if (font.Ok()) { style.SetFont(font); } style.SetTextColour(wxColour(cf.crTextColor)); #if wxUSE_RICHEDIT2 if ( m_verRichEdit != 1 ) { // cf.dwMask |= CFM_BACKCOLOR; style.SetBackgroundColour(wxColour(cf.crBackColor)); } #endif // wxUSE_RICHEDIT2 // now get the paragraph formatting PARAFORMAT2 pf; wxZeroMemory(pf); // we can't use PARAFORMAT2 with RichEdit 1.0, so pretend it is a simple // PARAFORMAT in that case #if wxUSE_RICHEDIT2 if ( m_verRichEdit == 1 ) { // this is the only thing the control is going to grok pf.cbSize = sizeof(PARAFORMAT); } else #endif { // PARAFORMAT or PARAFORMAT2 pf.cbSize = sizeof(pf); } // do format the selection (void) ::SendMessage(GetHwnd(), EM_GETPARAFORMAT, 0, (LPARAM) &pf) ; style.SetLeftIndent( (int) ((double) pf.dxStartIndent * twips2mm * 10.0), (int) ((double) pf.dxOffset * twips2mm * 10.0) ); style.SetRightIndent( (int) ((double) pf.dxRightIndent * twips2mm * 10.0) ); if (pf.wAlignment == PFA_CENTER) style.SetAlignment(wxTEXT_ALIGNMENT_CENTRE); else if (pf.wAlignment == PFA_RIGHT) style.SetAlignment(wxTEXT_ALIGNMENT_RIGHT); else if (pf.wAlignment == PFA_JUSTIFY) style.SetAlignment(wxTEXT_ALIGNMENT_JUSTIFIED); else style.SetAlignment(wxTEXT_ALIGNMENT_LEFT); wxArrayInt tabStops; size_t i; for (i = 0; i < (size_t) pf.cTabCount; i++) { tabStops.Add( (int) ((double) (pf.rgxTabs[i] & 0xFFFF) * twips2mm * 10.0) ); } if ( changeSel ) { // restore the original selection DoSetSelection(startOld, endOld, false); } return true; } #endif // ---------------------------------------------------------------------------- // wxRichEditModule // ---------------------------------------------------------------------------- static const HINSTANCE INVALID_HINSTANCE = (HINSTANCE)-1; bool wxRichEditModule::OnInit() { // don't do anything - we will load it when needed return true; } void wxRichEditModule::OnExit() { for ( size_t i = 0; i < WXSIZEOF(ms_hRichEdit); i++ ) { if ( ms_hRichEdit[i] && ms_hRichEdit[i] != INVALID_HINSTANCE ) { ::FreeLibrary(ms_hRichEdit[i]); ms_hRichEdit[i] = NULL; } } #if wxUSE_INKEDIT if (ms_inkEditLib.IsLoaded()) ms_inkEditLib.Unload(); #endif } /* static */ bool wxRichEditModule::Load(Version version) { if ( ms_hRichEdit[version] == INVALID_HINSTANCE ) { // we had already tried to load it and failed return false; } if ( ms_hRichEdit[version] ) { // we've already got this one return true; } static const wxChar *dllnames[] = { _T("riched32"), _T("riched20"), _T("msftedit"), }; wxCOMPILE_TIME_ASSERT( WXSIZEOF(dllnames) == Version_Max, RichEditDllNamesVersionsMismatch ); ms_hRichEdit[version] = ::LoadLibrary(dllnames[version]); if ( !ms_hRichEdit[version] ) { ms_hRichEdit[version] = INVALID_HINSTANCE; return false; } return true; } #if wxUSE_INKEDIT // load the InkEdit library bool wxRichEditModule::LoadInkEdit() { if (ms_inkEditLibLoadAttemped) return ms_inkEditLib.IsLoaded(); ms_inkEditLibLoadAttemped = true; wxLogNull logNull; return ms_inkEditLib.Load(wxT("inked")); } #endif #endif // wxUSE_RICHEDIT #endif // wxUSE_TEXTCTRL && !(__SMARTPHONE__ && __WXWINCE__)
radiaku/decoda
libs/wxWidgets/src/msw/textctrl.cpp
C++
gpl-3.0
87,388
//*@@@+++@@@@****************************************************************** // // Microsoft Windows Media Foundation // Copyright (C) Microsoft Corporation. All rights reserved. // // Portions Copyright (c) Microsoft Open Technologies, Inc. // //*@@@---@@@@****************************************************************** #include "MFIncludes.h" #include "MediaStreamSink.h" using namespace Media; using namespace Microsoft::WRL; using namespace Platform; using namespace Windows::Foundation; MediaStreamSink::MediaStreamSink( __in const ComPtr<IMFMediaSink>& sink, __in DWORD id, __in const ComPtr<IMFMediaType>& mt, __in MediaSampleHandler^ sampleHandler ) : _shutdown(false) , _id(-1) , _width(0) , _height(0) { CHK(MFCreateEventQueue(&_eventQueue)); CHK(MFCreateMediaType(&_curMT)); _UpdateMediaType(mt); _sink = sink; _id = id; _sampleHandler = sampleHandler; } HRESULT MediaStreamSink::GetMediaSink(__deref_out IMFMediaSink **sink) { return ExceptionBoundary([this, sink]() { auto lock = _lock.LockExclusive(); CHKNULL(sink); *sink = nullptr; _VerifyNotShutdown(); CHK(_sink.CopyTo(sink)); }); } HRESULT MediaStreamSink::GetIdentifier(__out DWORD *identifier) { return ExceptionBoundary([this, identifier]() { auto lock = _lock.LockExclusive(); CHKNULL(identifier); _VerifyNotShutdown(); *identifier = _id; }); } HRESULT MediaStreamSink::GetMediaTypeHandler(__deref_out IMFMediaTypeHandler **handler) { return ExceptionBoundary([this, handler]() { auto lock = _lock.LockExclusive(); CHKNULL(handler); *handler = nullptr; _VerifyNotShutdown(); *handler = this; this->AddRef(); }); } void MediaStreamSink::RequestSample() { auto lock = _lock.LockExclusive(); _VerifyNotShutdown(); CHK(_eventQueue->QueueEventParamVar(MEStreamSinkRequestSample, GUID_NULL, S_OK, nullptr)); } HRESULT MediaStreamSink::ProcessSample(__in_opt IMFSample *sample) { return ExceptionBoundary([this, sample]() { MediaSampleHandler^ sampleHandler; auto mediaSample = ref new MediaSample(); { auto lock = _lock.LockExclusive(); _VerifyNotShutdown(); if (sample == nullptr) { return; } mediaSample->Sample = sample; sampleHandler = _sampleHandler; } // Call back without the lock taken to avoid deadlocks sampleHandler(mediaSample); }); } HRESULT MediaStreamSink::PlaceMarker(__in MFSTREAMSINK_MARKER_TYPE /*markerType*/, __in const PROPVARIANT * /*markerValue*/, __in const PROPVARIANT * contextValue) { return ExceptionBoundary([this, contextValue]() { auto lock = _lock.LockExclusive(); CHKNULL(contextValue); _VerifyNotShutdown(); CHK(_eventQueue->QueueEventParamVar(MEStreamSinkMarker, GUID_NULL, S_OK, contextValue)); }); } HRESULT MediaStreamSink::Flush() { return ExceptionBoundary([this]() { auto lock = _lock.LockExclusive(); _VerifyNotShutdown(); }); } HRESULT MediaStreamSink::GetEvent(__in DWORD flags, __deref_out IMFMediaEvent **event) { return ExceptionBoundary([this, flags, event]() { CHKNULL(event); *event = nullptr; ComPtr<IMFMediaEventQueue> eventQueue; { auto lock = _lock.LockExclusive(); _VerifyNotShutdown(); eventQueue = _eventQueue; } // May block for a while CHK(eventQueue->GetEvent(flags, event)); }); } HRESULT MediaStreamSink::BeginGetEvent(__in IMFAsyncCallback *callback, __in_opt IUnknown *state) { return ExceptionBoundary([this, callback, state]() { auto lock = _lock.LockExclusive(); _VerifyNotShutdown(); CHK(_eventQueue->BeginGetEvent(callback, state)); }); } HRESULT MediaStreamSink::EndGetEvent(__in IMFAsyncResult *result, __deref_out IMFMediaEvent **event) { return ExceptionBoundary([this, result, event]() { auto lock = _lock.LockExclusive(); CHKNULL(event); *event = nullptr; _VerifyNotShutdown(); CHK(_eventQueue->EndGetEvent(result, event)); }); } HRESULT MediaStreamSink::QueueEvent( __in MediaEventType met, __in REFGUID extendedType, __in HRESULT status, __in_opt const PROPVARIANT *value ) { return ExceptionBoundary([this, met, extendedType, status, value]() { auto lock = _lock.LockExclusive(); _VerifyNotShutdown(); CHK(_eventQueue->QueueEventParamVar(met, extendedType, status, value)); }); } HRESULT MediaStreamSink::IsMediaTypeSupported(__in IMFMediaType *mediaType, __deref_out_opt IMFMediaType **closestMediaType) { bool supported = false; HRESULT hr = ExceptionBoundary([this, mediaType, closestMediaType, &supported]() { auto lock = _lock.LockExclusive(); HRESULT hr = S_OK; if (closestMediaType != nullptr) { *closestMediaType = nullptr; } CHKNULL(mediaType); _VerifyNotShutdown(); supported = _IsMediaTypeSupported(mediaType); }); // Avoid throwing an exception to return MF_E_INVALIDMEDIATYPE as this is not a exceptional case return FAILED(hr) ? hr : supported ? S_OK : MF_E_INVALIDMEDIATYPE; } HRESULT MediaStreamSink::GetMediaTypeCount(__out DWORD *typeCount) { return ExceptionBoundary([this, typeCount]() { auto lock = _lock.LockExclusive(); CHKNULL(typeCount); _VerifyNotShutdown(); // No media type provided by default (app needs to specify it) *typeCount = 0; }); } HRESULT MediaStreamSink::GetMediaTypeByIndex(__in DWORD /*index*/, __deref_out IMFMediaType **mediaType) { HRESULT hr = ExceptionBoundary([this, mediaType]() { auto lock = _lock.LockExclusive(); CHKNULL(mediaType); *mediaType = nullptr; _VerifyNotShutdown(); }); // Avoid throwing an exception to return MF_E_NO_MORE_TYPES as this is not a exceptional case return FAILED(hr) ? hr : MF_E_NO_MORE_TYPES; } HRESULT MediaStreamSink::SetCurrentMediaType(__in IMFMediaType *mediaType) { return ExceptionBoundary([this, mediaType]() { auto lock = _lock.LockExclusive(); HRESULT hr = S_OK; CHKNULL(mediaType); _VerifyNotShutdown(); if (!_IsMediaTypeSupported(mediaType)) { CHK(MF_E_INVALIDMEDIATYPE); } _UpdateMediaType(mediaType); }); } HRESULT MediaStreamSink::GetCurrentMediaType(__deref_out_opt IMFMediaType **mediaType) { return ExceptionBoundary([this, mediaType]() { auto lock = _lock.LockExclusive(); CHKNULL(mediaType); *mediaType = nullptr; _VerifyNotShutdown(); ComPtr<IMFMediaType> mt; CHK(MFCreateMediaType(&mt)); CHK(_curMT->CopyAllItems(mt.Get())); *mediaType = mt.Detach(); }); } HRESULT MediaStreamSink::GetMajorType(__out GUID *majorType) { return ExceptionBoundary([this, majorType]() { auto lock = _lock.LockExclusive(); CHKNULL(majorType); _VerifyNotShutdown(); *majorType = _majorType; }); } void MediaStreamSink::InternalSetCurrentMediaType(__in const ComPtr<IMFMediaType>& mediaType) { auto lock = _lock.LockExclusive(); CHKNULL(mediaType); _VerifyNotShutdown(); _UpdateMediaType(mediaType); } void MediaStreamSink::Shutdown() { auto lock = _lock.LockExclusive(); if (_shutdown) { return; } _shutdown = true; (void)_eventQueue->Shutdown(); _eventQueue = nullptr; _curMT = nullptr; _sink = nullptr; _sampleHandler = nullptr; } bool MediaStreamSink::_IsMediaTypeSupported(__in const ComPtr<IMFMediaType>& mt) const { GUID majorType; GUID subType; if (SUCCEEDED(mt->GetGUID(MF_MT_MAJOR_TYPE, &majorType)) && SUCCEEDED(mt->GetGUID(MF_MT_SUBTYPE, &subType)) && (majorType == _majorType) && (subType == _subType)) { return true; } return false; } void MediaStreamSink::_UpdateMediaType(__in const ComPtr<IMFMediaType>& mt) { CHK(mt->GetGUID(MF_MT_MAJOR_TYPE, &_majorType)); CHK(mt->GetGUID(MF_MT_SUBTYPE, &_subType)); if (_majorType == MFMediaType_Video) { CHK(MFGetAttributeSize(mt.Get(), MF_MT_FRAME_SIZE, &_width, &_height)); } CHK(mt->CopyAllItems(_curMT.Get())); }
lazyjarvis/artoolkit5
lib/SRC/VideoWinMC/CaptureFrameGrabber/MediaStreamSink.cpp
C++
gpl-3.0
8,667
var nodeListTemplate = "<% _.each(nodes, function(name) { %> <li><%= nodes.name %></li> <% }); %>"; //<li><a href="#" class="list-link" data-slug='+nodes.slug+' >' + nodes.name + '</a></li>
PabloCastellano/nodeshot
nodeshot/ui/open311_demo/static/open311/js/templates.js
JavaScript
gpl-3.0
189
--TEST-- ldap_count_entries() - Testing counting LDAP entries that should fail --CREDITS-- Patrick Allaert <[email protected]> # Belgian PHP Testfest 2009 --SKIPIF-- <?php require_once('skipif.inc'); ?> --FILE-- <?php require "connect.inc"; $link = ldap_connect($host, $port); var_dump(ldap_count_entries($link)); var_dump(ldap_count_entries($link, $link)); ?> ===DONE=== --EXPECTF-- Warning: ldap_count_entries() expects exactly 2 parameters, 1 given in %s on line %d NULL Warning: ldap_count_entries(): supplied resource is not a valid ldap result resource in %s on line %d bool(false) ===DONE===
tukusejssirs/eSpievatko
spievatko/espievatko/prtbl/srv/php-5.5.11/ext/ldap/tests/ldap_count_entries_error.phpt
PHP
gpl-3.0
606
# -*- coding: utf-8 -*- from ..internal.XFSAccount import XFSAccount class ExashareCom(XFSAccount): __name__ = "ExashareCom" __type__ = "account" __version__ = "0.06" __status__ = "testing" __description__ = """Exashare.com account plugin""" __license__ = "GPLv3" __authors__ = [("Walter Purcaro", "[email protected]")] PLUGIN_DOMAIN = "exashare.com"
Arno-Nymous/pyload
module/plugins/accounts/ExashareCom.py
Python
gpl-3.0
388
<?php namespace Neos\Neos\Controller; /* * This file is part of the Neos.Neos package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; use Neos\Neos\Domain\Model\Site; use Neos\Neos\Domain\Service\ContentContext; use Neos\Neos\Domain\Service\SiteService; use Neos\ContentRepository\Domain\Model\NodeData; use Neos\ContentRepository\Domain\Utility\NodePaths; /** * A trait to add create a content context */ trait CreateContentContextTrait { /** * @Flow\Inject * @var \Neos\Neos\Domain\Service\ContentContextFactory */ protected $_contextFactory; /** * @Flow\Inject * @var \Neos\Neos\Domain\Repository\SiteRepository */ protected $_siteRepository; /** * Create a ContentContext based on the given workspace name * * @param string $workspaceName Name of the workspace to set for the context * @param array $dimensions Optional list of dimensions and their values which should be set * @return ContentContext */ protected function createContentContext($workspaceName, array $dimensions = []) { $contextProperties = [ 'workspaceName' => $workspaceName, 'invisibleContentShown' => true, 'inaccessibleContentShown' => true ]; if ($dimensions !== []) { $contextProperties['dimensions'] = $dimensions; $contextProperties['targetDimensions'] = array_map(function ($dimensionValues) { return array_shift($dimensionValues); }, $dimensions); } return $this->_contextFactory->create($contextProperties); } /** * Generates a Context that exactly fits the given NodeData Workspace, Dimensions & Site. * * @param NodeData $nodeData * @return ContentContext */ protected function createContextMatchingNodeData(NodeData $nodeData) { $nodePath = NodePaths::getRelativePathBetween(SiteService::SITES_ROOT_PATH, $nodeData->getPath()); list($siteNodeName) = explode('/', $nodePath); $site = $this->_siteRepository->findOneByNodeName($siteNodeName); $contextProperties = [ 'workspaceName' => $nodeData->getWorkspace()->getName(), 'invisibleContentShown' => true, 'inaccessibleContentShown' => true, 'removedContentShown' => true, 'dimensions' => $nodeData->getDimensionValues(), 'currentSite' => $site ]; if ($site instanceof Site && $domain = $site->getFirstActiveDomain()) { $contextProperties['currentDomain'] = $domain; } return $this->_contextFactory->create($contextProperties); } }
kdambekalns/neos-development-collection
Neos.Neos/Classes/Controller/CreateContentContextTrait.php
PHP
gpl-3.0
2,909
/* Unix SMB/CIFS implementation. Windows NT Domain nsswitch module Copyright (C) Tim Potter 2000 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 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 Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "winbind_client.h" #if HAVE_PTHREAD_H #include <pthread.h> #endif #if HAVE_PTHREAD static pthread_mutex_t winbind_nss_mutex = PTHREAD_MUTEX_INITIALIZER; #endif /* Maximum number of users to pass back over the unix domain socket per call. This is not a static limit on the total number of users or groups returned in total. */ #define MAX_GETPWENT_USERS 250 #define MAX_GETGRENT_USERS 250 NSS_STATUS _nss_winbind_setpwent(void); NSS_STATUS _nss_winbind_endpwent(void); NSS_STATUS _nss_winbind_getpwent_r(struct passwd *result, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_getpwuid_r(uid_t uid, struct passwd *result, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_getpwnam_r(const char *name, struct passwd *result, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_setgrent(void); NSS_STATUS _nss_winbind_endgrent(void); NSS_STATUS _nss_winbind_getgrent_r(struct group *result, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_getgrlst_r(struct group *result, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_getgrnam_r(const char *name, struct group *result, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_getgrgid_r(gid_t gid, struct group *result, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_initgroups_dyn(char *user, gid_t group, long int *start, long int *size, gid_t **groups, long int limit, int *errnop); NSS_STATUS _nss_winbind_getusersids(const char *user_sid, char **group_sids, int *num_groups, char *buffer, size_t buf_size, int *errnop); NSS_STATUS _nss_winbind_nametosid(const char *name, char **sid, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_sidtoname(const char *sid, char **name, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_sidtouid(const char *sid, uid_t *uid, int *errnop); NSS_STATUS _nss_winbind_sidtogid(const char *sid, gid_t *gid, int *errnop); NSS_STATUS _nss_winbind_uidtosid(uid_t uid, char **sid, char *buffer, size_t buflen, int *errnop); NSS_STATUS _nss_winbind_gidtosid(gid_t gid, char **sid, char *buffer, size_t buflen, int *errnop); /************************************************************************* ************************************************************************/ #ifdef DEBUG_NSS static const char *nss_err_str(NSS_STATUS ret) { switch (ret) { case NSS_STATUS_TRYAGAIN: return "NSS_STATUS_TRYAGAIN"; case NSS_STATUS_SUCCESS: return "NSS_STATUS_SUCCESS"; case NSS_STATUS_NOTFOUND: return "NSS_STATUS_NOTFOUND"; case NSS_STATUS_UNAVAIL: return "NSS_STATUS_UNAVAIL"; #ifdef NSS_STATUS_RETURN case NSS_STATUS_RETURN: return "NSS_STATUS_RETURN"; #endif default: return "UNKNOWN RETURN CODE!!!!!!!"; } } #endif /* Prototypes from wb_common.c */ /* Allocate some space from the nss static buffer. The buffer and buflen are the pointers passed in by the C library to the _nss_ntdom_* functions. */ static char *get_static(char **buffer, size_t *buflen, size_t len) { char *result; /* Error check. We return false if things aren't set up right, or there isn't enough buffer space left. */ if ((buffer == NULL) || (buflen == NULL) || (*buflen < len)) { return NULL; } /* Return an index into the static buffer */ result = *buffer; *buffer += len; *buflen -= len; return result; } /* I've copied the strtok() replacement function next_token_Xalloc() from lib/util_str.c as I really don't want to have to link in any other objects if I can possibly avoid it. */ static bool next_token_alloc(const char **ptr, char **pp_buff, const char *sep) { const char *s; const char *saved_s; char *pbuf; bool quoted; size_t len=1; *pp_buff = NULL; if (!ptr) { return(false); } s = *ptr; /* default to simple separators */ if (!sep) { sep = " \t\n\r"; } /* find the first non sep char */ while (*s && strchr(sep,*s)) { s++; } /* nothing left? */ if (!*s) { return false; } /* When restarting we need to go from here. */ saved_s = s; /* Work out the length needed. */ for (quoted = false; *s && (quoted || !strchr(sep,*s)); s++) { if (*s == '\"') { quoted = !quoted; } else { len++; } } /* We started with len = 1 so we have space for the nul. */ *pp_buff = (char *)malloc(len); if (!*pp_buff) { return false; } /* copy over the token */ pbuf = *pp_buff; s = saved_s; for (quoted = false; *s && (quoted || !strchr(sep,*s)); s++) { if ( *s == '\"' ) { quoted = !quoted; } else { *pbuf++ = *s; } } *ptr = (*s) ? s+1 : s; *pbuf = 0; return true; } /* Fill a pwent structure from a winbindd_response structure. We use the static data passed to us by libc to put strings and stuff in. Return NSS_STATUS_TRYAGAIN if we run out of memory. */ static NSS_STATUS fill_pwent(struct passwd *result, struct winbindd_pw *pw, char **buffer, size_t *buflen) { /* User name */ if ((result->pw_name = get_static(buffer, buflen, strlen(pw->pw_name) + 1)) == NULL) { /* Out of memory */ return NSS_STATUS_TRYAGAIN; } strcpy(result->pw_name, pw->pw_name); /* Password */ if ((result->pw_passwd = get_static(buffer, buflen, strlen(pw->pw_passwd) + 1)) == NULL) { /* Out of memory */ return NSS_STATUS_TRYAGAIN; } strcpy(result->pw_passwd, pw->pw_passwd); /* [ug]id */ result->pw_uid = pw->pw_uid; result->pw_gid = pw->pw_gid; /* GECOS */ if ((result->pw_gecos = get_static(buffer, buflen, strlen(pw->pw_gecos) + 1)) == NULL) { /* Out of memory */ return NSS_STATUS_TRYAGAIN; } strcpy(result->pw_gecos, pw->pw_gecos); /* Home directory */ if ((result->pw_dir = get_static(buffer, buflen, strlen(pw->pw_dir) + 1)) == NULL) { /* Out of memory */ return NSS_STATUS_TRYAGAIN; } strcpy(result->pw_dir, pw->pw_dir); /* Logon shell */ if ((result->pw_shell = get_static(buffer, buflen, strlen(pw->pw_shell) + 1)) == NULL) { /* Out of memory */ return NSS_STATUS_TRYAGAIN; } strcpy(result->pw_shell, pw->pw_shell); /* The struct passwd for Solaris has some extra fields which must be initialised or nscd crashes. */ #if HAVE_PASSWD_PW_COMMENT result->pw_comment = ""; #endif #if HAVE_PASSWD_PW_AGE result->pw_age = ""; #endif return NSS_STATUS_SUCCESS; } /* Fill a grent structure from a winbindd_response structure. We use the static data passed to us by libc to put strings and stuff in. Return NSS_STATUS_TRYAGAIN if we run out of memory. */ static NSS_STATUS fill_grent(struct group *result, struct winbindd_gr *gr, char *gr_mem, char **buffer, size_t *buflen) { char *name; int i; char *tst; /* Group name */ if ((result->gr_name = get_static(buffer, buflen, strlen(gr->gr_name) + 1)) == NULL) { /* Out of memory */ return NSS_STATUS_TRYAGAIN; } strcpy(result->gr_name, gr->gr_name); /* Password */ if ((result->gr_passwd = get_static(buffer, buflen, strlen(gr->gr_passwd) + 1)) == NULL) { /* Out of memory */ return NSS_STATUS_TRYAGAIN; } strcpy(result->gr_passwd, gr->gr_passwd); /* gid */ result->gr_gid = gr->gr_gid; /* Group membership */ if (!gr_mem) { gr->num_gr_mem = 0; } /* this next value is a pointer to a pointer so let's align it */ /* Calculate number of extra bytes needed to align on pointer size boundry */ if ((i = (unsigned long)(*buffer) % sizeof(char*)) != 0) i = sizeof(char*) - i; if ((tst = get_static(buffer, buflen, ((gr->num_gr_mem + 1) * sizeof(char *)+i))) == NULL) { /* Out of memory */ return NSS_STATUS_TRYAGAIN; } result->gr_mem = (char **)(tst + i); if (gr->num_gr_mem == 0) { /* Group is empty */ *(result->gr_mem) = NULL; return NSS_STATUS_SUCCESS; } /* Start looking at extra data */ i = 0; while(next_token_alloc((const char **)&gr_mem, &name, ",")) { /* Allocate space for member */ if (((result->gr_mem)[i] = get_static(buffer, buflen, strlen(name) + 1)) == NULL) { free(name); /* Out of memory */ return NSS_STATUS_TRYAGAIN; } strcpy((result->gr_mem)[i], name); free(name); i++; } /* Terminate list */ (result->gr_mem)[i] = NULL; return NSS_STATUS_SUCCESS; } /* * NSS user functions */ static struct winbindd_response getpwent_response; static int ndx_pw_cache; /* Current index into pwd cache */ static int num_pw_cache; /* Current size of pwd cache */ /* Rewind "file pointer" to start of ntdom password database */ NSS_STATUS _nss_winbind_setpwent(void) { NSS_STATUS ret; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: setpwent\n", getpid()); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif if (num_pw_cache > 0) { ndx_pw_cache = num_pw_cache = 0; winbindd_free_response(&getpwent_response); } ret = winbindd_request_response(WINBINDD_SETPWENT, NULL, NULL); #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: setpwent returns %s (%d)\n", getpid(), nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* Close ntdom password database "file pointer" */ NSS_STATUS _nss_winbind_endpwent(void) { NSS_STATUS ret; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: endpwent\n", getpid()); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif if (num_pw_cache > 0) { ndx_pw_cache = num_pw_cache = 0; winbindd_free_response(&getpwent_response); } ret = winbindd_request_response(WINBINDD_ENDPWENT, NULL, NULL); #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: endpwent returns %s (%d)\n", getpid(), nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* Fetch the next password entry from ntdom password database */ NSS_STATUS _nss_winbind_getpwent_r(struct passwd *result, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; struct winbindd_request request; static int called_again; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getpwent\n", getpid()); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif /* Return an entry from the cache if we have one, or if we are called again because we exceeded our static buffer. */ if ((ndx_pw_cache < num_pw_cache) || called_again) { goto return_result; } /* Else call winbindd to get a bunch of entries */ if (num_pw_cache > 0) { winbindd_free_response(&getpwent_response); } ZERO_STRUCT(request); ZERO_STRUCT(getpwent_response); request.data.num_entries = MAX_GETPWENT_USERS; ret = winbindd_request_response(WINBINDD_GETPWENT, &request, &getpwent_response); if (ret == NSS_STATUS_SUCCESS) { struct winbindd_pw *pw_cache; /* Fill cache */ ndx_pw_cache = 0; num_pw_cache = getpwent_response.data.num_entries; /* Return a result */ return_result: pw_cache = (struct winbindd_pw *) getpwent_response.extra_data.data; /* Check data is valid */ if (pw_cache == NULL) { ret = NSS_STATUS_NOTFOUND; goto done; } ret = fill_pwent(result, &pw_cache[ndx_pw_cache], &buffer, &buflen); /* Out of memory - try again */ if (ret == NSS_STATUS_TRYAGAIN) { called_again = true; *errnop = errno = ERANGE; goto done; } *errnop = errno = 0; called_again = false; ndx_pw_cache++; /* If we've finished with this lot of results free cache */ if (ndx_pw_cache == num_pw_cache) { ndx_pw_cache = num_pw_cache = 0; winbindd_free_response(&getpwent_response); } } done: #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getpwent returns %s (%d)\n", getpid(), nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* Return passwd struct from uid */ NSS_STATUS _nss_winbind_getpwuid_r(uid_t uid, struct passwd *result, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; static struct winbindd_response response; struct winbindd_request request; static int keep_response; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getpwuid_r %d\n", getpid(), (unsigned int)uid); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif /* If our static buffer needs to be expanded we are called again */ if (!keep_response || uid != response.data.pw.pw_uid) { /* Call for the first time */ ZERO_STRUCT(response); ZERO_STRUCT(request); request.data.uid = uid; ret = winbindd_request_response(WINBINDD_GETPWUID, &request, &response); if (ret == NSS_STATUS_SUCCESS) { ret = fill_pwent(result, &response.data.pw, &buffer, &buflen); if (ret == NSS_STATUS_TRYAGAIN) { keep_response = true; *errnop = errno = ERANGE; goto done; } } } else { /* We've been called again */ ret = fill_pwent(result, &response.data.pw, &buffer, &buflen); if (ret == NSS_STATUS_TRYAGAIN) { *errnop = errno = ERANGE; goto done; } keep_response = false; *errnop = errno = 0; } winbindd_free_response(&response); done: #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getpwuid %d returns %s (%d)\n", getpid(), (unsigned int)uid, nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* Return passwd struct from username */ NSS_STATUS _nss_winbind_getpwnam_r(const char *name, struct passwd *result, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; static struct winbindd_response response; struct winbindd_request request; static int keep_response; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getpwnam_r %s\n", getpid(), name); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif /* If our static buffer needs to be expanded we are called again */ if (!keep_response || strcmp(name,response.data.pw.pw_name) != 0) { /* Call for the first time */ ZERO_STRUCT(response); ZERO_STRUCT(request); strncpy(request.data.username, name, sizeof(request.data.username) - 1); request.data.username [sizeof(request.data.username) - 1] = '\0'; ret = winbindd_request_response(WINBINDD_GETPWNAM, &request, &response); if (ret == NSS_STATUS_SUCCESS) { ret = fill_pwent(result, &response.data.pw, &buffer, &buflen); if (ret == NSS_STATUS_TRYAGAIN) { keep_response = true; *errnop = errno = ERANGE; goto done; } } } else { /* We've been called again */ ret = fill_pwent(result, &response.data.pw, &buffer, &buflen); if (ret == NSS_STATUS_TRYAGAIN) { keep_response = true; *errnop = errno = ERANGE; goto done; } keep_response = false; *errnop = errno = 0; } winbindd_free_response(&response); done: #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getpwnam %s returns %s (%d)\n", getpid(), name, nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* * NSS group functions */ static struct winbindd_response getgrent_response; static int ndx_gr_cache; /* Current index into grp cache */ static int num_gr_cache; /* Current size of grp cache */ /* Rewind "file pointer" to start of ntdom group database */ NSS_STATUS _nss_winbind_setgrent(void) { NSS_STATUS ret; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: setgrent\n", getpid()); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif if (num_gr_cache > 0) { ndx_gr_cache = num_gr_cache = 0; winbindd_free_response(&getgrent_response); } ret = winbindd_request_response(WINBINDD_SETGRENT, NULL, NULL); #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: setgrent returns %s (%d)\n", getpid(), nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* Close "file pointer" for ntdom group database */ NSS_STATUS _nss_winbind_endgrent(void) { NSS_STATUS ret; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: endgrent\n", getpid()); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif if (num_gr_cache > 0) { ndx_gr_cache = num_gr_cache = 0; winbindd_free_response(&getgrent_response); } ret = winbindd_request_response(WINBINDD_ENDGRENT, NULL, NULL); #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: endgrent returns %s (%d)\n", getpid(), nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* Get next entry from ntdom group database */ static NSS_STATUS winbind_getgrent(enum winbindd_cmd cmd, struct group *result, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; static struct winbindd_request request; static int called_again; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getgrent\n", getpid()); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif /* Return an entry from the cache if we have one, or if we are called again because we exceeded our static buffer. */ if ((ndx_gr_cache < num_gr_cache) || called_again) { goto return_result; } /* Else call winbindd to get a bunch of entries */ if (num_gr_cache > 0) { winbindd_free_response(&getgrent_response); } ZERO_STRUCT(request); ZERO_STRUCT(getgrent_response); request.data.num_entries = MAX_GETGRENT_USERS; ret = winbindd_request_response(cmd, &request, &getgrent_response); if (ret == NSS_STATUS_SUCCESS) { struct winbindd_gr *gr_cache; int mem_ofs; /* Fill cache */ ndx_gr_cache = 0; num_gr_cache = getgrent_response.data.num_entries; /* Return a result */ return_result: gr_cache = (struct winbindd_gr *) getgrent_response.extra_data.data; /* Check data is valid */ if (gr_cache == NULL) { ret = NSS_STATUS_NOTFOUND; goto done; } /* Fill group membership. The offset into the extra data for the group membership is the reported offset plus the size of all the winbindd_gr records returned. */ mem_ofs = gr_cache[ndx_gr_cache].gr_mem_ofs + num_gr_cache * sizeof(struct winbindd_gr); ret = fill_grent(result, &gr_cache[ndx_gr_cache], ((char *)getgrent_response.extra_data.data)+mem_ofs, &buffer, &buflen); /* Out of memory - try again */ if (ret == NSS_STATUS_TRYAGAIN) { called_again = true; *errnop = errno = ERANGE; goto done; } *errnop = 0; called_again = false; ndx_gr_cache++; /* If we've finished with this lot of results free cache */ if (ndx_gr_cache == num_gr_cache) { ndx_gr_cache = num_gr_cache = 0; winbindd_free_response(&getgrent_response); } } done: #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getgrent returns %s (%d)\n", getpid(), nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } NSS_STATUS _nss_winbind_getgrent_r(struct group *result, char *buffer, size_t buflen, int *errnop) { return winbind_getgrent(WINBINDD_GETGRENT, result, buffer, buflen, errnop); } NSS_STATUS _nss_winbind_getgrlst_r(struct group *result, char *buffer, size_t buflen, int *errnop) { return winbind_getgrent(WINBINDD_GETGRLST, result, buffer, buflen, errnop); } /* Return group struct from group name */ NSS_STATUS _nss_winbind_getgrnam_r(const char *name, struct group *result, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; static struct winbindd_response response; struct winbindd_request request; static int keep_response; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getgrnam %s\n", getpid(), name); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif /* If our static buffer needs to be expanded we are called again */ /* Or if the stored response group name differs from the request. */ if (!keep_response || strcmp(name,response.data.gr.gr_name) != 0) { /* Call for the first time */ ZERO_STRUCT(request); ZERO_STRUCT(response); strncpy(request.data.groupname, name, sizeof(request.data.groupname)); request.data.groupname [sizeof(request.data.groupname) - 1] = '\0'; ret = winbindd_request_response(WINBINDD_GETGRNAM, &request, &response); if (ret == NSS_STATUS_SUCCESS) { ret = fill_grent(result, &response.data.gr, (char *)response.extra_data.data, &buffer, &buflen); if (ret == NSS_STATUS_TRYAGAIN) { keep_response = true; *errnop = errno = ERANGE; goto done; } } } else { /* We've been called again */ ret = fill_grent(result, &response.data.gr, (char *)response.extra_data.data, &buffer, &buflen); if (ret == NSS_STATUS_TRYAGAIN) { keep_response = true; *errnop = errno = ERANGE; goto done; } keep_response = false; *errnop = 0; } winbindd_free_response(&response); done: #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getgrnam %s returns %s (%d)\n", getpid(), name, nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* Return group struct from gid */ NSS_STATUS _nss_winbind_getgrgid_r(gid_t gid, struct group *result, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; static struct winbindd_response response; struct winbindd_request request; static int keep_response; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getgrgid %d\n", getpid(), gid); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif /* If our static buffer needs to be expanded we are called again */ /* Or if the stored response group name differs from the request. */ if (!keep_response || gid != response.data.gr.gr_gid) { /* Call for the first time */ ZERO_STRUCT(request); ZERO_STRUCT(response); request.data.gid = gid; ret = winbindd_request_response(WINBINDD_GETGRGID, &request, &response); if (ret == NSS_STATUS_SUCCESS) { ret = fill_grent(result, &response.data.gr, (char *)response.extra_data.data, &buffer, &buflen); if (ret == NSS_STATUS_TRYAGAIN) { keep_response = true; *errnop = errno = ERANGE; goto done; } } } else { /* We've been called again */ ret = fill_grent(result, &response.data.gr, (char *)response.extra_data.data, &buffer, &buflen); if (ret == NSS_STATUS_TRYAGAIN) { keep_response = true; *errnop = errno = ERANGE; goto done; } keep_response = false; *errnop = 0; } winbindd_free_response(&response); done: #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getgrgid %d returns %s (%d)\n", getpid(), (unsigned int)gid, nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* Initialise supplementary groups */ NSS_STATUS _nss_winbind_initgroups_dyn(char *user, gid_t group, long int *start, long int *size, gid_t **groups, long int limit, int *errnop) { NSS_STATUS ret; struct winbindd_request request; struct winbindd_response response; int i; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: initgroups %s (%d)\n", getpid(), user, group); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif ZERO_STRUCT(request); ZERO_STRUCT(response); strncpy(request.data.username, user, sizeof(request.data.username) - 1); ret = winbindd_request_response(WINBINDD_GETGROUPS, &request, &response); if (ret == NSS_STATUS_SUCCESS) { int num_gids = response.data.num_entries; gid_t *gid_list = (gid_t *)response.extra_data.data; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: initgroups %s: got NSS_STATUS_SUCCESS " "and %d gids\n", getpid(), user, num_gids); #endif if (gid_list == NULL) { ret = NSS_STATUS_NOTFOUND; goto done; } /* Copy group list to client */ for (i = 0; i < num_gids; i++) { #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: initgroups %s (%d): " "processing gid %d \n", getpid(), user, group, gid_list[i]); #endif /* Skip primary group */ if (gid_list[i] == group) { continue; } /* Filled buffer ? If so, resize. */ if (*start == *size) { long int newsize; gid_t *newgroups; newsize = 2 * (*size); if (limit > 0) { if (*size == limit) { goto done; } if (newsize > limit) { newsize = limit; } } newgroups = (gid_t *) realloc((*groups), newsize * sizeof(**groups)); if (!newgroups) { *errnop = ENOMEM; ret = NSS_STATUS_NOTFOUND; goto done; } *groups = newgroups; *size = newsize; } /* Add to buffer */ (*groups)[*start] = gid_list[i]; *start += 1; } } /* Back to your regularly scheduled programming */ done: #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: initgroups %s returns %s (%d)\n", getpid(), user, nss_err_str(ret), ret); #endif #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* return a list of group SIDs for a user SID */ NSS_STATUS _nss_winbind_getusersids(const char *user_sid, char **group_sids, int *num_groups, char *buffer, size_t buf_size, int *errnop) { NSS_STATUS ret; struct winbindd_request request; struct winbindd_response response; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: getusersids %s\n", getpid(), user_sid); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif ZERO_STRUCT(request); ZERO_STRUCT(response); strncpy(request.data.sid, user_sid,sizeof(request.data.sid) - 1); request.data.sid[sizeof(request.data.sid) - 1] = '\0'; ret = winbindd_request_response(WINBINDD_GETUSERSIDS, &request, &response); if (ret != NSS_STATUS_SUCCESS) { goto done; } if (buf_size < response.length - sizeof(response)) { ret = NSS_STATUS_TRYAGAIN; errno = *errnop = ERANGE; goto done; } *num_groups = response.data.num_entries; *group_sids = buffer; memcpy(buffer, response.extra_data.data, response.length - sizeof(response)); errno = *errnop = 0; done: winbindd_free_response(&response); #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* map a user or group name to a SID string */ NSS_STATUS _nss_winbind_nametosid(const char *name, char **sid, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; struct winbindd_response response; struct winbindd_request request; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: nametosid %s\n", getpid(), name); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif ZERO_STRUCT(response); ZERO_STRUCT(request); strncpy(request.data.name.name, name, sizeof(request.data.name.name) - 1); request.data.name.name[sizeof(request.data.name.name) - 1] = '\0'; ret = winbindd_request_response(WINBINDD_LOOKUPNAME, &request, &response); if (ret != NSS_STATUS_SUCCESS) { *errnop = errno = EINVAL; goto failed; } if (buflen < strlen(response.data.sid.sid)+1) { ret = NSS_STATUS_TRYAGAIN; *errnop = errno = ERANGE; goto failed; } *errnop = errno = 0; *sid = buffer; strcpy(*sid, response.data.sid.sid); failed: winbindd_free_response(&response); #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* map a sid string to a user or group name */ NSS_STATUS _nss_winbind_sidtoname(const char *sid, char **name, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; struct winbindd_response response; struct winbindd_request request; static char sep_char; unsigned needed; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: sidtoname %s\n", getpid(), sid); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif ZERO_STRUCT(response); ZERO_STRUCT(request); /* we need to fetch the separator first time through */ if (!sep_char) { ret = winbindd_request_response(WINBINDD_INFO, &request, &response); if (ret != NSS_STATUS_SUCCESS) { *errnop = errno = EINVAL; goto failed; } sep_char = response.data.info.winbind_separator; winbindd_free_response(&response); } strncpy(request.data.sid, sid, sizeof(request.data.sid) - 1); request.data.sid[sizeof(request.data.sid) - 1] = '\0'; ret = winbindd_request_response(WINBINDD_LOOKUPSID, &request, &response); if (ret != NSS_STATUS_SUCCESS) { *errnop = errno = EINVAL; goto failed; } needed = strlen(response.data.name.dom_name) + strlen(response.data.name.name) + 2; if (buflen < needed) { ret = NSS_STATUS_TRYAGAIN; *errnop = errno = ERANGE; goto failed; } snprintf(buffer, needed, "%s%c%s", response.data.name.dom_name, sep_char, response.data.name.name); *name = buffer; *errnop = errno = 0; failed: winbindd_free_response(&response); #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* map a sid to a uid */ NSS_STATUS _nss_winbind_sidtouid(const char *sid, uid_t *uid, int *errnop) { NSS_STATUS ret; struct winbindd_response response; struct winbindd_request request; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: sidtouid %s\n", getpid(), sid); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif ZERO_STRUCT(request); ZERO_STRUCT(response); strncpy(request.data.sid, sid, sizeof(request.data.sid) - 1); request.data.sid[sizeof(request.data.sid) - 1] = '\0'; ret = winbindd_request_response(WINBINDD_SID_TO_UID, &request, &response); if (ret != NSS_STATUS_SUCCESS) { *errnop = errno = EINVAL; goto failed; } *uid = response.data.uid; failed: #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* map a sid to a gid */ NSS_STATUS _nss_winbind_sidtogid(const char *sid, gid_t *gid, int *errnop) { NSS_STATUS ret; struct winbindd_response response; struct winbindd_request request; #ifdef DEBUG_NSS fprintf(stderr, "[%5d]: sidtogid %s\n", getpid(), sid); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif ZERO_STRUCT(request); ZERO_STRUCT(response); strncpy(request.data.sid, sid, sizeof(request.data.sid) - 1); request.data.sid[sizeof(request.data.sid) - 1] = '\0'; ret = winbindd_request_response(WINBINDD_SID_TO_GID, &request, &response); if (ret != NSS_STATUS_SUCCESS) { *errnop = errno = EINVAL; goto failed; } *gid = response.data.gid; failed: #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* map a uid to a SID string */ NSS_STATUS _nss_winbind_uidtosid(uid_t uid, char **sid, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; struct winbindd_response response; struct winbindd_request request; #ifdef DEBUG_NSS fprintf(stderr, "[%5u]: uidtosid %u\n", (unsigned int)getpid(), (unsigned int)uid); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif ZERO_STRUCT(response); ZERO_STRUCT(request); request.data.uid = uid; ret = winbindd_request_response(WINBINDD_UID_TO_SID, &request, &response); if (ret != NSS_STATUS_SUCCESS) { *errnop = errno = EINVAL; goto failed; } if (buflen < strlen(response.data.sid.sid)+1) { ret = NSS_STATUS_TRYAGAIN; *errnop = errno = ERANGE; goto failed; } *errnop = errno = 0; *sid = buffer; strcpy(*sid, response.data.sid.sid); failed: winbindd_free_response(&response); #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; } /* map a gid to a SID string */ NSS_STATUS _nss_winbind_gidtosid(gid_t gid, char **sid, char *buffer, size_t buflen, int *errnop) { NSS_STATUS ret; struct winbindd_response response; struct winbindd_request request; #ifdef DEBUG_NSS fprintf(stderr, "[%5u]: gidtosid %u\n", (unsigned int)getpid(), (unsigned int)gid); #endif #if HAVE_PTHREAD pthread_mutex_lock(&winbind_nss_mutex); #endif ZERO_STRUCT(response); ZERO_STRUCT(request); request.data.gid = gid; ret = winbindd_request_response(WINBINDD_GID_TO_SID, &request, &response); if (ret != NSS_STATUS_SUCCESS) { *errnop = errno = EINVAL; goto failed; } if (buflen < strlen(response.data.sid.sid)+1) { ret = NSS_STATUS_TRYAGAIN; *errnop = errno = ERANGE; goto failed; } *errnop = errno = 0; *sid = buffer; strcpy(*sid, response.data.sid.sid); failed: winbindd_free_response(&response); #if HAVE_PTHREAD pthread_mutex_unlock(&winbind_nss_mutex); #endif return ret; }
hef/samba
nsswitch/winbind_nss_linux.c
C
gpl-3.0
32,895
/* * Copyright 2020 Free Software Foundation, Inc. * * This file is part of GNU Radio * * SPDX-License-Identifier: GPL-3.0-or-later * */ /***********************************************************************************/ /* This file is automatically generated using bindtool and can be manually edited */ /* The following lines can be configured to regenerate this file during cmake */ /* If manual edits are made, the following tags should be modified accordingly. */ /* BINDTOOL_GEN_AUTOMATIC(0) */ /* BINDTOOL_USE_PYGCCXML(0) */ /* BINDTOOL_HEADER_FILE(agc3_cc.h) */ /* BINDTOOL_HEADER_FILE_HASH(a3249a33ccef3b89642aa41df853772e) */ /***********************************************************************************/ #include <pybind11/complex.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; #include <gnuradio/analog/agc3_cc.h> // pydoc.h is automatically generated in the build directory #include <agc3_cc_pydoc.h> void bind_agc3_cc(py::module& m) { using agc3_cc = ::gr::analog::agc3_cc; py::class_<agc3_cc, gr::sync_block, gr::block, gr::basic_block, std::shared_ptr<agc3_cc>>(m, "agc3_cc", D(agc3_cc)) .def(py::init(&agc3_cc::make), py::arg("attack_rate") = 0.10000000000000001, py::arg("decay_rate") = 0.01, py::arg("reference") = 1., py::arg("gain") = 1., py::arg("iir_update_decim") = 1, D(agc3_cc, make)) .def("attack_rate", &agc3_cc::attack_rate, D(agc3_cc, attack_rate)) .def("decay_rate", &agc3_cc::decay_rate, D(agc3_cc, decay_rate)) .def("reference", &agc3_cc::reference, D(agc3_cc, reference)) .def("gain", &agc3_cc::gain, D(agc3_cc, gain)) .def("max_gain", &agc3_cc::max_gain, D(agc3_cc, max_gain)) .def("set_attack_rate", &agc3_cc::set_attack_rate, py::arg("rate"), D(agc3_cc, set_attack_rate)) .def("set_decay_rate", &agc3_cc::set_decay_rate, py::arg("rate"), D(agc3_cc, set_decay_rate)) .def("set_reference", &agc3_cc::set_reference, py::arg("reference"), D(agc3_cc, set_reference)) .def("set_gain", &agc3_cc::set_gain, py::arg("gain"), D(agc3_cc, set_gain)) .def("set_max_gain", &agc3_cc::set_max_gain, py::arg("max_gain"), D(agc3_cc, set_max_gain)) ; }
jdemel/gnuradio
gr-analog/python/analog/bindings/agc3_cc_python.cc
C++
gpl-3.0
2,731
# Add support for launching apps in the iOS 10 simulator
thierrydouez/livecode
docs/notes/bugfix-18332.md
Markdown
gpl-3.0
57
/* ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010, 2011,2012 Giovanni Di Sirio. This file is part of ChibiOS/RT. ChibiOS/RT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. ChibiOS/RT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @file ch.h * @brief ChibiOS/RT main include file. * @details This header includes all the required kernel headers so it is the * only kernel header you usually want to include in your application. * * @addtogroup kernel_info * @details Kernel related info. * @{ */ #ifndef _CH_H_ #define _CH_H_ /** * @brief ChibiOS/RT identification macro. */ #define _CHIBIOS_RT_ /** * @brief Kernel version string. */ #define CH_KERNEL_VERSION "2.5.1unstable" /** * @name Kernel version * @{ */ /** * @brief Kernel version major number. */ #define CH_KERNEL_MAJOR 2 /** * @brief Kernel version minor number. */ #define CH_KERNEL_MINOR 5 /** * @brief Kernel version patch number. */ #define CH_KERNEL_PATCH 1 /** @} */ /** * @name Common constants */ /** * @brief Generic 'false' boolean constant. */ #if !defined(FALSE) || defined(__DOXYGEN__) #define FALSE 0 #endif /** * @brief Generic 'true' boolean constant. */ #if !defined(TRUE) || defined(__DOXYGEN__) #define TRUE (!FALSE) #endif /** * @brief Generic success constant. * @details This constant is functionally equivalent to @p FALSE but more * readable, it can be used as return value of all those functions * returning a @p bool_t as a status indicator. */ #if !defined(CH_SUCCESS) || defined(__DOXYGEN__) #define CH_SUCCESS FALSE #endif /** * @brief Generic failure constant. * @details This constant is functionally equivalent to @p TRUE but more * readable, it can be used as return value of all those functions * returning a @p bool_t as a status indicator. */ #if !defined(CH_FAILED) || defined(__DOXYGEN__) #define CH_FAILED TRUE #endif /** @} */ #include "chconf.h" #include "chtypes.h" #include "chlists.h" #include "chcore.h" #include "chsys.h" #include "chvt.h" #include "chschd.h" #include "chsem.h" #include "chbsem.h" #include "chmtx.h" #include "chcond.h" #include "chevents.h" #include "chmsg.h" #include "chmboxes.h" #include "chmemcore.h" #include "chheap.h" #include "chmempools.h" #include "chthreads.h" #include "chdynamic.h" #include "chregistry.h" #include "chinline.h" #include "chqueues.h" #include "chstreams.h" #include "chfiles.h" #include "chdebug.h" #if !defined(__DOXYGEN__) extern WORKING_AREA(_idle_thread_wa, PORT_IDLE_THREAD_STACK_SIZE); #endif #ifdef __cplusplus extern "C" { #endif void _idle_thread(void *p); #ifdef __cplusplus } #endif #endif /* _CH_H_ */ /** @} */
openrobots-dev/ChibiOS
os/kernel/include/ch.h
C
gpl-3.0
3,470
# redundant-alt Enforce img alt attribute does not contain the word image, picture, or photo. Screenreaders already announce `img` elements as an image. There is no need to use words such as *image*, *photo*, and/or *picture*. ## Rule details This rule takes no arguments. This rule will first check if `aria-hidden` is true to determine whether to enforce the rule. If the image is hidden, then rule will always succeed. ### Succeed ```jsx <img src="foo" alt="Foo eating a sandwich." /> <img src="bar" aria-hidden alt="Picture of me taking a photo of an image" /> // Will pass because it is hidden. <img src="baz" alt={`Baz taking a ${photo}`} /> // This is valid since photo is a variable name. ``` ### Fail ```jsx <img src="foo" alt="Photo of foo being weird." /> <img src="bar" alt="Image of me at a bar!" /> <img src="baz" alt="Picture of baz fixing a bug." /> ```
santosh-surya/pcb-cnc-machine
desktop-application/node_modules/eslint-plugin-jsx-a11y/docs/rules/redundant-alt.md
Markdown
gpl-3.0
875
// Copyright 2019 Google // // 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. #include "Crashlytics/Crashlytics/Components/FIRCLSContext.h" __BEGIN_DECLS extern FIRCLSContext _firclsContext; extern dispatch_queue_t _firclsLoggingQueue; extern dispatch_queue_t _firclsBinaryImageQueue; extern dispatch_queue_t _firclsExceptionQueue; #define FIRCLSGetLoggingQueue() (_firclsLoggingQueue) #define FIRCLSGetBinaryImageQueue() (_firclsBinaryImageQueue) #define FIRCLSGetExceptionQueue() (_firclsExceptionQueue) __END_DECLS
EclipseSoundscapes/EclipseSoundscapes
Pods/FirebaseCrashlytics/Crashlytics/Crashlytics/Components/FIRCLSGlobals.h
C
gpl-3.0
1,029
<?php /* Copyright (C) 2004-2005 Rodolphe Quiedeville <[email protected]> * Copyright (C) 2005-2012 Laurent Destailleur <[email protected]> * Copyright (C) 2005-2012 Regis Houssin <[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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * or see http://www.gnu.org/ */ /** * \file htdocs/viewimage.php * \brief Wrapper to show images into Dolibarr screens * \remarks Call to wrapper is '<img src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=diroffile&file=relativepathofofile&cache=0">' */ //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language //if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled cause need to load personalized language if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Pour autre que companylogo, on charge environnement + info issus de logon comme le user if ((isset($_GET["modulepart"]) && $_GET["modulepart"] == 'companylogo') && ! defined("NOLOGIN")) define("NOLOGIN",'1'); /** * Header empty * * @return void */ function llxHeader() { } /** * Footer empty * * @return void */ function llxFooter() { } require 'main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $action=GETPOST('action','alpha'); $original_file=GETPOST("file"); $modulepart=GETPOST('modulepart','alpha'); $urlsource=GETPOST("urlsource"); $entity=GETPOST('entity')?GETPOST('entity','int'):$conf->entity; // Security check if (empty($modulepart)) accessforbidden('Bad value for parameter modulepart'); /* * Actions */ // None /* * View */ if (GETPOST("cache")) { // Important: Following code is to avoid page request by browser and PHP CPU at // each Dolibarr page access. if (empty($dolibarr_nocache)) { header('Cache-Control: max-age=3600, public, must-revalidate'); header('Pragma: cache'); // This is to avoid having Pragma: no-cache } else header('Cache-Control: no-cache'); //print $dolibarr_nocache; exit; } // Define mime type $type = 'application/octet-stream'; if (! empty($_GET["type"])) $type=$_GET["type"]; else $type=dol_mimetype($original_file); // Suppression de la chaine de caractere ../ dans $original_file $original_file = str_replace("../","/", $original_file); // Find the subdirectory name as the reference $refname=basename(dirname($original_file)."/"); // Security check if (empty($modulepart)) accessforbidden('Bad value for parameter modulepart'); $check_access = dol_check_secure_access_document($modulepart,$original_file,$entity,$refname); $accessallowed = $check_access['accessallowed']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $original_file = $check_access['original_file']; // Security: // Limit access if permissions are wrong if (! $accessallowed) { accessforbidden(); } // Security: // On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers. if (preg_match('/\.\./',$original_file) || preg_match('/[<>|]/',$original_file)) { dol_syslog("Refused to deliver file ".$original_file, LOG_WARNING); // Do no show plain path in shown error message dol_print_error(0,'Error: File '.$_GET["file"].' does not exists'); exit; } if ($modulepart == 'barcode') { $generator=GETPOST("generator","alpha"); $code=GETPOST("code"); $encoding=GETPOST("encoding","alpha"); $readable=GETPOST("readable")?GETPOST("readable","alpha"):"Y"; if (empty($generator) || empty($encoding)) { dol_print_error(0,'Error, parameter "generator" or "encoding" not defined'); exit; } $dirbarcode=array_merge(array("/core/modules/barcode/doc/"),$conf->modules_parts['barcode']); $result=0; foreach($dirbarcode as $reldir) { $dir=dol_buildpath($reldir,0); $newdir=dol_osencode($dir); // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php) if (! is_dir($newdir)) continue; $result=@include_once $newdir.$generator.'.modules.php'; if ($result) break; } // Load barcode class $classname = "mod".ucfirst($generator); $module = new $classname($db); if ($module->encodingIsSupported($encoding)) { $result=$module->buildBarCode($code,$encoding,$readable); } } else // Open and return file { clearstatcache(); // Output files on browser dol_syslog("viewimage.php return file $original_file content-type=$type"); // This test is to avoid error images when image is not available (for example thumbs). if (! dol_is_file($original_file)) { $original_file=DOL_DOCUMENT_ROOT.'/public/theme/common/nophoto.jpg'; /*$error='Error: File '.$_GET["file"].' does not exists or filesystems permissions are not allowed'; dol_print_error(0,$error); print $error; exit;*/ } // Les drois sont ok et fichier trouve if ($type) { header('Content-Disposition: inline; filename="'.basename($original_file).'"'); header('Content-type: '.$type); } else { header('Content-Disposition: inline; filename="'.basename($original_file).'"'); header('Content-type: image/png'); } $original_file_osencoded=dol_osencode($original_file); readfile($original_file_osencoded); } if (is_object($db)) $db->close();
maestrano/dolibarr
htdocs/viewimage.php
PHP
gpl-3.0
6,453
/************************************************************* * keywords.h * This file defines the pascal compilation environment * * Copyright (C) 2008 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * 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. * 3. Neither the name NuttX 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 __KEYWORDS_H #define __KEYWORDS_H /************************************************************* * Included Files *************************************************************/ #include <nuttx/config.h> #include <nuttx/compiler.h> #include <debug.h> /************************************************************* * Definitions *************************************************************/ #ifndef CONFIG_DEBUG # define CONFIG_DEBUG 0 #endif #ifndef CONFIG_TRACE # define CONFIG_TRACE 0 #endif #ifdef CONFIG_CPP_HAVE_VARARGS # define DEBUG(stream, format, arg...) dbg(format, ##arg) # define TRACE(stream, format, arg...) dbg(format, ##arg) #else # define DEBUG dbg # define TRACE dbg #endif #endif /* __KEYWORDS_H */
evancich/apm_motor
modules/PX4NuttX/misc/pascal/nuttx/keywords.h
C
gpl-3.0
2,549
<html lang="en"> <head> <title>Ln - Using as</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Using as"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Pseudo-Ops.html#Pseudo-Ops" title="Pseudo Ops"> <link rel="prev" href="List.html#List" title="List"> <link rel="next" href="Loc.html#Loc" title="Loc"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This file documents the GNU Assembler "as". Copyright (C) 1991-2013 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <a name="Ln"></a> <p> Next:&nbsp;<a rel="next" accesskey="n" href="Loc.html#Loc">Loc</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="List.html#List">List</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Pseudo-Ops.html#Pseudo-Ops">Pseudo Ops</a> <hr> </div> <h3 class="section">7.74 <code>.ln </code><var>line-number</var></h3> <p><a name="index-g_t_0040code_007bln_007d-directive-392"></a>&lsquo;<samp><span class="samp">.ln</span></samp>&rsquo; is a synonym for &lsquo;<samp><span class="samp">.line</span></samp>&rsquo;. </body></html>
darth-vader-lg/glcncrpi
tools/arm-bcm2708/gcc-linaro-arm-none-eabi-4.8-2014.04/share/doc/gcc-linaro-arm-none-eabi/html/as.html/Ln.html
HTML
gpl-3.0
2,144
/** * ----------------------------------------------------------------------------- * @package smartVISU * @author Martin GleiรŸ * @copyright 2012 - 2015 * @license GPL <http://www.gnu.de> * ----------------------------------------------------------------------------- */ {% extends "rooms.html" %} {% block content %} <h1><img class="icon" src='{{ icon0 }}szene_garten.png'/>Garten</h1> <div class="preblock"> </div> <div class="block"> <div class="set-2" data-role="collapsible-set" data-theme="c" data-content-theme="a" data-mini="true"> <div data-role="collapsible" data-collapsed="false" > <h3>Hausbeleuchtung</h3> <table width="90%"><tr><td align="left" width="100px">&nbsp; {{ basic.switch('switch1', 'haustuer_beleuchtung_schalten', icon1~'light_light.png', icon0~'light_light.png') }} </td><td>Wandleuchten Haustรผr</td></tr> <tr><td align="left" width="100px">&nbsp; {{ basic.switch('switch2', 'dachueberstand_ost_beleuchtung_schalten', icon1~'light_light.png', icon0~'light_light.png') }} </td><td>Strahler Dachรผberstand Hauswirtschaftsraum</td></tr> <tr><td align="left" width="100px">&nbsp; {{ basic.switch('switch3', 'dachueberstand_west_beleuchtung_schalten', icon1~'light_light.png', icon0~'light_light.png') }} </td><td>Strahler Dachรผberstand Bรผro</td></tr> <tr><td align="left" width="100px">&nbsp; {{ basic.switch('switch4', 'giebel_west_beleuchtung_schalten', icon1~'light_light.png', icon0~'light_light.png') }} </td><td>Wandleuchten Westgiebel</td></tr> </table> </div> </div> </div> {% endblock %}
bjko/smartvisu
pages/alber.smarthome.py/room0.garten.html
HTML
gpl-3.0
1,637
----------------------------------- -- Area: Pashhow Marshlands -- MOB: Copper Quadav ----------------------------------- require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) checkRegime(ally,mob,60,1); end;
nesstea/darkstar
scripts/zones/Pashhow_Marshlands/mobs/Copper_Quadav.lua
Lua
gpl-3.0
328
/** * Aptana Studio * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.aptana.editor.html.parsing; import org.eclipse.jface.text.rules.EndOfLineRule; import org.eclipse.jface.text.rules.ICharacterScanner; import org.eclipse.jface.text.rules.IPredicateRule; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.MultiLineRule; import org.eclipse.jface.text.rules.Token; import com.aptana.editor.common.text.rules.CollectingCharacterScanner; import com.aptana.editor.common.text.rules.ExtendedToken; import com.aptana.editor.common.text.rules.SequenceCharacterScanner; class HTMLParserTagRule extends MultiLineRule { private static final IToken singleQuoteStringTOKEN = new Token("SQS"); //$NON-NLS-1$ private static final IPredicateRule singleQuoteStringRule = new MultiLineRule( "'", "'", singleQuoteStringTOKEN, '\\'); //$NON-NLS-1$ //$NON-NLS-2$ private static final IPredicateRule singleQuoteStringEOLRule = new EndOfLineRule("'", singleQuoteStringTOKEN, '\\'); //$NON-NLS-1$ private static final IToken doubleQuoteStringTOKEN = new Token("DQS"); //$NON-NLS-1$ private static final IPredicateRule doubleQuoteStringRule = new MultiLineRule( "\"", "\"", doubleQuoteStringTOKEN, '\\'); //$NON-NLS-1$ //$NON-NLS-2$ private static final IPredicateRule doubleQuoteStringEOLRule = new EndOfLineRule("\"", doubleQuoteStringTOKEN, '\\'); //$NON-NLS-1$ private boolean fIgnoreCase; private int fEmbeddedStart; HTMLParserTagRule(IToken token) { this("", token); //$NON-NLS-1$ } HTMLParserTagRule(String tag, IToken token) { this(tag, token, false); } HTMLParserTagRule(String tag, IToken token, boolean ignoreCase) { this("<" + tag, ">", token, ignoreCase); //$NON-NLS-1$ //$NON-NLS-2$ } protected HTMLParserTagRule(String startSequence, String endSequence, IToken token, boolean ignoreCase) { super(startSequence, endSequence, token); fIgnoreCase = ignoreCase; } @Override protected boolean sequenceDetected(ICharacterScanner scanner, char[] sequence, boolean eofAllowed) { boolean detected = true; for (int i = 1; i < sequence.length; ++i) { int c = scanner.read(); if (c == ICharacterScanner.EOF && eofAllowed) { break; } if ((fIgnoreCase && Character.toLowerCase(c) != Character.toLowerCase(sequence[i])) || (!fIgnoreCase && c != sequence[i])) { // Non-matching character detected, rewind the scanner back to the start. // Do not unread the first character. scanner.unread(); for (int j = i - 1; j > 0; --j) { scanner.unread(); } detected = false; break; } } if (!detected) { return detected; } if ((sequence.length == 1 && sequence[0] == '<') || (sequence.length == 2 && sequence[0] == '<' && sequence[1] == '/')) { int nextChar = scanner.read(); if (nextChar == ICharacterScanner.EOF) { return false; } scanner.unread(); return Character.isJavaIdentifierStart(nextChar); } return detected; } /* * (non-Javadoc) * @see org.eclipse.jface.text.rules.PatternRule#endSequenceDetected(org.eclipse.jface.text.rules.ICharacterScanner) */ protected boolean endSequenceDetected(ICharacterScanner scanner) { CollectingCharacterScanner collectingCharacterScanner = new CollectingCharacterScanner(scanner, String.valueOf(fStartSequence)); int c, length = 0; while ((c = collectingCharacterScanner.read()) != ICharacterScanner.EOF) { length++; if (c == '\'') { collectingCharacterScanner.unread(); IToken token = singleQuoteStringRule.evaluate(collectingCharacterScanner); if (token.isUndefined()) { token = singleQuoteStringEOLRule.evaluate(collectingCharacterScanner); } } else if (c == '"') { collectingCharacterScanner.unread(); IToken token = doubleQuoteStringRule.evaluate(collectingCharacterScanner); if (token.isUndefined()) { token = doubleQuoteStringEOLRule.evaluate(collectingCharacterScanner); } } else if (c == fStartSequence[0]) { fEmbeddedStart++; } else if (c == fEndSequence[0]) { if (fEmbeddedStart == 0) { if (fToken instanceof ExtendedToken) { ((ExtendedToken) fToken).setContents(collectingCharacterScanner.getContents()); } return true; } fEmbeddedStart--; } } if (scanner instanceof SequenceCharacterScanner && ((SequenceCharacterScanner) scanner).foundSequence()) { // this means the EOF came from seeing a switching sequence, so assumes the end is detected and no need to // rewind one character if (fToken instanceof ExtendedToken) { ((ExtendedToken) fToken).setContents(collectingCharacterScanner.getContents()); } return true; } for (int i = 0; i < length; ++i) { collectingCharacterScanner.unread(); } // unread the original character collectingCharacterScanner.unread(); return false; } }
HossainKhademian/Studio3
plugins/com.aptana.editor.html/src/com/aptana/editor/html/parsing/HTMLParserTagRule.java
Java
gpl-3.0
5,168
#region License // Copyright (c) 2013, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This file is part of the ClearCanvas RIS/PACS open source project. // // The ClearCanvas RIS/PACS open source project is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // The ClearCanvas RIS/PACS open source project 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 // the ClearCanvas RIS/PACS open source project. If not, see // <http://www.gnu.org/licenses/>. #endregion using System; using System.IO; using System.Text; using ClearCanvas.Common.Utilities; namespace ClearCanvas.Dicom.IO { /// <summary> /// Used internally by the framework. /// </summary> public class ByteBuffer : IByteBuffer, IDisposable { /// <summary> /// Buffer size of 4096 for bulk byte copies. /// </summary> /// <remarks> /// This seems to be the buffer size most commonly used internally by the .NET framework for bulk byte copies, /// and testing does seem to indicate that this value gives better performance than a larger value (like 4MB) /// </remarks> private const int _bufferSize = 4096; private const int _highCapacityModeThreshold = 84000; public static Endian LocalMachineEndian = BitConverter.IsLittleEndian ? Endian.Little : Endian.Big; #region Private Members private readonly bool _highCapacityMode; private byte[] _data; private Stream _ms; private BinaryReader _br; private BinaryWriter _bw; private Endian _endian; #endregion #region Public Constructors public ByteBuffer(long length = 0) : this(null, LocalMachineEndian, length > _highCapacityModeThreshold) {} public ByteBuffer(Endian endian, long length = 0) : this(null, endian, length > _highCapacityModeThreshold) {} public ByteBuffer(byte[] data) : this(data, LocalMachineEndian, data != null && data.Length > _highCapacityModeThreshold) {} public ByteBuffer(byte[] data, Endian endian) : this(data, endian, data != null && data.Length > _highCapacityModeThreshold) {} private ByteBuffer(byte[] data, Endian endian, bool highCapacityMode = false) { _data = data; _endian = endian; Encoding = Encoding.ASCII; SpecificCharacterSet = null; _highCapacityMode = highCapacityMode; } #endregion #region Destructor and Disposal ~ByteBuffer() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_ms != null) { _ms.Dispose(); _ms = null; } if (_br != null) { _br.Dispose(); _br = null; } if (_bw != null) { _bw.Dispose(); _bw = null; } _data = null; } } #endregion #region Public Properties public Stream Stream { get { if (_ms != null) return _ms; AllocateStream(); return _ms; } } private void AllocateStream(int lengthHint = 0) { if (_ms != null) return; if (_highCapacityMode) { _ms = new LargeMemoryStream(_data); } else { if (_data != null) { _ms = new MemoryStream(_data.Length);// do not use overload with byte[] because that will make the stream non-expandable _ms.Write(_data, 0, _data.Length); _ms.Position = 0; } else { if (lengthHint <= 0) _ms = new MemoryStream(); else _ms = new MemoryStream(lengthHint); } } _data = null; } public BinaryReader Reader { get { return _br ?? (_br = EndianBinaryReader.Create(Stream, Endian)); } } public BinaryWriter Writer { get { return _bw ?? (_bw = EndianBinaryWriter.Create(Stream, Endian)); } } public Endian Endian { get { return _endian; } set { _endian = value; _br = null; _bw = null; } } public Encoding Encoding { get; set; } public string SpecificCharacterSet { get; set; } public int Length { get { if (_ms != null) return (int) _ms.Length; return _data != null ? _data.Length : 0; } } #endregion #region Public Functions public void Clear() { _ms = null; _br = null; _bw = null; _data = null; } /// <summary> /// Truncates the buffer by removing the first <paramref name="count"/> bytes. /// </summary> /// <param name="count">Number of bytes to be truncated.</param> public void Chop(int count) { if (Length <= count) { // if chopping more bytes than we have data, just clear it all Clear(); return; } if (_ms != null) { var buffer = new byte[_bufferSize]; var position = _ms.Position = count; int bytesRead; while ((bytesRead = _ms.Read(buffer, 0, buffer.Length)) > 0) { // reset stream position back "count" bytes from where it was read from, and write the buffer back _ms.Position = position - count; _ms.Write(buffer, 0, bytesRead); // update the position position += bytesRead; _ms.Position = position; } // truncate the stream _ms.SetLength(position - count); _ms.Position = 0; return; } if (_data != null) { _data = GetChunk(count, _data.Length - count); } } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> public void Append(byte[] buffer, int offset, int count) { // for an append, it's much easier to just use Streams since the buffer copy would be needed anyway var pos = Stream.Position; Stream.Seek(0, SeekOrigin.End); Stream.Write(buffer, offset, count); Stream.Position = pos; } /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="count"></param> /// <returns></returns> public int CopyFrom(Stream s, int count) { // clear previous data so that next call to Stream property will create new stream instance Clear(); AllocateStream(count); // execute copy var copied = CopyBytes(s, Stream, count); // JY: the original implementation here made an assumption that count would never exceed actual data length, but this is what would have happened if you did if (count > copied) { ZeroBytes(Stream, count - copied); } Stream.Position = 0; return copied; } /// <summary> /// /// </summary> /// <param name="bw"></param> public void CopyTo(BinaryWriter bw) { if (_ms != null) { var position = _ms.Position; _ms.Position = 0; _ms.CopyTo(bw.BaseStream); _ms.Position = position; return; } if (_data != null) { // Discovered a bug when saving to a network drive, where // writing data in large chunks caused an IOException. // Limiting single writes to a smaller size seems to fix the issue. const int maxSize = 1024*1024*4; if (_data.Length > maxSize && bw.BaseStream is FileStream) { int bytesLeft = _data.Length; int offset = 0; while (bytesLeft > 0) { int bytesToWrite = bytesLeft > maxSize ? maxSize : bytesLeft; bw.Write(_data, offset, bytesToWrite); bytesLeft -= bytesToWrite; offset += bytesToWrite; } } else { bw.Write(_data, 0, _data.Length); } } } /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="offset"></param> /// <param name="count"></param> public void CopyTo(Stream s, int offset, int count) { if (_ms != null) { var position = _ms.Position; _ms.Position = offset; var copied = CopyBytes(_ms, s, count); // JY: the original implementation here made an assumption that count would never exceed actual data length, but this is what would have happened if you did if (count > copied) { ZeroBytes(s, count - copied); } _ms.Position = position; return; } if (_data != null) { var copiableBytes = Math.Min(count, _data.Length); s.Write(_data, offset, copiableBytes); // JY: the original implementation here made an assumption that count would never exceed actual data length, but this is what would have happened if you did if (count > copiableBytes) { var zero = new byte[count - copiableBytes]; s.Write(zero, 0, zero.Length); } } } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> public void CopyTo(byte[] buffer, int offset, int count) { CopyTo(buffer, offset, 0, count); } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="srcOffset"></param> /// <param name="dstOffset"></param> /// <param name="count"></param> public void CopyTo(byte[] buffer, int srcOffset, int dstOffset, int count) { if (_ms != null) { var position = _ms.Position; _ms.Position = srcOffset; _ms.Read(buffer, dstOffset, count); _ms.Position = position; return; } if (_data != null) { Array.Copy(_data, srcOffset, buffer, dstOffset, count); } } public byte[] GetChunk(int offset, int count) { byte[] chunk = new byte[count]; CopyTo(chunk, offset, count); return chunk; } public void FromBytes(byte[] bytes) { _data = bytes; _ms = null; _br = null; _bw = null; } public byte[] ToBytes() { // legacy behaviour here is to dump a MemoryStream into a byte array since we have to do a full array copy anyway ConvertToByteArray(); return ToBytesCore(); } private byte[] ToBytesCore() { if (_ms is LargeMemoryStream) { return ((LargeMemoryStream) _ms).ToArray(); } else if (_ms is MemoryStream) { return ((MemoryStream) _ms).ToArray(); } return _data ?? new byte[0]; } public byte[] ToBytes(int offset, int count) { var buffer = new byte[count]; CopyTo(buffer, offset, count); if (_ms != null) _ms.Position = 0; return buffer; } // ReSharper disable InconsistentNaming public ushort[] ToUInt16s() { return ByteConverter.ToUInt16Array(ToBytes()); } public short[] ToInt16s() { return ByteConverter.ToInt16Array(ToBytes()); } public uint[] ToUInt32s() { return ByteConverter.ToUInt32Array(ToBytes()); } public int[] ToInt32s() { return ByteConverter.ToInt32Array(ToBytes()); } // ReSharper restore InconsistentNaming public float[] ToFloats() { return ByteConverter.ToFloatArray(ToBytes()); } public double[] ToDoubles() { return ByteConverter.ToDoubleArray(ToBytes()); } public string GetString() { var buffer = ToBytes(); if (SpecificCharacterSet != null) return DicomImplementation.CharacterParser.Decode(buffer, SpecificCharacterSet); return Encoding.GetString(buffer); } public void SetString(string stringValue) { Clear(); if (string.IsNullOrEmpty(stringValue)) return; if (SpecificCharacterSet != null) { _data = DicomImplementation.CharacterParser.Encode(stringValue, SpecificCharacterSet); } else { _data = Encoding.GetBytes(stringValue); } } public void SetString(string stringValue, byte paddingByte) { Clear(); if (string.IsNullOrEmpty(stringValue)) return; if (SpecificCharacterSet != null) { _data = DicomImplementation.CharacterParser.Encode(stringValue, SpecificCharacterSet); if (_data != null && (_data.Length & 1) == 1) { byte[] rawBytes = new byte[_data.Length + 1]; rawBytes[_data.Length] = paddingByte; _data.CopyTo(rawBytes, 0); _data = rawBytes; } } else { int count = Encoding.GetByteCount(stringValue); if ((count & 1) == 1) count++; byte[] bytes = new byte[count]; if (Encoding.GetBytes(stringValue, 0, stringValue.Length, bytes, 0) < count) bytes[count - 1] = paddingByte; _data = bytes; } } public void Swap(int bytesToSwap) { // use the more efficient methods if it's one of the common swap window sizes switch (bytesToSwap) { case 1: return; // NOP case 2: Swap2(); return; case 4: Swap4(); return; } if (bytesToSwap < 1) { const string message = "bytesToSwap must be a positive integer"; throw new ArgumentOutOfRangeException("bytesToSwap", bytesToSwap, message); } // switch stream to byte array if possible, since swapping is easier that way ConvertToByteArray(); if (_ms != null) { // the swap buffer must be a multiple of bytesToSwap var buffer = new byte[(_bufferSize/bytesToSwap + (_bufferSize%bytesToSwap != 0 ? 1 : 0))*bytesToSwap]; var position = _ms.Position = 0; // N.B. we know _ms is a LargeMemoryStream that will never read an incomplete buffer unless it's actually the end of stream // so we can assume that we won't be throwing in a padding zero when that byte just hasn't been read yet! int bytesRead; while ((bytesRead = _ms.Read(buffer, 0, buffer.Length)) > 0) { // if the buffer is not full, zero the bytes after the data because the swapping may cause those bytes to be introduced if (bytesRead < buffer.Length) Array.Clear(buffer, bytesRead, buffer.Length - bytesRead); // perform the swap SwapCore(buffer, bytesToSwap); // reset stream position back to where the buffer was read from, and write the swapped buffer back _ms.Position = position; _ms.Write(buffer, 0, bytesRead); // update the position position += bytesRead; } _ms.Position = 0; return; } if (_data != null) { // perform swap on the byte array SwapCore(_data, bytesToSwap); } } public void Swap2() { // switch stream to byte array if possible, since swapping is easier that way ConvertToByteArray(); if (_ms != null) { var buffer = new byte[_bufferSize]; var position = _ms.Position = 0; // N.B. we know _ms is a LargeMemoryStream that will never read an incomplete buffer unless it's actually the end of stream // so we can assume that we won't be throwing in a padding zero when that byte just hasn't been read yet! int bytesRead; while ((bytesRead = _ms.Read(buffer, 0, buffer.Length)) > 0) { // if the buffer is not full, zero the bytes after the data because the swapping may cause those bytes to be introduced if (bytesRead < buffer.Length) Array.Clear(buffer, bytesRead, buffer.Length - bytesRead); // perform the swap Swap2Core(buffer); // reset stream position back to where the buffer was read from, and write the swapped buffer back _ms.Position = position; _ms.Write(buffer, 0, bytesRead); // update the position position += bytesRead; } _ms.Position = 0; return; } if (_data != null) { // perform swap on the byte array Swap2Core(_data); } } public void Swap4() { // switch stream to byte array if possible, since swapping is easier that way ConvertToByteArray(); if (_ms != null) { var buffer = new byte[_bufferSize]; var position = _ms.Position = 0; // N.B. we know _ms is a LargeMemoryStream that will never read an incomplete buffer unless it's actually the end of stream // so we can assume that we won't be throwing in a padding zero when that byte just hasn't been read yet! int bytesRead; while ((bytesRead = _ms.Read(buffer, 0, buffer.Length)) > 0) { // if the buffer is not full, zero the bytes after the data because the swapping may cause those bytes to be introduced if (bytesRead < buffer.Length) Array.Clear(buffer, bytesRead, buffer.Length - bytesRead); // perform the swap Swap4Core(buffer); // reset stream position back to where the buffer was read from, and write the swapped buffer back _ms.Position = position; _ms.Write(buffer, 0, bytesRead); // update the position position += bytesRead; } _ms.Position = 0; return; } if (_data != null) { // perform swap on the byte array Swap4Core(_data); } } public void Swap8() { Swap(8); } private static void Swap2Core(byte[] data) { var length = data.Length - (data.Length%2); for (var i = 0; i < length; i += 2) { var b = data[i + 1]; data[i + 1] = data[i]; data[i] = b; } } private static void Swap4Core(byte[] data) { var length = data.Length - (data.Length%4); for (var i = 0; i < length; i += 4) { var b = data[i + 3]; data[i + 3] = data[i]; data[i] = b; b = data[i + 2]; data[i + 2] = data[i + 1]; data[i + 1] = b; } } private static void SwapCore(byte[] data, int windowSize) { var length = data.Length - (data.Length%windowSize); for (var i = 0; i < length; i += windowSize) { Array.Reverse(data, i, windowSize); } } #endregion #region Unit Test Support #if UNIT_TESTS internal ByteBuffer(bool highCapacityMode) : this(null, LocalMachineEndian, highCapacityMode) {} internal ByteBuffer(byte[] data, bool highCapacityMode) : this(data, LocalMachineEndian, highCapacityMode) {} internal byte[] GetTestData() { return _data; } internal Stream GetTestStream() { return _ms; } byte[] IByteBuffer.GetTestData() { return GetTestData(); } Stream IByteBuffer.GetTestStream() { return GetTestStream(); } #endif #endregion /// <summary> /// Converts internal storage to byte array if it was stored in a MemoryStream. Doesn't do anything otherwise. Costs one buffer copy, but may be useful if the next operation is better performed on an array. /// </summary> private void ConvertToByteArray() { if (_ms is MemoryStream) { _data = ((MemoryStream) _ms).ToArray(); _br = null; _bw = null; _ms = null; } } private static int CopyBytes(Stream src, Stream dst, int count) { var bytesCopied = 0; var buffer = new byte[_bufferSize]; int bytesRead; while (bytesCopied < count && (bytesRead = src.Read(buffer, 0, Math.Min(buffer.Length, count - bytesCopied))) > 0) { dst.Write(buffer, 0, bytesRead); bytesCopied += bytesRead; } return bytesCopied; } private static int ZeroBytes(Stream dst, int count) { var bytesZeroed = 0; var zeroes = new byte[_bufferSize]; while (bytesZeroed < count) { var bytesLeft = Math.Min(_bufferSize, count - bytesZeroed); dst.Write(zeroes, 0, bytesLeft); bytesZeroed += bytesLeft; } return bytesZeroed; } } }
testdoron/ClearCanvas
Dicom/IO/ByteBuffer.cs
C#
gpl-3.0
20,015
package com.earth2me.essentials.storage; import org.bukkit.plugin.Plugin; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.Reader; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.locks.ReentrantLock; public class YamlStorageReader implements IStorageReader { private transient static final Map<Class, Yaml> PREPARED_YAMLS = Collections.synchronizedMap(new HashMap<Class, Yaml>()); private transient static final Map<Class, ReentrantLock> LOCKS = new HashMap<Class, ReentrantLock>(); private transient final Reader reader; private transient final Plugin plugin; public YamlStorageReader(final Reader reader, final Plugin plugin) { this.reader = reader; this.plugin = plugin; } @Override public <T extends StorageObject> T load(final Class<? extends T> clazz) throws ObjectLoadException { Yaml yaml = PREPARED_YAMLS.get(clazz); if (yaml == null) { yaml = new Yaml(prepareConstructor(clazz)); PREPARED_YAMLS.put(clazz, yaml); } ReentrantLock lock; synchronized (LOCKS) { lock = LOCKS.get(clazz); if (lock == null) { lock = new ReentrantLock(); } } lock.lock(); try { T object = (T) yaml.load(reader); if (object == null) { object = clazz.newInstance(); } return object; } catch (IllegalAccessException ex) { throw new ObjectLoadException(ex); } catch (InstantiationException ex) { throw new ObjectLoadException(ex); } finally { lock.unlock(); } } private Constructor prepareConstructor(final Class<?> clazz) { final Constructor constructor = new BukkitConstructor(clazz, plugin); final Set<Class> classes = new HashSet<Class>(); prepareConstructor(constructor, classes, clazz); return constructor; } private void prepareConstructor(final Constructor constructor, final Set<Class> classes, final Class clazz) { classes.add(clazz); final TypeDescription description = new TypeDescription(clazz); for (Field field : clazz.getDeclaredFields()) { prepareList(field, description, classes, constructor); prepareMap(field, description, classes, constructor); if (StorageObject.class.isAssignableFrom(field.getType()) && !classes.contains(field.getType())) { prepareConstructor(constructor, classes, field.getType()); } } constructor.addTypeDescription(description); } private void prepareList(final Field field, final TypeDescription description, final Set<Class> classes, final Constructor constructor) { final ListType listType = field.getAnnotation(ListType.class); if (listType != null) { description.putListPropertyType(field.getName(), listType.value()); if (StorageObject.class.isAssignableFrom(listType.value()) && !classes.contains(listType.value())) { prepareConstructor(constructor, classes, listType.value()); } } } private void prepareMap(final Field field, final TypeDescription description, final Set<Class> classes, final Constructor constructor) { final MapValueType mapType = field.getAnnotation(MapValueType.class); if (mapType != null) { final MapKeyType mapKeyType = field.getAnnotation(MapKeyType.class); description.putMapPropertyType(field.getName(), mapKeyType == null ? String.class : mapKeyType.value(), mapType.value()); if (StorageObject.class.isAssignableFrom(mapType.value()) && !classes.contains(mapType.value())) { prepareConstructor(constructor, classes, mapType.value()); } } } }
dordsor21/dordsentials
Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java
Java
gpl-3.0
3,995
/* Copyright ยฉ 2014-2015 by The qTox Project Contributors This file is part of qTox, a Qt-based graphical interface for Tox. qTox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>. */ #include "maskablepixmapwidget.h" #include <QPainter> /** * @var QPixmap* MaskablePixmapWidget::renderTarget * @brief pointer to dynamically call the constructor. */ MaskablePixmapWidget::MaskablePixmapWidget(QWidget* parent, QSize size, QString maskName) : QWidget(parent) , renderTarget(nullptr) , maskName(maskName) , clickable(false) { setSize(size); } MaskablePixmapWidget::~MaskablePixmapWidget() { delete renderTarget; } void MaskablePixmapWidget::setClickable(bool clickable) { this->clickable = clickable; if (clickable) setCursor(Qt::PointingHandCursor); else unsetCursor(); } void MaskablePixmapWidget::setPixmap(const QPixmap& pmap) { if (!pmap.isNull()) { unscaled = pmap; pixmap = pmap.scaled(width() - 2, height() - 2, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); update(); } } QPixmap MaskablePixmapWidget::getPixmap() const { return *renderTarget; } void MaskablePixmapWidget::setSize(QSize size) { setFixedSize(size); delete renderTarget; renderTarget = new QPixmap(size); QPixmap pmapMask = QPixmap(maskName); if (!pmapMask.isNull()) mask = pmapMask.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); if (!unscaled.isNull()) { pixmap = unscaled.scaled(width() - 2, height() - 2, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); update(); } } void MaskablePixmapWidget::paintEvent(QPaintEvent*) { renderTarget->fill(Qt::transparent); QPoint offset((width() - pixmap.size().width()) / 2, (height() - pixmap.size().height()) / 2); // centering the pixmap QPainter painter(renderTarget); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawPixmap(offset, pixmap); painter.setCompositionMode(QPainter::CompositionMode_DestinationIn); painter.drawPixmap(0, 0, mask); painter.end(); painter.begin(this); painter.drawPixmap(0, 0, *renderTarget); } void MaskablePixmapWidget::mousePressEvent(QMouseEvent*) { if (clickable) emit clicked(); }
Grokafar/qTox
src/widget/maskablepixmapwidget.cpp
C++
gpl-3.0
2,972
package org.mozilla.osmdroid.tileprovider; import android.content.Context; import org.mozilla.mozstumbler.svclocator.services.log.LoggerUtil; import org.mozilla.osmdroid.tileprovider.modules.INetworkAvailablityCheck; import org.mozilla.osmdroid.tileprovider.modules.NetworkAvailabliltyCheck; import org.mozilla.osmdroid.tileprovider.modules.SmartFSProvider; import org.mozilla.osmdroid.tileprovider.modules.TileDownloaderDelegate; import org.mozilla.osmdroid.tileprovider.modules.TileIOFacade; import org.mozilla.osmdroid.tileprovider.tilesource.ITileSource; import org.mozilla.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.mozilla.osmdroid.tileprovider.util.SimpleRegisterReceiver; /** * This top-level tile provider implements a basic tile request chain which includes a * {@link SmartFSProvider}. * * @author Marc Kurtz */ public class BetterTileProvider extends BetterMapTileProviderArray implements IMapTileProviderCallback { private static final String LOG_TAG = LoggerUtil.makeLogTag(BetterTileProvider.class); public BetterTileProvider(final Context pContext) { // @TODO vng - this needs to be deleted as we are getting the // wrong tile source sometimes, and rely on some caller to // properly set the TileSource. This is a potential source of // race conditions. this(pContext, TileSourceFactory.DEFAULT_TILE_SOURCE); } public BetterTileProvider(final Context pContext, final ITileSource pTileSource) { this(new SimpleRegisterReceiver(pContext), new NetworkAvailabliltyCheck(pContext), pTileSource); } public BetterTileProvider(final IRegisterReceiver pRegisterReceiver, final INetworkAvailablityCheck aNetworkAvailablityCheck, final ITileSource pTileSource) { super(pTileSource, pRegisterReceiver); final TileIOFacade tileIOFacade = new TileIOFacade(); final SmartFSProvider smartProvider = new SmartFSProvider(pRegisterReceiver, pTileSource); // @TODO vng - something screwy is happening. Passing in the // pTileSource into TileDownloaderDelegate here gives us the // wrong tilesource when we try to write to disk. Something // must be clobbering the tilesource dynamically. // // The pTileSource being passed into SmartFSProvider must be // incorrect - which means that the single argument // constructor - BetterTileProvider(pContext) must be being // used. This mostly affects the overlay architecture as the // MozStumbler's MapFragment does dynamic substitution of the // TileSource. // // Suggested refactoring - create an interface that inherits // from ITileSource that provides a callback hooks. // In particular, we want a TileSource to subscribe to zoom // level changes a generic Map<String, String> callback so // that we can pass the equivalent of intents back without // having to implement bits of android. // // After that, remove the option to construct the TileProvider // with just a context. We never want to allow // TileSourceFactory.DEFAULT_TILE_SOURCE to be used. // // Once that is done, we should be able to remove all the // hacks in the MozStumbler MapFragment which swap the // TileSource within the TileProvider. TileDownloaderDelegate tileDelegate = new TileDownloaderDelegate(aNetworkAvailablityCheck, tileIOFacade); smartProvider.configureDelegate(tileDelegate); mTileProviderList.add(smartProvider); } }
petercpg/MozStumbler
android/src/main/java/org/mozilla/osmdroid/tileprovider/BetterTileProvider.java
Java
mpl-2.0
3,668
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //----------------------------------------------------------------------------- var BUGNUMBER = 452498; var summary = 'TM: upvar2 regression tests'; var actual = ''; var expect = ''; //------- Comment #192 From Brendan Eich //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); with({x: (x -= 0)}){([]); const x } reportCompare(expect, actual, summary); exitFunc ('test'); }
SlateScience/MozillaJS
js/src/tests/js1_8_1/regress/regress-452498-192.js
JavaScript
mpl-2.0
884
package egoscale import ( "context" "encoding/json" "fmt" "log" "time" ) // RunstatusPage runstatus page type RunstatusPage struct { Created *time.Time `json:"created,omitempty"` DarkTheme bool `json:"dark_theme,omitempty"` Domain string `json:"domain,omitempty"` GradientEnd string `json:"gradient_end,omitempty"` GradientStart string `json:"gradient_start,omitempty"` HeaderBackground string `json:"header_background,omitempty"` ID int `json:"id,omitempty"` Incidents []RunstatusIncident `json:"incidents,omitempty"` IncidentsURL string `json:"incidents_url,omitempty"` Logo string `json:"logo,omitempty"` Maintenances []RunstatusMaintenance `json:"maintenances,omitempty"` MaintenancesURL string `json:"maintenances_url,omitempty"` Name string `json:"name"` //fake field (used to post a new runstatus page) OkText string `json:"ok_text,omitempty"` Plan string `json:"plan,omitempty"` PublicURL string `json:"public_url,omitempty"` Services []RunstatusService `json:"services,omitempty"` ServicesURL string `json:"services_url,omitempty"` State string `json:"state,omitempty"` Subdomain string `json:"subdomain"` SupportEmail string `json:"support_email,omitempty"` TimeZone string `json:"time_zone,omitempty"` Title string `json:"title,omitempty"` TitleColor string `json:"title_color,omitempty"` TwitterUsername string `json:"twitter_username,omitempty"` URL string `json:"url,omitempty"` } // Match returns true if the other page has got similarities with itself func (page RunstatusPage) Match(other RunstatusPage) bool { if other.Subdomain != "" && page.Subdomain == other.Subdomain { return true } if other.ID > 0 && page.ID == other.ID { return true } return false } // RunstatusPageList runstatus page list type RunstatusPageList struct { Next string `json:"next"` Previous string `json:"previous"` Pages []RunstatusPage `json:"results"` } // CreateRunstatusPage create runstatus page func (client *Client) CreateRunstatusPage(ctx context.Context, page RunstatusPage) (*RunstatusPage, error) { resp, err := client.runstatusRequest(ctx, client.Endpoint+runstatusPagesURL, page, "POST") if err != nil { return nil, err } var p *RunstatusPage if err := json.Unmarshal(resp, &p); err != nil { return nil, err } return p, nil } // DeleteRunstatusPage delete runstatus page func (client *Client) DeleteRunstatusPage(ctx context.Context, page RunstatusPage) error { if page.URL == "" { return fmt.Errorf("empty URL for %#v", page) } _, err := client.runstatusRequest(ctx, page.URL, nil, "DELETE") return err } // GetRunstatusPage fetches the runstatus page func (client *Client) GetRunstatusPage(ctx context.Context, page RunstatusPage) (*RunstatusPage, error) { if page.URL != "" { return client.getRunstatusPage(ctx, page.URL) } ps, err := client.ListRunstatusPages(ctx) if err != nil { return nil, err } for i := range ps { if ps[i].Match(page) { return client.getRunstatusPage(ctx, ps[i].URL) } } return nil, fmt.Errorf("%#v not found", page) } func (client *Client) getRunstatusPage(ctx context.Context, pageURL string) (*RunstatusPage, error) { resp, err := client.runstatusRequest(ctx, pageURL, nil, "GET") if err != nil { return nil, err } p := new(RunstatusPage) if err := json.Unmarshal(resp, p); err != nil { return nil, err } // NOTE: fix the missing IDs for i := range p.Maintenances { if err := p.Maintenances[i].FakeID(); err != nil { log.Printf("bad fake ID for %#v, %s", p.Maintenances[i], err) } } for i := range p.Services { if err := p.Services[i].FakeID(); err != nil { log.Printf("bad fake ID for %#v, %s", p.Services[i], err) } } return p, nil } // ListRunstatusPages list all the runstatus pages func (client *Client) ListRunstatusPages(ctx context.Context) ([]RunstatusPage, error) { resp, err := client.runstatusRequest(ctx, client.Endpoint+runstatusPagesURL, nil, "GET") if err != nil { return nil, err } var p *RunstatusPageList if err := json.Unmarshal(resp, &p); err != nil { return nil, err } return p.Pages, nil } //PaginateRunstatusPages paginate on runstatus pages func (client *Client) PaginateRunstatusPages(ctx context.Context, callback func(pages []RunstatusPage, e error) bool) { pageURL := client.Endpoint + runstatusPagesURL for pageURL != "" { resp, err := client.runstatusRequest(ctx, pageURL, nil, "GET") if err != nil { callback(nil, err) return } var p *RunstatusPageList if err := json.Unmarshal(resp, &p); err != nil { callback(nil, err) return } if ok := callback(p.Pages, nil); ok { return } pageURL = p.Next } }
bryson/packer
vendor/github.com/exoscale/egoscale/runstatus_page.go
GO
mpl-2.0
5,239
if (getJitCompilerOptions()["ion.warmup.trigger"] > 20) setJitCompilerOption("ion.warmup.trigger", 20); function callRegExpTest(i) { var s = "" + i; var re = /(\d+)/; re.test(s); assertEq(RegExp.$1, s); } function callRegExpExec(i) { var s = "" + i; var re = /(\d+)/; var res = re.exec(s); assertEq(RegExp.$1, s); return res; } function callRegExpReplace(i) { var s = "" + i; var re = /(\d+)/; s.replace(re, ""); assertEq(RegExp.$1, s); } for (var i = 0; i < 60; i++) { callRegExpTest(i); callRegExpExec(i); callRegExpReplace(i); }
cstipkovic/spidermonkey-research
js/src/jit-test/tests/ion/bug1132128.js
JavaScript
mpl-2.0
600
# This script does 1 unit-test on given relative dir path and on given language. # Here's its syntax: # .\unit-test.ps1 RELATIVE_PATH LANG # It return 0 if result is OK # -1 if result is KO # -2 if exception # 1 if unitTest file not found $testRoot = ".\" $dirName=$args[0] $langName=$args[1] Try { if ((Get-Item $testRoot$dirName) -is [System.IO.DirectoryInfo]) { if (-Not (Test-Path $testRoot$dirName\unitTest)) { return 1 } if ($langName.StartsWith("udl-")) { $langName = $langName.Replace("udl-", "") ..\..\bin\notepad++.exe -export=functionList -udl="`"$langName"`" $testRoot$dirName\unitTest | Out-Null } else { ..\..\bin\notepad++.exe -export=functionList -l"$langName" $testRoot$dirName\unitTest | Out-Null } $expectedRes = Get-Content $testRoot$dirName\unitTest.expected.result $generatedRes = Get-Content $testRoot$dirName\unitTest.result.json if ($generatedRes -eq $expectedRes) { Remove-Item $testRoot$dirName\unitTest.result.json return 0 } else { return -1 } } } Catch { return -2 }
papyrussolution/OpenPapyrus
Src/OSF/npp-gh20210917/PowerEditor/Test/FunctionList/unitTest.ps1
PowerShell
agpl-3.0
1,097
<%! from django.utils.translation import ugettext as _ %> <%! import django_comment_client.helpers as helpers %> <%! from django.template.defaultfilters import escapejs %> <%! from django.core.urlresolvers import reverse %> <%inherit file="../main.html" /> <%namespace name='static' file='../static_content.html'/> <%block name="bodyclass">discussion</%block> <%block name="title"><title>${_("Discussion - {course_number}").format(course_number=course.display_number_with_default) | h}</title></%block> <%block name="headextra"> <%static:css group='course'/> <%include file="_js_head_dependencies.html" /> </%block> <%block name="js_extra"> <%include file="_js_body_dependencies.html" /> <%static:js group='discussion'/> </%block> <%include file="_discussion_course_navigation.html" args="active_page='discussion'" /> <%include file="_new_post.html" /> <section class="discussion container" id="discussion-container" data-roles="${roles}" data-course-id="${course_id}" data-user-info="${user_info}" data-threads="${threads}" data-thread-pages="${thread_pages}" data-content-info="${annotated_content_info}" data-flag-moderator="${flag_moderator}"> <div class="discussion-body"> <div class="sidebar"></div> <div class="discussion-column"> </div> </div> </section> <%include file="_underscore_templates.html" /> <%include file="_thread_list_template.html" />
PepperPD/edx-pepper-platform
lms/templates/discussion/index.html
HTML
agpl-3.0
1,398
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Service_Flickr * @subpackage UnitTests * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: OnlineTest.php 24593 2012-01-05 20:35:02Z matthew $ */ /** * @category Zend * @package Zend_Service_Flickr * @subpackage UnitTests * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Service * @group Zend_Service_Flickr */ class Zend_Service_Flickr_OnlineTest extends PHPUnit_Framework_TestCase { /** * Reference to Flickr service consumer object * * @var Zend_Service_Flickr */ protected $_flickr; /** * Socket based HTTP client adapter * * @var Zend_Http_Client_Adapter_Socket */ protected $_httpClientAdapterSocket; /** * Sets up this test case * * @return void */ public function setUp() { /** * @see Zend_Service_Flickr */ require_once 'Zend/Service/Flickr.php'; $this->_flickr = new Zend_Service_Flickr(constant('TESTS_ZEND_SERVICE_FLICKR_ONLINE_APIKEY')); /** * @see Zend_Http_Client_Adapter_Socket */ require_once 'Zend/Http/Client/Adapter/Socket.php'; $this->_httpClientAdapterSocket = new Zend_Http_Client_Adapter_Socket(); $this->_flickr->getRestClient() ->getHttpClient() ->setAdapter($this->_httpClientAdapterSocket); } /** * Basic testing to ensure that groupPoolGetPhotos works as expected * * @return void */ public function testGroupPoolGetPhotosBasic() { $options = array('per_page' => 10, 'page' => 1, 'extras' => 'license, date_upload, date_taken, owner_name, icon_server'); $resultSet = $this->_flickr->groupPoolGetPhotos('20083316@N00', $options); $this->assertGreaterThan(20000, $resultSet->totalResultsAvailable); $this->assertEquals(10, $resultSet->totalResults()); $this->assertEquals(10, $resultSet->totalResultsReturned); $this->assertEquals(1, $resultSet->firstResultPosition); $this->assertEquals(0, $resultSet->key()); try { $resultSet->seek(-1); $this->fail('Expected OutOfBoundsException not thrown'); } catch (OutOfBoundsException $e) { $this->assertContains('Illegal index', $e->getMessage()); } $resultSet->seek(9); try { $resultSet->seek(10); $this->fail('Expected OutOfBoundsException not thrown'); } catch (OutOfBoundsException $e) { $this->assertContains('Illegal index', $e->getMessage()); } $resultSet->rewind(); $count = 0; foreach ($resultSet as $result) { $this->assertTrue($result instanceof Zend_Service_Flickr_Result); $count++; } $this->assertEquals(10, $count); } /** * Basic testing to ensure that userSearch() works as expected * * @return void */ public function testUserSearchBasic() { $options = array('per_page' => 10, 'page' => 1, 'extras' => 'license, date_upload, date_taken, owner_name, icon_server'); $resultSet = $this->_flickr->userSearch('[email protected]', $options); $this->assertEquals(16, $resultSet->totalResultsAvailable); $this->assertEquals(10, $resultSet->totalResults()); $this->assertEquals(10, $resultSet->totalResultsReturned); $this->assertEquals(1, $resultSet->firstResultPosition); $this->assertEquals(0, $resultSet->key()); try { $resultSet->seek(-1); $this->fail('Expected OutOfBoundsException not thrown'); } catch (OutOfBoundsException $e) { $this->assertContains('Illegal index', $e->getMessage()); } $resultSet->seek(9); try { $resultSet->seek(10); $this->fail('Expected OutOfBoundsException not thrown'); } catch (OutOfBoundsException $e) { $this->assertContains('Illegal index', $e->getMessage()); } $resultSet->rewind(); $count = 0; foreach ($resultSet as $result) { $this->assertTrue($result instanceof Zend_Service_Flickr_Result); $count++; } $this->assertEquals(10, $count); } /** * Basic testing to ensure that getIdByUsername() works as expected * * @return void */ public function testGetIdByUsernameBasic() { $userId = $this->_flickr->getIdByUsername('darby.felton'); $this->assertEquals('7414329@N07', $userId); } /** * Ensures that tagSearch() works as expected with the sort option * * @return void */ public function testTagSearchOptionSort() { $options = array( 'per_page' => 10, 'page' => 1, 'tag_mode' => 'or', 'sort' => 'date-taken-asc', 'extras' => 'license, date_upload, date_taken, owner_name, icon_server' ); $resultSet = $this->_flickr->tagSearch('php', $options); $this->assertTrue(10 < $resultSet->totalResultsAvailable); $this->assertEquals(10, $resultSet->totalResults()); $this->assertEquals(10, $resultSet->totalResultsReturned); $this->assertEquals(1, $resultSet->firstResultPosition); foreach ($resultSet as $result) { $this->assertTrue($result instanceof Zend_Service_Flickr_Result); if (isset($dateTakenPrevious)) { $this->assertTrue(strcmp($result->datetaken, $dateTakenPrevious) > 0); } $dateTakenPrevious = $result->datetaken; } } /** * @see ZF-6397 */ function testTotalForEmptyResultSet() { $this->assertEquals(0, $this->_flickr->tagSearch('zendflickrtesttagnoresults')->totalResults()); } } /** * @category Zend * @package Zend_Service_Flickr * @subpackage UnitTests * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Service * @group Zend_Service_Flickr */ class Zend_Service_Flickr_OnlineTest_Skip extends PHPUnit_Framework_TestCase { public function testNothing() { $this->markTestSkipped('Zend_Service_Flickr online tests not enabled in TestConfiguration.php'); } }
conjoon/webmail
vendor/zendframework/tests/Zend/Service/Flickr/OnlineTest.php
PHP
agpl-3.0
7,320
<?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Joas Schilling <[email protected]> * @author Victor Dubiniuk <[email protected]> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCA\Files_Trashbin\Tests\BackgroundJob; use \OCA\Files_Trashbin\BackgroundJob\ExpireTrash; use OCP\BackgroundJob\IJobList; use OCP\IUserManager; class ExpireTrashTest extends \Test\TestCase { public function testConstructAndRun() { $backgroundJob = new ExpireTrash( $this->createMock(IUserManager::class), $this->getMockBuilder('OCA\Files_Trashbin\Expiration')->disableOriginalConstructor()->getMock() ); $jobList = $this->createMock(IJobList::class); /** @var \OC\BackgroundJob\JobList $jobList */ $backgroundJob->execute($jobList); $this->assertTrue(true); } }
jbicha/server
apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php
PHP
agpl-3.0
1,405
# This file is part of OpenHatch. # Copyright (C) 2010 Parker Phinney # Copyright (C) 2010 Jack Grigg # Copyright (C) 2011 Krzysztof Tarnowski ([email protected]) # Copyright (C) 2009, 2010, 2011 OpenHatch, Inc. # Copyright (C) 2011 Jairo E. Lopez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import django.test from django.core.urlresolvers import reverse import twill from twill import commands as tc from django.core.handlers.wsgi import WSGIHandler from django.contrib.staticfiles.handlers import StaticFilesHandler from StringIO import StringIO from django.test.client import Client import os import os.path import subprocess from django.core.cache import cache from django.conf import settings import mock import datetime import logging from django.utils import unittest from django.utils.unittest import expectedFailure import mysite.base.view_helpers import mysite.base.decorators import mysite.search.models import mysite.base.templatetags.base_extras import mysite.base.unicode_sanity import mysite.profile.views import mysite.base.views import mysite.project.views import mysite.settings import mysite.base.management.commands.nagios import mysite.profile.management.commands.send_emails logger = logging.getLogger(__name__) def make_twill_url(url): # modify this return url.replace("http://openhatch.org/", "http://127.0.0.1:8080/") def better_make_twill_url(url): return make_twill_url(url.replace('+', '%2B')) def twill_goto_view(view_name, kwargs): url = "http://openhatch.org" + reverse(view_name, kwargs=kwargs) tc.go(better_make_twill_url(url)) mock_get = mock.Mock() mock_get.return_value = None class TwillTests(django.test.TestCase): @staticmethod def _twill_setup(): app = StaticFilesHandler(WSGIHandler()) twill.add_wsgi_intercept("127.0.0.1", 8080, lambda: app) @staticmethod def _twill_quiet(): # suppress normal output of twill.. You don't want to # call this if you want an interactive session twill.set_output(StringIO()) '''Some basic methods needed by other testing classes.''' def setUp(self): self.real_get = django.core.cache.cache.get django.core.cache.cache.get = mock_get self.old_dbe = settings.DEBUG_PROPAGATE_EXCEPTIONS settings.DEBUG_PROPAGATE_EXCEPTIONS = True TwillTests._twill_setup() TwillTests._twill_quiet() def tearDown(self): # If you get an error on one of these lines, # maybe you didn't run base.TwillTests.setUp? settings.DEBUG_PROPAGATE_EXCEPTIONS = self.old_dbe twill.remove_wsgi_intercept('127.0.0.1', 8080) tc.reset_browser() django.core.cache.cache.get = self.real_get def login_with_twill(self): # Visit login page login_url = 'http://openhatch.org/account/login/old' tc.go(make_twill_url(login_url)) # Log in username = "paulproteus" password = "paulproteus's unbreakable password" tc.fv('login', 'username', username) tc.fv('login', 'password', password) tc.submit() def login_with_client(self, username='paulproteus', password="paulproteus's unbreakable password"): client = Client() success = client.login(username=username, password=password) self.assertTrue(success) return client def login_with_client_as_barry(self): return self.login_with_client(username='barry', password='parallelism') class MySQLRegex(TwillTests): def test_escape(self): before2after = { 'n': '[n]', ']': ']', '[n': '[[][n]' } for before, after in before2after.items(): self.assertEqual( mysite.base.view_helpers.mysql_regex_escape(before), after) class TestUriDataHelper(TwillTests): def test(self): request = mysite.base.view_helpers.ObjectFromDict({ 'is_secure': lambda: True, 'META': {'SERVER_PORT': '443', 'SERVER_NAME': 'name'}}) data = ((mysite.base.view_helpers. get_uri_metadata_for_generating_absolute_links(request))) self.assertEqual(data, {'uri_scheme': 'https', 'url_prefix': 'name'}) class GeocoderCanGeocode(TwillTests): def get_geocoding_in_json_for_unicode_string(self): unicode_str = u'Bark\xe5ker, T\xf8nsberg, Vestfold, Norway' # Just exercise the geocoder and ensure it doesn't blow up. return mysite.base.view_helpers.cached_geocoding_in_json(unicode_str) def test_unicode_string(self): self.get_geocoding_in_json_for_unicode_string() class RemoveByteOrderMarker(unittest.TestCase): def test(self): sample_bytes = '\xef\xbb\xbf' + 'hi' as_fd = StringIO(sample_bytes) self.assertNotEqual('hi', as_fd.read()) as_fd = StringIO(sample_bytes) cleaned_up_fd = ( mysite.base.unicode_sanity.wrap_file_object_in_utf8_check(as_fd)) result = cleaned_up_fd.read() self.assertEqual(type(result), str) # not unicode self.assertEqual(result, 'hi') class GeocoderCanCache(django.test.TestCase): unicode_address = u'Bark\xe5ker, T\xf8nsberg, Vestfold, Norway' def get_geocoding_in_json_for_unicode_string(self): # Just exercise the geocoder and ensure it doesn't blow up. return mysite.base.view_helpers.cached_geocoding_in_json( self.unicode_address) mock_geocoder = mock.Mock() @mock.patch("mysite.base.view_helpers._geocode", mock_geocoder) def test_unicode_strings_get_cached(self): # Let's make sure that the first time, this runs with original_json, # that the cache is empty, and we populate it with original_json. cache.delete( mysite.base.view_helpers.address2cache_key_name( self.unicode_address)) # NOTE This test uses django.tests.TestCase to skip our # monkey-patching of the cache framework # When the geocoder's results are being cached properly, # the base controller named '_geocode' will not run more than once. original_json = "{'key': 'original value'}" different_json = ( "{'key': 'if caching works we should never get this value'}") self.mock_geocoder.return_value = eval(original_json) self.assertTrue( 'original value' in self.get_geocoding_in_json_for_unicode_string()) self.mock_geocoder.return_value = eval(different_json) try: json = self.get_geocoding_in_json_for_unicode_string() self.assertTrue('original value' in json) except AssertionError: raise AssertionError( "Geocoded location in json was not cached; it now equals " + json) class TestUnicodifyDecorator(TwillTests): def test(self): utf8_data = u'\xc3\xa9'.encode('utf-8') # &eacute; @mysite.base.decorators.unicodify_strings_when_inputted def sample_thing(arg): self.assertEqual(type(arg), unicode) sample_thing(utf8_data) class Feed(TwillTests): fixtures = ['user-paulproteus', 'person-paulproteus'] def test_feed_shows_answers(self): # Visit the homepage, notice that there are no answers in the context. def get_answers_from_homepage(): homepage_response = self.client.get('/') return homepage_response.context[0]['recent_feed_items'] self.assertFalse(get_answers_from_homepage()) # Create a few answers on the project discussion page. for x in range(4): mysite.search.models.Answer.create_dummy() recent_feed_items = ( mysite.search.models.Answer.objects.all().order_by( '-modified_date')) # Visit the homepage, assert that the feed item data is on the page, # ordered by date descending. actual_answer_pks = [ answer.pk for answer in get_answers_from_homepage()] expected_answer_pks = [answer.pk for answer in recent_feed_items] self.assertEqual(actual_answer_pks, expected_answer_pks) def test_feed_shows_wanna_help(self): # set things up so there was a wanna help button click person = mysite.profile.models.Person.objects.get( user__username='paulproteus') p_before = mysite.search.models.Project.create_dummy() client = self.login_with_client() post_to = reverse(mysite.project.views.wanna_help_do) response = client.post(post_to, {u'project': unicode(p_before.pk)}) # Now when we GET the home page, we see a Note # to that effect in the feed response = client.get('/') items = response.context[0]['recent_feed_items'] note_we_want_to_see = ( mysite.search.models.WannaHelperNote.objects.get( person=person, project=p_before)) self.assertTrue(note_we_want_to_see in items) class CacheMethod(TwillTests): @mock.patch('django.core.cache.cache') def test(self, mock_cache): # Step 0: mock_cache.get() needs to return None mock_cache.get.return_value = None # Step 1: Create a method where we can test if it was cached (+ cache # it) class SomeClass: def __init__(self): self.call_counter = 0 def cache_key_getter_name(self): return 'doodles' @mysite.base.decorators.cache_method('cache_key_getter_name') def some_method(self): self.call_counter += 1 return str(self.call_counter) # Step 2: Call it once to fill the cache sc = SomeClass() self.assertEqual(sc.some_method(), '1') # Step 3: See if the cache has it now mock_cache.set.assert_called_with( 'doodles', '{"value": "1"}', 86400 * 10) class EnhanceNextWithNewUserMetadata(TwillTests): def test_easy(self): sample_input = '/' wanted = '/?newuser=true' got = ( mysite.base.templatetags.base_extras. enhance_next_to_annotate_it_with_newuser_is_true(sample_input)) self.assertEqual(wanted, got) def test_with_existing_query_string(self): sample_input = '/?a=b' wanted = '/?a=b&newuser=true' got = ( mysite.base.templatetags.base_extras. enhance_next_to_annotate_it_with_newuser_is_true(sample_input)) self.assertEqual(wanted, got) def test_with_existing_newuser_equals_true(self): sample_input = '/?a=b&newuser=true' wanted = sample_input got = (mysite.base.templatetags.base_extras. enhance_next_to_annotate_it_with_newuser_is_true(sample_input)) self.assertEqual(wanted, got) class Unsubscribe(TwillTests): fixtures = ['user-paulproteus', 'person-paulproteus'] def test_verify_unsubscribe_token(self): """Generate a valid unsubscribe token. Use it. See that it works. Use an invalid one. See that it doesn't work.""" dude = mysite.profile.models.Person.objects.get(user__username='paulproteus') # Generate an invalid token (easiest to do this first) plausible_but_invalid_token_string = dude.generate_new_unsubscribe_token().string # Make that token invalid by nuking the UnsubscribeToken table mysite.profile.models.UnsubscribeToken.objects.all().delete() # Generate a once-valid but now-expired token expired_token = dude.generate_new_unsubscribe_token() just_over_three_months_ago = datetime.datetime.utcnow() - datetime.timedelta(days=91) expired_token.created_date = just_over_three_months_ago expired_token.save() # Generate a valid token valid_token_string = dude.generate_new_unsubscribe_token().string owner = mysite.profile.models.UnsubscribeToken.whose_token_string_is_this(valid_token_string) self.assertEqual(owner, dude) # This should definitely be false self.assertNotEqual(valid_token_string, plausible_but_invalid_token_string) # The invalid token should fail self.assertFalse(mysite.profile.models.UnsubscribeToken.whose_token_string_is_this(plausible_but_invalid_token_string)) self.assertFalse(mysite.profile.models.UnsubscribeToken.whose_token_string_is_this(expired_token.string)) def test_unsubscribe_view(self): dude = mysite.profile.models.Person.objects.get(user__username='paulproteus') # Generate a valid token valid_token_string = dude.generate_new_unsubscribe_token().string # Test that the unsubscribe view's context contains the owner url = reverse(mysite.profile.views.unsubscribe, kwargs={'token_string': valid_token_string}) logger.debug("url %s", url) response = self.client.get(url) logger.debug("response %s", response) self.assertEqual( mysite.profile.models.Person.objects.get(), response.context['unsubscribe_this_user']) def test_unsubscribe_post_handler(self): def get_dude(): return mysite.profile.models.Person.objects.get(user__username='paulproteus') dude = get_dude() self.assertTrue(get_dude().email_me_re_projects) # Generate a valid token valid_token_string = dude.generate_new_unsubscribe_token().string self.client.post(reverse(mysite.profile.views.unsubscribe_do), {'token_string': valid_token_string}) self.assertFalse(get_dude().email_me_re_projects) @expectedFailure def test_submit_form(self): def get_dude(): return mysite.profile.models.Person.objects.get(user__username='paulproteus') dude = get_dude() self.assertTrue(get_dude().email_me_re_projects) # Generate a valid token valid_token_string = dude.generate_new_unsubscribe_token().string self.assertIsNone(twill_goto_view(mysite.profile.views.unsubscribe, kwargs={'token_string': valid_token_string})) #TODO Figure out why tc.submit() returns a NoneType and fails #A couple of ideas: # South migration on MySQL # submit is broken # twill should leave the code base for WebTest self.assertIsNone(tc.submit()) self.assertIsNotNone(get_dude().email_me_re_projects) class TimestampTests(django.test.TestCase): def test_bugzilla_urls_get_and_update_timestamp_without_errors(self): # List of URLs to test (from Bugzila trackers) urls = { 'Miro bitesized': 'http://bugzilla.pculture.org/buglist.cgi?bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&field-1-0-0=bug_status&field-1-1-0=product&field-1-2-0=keywords&keywords=bitesized&product=Miro&query_format=advanced&remaction=&type-1-0-0=anyexact&type-1-1-0=anyexact&type-1-2-0=anywords&value-1-0-0=NEW%2CASSIGNED%2CREOPENED&value-1-1-0=Miro&value-1-2-0=bitesized', 'KDE bitesized': 'https://bugs.kde.org/buglist.cgi?query_format=advanced&keywords=junior-jobs&resolution=---', 'KDE documentation': 'https://bugs.kde.org/buglist.cgi?query_format=advanced&product=docs&resolution=---', 'MediaWiki bitesized': 'https://bugzilla.wikimedia.org/buglist.cgi?keywords=easy&query_format=advanced&resolution=LATER&resolution=---', 'MediaWiki documentation': 'https://bugzilla.wikimedia.org/buglist.cgi?query_format=advanced&component=Documentation&resolution=---', 'Gnome bitesized': 'https://bugzilla.gnome.org/buglist.cgi?columnlist=id&keywords=gnome-love&query_format=advanced&resolution=---', 'Mozilla bitesized': 'https://bugzilla.mozilla.org/buglist.cgi?resolution=---;status_whiteboard_type=substring;query_format=advanced;status_whiteboard=[good%20first%20bug]', 'Songbird helpwanted': 'http://bugzilla.songbirdnest.com/buglist.cgi?query_format=advanced&resolution=---&keywords=helpwanted', 'Songbird documentation': 'http://bugzilla.songbirdnest.com/buglist.cgi?query_format=advanced&component=Documentation&resolution=---', 'Apertium': 'http://bugs.apertium.org/cgi-bin/bugzilla/buglist.cgi?query_format=advanced&resolution=---', 'RTEMS': 'https://www.rtems.org/bugzilla/buglist.cgi?query_format=advanced&resolution=---', 'XOrg bitesized': 'https://bugs.freedesktop.org/buglist.cgi?query_format=advanced&keywords=janitor&resolution=---&product=xorg', 'XOrg documentation': 'https://bugs.freedesktop.org/buglist.cgi?query_format=advanced&component=Docs%2Fother&component=Documentation&component=Fonts%2Fdoc&resolution=---&product=xorg', 'Locamotion': 'http://bugs.locamotion.org/buglist.cgi?query_format=advanced&resolution=---', 'Hypertriton': 'https://hypertriton.com/bugzilla/buglist.cgi?query_format=advanced&resolution=---&product=Agar&product=EDAcious&product=FabBSD&product=FreeSG', 'pygame': 'http://pygame.motherhamster.org/bugzilla/buglist.cgi?query_format=advanced&resolution=---' } for url_name in urls: logger.info('Testing %s bugs URL.' % url_name) url = urls[url_name] # Check there is no timestamp i.e. get zero o'clock first_timestamp = ( mysite.base.models.Timestamp.get_timestamp_for_string(url)) self.assertEqual(first_timestamp, mysite.base.models.Timestamp.ZERO_O_CLOCK) # Check the timestamp of the URL can be updated mysite.base.models.Timestamp.update_timestamp_for_string(url) # Check the new timestamp is after zero o'clock new_timestamp = ( mysite.base.models.Timestamp.get_timestamp_for_string(url)) self.assertTrue(new_timestamp > mysite.base.models.Timestamp.ZERO_O_CLOCK) # Test cases for Nagios integration class NagiosTests(django.test.TestCase): # Test for OK Nagios meta data return (0) def test_nagios_meta_return_ok(self): data = {} data['bug_diagnostics'] = {} my = data['bug_diagnostics'] my['Bugs last polled more than than two days + one hour ago'] = 0 my['Bugs last polled more than three days ago'] = 0 my['Bugs last polled more than three days ago (in percent)'] = 0.0 self.assertEqual(0, mysite.base.views.meta_exit_code(data)) # Test for WARNING Nagios meta data return (1) def test_nagios_meta_return_warning(self): data = {} data['bug_diagnostics'] = {} my = data['bug_diagnostics'] my['Bugs last polled more than than two days + one hour ago'] = 1 my['Bugs last polled more than three days ago'] = 0 my['Bugs last polled more than three days ago (in percent)'] = 0.0 self.assertEqual(1, mysite.base.views.meta_exit_code(data)) # Test for CRITICAL Nagios meta data return (2) def test_nagios_meta_return_critical(self): data = {} data['bug_diagnostics'] = {} my = data['bug_diagnostics'] my['Bugs last polled more than than two days + one hour ago'] = 0 my['Bugs last polled more than three days ago'] = 1 my['Bugs last polled more than three days ago (in percent)'] = 0.0 self.assertEqual(2, mysite.base.views.meta_exit_code(data)) # Test for OK Nagios weekly mail return (0) def test_nagios_weeklymail_return_ok(self): newtime = datetime.datetime.utcnow() - datetime.timedelta(days=4) self.assertEqual(0, mysite.base.management.commands.nagios.Command. send_weekly_exit_code(newtime)) # Test for OK Nagios weekly mail return (0) after send_emails is # run as a management command def test_nagios_weeklymail_return_ok_after_send(self): # Run the send_mail command = mysite.profile.management.commands.send_emails.Command() command.handle() # Now run to see if the function sees things are ok in the # database self.assertEqual(0, mysite.base.management.commands.nagios.Command. send_weekly_exit_code()) # Test for CRITICAL Nagios weekly mail return (2) def test_nagios_weeklymail_return_critical(self): newtime = datetime.datetime.utcnow() - datetime.timedelta(days=8) self.assertEqual(2, mysite.base.management.commands.nagios.Command. send_weekly_exit_code(newtime)) # Test for CRITICAL Nagios weekly mail return (2) on new database def test_nagios_weeklymail_return_critical_newdb(self): self.assertEqual(2, mysite.base.management.commands.nagios.Command. send_weekly_exit_code()) # Test cases for meta data generation class MetaDataTests(django.test.TestCase): def test_meta_data_zero_div(self): mysite.base.views.meta_data() def find_git_path(): maybe_git_dir = os.path.abspath(os.getcwd()) while not os.path.exists(os.path.join(maybe_git_dir, '.git')): maybe_git_dir = os.path.abspath(os.path.join(maybe_git_dir, '..')) if os.path.exists(os.path.join(maybe_git_dir, '.git')): return maybe_git_dir raise ValueError("Could not find git directory path.") # Test that the git repository has no files that conflict with Windows class WindowsFilesystemCompatibilityTests(unittest.TestCase): def test(self): # Find the base directory dir_with_git = find_git_path() # Get a list of files from git files = subprocess.Popen( ['git', 'ls-files'], shell=False, stdout=subprocess.PIPE, cwd=dir_with_git) stdout, stderr = files.communicate() file_set = set(stdout.rstrip().split('\n')) # Filter that file set down by constraints that would # apply on Windows. To that end: # Unify files based on case-insensitivity files_filtered = set( [x.lower() for x in file_set]) # Filter out any files with '?' in their names, because that is an # invalid character for filenames on Windows. files_filtered = set( [x for x in file_set if ('?' not in x)]) self.assertEqual(file_set, files_filtered) class GoogleApiTests(unittest.TestCase): def test_google_api(self): """ Test to see if the google api is returning what we expect """ response_file_path = os.path.join(settings.MEDIA_ROOT, 'sample-data', 'google_api', 'sample_response') with open(response_file_path, 'r') as f: response = f.read() # Check that latitude and longitude are returned and status is 'OK' geocode = mysite.base.view_helpers._geocode(response_data=response) self.assertNotEqual(geocode, None) # Test cases for robots generation class RenderLiveRobotsTest(django.test.TestCase): def test_robots_with_debug_false(self): '''Verify that robots.txt returns render_robots_live_site.txt with DEBUG set to False ''' response = self.client.get('/robots.txt') robots_text = "" with open('mysite/base/templates/robots_for_live_site.txt', 'rU') as f: robots_text += f.read() self.assertEqual(response.content, robots_text) class RenderDevRobotsTest(django.test.TestCase): def setUp(self): self.original_value = settings.DEBUG settings.DEBUG = True def test_robots_with_debug_true(self): '''Verify that robots.txt contains text identical to that seen in render_robots_for_dev_env.txt with DEBUG set to True ''' response = self.client.get('/robots.txt') robots_text = "" with open('mysite/base/templates/robots_for_dev_env.txt', 'rU') as f: robots_text += f.read() settings.DEBUG = False self.assertEqual(response.content, robots_text) def tearDown(self): settings.DEBUG = self.original_value
nirmeshk/oh-mainline
mysite/base/tests.py
Python
agpl-3.0
25,144
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: [email protected] or [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.extensions.annotation.migratable; import java.io.Serializable; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.objectweb.proactive.extensions.annotation.ActiveObject; import org.objectweb.proactive.extensions.annotation.common.ErrorMessages; import com.sun.source.tree.ClassTree; import com.sun.source.util.TreePathScanner; import com.sun.source.util.Trees; /** * CTree visitor for the Migratable annotation * @author fabratu * @version %G%, %I% * @since ProActive 4.10 */ public class MigratableVisitorCTree extends TreePathScanner<Void, Trees> { private final Messager _compilerOutput; private final Types _typeUtils; public MigratableVisitorCTree(ProcessingEnvironment processingEnv) { super(); _compilerOutput = processingEnv.getMessager(); _typeUtils = processingEnv.getTypeUtils(); } @Override public Void visitClass(ClassTree clazzDecl, Trees trees) { Element clazzElement = trees.getElement(getCurrentPath()); // sanity check if (!((clazzElement != null) && (clazzElement instanceof TypeElement) && (clazzElement.getKind() .isClass()))) return super.visitClass(clazzDecl, trees); TypeElement clazzDef = (TypeElement) clazzElement; if (clazzElement.getAnnotation(ActiveObject.class) == null) { _compilerOutput .printMessage(Diagnostic.Kind.ERROR, ErrorMessages.MIGRATABLE_NOT_AO, clazzElement); } if (!implementsSerializable(clazzDef)) { _compilerOutput.printMessage(Diagnostic.Kind.ERROR, ErrorMessages.MIGRATABLE_SERIALIZABLE, clazzElement); } return super.visitClass(clazzDecl, trees); } private boolean implementsSerializable(TypeElement clazzDecl) { // is this serializable? if (clazzDecl.getQualifiedName().toString().equals(Serializable.class.getCanonicalName())) return true; // test the superclass TypeMirror zuper = clazzDecl.getSuperclass(); if (!zuper.getKind().equals(TypeKind.NONE)) { Element zuperClass = _typeUtils.asElement(zuper); if (zuperClass.getKind().isClass()) if (implementsSerializable((TypeElement) zuperClass)) return true; } // verify the superinterfaces for (TypeMirror ifType : clazzDecl.getInterfaces()) { Element ifElem = _typeUtils.asElement(ifType); if (!(ifElem.getKind().isInterface())) continue; if (implementsSerializable((TypeElement) ifElem)) return true; } return false; } }
acontes/programming
src/Extensions/org/objectweb/proactive/extensions/annotation/migratable/MigratableVisitorCTree.java
Java
agpl-3.0
4,461
/* /% C %/ */ /*********************************************************************** * The WildCard interpreter ************************************************************************ * parameter information file TCLTK.h ************************************************************************ * Description: * This header file is given to makecint by -h option. This header file * is parsed by C preprocessor then by cint. ************************************************************************ * Copyright(c) 1996-1997 Masaharu Goto ([email protected]) * * For the licensing terms see the file COPYING * ************************************************************************/ #ifndef G__TCLTK_H #define G__TCLTK_H #ifdef __MAKECINT__ /************************************************************** * Defining _XLIB_H here prevents reading X11 header files in * tk.h. There are several X11 declarations needed in tk.h though, * the dummy is provided here. **************************************************************/ #define _XLIB_H #ifndef __STDC__ #define __STDC__ #endif typedef int Bool ; typedef struct { } Visual; /* ./tk.h 380 */ typedef unsigned long Window ; /* ./tk.h 382 */ typedef struct { } XWindowChanges ; /* ./tk.h 391 */ typedef struct { } XSetWindowAttributes ; /* ./tk.h 393 */ typedef struct { } XColor ; typedef struct { } XFontStruct ; typedef struct { } Font; /* RH5.1 */ typedef unsigned long Pixmap ; typedef unsigned long Cursor ; typedef unsigned long Colormap; typedef unsigned long Atom ; typedef union _XEvent { } XEvent ; typedef struct {} XPoint ; typedef struct {} XGCValues ; typedef struct _XGC { } *GC ; typedef struct _XDisplay { } Display; /* ./tk.h 377 */ typedef unsigned long Time; #endif /* __MAKECINT__ */ /************************************************************** * include tk.h **************************************************************/ #define XLIB_ILLEGAL_ACCESS #include <tk.h> /************************************************************** * global interpreter object instantiated by Tk in TkInit.c is * exposed to CINT. **************************************************************/ extern Tcl_Interp *interp; /************************************************************** * add #pragma tcl statement in the CINT parser **************************************************************/ #ifndef __MAKECINT__ void G__cinttk_init(); #endif /************************************************************** * WildCard/X11 Event Loop function **************************************************************/ void WildCard_MainLoop(); void WildCard_Exit(); int WildCard_AllocConsole(); int WildCard_FreeConsole(); #ifdef __MAKECINT__ /************************************************************** * following description is optional, hence, cint -c-2 * automatically ignores undefined structs for creating * interface method. **************************************************************/ #pragma link off class Tcl_AsyncHandler_; #pragma link off class Tcl_RegExp_; #pragma link off class Tk_BindingTable_; #pragma link off class Tk_Canvas_; #pragma link off class Tk_ErrorHandler_; #pragma link off class Tk_Image__; #pragma link off class Tk_ImageMaster_; #pragma link off class Tk_TimerToken_; #pragma link off class Tk_Window_; #pragma link off class Tk_3DBorder_; #pragma link off function Tcl_GetCwd; #pragma link off function Tcl_CreatePipeline; #pragma link off function Tk_FileeventCmd; #pragma link off function Tk_CreateMainWindow; #pragma link off function Tk_ChooseFontCmd; /* RH5.1 */ #pragma link off function Tcl_GetErrorLine; #pragma link off function Tcl_GetOriginalCommand; #pragma link off function Tcl_RestartIdleTimer; #pragma link off function Tcl_UpdatePointer; #pragma link off function Tcl_AfterCmd; #pragma link off function Tk_UpdatePointer; /* END RH5.1 */ #ifdef __hpux #pragma link off function Tk_ConfigureFree; #pragma link off function Tk_ApplicationCmd; #endif #endif /* __MAKECINT__ */ #endif /* G__TCLTK_H */ /* * Local Variables: * c-tab-always-indent:nil * c-indent-level:2 * c-continued-statement-offset:2 * c-brace-offset:-2 * c-brace-imaginary-offset:0 * c-argdecl-indent:0 * c-label-offset:-2 * compile-command:"make -k" * End: */
dawehner/root
cint/cint/lib/WildCard/TCLTK.h
C
lgpl-2.1
4,289
/* Copyright (C) 2004, 2005 Nikolas Zimmermann <[email protected]> 2004, 2005, 2006 Rob Buis <[email protected]> This file is part of the KDE project 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. */ #include "config.h" #if ENABLE(SVG) && ENABLE(SVG_FILTERS) #include "SVGFEFuncAElement.h" namespace WebCore { SVGFEFuncAElement::SVGFEFuncAElement(const QualifiedName& tagName, Document* doc) : SVGComponentTransferFunctionElement(tagName, doc) { } SVGFEFuncAElement::~SVGFEFuncAElement() { } } #endif // ENABLE(SVG) // vim:ts=4:noet
RLovelett/qt
src/3rdparty/webkit/WebCore/svg/SVGFEFuncAElement.cpp
C++
lgpl-2.1
1,302
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.3053 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace N2.Addons.Wiki.UI.WikiTemplates { public partial class LinkFromParameter { } }
nimore/n2cms
src/WebForms/WebFormsTemplates/Addons/Wiki/UI/WikiTemplates/LinkFromParameter.ascx.designer.cs
C#
lgpl-2.1
503
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef ODETIMEKERNEL_H #define ODETIMEKERNEL_H #include "ODEKernel.h" // Forward Declarations class ODETimeKernel; template<> InputParameters validParams<ODETimeKernel>(); /** * Base class for ODEKernels that contribute to the time residual * vector. */ class ODETimeKernel : public ODEKernel { public: ODETimeKernel(const InputParameters & parameters); virtual void computeResidual() override; }; #endif
katyhuff/moose
framework/include/kernels/ODETimeKernel.h
C
lgpl-2.1
1,292
/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 // // Arjuna Technologies Ltd., // Newcastle upon Tyne, // Tyne and Wear, // UK. // package org.jboss.jbossts.qa.RawSubtransactionAwareResources02Clients2; /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client003.java,v 1.2 2003/06/26 11:45:03 rbegg Exp $ */ /* * Try to get around the differences between Ansi CPP and * K&R cpp with concatenation. */ /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client003.java,v 1.2 2003/06/26 11:45:03 rbegg Exp $ */ import org.jboss.jbossts.qa.RawSubtransactionAwareResources02.*; import org.jboss.jbossts.qa.Utils.OAInterface; import org.jboss.jbossts.qa.Utils.ORBInterface; import org.jboss.jbossts.qa.Utils.OTS; import org.jboss.jbossts.qa.Utils.ServerIORStore; public class Client003 { public static void main(String[] args) { try { ORBInterface.initORB(args, null); OAInterface.initOA(); String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]); Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1)); String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]); Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2)); boolean correct = true; OTS.current().begin(); OTS.current().begin(); service1.oper(1, OTS.current().get_control()); service2.oper(1, OTS.current().get_control()); OTS.current().rollback(); OTS.current().commit(true); correct = correct && service1.is_correct(); correct = correct && service2.is_correct(); correct = correct && (service1.get_subtransaction_aware_resource_trace(0) == SubtransactionAwareResourceTrace.SubtransactionAwareResourceTraceRollbackSubtransaction); correct = correct && (service2.get_subtransaction_aware_resource_trace(0) == SubtransactionAwareResourceTrace.SubtransactionAwareResourceTraceRollbackSubtransaction); if (correct) { System.out.println("Passed"); } else { System.out.println("Failed"); } } catch (Exception exception) { System.out.println("Failed"); System.err.println("Client003.main: " + exception); exception.printStackTrace(System.err); } try { OAInterface.shutdownOA(); ORBInterface.shutdownORB(); } catch (Exception exception) { System.err.println("Client003.main: " + exception); exception.printStackTrace(System.err); } } }
gytis/narayana
qa/tests/src/org/jboss/jbossts/qa/RawSubtransactionAwareResources02Clients2/Client003.java
Java
lgpl-2.1
3,637
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / Authoring Tools sub-project * * GPAC 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, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #ifndef _GF_ISMACRYP_H_ #define _GF_ISMACRYP_H_ #ifdef __cplusplus extern "C" { #endif #include <gpac/isomedia.h> /*loads key and salt from a LOCAL gpac-DRM file (cf MP4Box doc)*/ GF_Err gf_ismacryp_gpac_get_info(u32 stream_id, char *drm_file, char *key, char *salt); /*loads key and salt for MPEG4IP protected files*/ Bool gf_ismacryp_mpeg4ip_get_info(char *kms_uri, char *key, char *salt); enum { /*no selective encryption*/ GF_CRYPT_SELENC_NONE = 0, /*only encrypts RAP samples*/ GF_CRYPT_SELENC_RAP = 1, /*only encrypts non-RAP samples*/ GF_CRYPT_SELENC_NON_RAP = 2, /*selective encryption of random samples*/ GF_CRYPT_SELENC_RAND = 3, /*selective encryption of a random sample in given range*/ GF_CRYPT_SELENC_RAND_RANGE = 4, /*selective encryption of first sample in given range*/ GF_CRYPT_SELENC_RANGE = 5, /*encryption of all samples but the preview range*/ GF_CRYPT_SELENC_PREVIEW = 6, }; typedef struct { /*0: ISMACryp - 1: OMA DRM - 2: CENC CTR - 3: CENC CBC - 4: ADOBE*/ u32 enc_type; u32 trackID; unsigned char key[16]; unsigned char salt[16]; /*the rest is only used for encryption*/ char KMS_URI[5000]; char Scheme_URI[5000]; /*selecive encryption type*/ u32 sel_enc_type; u32 sel_enc_range; /*IPMP signaling: 0: none, 1: IPMP, 2: IPMPX when IPMP signaling is enabled, the OD stream will be updated with IPMP Update commands*/ u32 ipmp_type; /*if not set and IPMP enabled, defaults to TrackID*/ u32 ipmp_desc_id; /*type of box where sample auxiliary informations is saved, or 0 in case of ISMACrypt (it will be written in samples)*/ u32 sai_saved_box_type; /*OMA extensions*/ /*0: none, 1: AES CBC, 2: AES CTR*/ u8 encryption; char TextualHeaders[5000]; u32 TextualHeadersLen; char TransactionID[17]; /*CENC extensions*/ u32 IsEncrypted; u8 IV_size; bin128 default_KID; u32 KID_count; bin128 *KIDs; bin128 *keys; /*IV of first sample in track*/ unsigned char first_IV[16]; u32 defaultKeyIdx; u32 keyRoll; char metadata[5000]; u32 metadata_len; } GF_TrackCryptInfo; #if !defined(GPAC_DISABLE_MCRYPT) && !defined(GPAC_DISABLE_ISOM_WRITE) /*encrypts track - logs, progress: info callbacks, NULL for default*/ GF_Err gf_ismacryp_encrypt_track(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); /*decrypts track - logs, progress: info callbacks, NULL for default*/ GF_Err gf_ismacryp_decrypt_track(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); /*Common Encryption*/ /*AES-CTR*/ GF_Err gf_cenc_encrypt_track(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); GF_Err gf_cenc_decrypt_track(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); /*AES-CBC*/ GF_Err gf_cbc_encrypt_track(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); GF_Err gf_cbc_decrypt_track(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); /*ADOBE*/ GF_Err gf_adobe_encrypt_track(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); GF_Err gf_adobe_decrypt_track(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); GF_Err (*gf_encrypt_track)(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); GF_Err (*gf_decrypt_track)(GF_ISOFile *mp4, GF_TrackCryptInfo *tci, void (*progress)(void *cbk, u64 done, u64 total), void *cbk); /*decrypt a file @drm_file: location of DRM data (cf MP4Box doc). @LogMsg: redirection for message or NULL for default */ GF_Err gf_decrypt_file(GF_ISOFile *mp4file, const char *drm_file); /*Crypt a the file @drm_file: location of DRM data. @LogMsg: redirection for message or NULL for default */ GF_Err gf_crypt_file(GF_ISOFile *mp4file, const char *drm_file); #endif /*!defined(GPAC_DISABLE_MCRYPT) && !defined(GPAC_DISABLE_ISOM_WRITE)*/ #ifdef __cplusplus } #endif #endif /*_GF_ISMACRYP_H_*/
psteinb/gpac
include/gpac/ismacryp.h
C
lgpl-2.1
5,081
#!/usr/bin/perl use r_bp; $a = new r_bp::RBreakpoint (); $a->use ("x86"); $a->add_hw (0x8048000, 10, 0); $a->add_sw (0x8048000, 10, 0); $a->list (0);
skuater/radare2-bindings
perl/test-r_bp.pl
Perl
lgpl-3.0
152
/** * Copyright 2013-2014 University Of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.workflowsim.scheduling; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.cloudbus.cloudsim.Cloudlet; import org.workflowsim.CondorVM; import org.workflowsim.WorkflowSimTags; /** * The Round Robin algorithm. * * @author Weiwei Chen * @since WorkflowSim Toolkit 1.0 * @date May 12, 2014 */ public class RoundRobinSchedulingAlgorithm extends BaseSchedulingAlgorithm { /** * The main function */ @Override public void run() { int vmIndex = 0; int size = getCloudletList().size(); Collections.sort(getCloudletList(), new CloudletListComparator()); List vmList = getVmList(); Collections.sort(vmList, new VmListComparator()); for (int j = 0; j < size; j++) { Cloudlet cloudlet = (Cloudlet) getCloudletList().get(j); int vmSize = vmList.size(); CondorVM firstIdleVm = null;//(CondorVM)getVmList().get(0); for (int l = 0; l < vmSize; l++) { CondorVM vm = (CondorVM) vmList.get(l); if (vm.getState() == WorkflowSimTags.VM_STATUS_IDLE) { firstIdleVm = vm; break; } } if (firstIdleVm == null) { break; } ((CondorVM) firstIdleVm).setState(WorkflowSimTags.VM_STATUS_BUSY); cloudlet.setVmId(firstIdleVm.getId()); getScheduledList().add(cloudlet); vmIndex = (vmIndex + 1) % vmList.size(); } } /** * Sort it based on vm index */ public class VmListComparator implements Comparator<CondorVM>{ @Override public int compare(CondorVM v1, CondorVM v2){ return Integer.compare(v1.getId(), v2.getId()); } } public class CloudletListComparator implements Comparator<Cloudlet>{ @Override public int compare(Cloudlet c1, Cloudlet c2){ return Integer.compare(c1.getCloudletId(), c2.getCloudletId()); } } }
AnnanCheng/WorkflowSim_Annan
sources/org/workflowsim/scheduling/RoundRobinSchedulingAlgorithm.java
Java
lgpl-3.0
2,702
// // ControlFloor.h // TonicDemo // // Created by Morgan Packard on 3/4/13. // // See LICENSE.txt for license and usage information. // #ifndef __TonicDemo__ControlFloor__ #define __TonicDemo__ControlFloor__ #include "ControlConditioner.h" namespace Tonic{ namespace Tonic_{ class ControlFloor_ : public ControlConditioner_{ inline void computeOutput(const SynthesisContext_ & context){ output_.value = (int)input_.tick(context).value; output_.triggered = input_.tick(context).triggered; } }; } class ControlFloor : public TemplatedControlConditioner<ControlFloor, Tonic_::ControlFloor_> {}; } #endif /* defined(__TonicDemo__ControlFloor__) */
TheWindInTheWillows/Tonic
src/Tonic/ControlFloor.h
C
unlicense
714
/* * Copyright (c) 2012-2015 The original author or authors * ------------------------------------------------------ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.eclipse.moquette.server.netty.metrics; public class BytesMetrics { private long m_readBytes = 0; private long m_wroteBytes = 0; void incrementRead(long numBytes) { m_readBytes += numBytes; } void incrementWrote(long numBytes) { m_wroteBytes += numBytes; } public long readBytes() { return m_readBytes; } public long wroteBytes() { return m_wroteBytes; } }
dant3/moquette
broker/src/main/java/org/eclipse/moquette/server/netty/metrics/BytesMetrics.java
Java
apache-2.0
1,042
/* * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.spi.hive; import com.google.common.collect.Sets; import java.util.Set; import org.apache.avro.generic.GenericData; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.TableType; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Table; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.kitesdk.data.Dataset; import org.kitesdk.data.DatasetDescriptor; import org.kitesdk.data.DatasetNotFoundException; import org.kitesdk.data.Datasets; import org.kitesdk.data.TestHelpers; import org.kitesdk.data.spi.DatasetRepositories; import org.kitesdk.data.spi.DatasetRepository; public class TestManagedExternalHandling { private static final DatasetDescriptor descriptor = new DatasetDescriptor.Builder() .schemaLiteral("\"string\"") .build(); private DatasetRepository managed; private DatasetRepository external; @Before public void setupRepositories() { // ensure the datasets do not already exist Datasets.delete("dataset:hive?dataset=managed"); Datasets.delete("dataset:hive:target/test-repo/ns/external"); // ensure no other metadata is left in the metastore cleanHive(); // create datasets this.managed = DatasetRepositories.repositoryFor("repo:hive"); Datasets.create("dataset:hive?dataset=managed", descriptor); this.external = DatasetRepositories.repositoryFor("repo:hive:target/test-repo"); external.create("ns", "external", descriptor); } @After public void cleanHive() { // ensures all tables are removed MetaStoreUtil metastore = MetaStoreUtil.get(new Configuration()); for (String database : metastore.getAllDatabases()) { for (String table : metastore.getAllTables(database)) { metastore.dropTable(database, table); } if (!"default".equals(database)) { metastore.dropDatabase(database, true); } } } @Test public void testManagedWithExternal() { HiveAbstractMetadataProvider provider = new HiveManagedMetadataProvider( new HiveConf()); Assert.assertTrue(provider.isExternal("ns", "external")); Dataset<GenericData.Record> dataset = managed.load("ns", "external"); Assert.assertNotNull("Should open external dataset with managed", dataset); Assert.assertEquals("Should match external dataset", external.load("ns", "external").getDescriptor(), dataset.getDescriptor()); DatasetDescriptor updatedDescriptor = new DatasetDescriptor.Builder(dataset.getDescriptor()) .property("kite.writer.cache-size", "34") .schemaLiteral("\"string\"") .build(); Dataset<GenericData.Record> updated = managed .update("ns", "external", updatedDescriptor); Assert.assertNotNull("Should update external dataset with managed", updated); Assert.assertEquals("Should see changes in external dataset", external.load("ns", "external").getDescriptor(), updated.getDescriptor()); Assert.assertTrue("Should delete external tables with managed", managed.delete("ns", "external")); TestHelpers.assertThrows("Should delete external table correctly", DatasetNotFoundException.class, new Runnable() { @Override public void run() { external.load("ns", "external"); } }); } @Test public void testExternalWithManaged() { HiveAbstractMetadataProvider provider = new HiveManagedMetadataProvider( new HiveConf()); Assert.assertTrue(provider.isManaged("default", "managed")); Dataset<GenericData.Record> dataset = external.load("default", "managed"); Assert.assertNotNull("Should open managed dataset with external", dataset); Assert.assertEquals("Should match managed dataset", managed.load("default", "managed").getDescriptor(), dataset.getDescriptor()); DatasetDescriptor updatedDescriptor = new DatasetDescriptor.Builder(dataset.getDescriptor()) .property("kite.writer.cache-size", "34") .schemaLiteral("\"string\"") .build(); Dataset<GenericData.Record> updated = external .update("default", "managed", updatedDescriptor); Assert.assertNotNull("Should update managed dataset with external", updated); Assert.assertEquals("Should see changes in managed dataset", managed.load("default", "managed").getDescriptor(), updated.getDescriptor()); Assert.assertTrue("Should delete managed tables with external", external.delete("default", "managed")); TestHelpers.assertThrows("Should delete managed table correctly", DatasetNotFoundException.class, new Runnable() { @Override public void run() { managed.load("default", "managed"); } }); } @Test public void testRepositoryList() throws Exception { // create unreadable hive tables MetaStoreUtil metastore = MetaStoreUtil.get(new Configuration()); metastore.dropTable("default", "bad_type"); metastore.dropTable("bad", "bad_serde"); metastore.dropTable("bad", "bad_schema"); Table badType = HiveUtils.createEmptyTable("default", "bad_type"); badType.setTableType(TableType.VIRTUAL_VIEW.toString()); metastore.createTable(badType); Table badSerDe = HiveUtils.createEmptyTable("bad", "bad_serde"); badSerDe.setTableType(TableType.MANAGED_TABLE.toString()); // readable type badSerDe.getSd().getSerdeInfo().setSerializationLib("com.example.ExampleHiveSerDe"); metastore.createTable(badSerDe); // add a bad schema if decimal is supported (not supported by Kite) if (HiveSchemaConverter.decimalClass != null) { Table badSchema = HiveUtils.createEmptyTable("bad", "bad_schema"); badSchema.setTableType(TableType.MANAGED_TABLE.toString()); // readable type badSchema.getSd().getSerdeInfo().setSerializationLib("org.apache.hadoop.hive.serde2.avro.AvroSerDe"); badSchema.getSd().setInputFormat("org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat"); badSchema.getSd().setOutputFormat("org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat"); badSchema.getSd().getCols().add(new FieldSchema("invalid", "decimal(1,2)", null)); metastore.createTable(badSchema); } // note that unreadable tables are not in the lists Set<String> expectedNamespaces = Sets.newHashSet("default", "ns"); Assert.assertEquals("Managed should list namespaces with external and managed tables", expectedNamespaces, Sets.newHashSet(managed.namespaces())); Assert.assertEquals("External should list namespaces with external and managed tables", expectedNamespaces, Sets.newHashSet(external.namespaces())); Set<String> expectedInDefault = Sets.newHashSet("managed"); Assert.assertEquals("Managed should list external and managed tables", expectedInDefault, Sets.newHashSet(managed.datasets("default"))); Assert.assertEquals("External should list external and managed tables", expectedInDefault, Sets.newHashSet(external.datasets("default"))); Set<String> expectedInNS = Sets.newHashSet("external"); Assert.assertEquals("Managed should list external and managed tables", expectedInNS, Sets.newHashSet(managed.datasets("ns"))); Assert.assertEquals("External should list external and managed tables", expectedInNS, Sets.newHashSet(external.datasets("ns"))); } }
tinkujohn/kite
kite-data/kite-data-hive/src/test/java/org/kitesdk/data/spi/hive/TestManagedExternalHandling.java
Java
apache-2.0
8,205
contrail-puppet =============== Puppet recipes for Contrail components This repo contains modules that contain custom resources for contrail roles. At present, following roles are defined. 1. contrail-common - Contains common resources to be instantiated for all the servers regardless of other contrail roles they are providing. 2. contrail-config - Resources used by contrail config role. 3. contrail-control - Resources used by contrail control role. 4. contrail-collector - Resources used by contrail collector role. 5. contrail-compute - Resources used by contrail compute role. 6. contrail-database - Resources used by contrail database role. 7. contrail-openstack - Resources used by contrail openstack role. 8. contrail-webui - Resources used by contrail webui role.
dgautam/contrail-puppet
contrail/environment/modules/contrail/README.md
Markdown
apache-2.0
806
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/cloudformation/model/Capability.h> #include <aws/core/utils/HashingUtils.h> using namespace Aws::Utils; static const int CAPABILITY_IAM_HASH = HashingUtils::HashString("CAPABILITY_IAM"); namespace Aws { namespace CloudFormation { namespace Model { namespace CapabilityMapper { Capability GetCapabilityForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == CAPABILITY_IAM_HASH) { return Capability::CAPABILITY_IAM; } return Capability::NOT_SET; } Aws::String GetNameForCapability(Capability value) { switch(value) { case Capability::CAPABILITY_IAM: return "CAPABILITY_IAM"; default: return ""; } } } // namespace CapabilityMapper } // namespace Model } // namespace CloudFormation } // namespace Aws
d9magai/aws-sdk-cpp
aws-cpp-sdk-cloudformation/source/model/Capability.cpp
C++
apache-2.0
1,375
require 'chef/provisioning/aws_driver/aws_resource' class Chef::Resource::AwsServerCertificate < Chef::Provisioning::AWSDriver::AWSResource aws_sdk_type AWS::IAM::ServerCertificate attribute :name, kind_of: String, name_attribute: true attribute :certificate_body, kind_of: String attribute :private_key, kind_of: String def aws_object begin cert = driver.iam.server_certificates[name] # this will trigger a AWS::IAM::Errors::NoSuchEntity if the cert does not exist cert.arn cert rescue AWS::IAM::Errors::NoSuchEntity nil end end end
tarak/chef-provisioning-aws
lib/chef/resource/aws_server_certificate.rb
Ruby
apache-2.0
592
# Encoding: utf-8 # # Author:: [email protected] (Danial Klimkin) # # Copyright:: Copyright 2011, Google Inc. All Rights Reserved. # # License:: 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. # # Contains utility methods specific to reporting. require 'cgi' require 'gyoku' require 'nori' require 'ads_common/http' require 'adwords_api/errors' require 'adwords_api/report_header_handler' module AdwordsApi class ReportUtils # Default constructor. # # Args: # - api: AdwordsApi object # - version: API version to use # def initialize(api, version) @api, @version = api, version end # Downloads and returns a report. # # Args: # - report_definition: definition of the report in XML text or hash # - cid: optional customer ID to run against # # Returns: # - report body # # Raises: # - AdwordsApi::Errors::InvalidReportDefinitionError if the report # definition is invalid # - AdwordsApi::Errors::ReportError if server-side error occurred # def download_report(report_definition, cid = nil) return get_report_response(report_definition, cid).body end # Downloads a report and saves it to a file. # # Args: # - report_definition: definition of the report in XML text or hash # - path: path to save report to # - cid: optional customer ID to run against # # Returns: # - nil # # Raises: # - AdwordsApi::Errors::InvalidReportDefinitionError if the report # definition is invalid # - AdwordsApi::Errors::ReportError if server-side error occurred # def download_report_as_file(report_definition, path, cid = nil) report_body = download_report(report_definition, cid) save_to_file(report_body, path) return nil end # Downloads and returns a report with AWQL. # # Args: # - report_query: query for the report as string # - format: format for the report as string # - cid: optional customer ID to run report against # # Returns: # - report body # # Raises: # - AdwordsApi::Errors::ReportError if a server-side error has occurred # def download_report_with_awql(report_query, format, cid = nil) return get_report_response_with_awql(report_query, format, cid).body end # Downloads a report with AWQL and saves it to a file. # # Args: # - report_query: query for the report as string # - format: format for the report as string # - path: path to save report to # - cid: optional customer ID to run report against # # Returns: # - nil # # Raises: # - AdwordsApi::Errors::ReportError if server-side error occurred # def download_report_as_file_with_awql(report_query, format, path, cid = nil) report_body = download_report_with_awql(report_query, format, cid) save_to_file(report_body, path) return nil end private # Minimal set of required fields for report definition. REQUIRED_FIELDS = [:selector, :report_name, :report_type, :date_range_type] # Definition fields have to be in particular order in the XML. Here is its # specification. REPORT_DEFINITION_ORDER = { :root => [:selector, :report_name, :report_type, :date_range_type, :download_format, :include_zero_impressions], :selector => [:fields, :predicates, :date_range, :ordering, :paging], :predicates => [:field, :operator, :values], :ordering => [:field, :sort_order], :paging => [:start_index, :number_results], :date_range => [:min, :max] } # Send POST request for a report and returns Response object. def get_report_response(report_definition, cid) definition_text = get_report_definition_text(report_definition) data = '__rdxml=%s' % CGI.escape(definition_text) return make_adhoc_request(data, cid) end # Send POST request for a report with AWQL and returns Response object. def get_report_response_with_awql(report_query, format, cid) data = '__rdquery=%s&__fmt=%s' % [CGI.escape(report_query), CGI.escape(format)] return make_adhoc_request(data, cid) end # Makes request and AdHoc service and returns response. def make_adhoc_request(data, cid) url = @api.api_config.adhoc_report_download_url( @api.config.read('service.environment'), @version) headers = get_report_request_headers(url, cid) log_request(url, headers, data) response = AdsCommon::Http.post_response(url, data, @api.config, headers) check_for_errors(response) return response end # Converts passed object to XML text. Currently support String (no changes) # and Hash (renders XML). def get_report_definition_text(report_definition) return case report_definition when String then report_definition when Hash then report_definition_to_xml(report_definition) else raise AdwordsApi::Errors::InvalidReportDefinitionError, 'Unknown object for report definition: %s' % report_definition.class end end # Prepares headers for report request. def get_report_request_headers(url, cid) @header_handler ||= AdwordsApi::ReportHeaderHandler.new( @api.credential_handler, @api.get_auth_handler(), @api.config) return @header_handler.headers(url, cid) end # Saves raw data to a file. def save_to_file(data, path) open(path, 'wb') { |file| file.write(data) } if path end # Logs the request on debug level. def log_request(url, headers, body) logger = @api.logger logger.debug("Report request to: '%s'" % url) logger.debug('HTTP headers: [%s]' % (headers.map { |k, v| [k, v].join(': ') }.join(', '))) logger.debug(body) end # Checks downloaded data for error signature. Raises ReportError if it # detects an error. def check_for_errors(response) # Check for error code. if response.code != 200 # Check for error in body. report_body = response.body check_for_xml_error(report_body, response.code) # No XML error found nor raised, falling back to a default message. raise AdwordsApi::Errors::ReportError.new(response.code, 'HTTP code: %d, body: %s' % [response.code, response.body]) end return nil end # Checks for an XML error in the response body and raises an exception if # it was found. def check_for_xml_error(report_body, response_code) error_response = Nori.parse(report_body) if error_response.include?(:report_download_error) and error_response[:report_download_error].include?(:api_error) api_error = error_response[:report_download_error][:api_error] raise AdwordsApi::Errors::ReportXmlError.new(response_code, api_error[:type], api_error[:trigger], api_error[:field_path]) end end # Renders a report definition hash into XML text. def report_definition_to_xml(report_definition) check_report_definition_hash(report_definition) add_report_definition_hash_order(report_definition) return Gyoku.xml({:report_definition => report_definition}) end # Checks if the report definition looks correct. def check_report_definition_hash(report_definition) # Minimal set of fields required. REQUIRED_FIELDS.each do |field| unless report_definition.include?(field) raise AdwordsApi::Errors::InvalidReportDefinitionError, "Required field '%s' is missing in the definition" % field end end # Fields list is also required. unless report_definition[:selector].include?(:fields) raise AdwordsApi::Errors::InvalidReportDefinitionError, 'Fields list is required' end # 'Fields' must be an Array. unless report_definition[:selector][:fields].kind_of?(Array) raise AdwordsApi::Errors::InvalidReportDefinitionError, 'Fields list must be an array' end # We should request at least one field. if report_definition[:selector][:fields].empty? raise AdwordsApi::Errors::InvalidReportDefinitionError, 'At least one field needs to be requested' end end # Adds fields order hint to generator based on specification. def add_report_definition_hash_order(node, name = :root) def_order = REPORT_DEFINITION_ORDER[name] var_order = def_order.reject { |field| !node.include?(field) } node.keys.each do |key| if REPORT_DEFINITION_ORDER.include?(key) case node[key] when Hash add_report_definition_hash_order(node[key], key) when Array node[key].each do |item| add_report_definition_hash_order(item, key) end end end end node[:order!] = var_order return nil end end end
SumitBisht/adwords-api-v201302
lib/adwords_api/report_utils.rb
Ruby
apache-2.0
9,629
//! Platform-specific extensions to `std` for Unix platforms. //! //! Provides access to platform-level information on Unix platforms, and //! exposes Unix-specific functions that would otherwise be inappropriate as //! part of the core `std` library. //! //! It exposes more ways to deal with platform-specific strings ([`OsStr`], //! [`OsString`]), allows to set permissions more granularly, extract low-level //! file descriptors from files and sockets, and has platform-specific helpers //! for spawning processes. //! //! # Examples //! //! ```no_run //! use std::fs::File; //! use std::os::unix::prelude::*; //! //! fn main() -> std::io::Result<()> { //! let f = File::create("foo.txt")?; //! let fd = f.as_raw_fd(); //! //! // use fd with native unix bindings //! //! Ok(()) //! } //! ``` //! //! [`OsStr`]: crate::ffi::OsStr //! [`OsString`]: crate::ffi::OsString #![stable(feature = "rust1", since = "1.0.0")] #![doc(cfg(unix))] // Use linux as the default platform when documenting on other platforms like Windows #[cfg(doc)] use crate::os::linux as platform; #[cfg(not(doc))] mod platform { #[cfg(target_os = "android")] pub use crate::os::android::*; #[cfg(target_os = "dragonfly")] pub use crate::os::dragonfly::*; #[cfg(target_os = "emscripten")] pub use crate::os::emscripten::*; #[cfg(target_os = "espidf")] pub use crate::os::espidf::*; #[cfg(target_os = "freebsd")] pub use crate::os::freebsd::*; #[cfg(target_os = "fuchsia")] pub use crate::os::fuchsia::*; #[cfg(target_os = "haiku")] pub use crate::os::haiku::*; #[cfg(target_os = "illumos")] pub use crate::os::illumos::*; #[cfg(target_os = "ios")] pub use crate::os::ios::*; #[cfg(any(target_os = "linux", target_os = "l4re"))] pub use crate::os::linux::*; #[cfg(target_os = "macos")] pub use crate::os::macos::*; #[cfg(target_os = "netbsd")] pub use crate::os::netbsd::*; #[cfg(target_os = "openbsd")] pub use crate::os::openbsd::*; #[cfg(target_os = "redox")] pub use crate::os::redox::*; #[cfg(target_os = "solaris")] pub use crate::os::solaris::*; #[cfg(target_os = "vxworks")] pub use crate::os::vxworks::*; } pub mod ffi; pub mod fs; pub mod io; pub mod net; pub mod process; pub mod raw; pub mod thread; #[unstable(feature = "peer_credentials_unix_socket", issue = "42839", reason = "unstable")] #[cfg(any( target_os = "android", target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] pub mod ucred; /// A prelude for conveniently writing platform-specific code. /// /// Includes all extension traits, and some important type definitions. #[stable(feature = "rust1", since = "1.0.0")] pub mod prelude { #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] pub use super::ffi::{OsStrExt, OsStringExt}; #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] pub use super::fs::DirEntryExt; #[doc(no_inline)] #[stable(feature = "file_offset", since = "1.15.0")] pub use super::fs::FileExt; #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] pub use super::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}; #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] pub use super::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] pub use super::process::{CommandExt, ExitStatusExt}; #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")] pub use super::thread::JoinHandleExt; }
graydon/rust
library/std/src/os/unix/mod.rs
Rust
apache-2.0
3,768
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.svn.actions; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.svn.SvnBundle; import org.jetbrains.idea.svn.SvnStatusUtil; import org.jetbrains.idea.svn.SvnVcs; import static java.util.Collections.singletonList; public class CleanupAction extends BasicAction { @NotNull @Override protected String getActionName() { return SvnBundle.message("cleanup.action.name"); } @Override protected boolean isEnabled(@NotNull SvnVcs vcs, @NotNull VirtualFile file) { return SvnStatusUtil.isUnderControl(vcs, file); } @Override protected void execute(@NotNull SvnVcs vcs, @NotNull VirtualFile file, @NotNull DataContext context) throws VcsException { perform(vcs, file, context); } @Override protected void perform(@NotNull SvnVcs vcs, @NotNull VirtualFile file, @NotNull DataContext context) { new CleanupWorker(vcs, singletonList(file)).execute(); } @Override protected void batchPerform(@NotNull SvnVcs vcs, @NotNull VirtualFile[] files, @NotNull DataContext context) throws VcsException { throw new VcsException(SvnBundle.message("exception.text.cleanupaction.batchperform.not.implemented")); } protected boolean isBatchAction() { return false; } }
jk1/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/actions/CleanupAction.java
Java
apache-2.0
2,000
/* Q Light Controller vcxypadfixtureeditor.h Copyright (c) Heikki Junnila 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.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef VCXYPADFIXTUREEDITOR #define VCXYPADFIXTUREEDITOR #include <QDialog> #include "ui_vcxypadfixtureeditor.h" #include "vcxypadfixture.h" /** @addtogroup ui_vc_props * @{ */ class VCXYPadFixtureEditor : public QDialog, public Ui_VCXYPadFixtureEditor { Q_OBJECT Q_DISABLE_COPY(VCXYPadFixtureEditor) /******************************************************************** * Initialization ********************************************************************/ public: VCXYPadFixtureEditor(QWidget* parent, QList <VCXYPadFixture> fixtures); ~VCXYPadFixtureEditor(); protected slots: void accept(); void slotXMinChanged(int value); void slotXMaxChanged(int value); void slotYMinChanged(int value); void slotYMaxChanged(int value); /******************************************************************** * Fixtures ********************************************************************/ public: QList <VCXYPadFixture> fixtures() const; protected: QList <VCXYPadFixture> m_fixtures; int m_maxXVal, m_maxYVal; }; /** @} */ #endif
nedmech/qlcplus
ui/src/virtualconsole/vcxypadfixtureeditor.h
C
apache-2.0
1,741
๏ปฟusing Nop.Core.Domain.Messages; using Nop.Tests; using NUnit.Framework; namespace Nop.Data.Tests.Messages { [TestFixture] public class EmailAccountPersistenceTests : PersistenceTest { [Test] public void Can_save_and_load_emailAccount() { var emailAccount = new EmailAccount { Email = "[email protected]", DisplayName = "Administrator", Host = "127.0.0.1", Port = 125, Username = "John", Password = "111", EnableSsl = true, UseDefaultCredentials = true }; var fromDb = SaveAndLoadEntity(emailAccount); fromDb.ShouldNotBeNull(); fromDb.Email.ShouldEqual("[email protected]"); fromDb.DisplayName.ShouldEqual("Administrator"); fromDb.Host.ShouldEqual("127.0.0.1"); fromDb.Port.ShouldEqual(125); fromDb.Username.ShouldEqual("John"); fromDb.Password.ShouldEqual("111"); fromDb.EnableSsl.ShouldBeTrue(); fromDb.UseDefaultCredentials.ShouldBeTrue(); } } }
jornfilho/nopCommerce
source/Tests/Nop.Data.Tests/Messages/EmailAccountPersistenceTests.cs
C#
apache-2.0
1,190
if(NOT CUSTOM_PLATFORM_DIR ) message(FATAL_ERROR "Custom platforms require the CUSTOM_PLATFORM_DIR parameter to be set") endif() file(TO_CMAKE_PATH "${CUSTOM_PLATFORM_DIR}" __custom_platform_dir) if(NOT IS_DIRECTORY "${__custom_platform_dir}") message(FATAL_ERROR "${CUSTOM_PLATFORM_DIR} is not a valid directory for a custom platform") endif() set(__toolchain_file ${__custom_platform_dir}/${TARGET_ARCH}.toolchain.cmake) IF(NOT (EXISTS ${__toolchain_file})) message(FATAL_ERROR "Custom architecture target ${TARGET_ARCH} requires a cmake toolchain file at: ${__toolchain_file}") endif() SET(CMAKE_TOOLCHAIN_FILE ${__toolchain_file}) set(CUSTOM_PLATFORM_SOURCE_PATH "${__custom_platform_dir}/src") list(APPEND CMAKE_MODULE_PATH "${__custom_platform_dir}/modules") string(TOLOWER "${TARGET_ARCH}" __lower_arch) set(SDK_INSTALL_BINARY_PREFIX ${__lower_arch}) include(${__custom_platform_dir}/${__lower_arch}_platform.cmake) message(STATUS "Generating ${__lower_arch} build config")
cedral/aws-sdk-cpp
cmake/platform/custom.cmake
CMake
apache-2.0
999
package net.floodlightcontroller.restserver; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.restlet.Application; import org.restlet.Component; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Protocol; import org.restlet.data.Reference; import org.restlet.data.Status; import org.restlet.ext.jackson.JacksonRepresentation; import org.restlet.representation.Representation; import org.restlet.routing.Filter; import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.service.StatusService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; public class RestApiServer implements IFloodlightModule, IRestApiService { protected static Logger logger = LoggerFactory.getLogger(RestApiServer.class); protected List<RestletRoutable> restlets; protected FloodlightModuleContext fmlContext; protected int restPort = 8080; // *********** // Application // *********** protected class RestApplication extends Application { protected Context context; public RestApplication() { super(new Context()); this.context = getContext(); } @Override public Restlet createInboundRoot() { Router baseRouter = new Router(context); baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH); for (RestletRoutable rr : restlets) { baseRouter.attach(rr.basePath(), rr.getRestlet(context)); } Filter slashFilter = new Filter() { @Override protected int beforeHandle(Request request, Response response) { Reference ref = request.getResourceRef(); String originalPath = ref.getPath(); if (originalPath.contains("//")) { String newPath = originalPath.replaceAll("/+", "/"); ref.setPath(newPath); } return Filter.CONTINUE; } }; slashFilter.setNext(baseRouter); return slashFilter; } public void run(FloodlightModuleContext fmlContext, int restPort) { setStatusService(new StatusService() { @Override public Representation getRepresentation(Status status, Request request, Response response) { return new JacksonRepresentation<Status>(status); } }); // Add everything in the module context to the rest for (Class<? extends IFloodlightService> s : fmlContext.getAllServices()) { if (logger.isDebugEnabled()) { logger.debug("Adding {} for service {} into context", s.getCanonicalName(), fmlContext.getServiceImpl(s)); } context.getAttributes().put(s.getCanonicalName(), fmlContext.getServiceImpl(s)); } // Start listening for REST requests try { final Component component = new Component(); component.getServers().add(Protocol.HTTP, restPort); component.getClients().add(Protocol.CLAP); component.getDefaultHost().attach(this); component.start(); } catch (Exception e) { throw new RuntimeException(e); } } } // *************** // IRestApiService // *************** @Override public void addRestletRoutable(RestletRoutable routable) { restlets.add(routable); } @Override public void run() { if (logger.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("REST API routables: "); for (RestletRoutable routable : restlets) { sb.append(routable.getClass().getSimpleName()); sb.append(" ("); sb.append(routable.basePath()); sb.append("), "); } logger.debug(sb.toString()); } RestApplication restApp = new RestApplication(); restApp.run(fmlContext, restPort); } // ***************** // IFloodlightModule // ***************** @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { Collection<Class<? extends IFloodlightService>> services = new ArrayList<Class<? extends IFloodlightService>>(1); services.add(IRestApiService.class); return services; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(); m.put(IRestApiService.class, this); return m; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { // We don't have any return null; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { // This has to be done here since we don't know what order the // startUp methods will be called this.restlets = new ArrayList<RestletRoutable>(); this.fmlContext = context; // read our config options Map<String, String> configOptions = context.getConfigParams(this); String port = configOptions.get("port"); if (port != null) { restPort = Integer.parseInt(port); } logger.info("REST port set to {}", restPort); } @Override public void startUp(FloodlightModuleContext Context) { // no-op } }
floodlight/ubuntu-packaging-floodlight
src/main/java/net/floodlightcontroller/restserver/RestApiServer.java
Java
apache-2.0
6,601
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.arjuna.webservices11.util; import org.jboss.ws.api.addressing.MAPBuilder; import java.security.AccessController; /** * @author <a href="mailto:[email protected]">Gytis Trikleris</a> */ public class PrivilegedMapBuilderFactory { private static final PrivilegedMapBuilderFactory INSTANCE = new PrivilegedMapBuilderFactory(); private PrivilegedMapBuilderFactory() { } public static PrivilegedMapBuilderFactory getInstance() { return INSTANCE; } public MAPBuilder getBuilderInstance() { final MapBuilderAction mapBuilderAction = MapBuilderAction.getInstance(); if (System.getSecurityManager() == null) { return mapBuilderAction.run(); } return AccessController.doPrivileged(mapBuilderAction); } }
nmcl/scratch
graalvm/transactions/fork/narayana/XTS/WS-C/dev/src/com/arjuna/webservices11/util/PrivilegedMapBuilderFactory.java
Java
apache-2.0
1,820
/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ package com.jboss.transaction.wstf.test; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; import com.jboss.transaction.wstf.interop.Sc007TestCase; import com.jboss.transaction.wstf.interop.InteropTestCase; import com.jboss.transaction.wstf.interop.InteropTestSuite; import com.jboss.transaction.wstf.interop.MessageLogging; /** * Class responsible for executing the appropriate JUnit test. * @author kevin */ public class TestRunner { /** * The log message prefix. */ private static final String LOG_MESSAGE_PREFIX = "<log:log xmlns:log=\"http://docs.oasis-open.org/ws-tx/logs/\">" ; /** * The log message suffix. */ private static final String LOG_MESSAGE_SUFFIX = "</log:log>"; /** * The AT test class. */ private static final Class SC007_TEST_CLASS = Sc007TestCase.class ; /** * Execute the specific test against the specified participant. * @param participantURI The URI of the participant. * @param testTimeout The test timeout. * @param asyncTest The asynchronous test flag. * @param testName The name of the test to execute. * @return The test result. */ public static TestResult execute(final String participantURI, final long testTimeout, final boolean asyncTest, final String testName) { MessageLogging.clearThreadLog() ; final Test test ; if (TestConstants.NAME_ALL_TESTS.equals(testName)) { final TestSuite testSuite = new TestSuite() ; testSuite.addTest(new InteropTestSuite(participantURI, testTimeout, asyncTest, SC007_TEST_CLASS)) ; test = testSuite ; } else if (testName.startsWith(TestConstants.PREFIX_TESTS)) { final Class testClass = SC007_TEST_CLASS; try { test = createTest(testClass, participantURI, testTimeout, asyncTest, testName) ; } catch (final Throwable th) { System.err.println("Unexpected error instantiating test class: " + th) ; return null ; } } else { System.err.println("Unidentified test name: " + testName) ; return null ; } MessageLogging.appendThreadLog(LOG_MESSAGE_PREFIX) ; final TestResult testResult = new FullTestResult() ; test.run(testResult) ; MessageLogging.appendThreadLog(LOG_MESSAGE_SUFFIX) ; return testResult ; } /** * Create the test instance. * @param testClass The test class name. * @param participantURI The participant URI. * @param testTimeout The test timeout. * @param asyncTest The asynchronous test flag. * @param testName The test name. * @return The test instance. * @throws IllegalAccessException For access exception instantiating the test class. * @throws InstantiationException For errors instantiating the test class. * @throws IllegalArgumentException For an invalid test class. */ private static TestCase createTest(final Class testClass, final String participantURI, final long testTimeout, final boolean asyncTest, final String testName) throws IllegalAccessException, InstantiationException, IllegalArgumentException { final Object testObject = testClass.newInstance() ; if (testObject instanceof InteropTestCase) { final InteropTestCase interopTestCase = (InteropTestCase)testObject ; interopTestCase.setParticipantURI(participantURI) ; interopTestCase.setTestTimeout(testTimeout) ; interopTestCase.setAsyncTest(asyncTest) ; interopTestCase.setName(testName) ; return interopTestCase ; } else if (testObject instanceof TestCase) { final TestCase test = (TestCase)testObject ; test.setName(testName) ; return test ; } throw new IllegalArgumentException("Invalid class: " + testClass.getName()) ; } }
nmcl/scratch
graalvm/transactions/fork/narayana/XTS/localjunit/WSTFSC07-interop/src/main/java/com/jboss/transaction/wstf/test/TestRunner.java
Java
apache-2.0
5,135
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.sql; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.calcite.util.ZonelessDate; import org.apache.calcite.util.ZonelessTime; import org.apache.calcite.util.ZonelessTimestamp; import java.util.Calendar; import java.util.TimeZone; /** * A SQL literal representing a DATE, TIME or TIMESTAMP value. * * <p>Examples: * * <ul> * <li>DATE '2004-10-22'</li> * <li>TIME '14:33:44.567'</li> * <li><code>TIMESTAMP '1969-07-21 03:15 GMT'</code></li> * </ul> */ abstract class SqlAbstractDateTimeLiteral extends SqlLiteral { //~ Instance fields -------------------------------------------------------- protected final boolean hasTimeZone; protected final String formatString; protected final int precision; //~ Constructors ----------------------------------------------------------- /** * Constructs a datetime literal based on a Calendar. If the literal is to * represent a Timestamp, the Calendar is expected to follow java.sql * semantics. If the Calendar is to represent a Time or Date, the Calendar * is expected to follow {@link org.apache.calcite.util.ZonelessTime} * and {@link org.apache.calcite.util.ZonelessDate} * semantics. */ protected SqlAbstractDateTimeLiteral( Calendar d, boolean tz, SqlTypeName typeName, int precision, String formatString, SqlParserPos pos) { super(d, typeName, pos); this.hasTimeZone = tz; this.precision = precision; this.formatString = formatString; } //~ Methods ---------------------------------------------------------------- public int getPrec() { return precision; } public String toValue() { return Long.toString(getCal().getTimeInMillis()); } public Calendar getCal() { return (Calendar) value; } /** * Returns timezone component of this literal. Technically, a sql date * doesn't come with a tz, but time and ts inherit this, and the calendar * object has one, so it seems harmless. * * @return timezone */ public TimeZone getTimeZone() { assert hasTimeZone : "Attempt to get timezone on Literal date: " + getCal() + ", which has no timezone"; return getCal().getTimeZone(); } /** * Returns e.g. <code>DATE '1969-07-21'</code>. */ public abstract String toString(); /** * Returns e.g. <code>1969-07-21</code>. */ public abstract String toFormattedString(); public RelDataType createSqlType(RelDataTypeFactory typeFactory) { return typeFactory.createSqlType( getTypeName(), getPrec()); } public void unparse( SqlWriter writer, int leftPrec, int rightPrec) { writer.literal(this.toString()); } /** * Converts this literal to a * {@link org.apache.calcite.util.ZonelessDate} object. */ protected ZonelessDate getDate() { ZonelessDate zd = new ZonelessDate(); zd.setZonelessTime(getCal().getTimeInMillis()); return zd; } /** * Converts this literal to a * {@link org.apache.calcite.util.ZonelessTime} object. */ protected ZonelessTime getTime() { ZonelessTime zt = new ZonelessTime(); zt.setZonelessTime(getCal().getTimeInMillis()); return zt; } /** * Converts this literal to a * {@link org.apache.calcite.util.ZonelessTimestamp} object. */ protected ZonelessTimestamp getTimestamp() { ZonelessTimestamp zt = new ZonelessTimestamp(); zt.setZonelessTime(getCal().getTimeInMillis()); return zt; } } // End SqlAbstractDateTimeLiteral.java
YrAuYong/incubator-calcite
core/src/main/java/org/apache/calcite/sql/SqlAbstractDateTimeLiteral.java
Java
apache-2.0
4,501
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.actionSystem; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.PossiblyDumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.util.SmartList; import com.intellij.util.ui.UIUtil; import org.intellij.lang.annotations.JdkConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; /** * Represents an entity that has a state, a presentation and can be performed. * * For an action to be useful, you need to implement {@link AnAction#actionPerformed} * and optionally to override {@link AnAction#update}. By overriding the * {@link AnAction#update} method you can dynamically change action's presentation * depending on the place (for more information on places see {@link com.intellij.openapi.actionSystem.ActionPlaces}. * * The same action can have various presentations. * * <pre> * public class MyAction extends AnAction { * public MyAction() { * // ... * } * * public void update(AnActionEvent e) { * Presentation presentation = e.getPresentation(); * if (e.getPlace().equals(ActionPlaces.MAIN_MENU)) { * presentation.setText("My Menu item name"); * } else if (e.getPlace().equals(ActionPlaces.MAIN_TOOLBAR)) { * presentation.setText("My Toolbar item name"); * } * } * * public void actionPerformed(AnActionEvent e) { ... } * } * </pre> * * @see AnActionEvent * @see Presentation * @see com.intellij.openapi.actionSystem.ActionPlaces */ public abstract class AnAction implements PossiblyDumbAware { private static final Logger LOG = Logger.getInstance(AnAction.class); public static final Key<List<AnAction>> ACTIONS_KEY = Key.create("AnAction.shortcutSet"); public static final AnAction[] EMPTY_ARRAY = new AnAction[0]; private Presentation myTemplatePresentation; private ShortcutSet myShortcutSet; private boolean myEnabledInModalContext; private boolean myIsDefaultIcon = true; private boolean myWorksInInjected; private boolean myIsGlobal; // action is registered in ActionManager /** * Creates a new action with its text, description and icon set to {@code null}. */ public AnAction(){ this(null, null, null); } /** * Creates a new action with {@code icon} provided. Its text, description set to {@code null}. * * @param icon Default icon to appear in toolbars and menus (Note some platform don't have icons in menu). */ public AnAction(Icon icon){ this(null, null, icon); } /** * Creates a new action with the specified text. Description and icon are * set to {@code null}. * * @param text Serves as a tooltip when the presentation is a button and the name of the * menu item when the presentation is a menu item. */ public AnAction(@Nullable String text){ this(text, null, null); } /** * Constructs a new action with the specified text, description and icon. * * @param text Serves as a tooltip when the presentation is a button and the name of the * menu item when the presentation is a menu item * * @param description Describes current action, this description will appear on * the status bar when presentation has focus * * @param icon Action's icon */ public AnAction(@Nullable String text, @Nullable String description, @Nullable Icon icon){ myShortcutSet = CustomShortcutSet.EMPTY; myEnabledInModalContext = false; Presentation presentation = getTemplatePresentation(); presentation.setText(text); presentation.setDescription(description); presentation.setIcon(icon); } /** * Returns the shortcut set associated with this action. * * @return shortcut set associated with this action */ public final ShortcutSet getShortcutSet(){ return myShortcutSet; } /** * Registers a set of shortcuts that will be processed when the specified component * is the ancestor of focused component. Note that the action doesn't have * to be registered in action manager in order for that shortcut to work. * * @param shortcutSet the shortcuts for the action. * @param component the component for which the shortcuts will be active. */ public final void registerCustomShortcutSet(@NotNull ShortcutSet shortcutSet, @Nullable JComponent component) { registerCustomShortcutSet(shortcutSet, component, null); } public final void registerCustomShortcutSet(int keyCode, @JdkConstants.InputEventMask int modifiers, @Nullable JComponent component) { registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(keyCode, modifiers)), component); } public final void registerCustomShortcutSet(@NotNull ShortcutSet shortcutSet, @Nullable JComponent component, @Nullable Disposable parentDisposable) { setShortcutSet(shortcutSet); registerCustomShortcutSet(component, parentDisposable); } public final void registerCustomShortcutSet(@Nullable JComponent component, @Nullable Disposable parentDisposable) { if (component == null) return; List<AnAction> actionList = UIUtil.getClientProperty(component, ACTIONS_KEY); if (actionList == null) { UIUtil.putClientProperty(component, ACTIONS_KEY, actionList = new SmartList<>()); } if (!actionList.contains(this)) { actionList.add(this); } if (parentDisposable != null) { Disposer.register(parentDisposable, () -> unregisterCustomShortcutSet(component)); } } public final void unregisterCustomShortcutSet(@Nullable JComponent component) { List<AnAction> actionList = UIUtil.getClientProperty(component, ACTIONS_KEY); if (actionList != null) { actionList.remove(this); } } /** * Copies template presentation and shortcuts set from {@code sourceAction}. * * @param sourceAction cannot be {@code null} */ public final void copyFrom(@NotNull AnAction sourceAction){ Presentation sourcePresentation = sourceAction.getTemplatePresentation(); Presentation presentation = getTemplatePresentation(); presentation.copyFrom(sourcePresentation); copyShortcutFrom(sourceAction); } public final void copyShortcutFrom(@NotNull AnAction sourceAction) { setShortcutSet(sourceAction.getShortcutSet()); } public final boolean isEnabledInModalContext() { return myEnabledInModalContext; } protected final void setEnabledInModalContext(boolean enabledInModalContext) { myEnabledInModalContext = enabledInModalContext; } /** * Override with true returned if your action has to display its text along with the icon when placed in the toolbar */ public boolean displayTextInToolbar() { return false; } /** * Updates the state of the action. Default implementation does nothing. * Override this method to provide the ability to dynamically change action's * state and(or) presentation depending on the context (For example * when your action state depends on the selection you can check for * selection and change the state accordingly). * This method can be called frequently, for instance, if an action is added to a toolbar, * it will be updated twice a second. This means that this method is supposed to work really fast, * no real work should be done at this phase. For example, checking selection in a tree or a list, * is considered valid, but working with a file system is not. If you cannot understand the state of * the action fast you should do it in the {@link #actionPerformed(AnActionEvent)} method and notify * the user that action cannot be executed if it's the case. * * @param e Carries information on the invocation place and data available */ public void update(AnActionEvent e) { } /** * Same as {@link #update(AnActionEvent)} but is calls immediately before actionPerformed() as final check guard. * Default implementation delegates to {@link #update(AnActionEvent)}. * * @param e Carries information on the invocation place and data available */ public void beforeActionPerformedUpdate(@NotNull AnActionEvent e) { boolean worksInInjected = isInInjectedContext(); e.setInjectedContext(worksInInjected); update(e); if (!e.getPresentation().isEnabled() && worksInInjected) { e.setInjectedContext(false); update(e); } } /** * Returns a template presentation that will be used * as a template for created presentations. * * @return template presentation */ @NotNull public final Presentation getTemplatePresentation() { Presentation presentation = myTemplatePresentation; if (presentation == null){ myTemplatePresentation = presentation = new Presentation(); } return presentation; } /** * Implement this method to provide your action handler. * * @param e Carries information on the invocation place */ public abstract void actionPerformed(AnActionEvent e); protected void setShortcutSet(ShortcutSet shortcutSet) { if (myIsGlobal && myShortcutSet != shortcutSet) { LOG.warn("ShortcutSet of global AnActions should not be changed outside of KeymapManager.\n" + "This is likely not what you wanted to do. Consider setting shortcut in keymap defaults, inheriting from other action " + "using `use-shortcut-of` or wrapping with EmptyAction.wrap().", new Throwable()); } myShortcutSet = shortcutSet; } /** * Sets the flag indicating whether the action has an internal or a user-customized icon. * @param isDefaultIconSet true if the icon is internal, false if the icon is customized by the user. */ public void setDefaultIcon(boolean isDefaultIconSet) { myIsDefaultIcon = isDefaultIconSet; } /** * Returns true if the action has an internal, not user-customized icon. * @return true if the icon is internal, false if the icon is customized by the user. */ public boolean isDefaultIcon() { return myIsDefaultIcon; } /** * Enables automatic detection of injected fragments in editor. Values in DataContext, passed to the action, like EDITOR, PSI_FILE * will refer to an injected fragment, if caret is currently positioned on it. */ public void setInjectedContext(boolean worksInInjected) { myWorksInInjected = worksInInjected; } public boolean isInInjectedContext() { return myWorksInInjected; } public boolean isTransparentUpdate() { return this instanceof TransparentUpdate; } @Override public boolean isDumbAware() { return this instanceof DumbAware; } /** * @return whether this action should be wrapped into a single transaction. PSI/VFS-related actions * that can show progresses or modal dialogs should return true. The default value is false, to prevent * transaction-related assertions from actions in harmless dialogs like "Enter password" shown inside invokeLater. * @see com.intellij.openapi.application.TransactionGuard */ public boolean startInTransaction() { return false; } public interface TransparentUpdate { } @Nullable public static Project getEventProject(AnActionEvent e) { return e == null ? null : e.getData(CommonDataKeys.PROJECT); } @Override public String toString() { return getTemplatePresentation().toString(); } void markAsGlobal() { myIsGlobal = true; } }
vvv1559/intellij-community
platform/editor-ui-api/src/com/intellij/openapi/actionSystem/AnAction.java
Java
apache-2.0
12,200
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file was automatically generated by informer-gen with arguments: --input-dirs=[k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/apis/apiregistration,k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/apis/apiregistration/v1alpha1] --internal-clientset-package=k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/clientset_generated/internalclientset --listers-package=k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/listers --output-package=k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/informers --versioned-clientset-package=k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/clientset_generated/clientset package informers import ( clientset "k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/clientset_generated/clientset" internalclientset "k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/clientset_generated/internalclientset" apiregistration "k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/informers/apiregistration" internalinterfaces "k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/informers/internalinterfaces" cache "k8s.io/kubernetes/pkg/client/cache" runtime "k8s.io/kubernetes/pkg/runtime" reflect "reflect" sync "sync" time "time" ) type sharedInformerFactory struct { internalClient internalclientset.Interface versionedClient clientset.Interface lock sync.Mutex defaultResync time.Duration informers map[reflect.Type]cache.SharedIndexInformer // startedInformers is used for tracking which informers have been started. // This allows Start() to be called multiple times safely. startedInformers map[reflect.Type]bool } // NewSharedInformerFactory constructs a new instance of sharedInformerFactory func NewSharedInformerFactory(internalClient internalclientset.Interface, versionedClient clientset.Interface, defaultResync time.Duration) SharedInformerFactory { return &sharedInformerFactory{ internalClient: internalClient, versionedClient: versionedClient, defaultResync: defaultResync, informers: make(map[reflect.Type]cache.SharedIndexInformer), startedInformers: make(map[reflect.Type]bool), } } // Start initializes all requested informers. func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { f.lock.Lock() defer f.lock.Unlock() for informerType, informer := range f.informers { if !f.startedInformers[informerType] { go informer.Run(stopCh) f.startedInformers[informerType] = true } } } // InternalInformerFor returns the SharedIndexInformer for obj using an internal // client. func (f *sharedInformerFactory) InternalInformerFor(obj runtime.Object, newFunc internalinterfaces.NewInternalInformerFunc) cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() informerType := reflect.TypeOf(obj) informer, exists := f.informers[informerType] if exists { return informer } informer = newFunc(f.internalClient, f.defaultResync) f.informers[informerType] = informer return informer } // VersionedInformerFor returns the SharedIndexInformer for obj using a // versioned client. func (f *sharedInformerFactory) VersionedInformerFor(obj runtime.Object, newFunc internalinterfaces.NewVersionedInformerFunc) cache.SharedIndexInformer { f.lock.Lock() defer f.lock.Unlock() informerType := reflect.TypeOf(obj) informer, exists := f.informers[informerType] if exists { return informer } informer = newFunc(f.versionedClient, f.defaultResync) f.informers[informerType] = informer return informer } // SharedInformerFactory provides shared informers for resources in all known // API group versions. type SharedInformerFactory interface { internalinterfaces.SharedInformerFactory Apiregistration() apiregistration.Interface } func (f *sharedInformerFactory) Apiregistration() apiregistration.Interface { return apiregistration.New(f) }
luomiao/kops
vendor/k8s.io/kubernetes/cmd/kubernetes-discovery/pkg/client/informers/factory.go
GO
apache-2.0
4,393
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.painless.symbol; import org.elasticsearch.painless.lookup.PainlessLookupUtility; import org.objectweb.asm.commons.Method; import java.lang.invoke.MethodType; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * Stores information about functions directly invokable on the generated script class. * Functions marked as internal are generated by lambdas or method references, and are * not directly callable by a user. */ public class FunctionTable { private static final String MANGLED_FUNCTION_NAME_PREFIX = "&"; public static class LocalFunction { protected final String functionName; protected final String mangledName; protected final Class<?> returnType; protected final List<Class<?>> typeParameters; protected final boolean isInternal; protected final boolean isStatic; protected final MethodType methodType; protected final Method asmMethod; public LocalFunction( String functionName, Class<?> returnType, List<Class<?>> typeParameters, boolean isInternal, boolean isStatic) { this(functionName, "", returnType, typeParameters, isInternal, isStatic); } private LocalFunction(String functionName, String mangle, Class<?> returnType, List<Class<?>> typeParameters, boolean isInternal, boolean isStatic) { this.functionName = Objects.requireNonNull(functionName); this.mangledName = Objects.requireNonNull(mangle) + this.functionName; this.returnType = Objects.requireNonNull(returnType); this.typeParameters = Collections.unmodifiableList(Objects.requireNonNull(typeParameters)); this.isInternal = isInternal; this.isStatic = isStatic; Class<?> javaReturnType = PainlessLookupUtility.typeToJavaType(returnType); Class<?>[] javaTypeParameters = typeParameters.stream().map(PainlessLookupUtility::typeToJavaType).toArray(Class<?>[]::new); this.methodType = MethodType.methodType(javaReturnType, javaTypeParameters); this.asmMethod = new org.objectweb.asm.commons.Method(mangledName, MethodType.methodType(javaReturnType, javaTypeParameters).toMethodDescriptorString()); } public String getMangledName() { return mangledName; } public Class<?> getReturnType() { return returnType; } public List<Class<?>> getTypeParameters() { return typeParameters; } public boolean isInternal() { return isInternal; } public boolean isStatic() { return isStatic; } public MethodType getMethodType() { return methodType; } public Method getAsmMethod() { return asmMethod; } } /** * Generates a {@code LocalFunction} key. * @param functionName the name of the {@code LocalFunction} * @param functionArity the number of parameters for the {@code LocalFunction} * @return a {@code LocalFunction} key used for {@code LocalFunction} look up within the {@code FunctionTable} */ public static String buildLocalFunctionKey(String functionName, int functionArity) { return functionName + "/" + functionArity; } protected Map<String, LocalFunction> localFunctions = new HashMap<>(); public LocalFunction addFunction( String functionName, Class<?> returnType, List<Class<?>> typeParameters, boolean isInternal, boolean isStatic) { String functionKey = buildLocalFunctionKey(functionName, typeParameters.size()); LocalFunction function = new LocalFunction(functionName, returnType, typeParameters, isInternal, isStatic); localFunctions.put(functionKey, function); return function; } public LocalFunction addMangledFunction(String functionName, Class<?> returnType, List<Class<?>> typeParameters, boolean isInternal, boolean isStatic) { String functionKey = buildLocalFunctionKey(functionName, typeParameters.size()); LocalFunction function = new LocalFunction(functionName, MANGLED_FUNCTION_NAME_PREFIX, returnType, typeParameters, isInternal, isStatic); localFunctions.put(functionKey, function); return function; } public LocalFunction getFunction(String functionName, int functionArity) { String functionKey = buildLocalFunctionKey(functionName, functionArity); return localFunctions.get(functionKey); } public LocalFunction getFunction(String functionKey) { return localFunctions.get(functionKey); } }
robin13/elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/FunctionTable.java
Java
apache-2.0
5,168
๏ปฟdefine( ({ visible: "ื”ืฆื’ ืžืคืช ื”ืชืžืฆืื•ืช ื›ื‘ืจื™ืจืช ืžื—ื“ืœ", minWidth: "ืจื•ื—ื‘ ืžื™ื ื™ืžืœื™", minHeight: "ื’ื•ื‘ื” ืžื™ื ื™ืžืœื™", maxWidth: "ืื•ืจืš ืžืงืกื™ืžืœื™", maxHeight: "ื’ื•ื‘ื” ืžืงืกื™ืžืœื™", minText: "ืžื™ื ื™ืžื•ื", maxText: "ืžืงืกื™ืžื•ื", attachText: "ืฆื™ื™ืŸ ืœืื™ื–ื• ืคื™ื ื” ืฉืœ ื”ืžืคื” ื™ืฉ ืœื”ืฆืžื™ื“ ื•ื™ื“ื’'ื˜ ื–ื”.", expandText: "ื”ืจื—ื‘ื” ืจืืฉื•ื ื™ืช ืฉืœ ื”ื•ื™ื“ื’'ื˜", topLeft: "ืฆื“ ืฉืžืืœ ืœืžืขืœื”", topRight: "ืฆื“ ื™ืžื™ืŸ ืœืžืขืœื”", bottomLeft: "ืฆื“ ืฉืžืืœ ืœืžื˜ื”", bottomRight: "ืฆื“ ื™ืžื™ืŸ ืœืžื˜ื”" }) );
cob222/CPG
widgets/OverviewMap/setting/nls/he/strings.js
JavaScript
apache-2.0
648
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.viewer.restfulobjects.applib.client; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.google.common.collect.Maps; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.core.BaseClientResponse; import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation; import org.apache.isis.viewer.restfulobjects.applib.util.Parser; public final class RestfulRequest { public enum DomainModel { NONE, SIMPLE, FORMAL, SELECTABLE; public static Parser<DomainModel> parser() { return new Parser<RestfulRequest.DomainModel>() { @Override public DomainModel valueOf(final String str) { return DomainModel.valueOf(str.toUpperCase()); } @Override public String asString(final DomainModel t) { return t.name().toLowerCase(); } }; } @Override public String toString() { return name().toLowerCase(); } } public static class RequestParameter<Q> { public static RequestParameter<List<List<String>>> FOLLOW_LINKS = new RequestParameter<List<List<String>>>("x-ro-follow-links", Parser.forListOfListOfStrings(), Collections.<List<String>> emptyList()); public static RequestParameter<Integer> PAGE = new RequestParameter<Integer>("x-ro-page", Parser.forInteger(), 1); public static RequestParameter<Integer> PAGE_SIZE = new RequestParameter<Integer>("x-ro-page-size", Parser.forInteger(), 25); public static RequestParameter<List<String>> SORT_BY = new RequestParameter<List<String>>("x-ro-sort-by", Parser.forListOfStrings(), Collections.<String> emptyList()); public static RequestParameter<DomainModel> DOMAIN_MODEL = new RequestParameter<DomainModel>("x-ro-domain-model", DomainModel.parser(), DomainModel.FORMAL); public static RequestParameter<Boolean> VALIDATE_ONLY = new RequestParameter<Boolean>("x-ro-validate-only", Parser.forBoolean(), false); private final String name; private final Parser<Q> parser; private final Q defaultValue; private RequestParameter(final String name, final Parser<Q> parser, final Q defaultValue) { this.name = name; this.parser = parser; this.defaultValue = defaultValue; } public String getName() { return name; } public Parser<Q> getParser() { return parser; } public Q valueOf(final JsonRepresentation parameterRepresentation) { if (parameterRepresentation == null) { return defaultValue; } if (!parameterRepresentation.isMap()) { return defaultValue; } final Q parsedValue = getParser().valueOf(parameterRepresentation.getRepresentation(getName())); return parsedValue != null ? parsedValue : defaultValue; } public Q getDefault() { return defaultValue; } @Override public String toString() { return getName(); } } public static class Header<X> { public static Header<String> IF_MATCH = new Header<String>("If-Match", Parser.forString()); public static Header<List<MediaType>> ACCEPT = new Header<List<MediaType>>("Accept", Parser.forListOfJaxRsMediaTypes()); private final String name; private final Parser<X> parser; /** * public visibility for testing purposes only. */ public Header(final String name, final Parser<X> parser) { this.name = name; this.parser = parser; } public String getName() { return name; } public Parser<X> getParser() { return parser; } void setHeader(final ClientRequestConfigurer clientRequestConfigurer, final X t) { clientRequestConfigurer.header(getName(), parser.asString(t)); } @Override public String toString() { return getName(); } } private final ClientRequestConfigurer clientRequestConfigurer; private final Map<RequestParameter<?>, Object> args = Maps.newLinkedHashMap(); public RestfulRequest(final ClientRequestConfigurer clientRequestConfigurer) { this.clientRequestConfigurer = clientRequestConfigurer; } public <T> RestfulRequest withHeader(final Header<T> header, final T t) { header.setHeader(clientRequestConfigurer, t); return this; } public <T> RestfulRequest withHeader(final Header<List<T>> header, final T... ts) { header.setHeader(clientRequestConfigurer, Arrays.asList(ts)); return this; } public <Q> RestfulRequest withArg(final RestfulRequest.RequestParameter<Q> queryParam, final String argStrFormat, final Object... args) { final String argStr = String.format(argStrFormat, args); final Q arg = queryParam.getParser().valueOf(argStr); return withArg(queryParam, arg); } public <Q> RestfulRequest withArg(final RestfulRequest.RequestParameter<Q> queryParam, final Q arg) { args.put(queryParam, arg); return this; } public RestfulResponse<JsonRepresentation> execute() { try { if (!args.isEmpty()) { clientRequestConfigurer.configureArgs(args); } final ClientRequest clientRequest = clientRequestConfigurer.getClientRequest(); final Response response = clientRequest.execute(); // this is a bit hacky @SuppressWarnings("unchecked") final BaseClientResponse<String> restEasyResponse = (BaseClientResponse<String>) response; restEasyResponse.setReturnType(String.class); return RestfulResponse.ofT(response); } catch (final Exception ex) { throw new RuntimeException(ex); } } @SuppressWarnings("unchecked") public <T extends JsonRepresentation> RestfulResponse<T> executeT() { final RestfulResponse<JsonRepresentation> restfulResponse = execute(); return (RestfulResponse<T>) restfulResponse; } /** * For testing only. */ ClientRequestConfigurer getClientRequestConfigurer() { return clientRequestConfigurer; } }
howepeng/isis
core/viewer-restfulobjects-applib/src/main/java/org/apache/isis/viewer/restfulobjects/applib/client/RestfulRequest.java
Java
apache-2.0
7,416
//// [recursiveSpecializationOfSignatures.ts] class S0<B, A> { set S1(S2: S0<any,any>) { } constructor(public S17: S0<any, (S18) => A>) { } } //// [recursiveSpecializationOfSignatures.js] var S0 = /** @class */ (function () { function S0(S17) { this.S17 = S17; } Object.defineProperty(S0.prototype, "S1", { set: function (S2) { }, enumerable: true, configurable: true }); return S0; }());
weswigham/TypeScript
tests/baselines/reference/recursiveSpecializationOfSignatures.js
JavaScript
apache-2.0
467
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.common.protocol.body; import java.util.HashSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.rocketmq.common.consumer.ConsumeFromWhere; import org.apache.rocketmq.common.protocol.heartbeat.ConsumeType; import org.apache.rocketmq.common.protocol.heartbeat.MessageModel; import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData; import org.apache.rocketmq.remoting.protocol.RemotingSerializable; public class ConsumerConnection extends RemotingSerializable { private HashSet<Connection> connectionSet = new HashSet<Connection>(); private ConcurrentMap<String/* Topic */, SubscriptionData> subscriptionTable = new ConcurrentHashMap<String, SubscriptionData>(); private ConsumeType consumeType; private MessageModel messageModel; private ConsumeFromWhere consumeFromWhere; public int computeMinVersion() { int minVersion = Integer.MAX_VALUE; for (Connection c : this.connectionSet) { if (c.getVersion() < minVersion) { minVersion = c.getVersion(); } } return minVersion; } public HashSet<Connection> getConnectionSet() { return connectionSet; } public void setConnectionSet(HashSet<Connection> connectionSet) { this.connectionSet = connectionSet; } public ConcurrentMap<String, SubscriptionData> getSubscriptionTable() { return subscriptionTable; } public void setSubscriptionTable(ConcurrentHashMap<String, SubscriptionData> subscriptionTable) { this.subscriptionTable = subscriptionTable; } public ConsumeType getConsumeType() { return consumeType; } public void setConsumeType(ConsumeType consumeType) { this.consumeType = consumeType; } public MessageModel getMessageModel() { return messageModel; } public void setMessageModel(MessageModel messageModel) { this.messageModel = messageModel; } public ConsumeFromWhere getConsumeFromWhere() { return consumeFromWhere; } public void setConsumeFromWhere(ConsumeFromWhere consumeFromWhere) { this.consumeFromWhere = consumeFromWhere; } }
Vansee/RocketMQ
common/src/main/java/org/apache/rocketmq/common/protocol/body/ConsumerConnection.java
Java
apache-2.0
3,072
//// [parserMemberAccessorDeclaration6.ts] class C { set 0(i) { } } //// [parserMemberAccessorDeclaration6.js] var C = /** @class */ (function () { function C() { } Object.defineProperty(C.prototype, 0, { set: function (i) { }, enumerable: true, configurable: true }); return C; }());
basarat/TypeScript
tests/baselines/reference/parserMemberAccessorDeclaration6.js
JavaScript
apache-2.0
346
//// [inheritance1.ts] class Control { private state: any; } interface SelectableControl extends Control { select(): void; } class Button extends Control implements SelectableControl { select() { } } class TextBox extends Control { select() { } } class ImageBase extends Control implements SelectableControl{ } class Image1 extends Control { } class Locations implements SelectableControl { select() { } } class Locations1 { select() { } } var sc: SelectableControl; var c: Control; var b: Button; sc = b; c = b; b = sc; b = c; var t: TextBox; sc = t; c = t; t = sc; t = c; var i: ImageBase; sc = i; c = i; i = sc; i = c; var i1: Image1; sc = i1; c = i1; i1 = sc; i1 = c; var l: Locations; sc = l; c = l; l = sc; l = c; var l1: Locations1; sc = l1; c = l1; l1 = sc; l1 = c; //// [inheritance1.js] var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Control = (function () { function Control() { } return Control; })(); var Button = (function (_super) { __extends(Button, _super); function Button() { _super.apply(this, arguments); } Button.prototype.select = function () { }; return Button; })(Control); var TextBox = (function (_super) { __extends(TextBox, _super); function TextBox() { _super.apply(this, arguments); } TextBox.prototype.select = function () { }; return TextBox; })(Control); var ImageBase = (function (_super) { __extends(ImageBase, _super); function ImageBase() { _super.apply(this, arguments); } return ImageBase; })(Control); var Image1 = (function (_super) { __extends(Image1, _super); function Image1() { _super.apply(this, arguments); } return Image1; })(Control); var Locations = (function () { function Locations() { } Locations.prototype.select = function () { }; return Locations; })(); var Locations1 = (function () { function Locations1() { } Locations1.prototype.select = function () { }; return Locations1; })(); var sc; var c; var b; sc = b; c = b; b = sc; b = c; var t; sc = t; c = t; t = sc; t = c; var i; sc = i; c = i; i = sc; i = c; var i1; sc = i1; c = i1; i1 = sc; i1 = c; var l; sc = l; c = l; l = sc; l = c; var l1; sc = l1; c = l1; l1 = sc; l1 = c;
ivogabe/TypeScript
tests/baselines/reference/inheritance1.js
JavaScript
apache-2.0
2,552
""" * Copyright 2007 Google Inc. # Copyright (C) 2009 Luke Kenneth Casson Leighton <[email protected]> * * 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. """ """* * Font size enumeration. Represents the seven basic HTML font sizes, as * defined in CSS. """ XX_SMALL = 1 X_SMALL = 2 SMALL = 3 MEDIUM = 4 LARGE = 5 X_LARGE = 6 XX_LARGE = 7 """* * Justification enumeration. The three values are <code>left</code>, * <code>right</code>, <code>center</code>. """ CENTER = "Center" LEFT = "Left" RIGHT = "Right"
spaceone/pyjs
pyjswidgets/pyjamas/ui/RichTextAreaConsts.py
Python
apache-2.0
998
package start import ( "crypto/tls" "crypto/x509/pkix" "fmt" "io/ioutil" "os" "path/filepath" "time" "github.com/golang/glog" kapi "k8s.io/kubernetes/pkg/api" kerrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/apis/certificates" kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" utilcert "k8s.io/kubernetes/pkg/util/cert" "k8s.io/kubernetes/pkg/util/wait" "crypto/rsa" configapilatest "github.com/openshift/origin/pkg/cmd/server/api/latest" "github.com/openshift/origin/pkg/cmd/server/crypto" ) // hasCSRCondition returns the first matching condition with the given type or nil. func hasCSRCondition(conditions []certificates.CertificateSigningRequestCondition, t certificates.RequestConditionType) *certificates.CertificateSigningRequestCondition { for i := range conditions { if conditions[i].Type == t { return &conditions[i] } } return nil } // readOrCreatePrivateKey attempts to read an rsa private key from the provided path, // or if that fails, to generate a new private key. func readOrCreatePrivateKey(path string) (*rsa.PrivateKey, error) { if data, err := ioutil.ReadFile(path); err == nil { if key, err := utilcert.ParsePrivateKeyPEM(data); err == nil { if pkey, ok := key.(*rsa.PrivateKey); ok { return pkey, nil } } } return utilcert.NewPrivateKey() } // loadBootstrapClientCertificate attempts to read a node.kubeconfig file from the config dir, // and otherwise tries to request a client certificate as a node (system:node:NODE_NAME). It will // reuse a private key if one exists, and exit with an error if the CSR is not completed within // timeout or if the current CSR does not validate against the local private key. func (o NodeOptions) loadBootstrapClientCertificate(nodeConfigDir string, c kclientset.Interface, timeout time.Duration) (kclientset.Interface, error) { nodeConfigPath := filepath.Join(nodeConfigDir, "node.kubeconfig") // if the node config exists, try to use it or fail if _, err := os.Stat(nodeConfigPath); err == nil { kubeClientConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(&clientcmd.ClientConfigLoadingRules{ExplicitPath: nodeConfigPath}, &clientcmd.ConfigOverrides{}).ClientConfig() if err != nil { return nil, err } return kclientset.NewForConfig(kubeClientConfig) } clientCertPath := filepath.Join(nodeConfigDir, "master-client.crt") clientKeyPath := filepath.Join(nodeConfigDir, "master-client.key") // create and sign a client cert privateKey, err := readOrCreatePrivateKey(clientKeyPath) if err != nil { return nil, err } privateKeyData := utilcert.EncodePrivateKeyPEM(privateKey) csrData, err := utilcert.MakeCSR(privateKey, &pkix.Name{ Organization: []string{"system:nodes"}, CommonName: fmt.Sprintf("system:node:%s", o.NodeArgs.NodeName), // TODO: indicate usage for client }, nil, nil) if err != nil { return nil, err } signingRequest := &certificates.CertificateSigningRequest{ ObjectMeta: kapi.ObjectMeta{ Name: fmt.Sprintf("node-bootstrapper-client-%s", safeSecretName(o.NodeArgs.NodeName)), }, Spec: certificates.CertificateSigningRequestSpec{ Request: csrData, }, } csr, err := c.Certificates().CertificateSigningRequests().Create(signingRequest) if err != nil { if !kerrors.IsAlreadyExists(err) { return nil, err } glog.V(3).Infof("Bootstrap client certificate already exists at %s", signingRequest.Name) csr, err = c.Certificates().CertificateSigningRequests().Get(signingRequest.Name) if err != nil { return nil, err } } if err := ioutil.WriteFile(clientKeyPath, privateKeyData, 0600); err != nil { return nil, err } err = wait.PollImmediate(1*time.Second, timeout, func() (bool, error) { if deny := hasCSRCondition(csr.Status.Conditions, certificates.CertificateDenied); deny != nil { glog.V(2).Infof("Bootstrap signing rejected (%s): %s", deny.Reason, deny.Message) return false, fmt.Errorf("certificate signing request rejected (%s): %s", deny.Reason, deny.Message) } if approved := hasCSRCondition(csr.Status.Conditions, certificates.CertificateApproved); approved != nil { glog.V(2).Infof("Bootstrap client cert approved") return true, nil } csr, err = c.Certificates().CertificateSigningRequests().Get(csr.Name) return false, err }) if err != nil { return nil, err } if err := ioutil.WriteFile(clientCertPath, csr.Status.Certificate, 0600); err != nil { return nil, err } if _, err := tls.LoadX509KeyPair(clientCertPath, clientKeyPath); err != nil { return nil, fmt.Errorf("bootstrap client certificate does not match private key, you may need to delete the client CSR: %v", err) } // write a kube config file for the node that contains the client cert cfg, err := o.NodeArgs.KubeConnectionArgs.ClientConfig.RawConfig() if err != nil { return nil, err } if err := clientcmdapi.MinifyConfig(&cfg); err != nil { return nil, err } ctx := cfg.Contexts[cfg.CurrentContext] if len(ctx.AuthInfo) == 0 { ctx.AuthInfo = "bootstrap" } cfg.AuthInfos = map[string]*clientcmdapi.AuthInfo{ ctx.AuthInfo: { ClientCertificateData: csr.Status.Certificate, ClientKeyData: privateKeyData, }, } if err := clientcmd.WriteToFile(cfg, nodeConfigPath); err != nil { return nil, err } kubeClientConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(&clientcmd.ClientConfigLoadingRules{ExplicitPath: nodeConfigPath}, &clientcmd.ConfigOverrides{}).ClientConfig() if err != nil { return nil, err } return kclientset.NewForConfig(kubeClientConfig) } // loadBootstrapServerCertificate attempts to read a server certificate file from the config dir, // and otherwise tries to request a server certificate for its registered addresses. It will // reuse a private key if one exists, and exit with an error if the CSR is not completed within // timeout or if the current CSR does not validate against the local private key. func (o NodeOptions) loadBootstrapServerCertificate(nodeConfigDir string, hostnames []string, c kclientset.Interface, timeout time.Duration) error { serverCertPath := filepath.Join(nodeConfigDir, "server.crt") serverKeyPath := filepath.Join(nodeConfigDir, "server.key") if _, err := os.Stat(serverCertPath); err == nil { if _, err := os.Stat(serverKeyPath); err == nil { if _, err := tls.LoadX509KeyPair(serverCertPath, serverKeyPath); err != nil { return fmt.Errorf("bootstrap server certificate does not match private key: %v", err) } // continue return nil } } privateKey, err := readOrCreatePrivateKey(serverKeyPath) if err != nil { return err } privateKeyData := utilcert.EncodePrivateKeyPEM(privateKey) ipAddresses, dnsNames := crypto.IPAddressesDNSNames(hostnames) csrData, err := utilcert.MakeCSR(privateKey, &pkix.Name{ CommonName: dnsNames[0], // TODO: indicate usage for server }, dnsNames, ipAddresses) if err != nil { return err } signingRequest := &certificates.CertificateSigningRequest{ ObjectMeta: kapi.ObjectMeta{ Name: fmt.Sprintf("node-bootstrapper-server-%s", safeSecretName(o.NodeArgs.NodeName)), }, Spec: certificates.CertificateSigningRequestSpec{ Request: csrData, }, } csr, err := c.Certificates().CertificateSigningRequests().Create(signingRequest) if err != nil { if !kerrors.IsAlreadyExists(err) { return err } glog.V(3).Infof("Bootstrap server certificate already exists at %s", signingRequest.Name) csr, err = c.Certificates().CertificateSigningRequests().Get(signingRequest.Name) if err != nil { return err } } if err := ioutil.WriteFile(serverKeyPath, privateKeyData, 0600); err != nil { return err } err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) { if deny := hasCSRCondition(csr.Status.Conditions, certificates.CertificateDenied); deny != nil { glog.V(2).Infof("Bootstrap signing rejected (%s): %s", deny.Reason, deny.Message) return false, fmt.Errorf("certificate signing request rejected (%s): %s", deny.Reason, deny.Message) } if approved := hasCSRCondition(csr.Status.Conditions, certificates.CertificateApproved); approved != nil { glog.V(2).Infof("Bootstrap serving cert approved") return true, nil } csr, err = c.Certificates().CertificateSigningRequests().Get(csr.Name) return false, err }) if err != nil { return err } if err := ioutil.WriteFile(serverCertPath, csr.Status.Certificate, 0600); err != nil { return err } if _, err := tls.LoadX509KeyPair(serverCertPath, serverKeyPath); err != nil { return fmt.Errorf("bootstrap server certificate does not match private key, you may need to delete the server CSR: %v", err) } return nil } // loadBootstrap attempts to ensure a bootstrap configuration exists inside the node config dir // by contacting the server and requesting a client and server certificate. If successful, it // will attempt to download a node config file from namespace openshift-infra from the node-config // ConfigMap. If no configuration is found, a new node config will be generated from the arguments // and used instead. If no error is returned, nodeConfigDir can be used as a valid node configuration. func (o NodeOptions) loadBootstrap(hostnames []string, nodeConfigDir string) error { if err := os.MkdirAll(nodeConfigDir, 0700); err != nil { return err } kubeClientConfig, err := o.NodeArgs.KubeConnectionArgs.ClientConfig.ClientConfig() if err != nil { return err } var c kclientset.Interface c, err = kclientset.NewForConfig(kubeClientConfig) if err != nil { return err } glog.Infof("Bootstrapping from API server %s (experimental)", kubeClientConfig.Host) c, err = o.loadBootstrapClientCertificate(nodeConfigDir, c, 1*time.Minute) if err != nil { return err } if err := o.loadBootstrapServerCertificate(nodeConfigDir, hostnames, c, 1*time.Minute); err != nil { return err } nodeClientCAPath := filepath.Join(nodeConfigDir, "node-client-ca.crt") if len(kubeClientConfig.CAData) > 0 { if err := ioutil.WriteFile(nodeClientCAPath, []byte(kubeClientConfig.CAData), 0600); err != nil { return err } } // try to refresh the latest node-config.yaml o.ConfigFile = filepath.Join(nodeConfigDir, "node-config.yaml") config, err := c.Core().ConfigMaps("openshift-infra").Get("node-config") if err == nil { // skip all the config we generated ourselves skipConfig := map[string]struct{}{"server.crt": {}, "server.key": {}, "master-client.crt": {}, "master-client.key": {}, "node.kubeconfig": {}} for k, v := range config.Data { if _, ok := skipConfig[k]; ok { continue } b := []byte(v) // if a node config is provided, override the setup. if k == "node-config.yaml" { if err := ioutil.WriteFile(o.ConfigFile, []byte(v), 0600); err != nil { return err } nodeConfig, err := configapilatest.ReadNodeConfig(o.ConfigFile) if err != nil { return err } if err := o.NodeArgs.MergeSerializeableNodeConfig(nodeConfig); err != nil { return err } nodeConfig.ServingInfo.ServerCert.CertFile = filepath.Join(nodeConfigDir, "server.crt") nodeConfig.ServingInfo.ServerCert.KeyFile = filepath.Join(nodeConfigDir, "server.key") nodeConfig.ServingInfo.ClientCA = nodeClientCAPath nodeConfig.MasterKubeConfig = filepath.Join(nodeConfigDir, "node.kubeconfig") b, err = configapilatest.WriteYAML(nodeConfig) if err != nil { return err } } if err := ioutil.WriteFile(filepath.Join(nodeConfigDir, k), b, 0600); err != nil { return err } } glog.V(3).Infof("Received %d bootstrap files into %s", len(config.Data), nodeConfigDir) } // if we had a previous node-config.yaml, continue using it if _, err2 := os.Stat(o.ConfigFile); err2 == nil { if err == nil { glog.V(2).Infof("Unable to load node configuration from the server: %v", err) } return nil } // if there is no node-config.yaml and no server config map, generate one if kerrors.IsNotFound(err) { glog.V(2).Infof("Generating a local configuration since no server config available") nodeConfig, err := o.NodeArgs.BuildSerializeableNodeConfig() if err != nil { return err } if err := o.NodeArgs.MergeSerializeableNodeConfig(nodeConfig); err != nil { return err } nodeConfig.ServingInfo.ServerCert.CertFile = "server.crt" nodeConfig.ServingInfo.ServerCert.KeyFile = "server.key" nodeConfig.ServingInfo.ClientCA = "node-client-ca.crt" nodeConfig.MasterKubeConfig = "node.kubeconfig" b, err := configapilatest.WriteYAML(nodeConfig) if err != nil { return err } if err := ioutil.WriteFile(o.ConfigFile, b, 0600); err != nil { return err } return nil } return err }
rawlingsj/gofabric8
vendor/github.com/openshift/origin/pkg/cmd/server/start/bootstrap_node.go
GO
apache-2.0
12,831
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.kafka.serialize; import org.apache.avro.generic.GenericRecord; import org.apache.kafka.common.errors.SerializationException; import org.apache.kafka.common.serialization.Serializer; /** * LinkedIn's implementation of Avro-schema based serialization for Kafka * TODO: Implement this for IndexedRecord not just GenericRecord * */ public class LiAvroSerializer extends LiAvroSerializerBase implements Serializer<GenericRecord> { @Override public byte[] serialize(String topic, GenericRecord data) { try { return super.serialize(topic, data); } catch (org.apache.gobblin.kafka.serialize.SerializationException e) { throw new SerializationException(e); } } }
shirshanka/gobblin
gobblin-modules/gobblin-kafka-09/src/main/java/org/apache/gobblin/kafka/serialize/LiAvroSerializer.java
Java
apache-2.0
1,521