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 |
|---|---|---|---|---|---|
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
# Relative path conversion top directories.
SET(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/alexander/projects/natural_editor")
SET(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/alexander/projects/natural_editor/build")
# Force unix paths in dependencies.
SET(CMAKE_FORCE_UNIX_PATHS 1)
# The C and CXX include file regular expressions for this directory.
SET(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$")
SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$")
SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})
SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
| alexandrustaetu/natural_editor | build_bak/external/freetype-2.5.2/CMakeFiles/CMakeDirectoryInformation.cmake | CMake | mit | 659 |
// ==========================================
// RECESS
// RULE: .js prefixes should not be styled
// ==========================================
// Copyright 2012 Twitter, Inc
// Licensed under the Apache License v2.0
// http://www.apache.org/licenses/LICENSE-2.0
// ==========================================
'use strict'
var util = require('../util')
, RULE = {
type: 'noJSPrefix'
, exp: /^\.js\-/
, message: '.js prefixes should not be styled'
}
// validation method
module.exports = function (def, data) {
// default validation to true
var isValid = true
// return if no selector to validate
if (!def.selectors) return isValid
// loop over selectors
def.selectors.forEach(function (selector) {
// loop over selector entities
selector.elements.forEach(function (element) {
var extract
// continue to next element if .js- prefix not styled
if (!RULE.exp.test(element.value)) return
// calculate line number for the extract
extract = util.getLine(element.index - element.value.length, data)
extract = util.padLine(extract)
// highlight invalid styling of .js- prefix
extract += element.value.replace(RULE.exp, '.js-'.magenta)
// set invalid flag to false
isValid = false
// set error object on defintion token
util.throwError(def, {
type: RULE.type
, message: RULE.message
, extract: extract
})
})
})
// return valid state
return isValid
} | jdsimcoe/briansimcoe | workspace/grunt/node_modules/grunt-recess/node_modules/recess/lib/lint/no-JS-prefix.js | JavaScript | mit | 1,504 |
Refinery::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end
| Vizzuality/methanehydrates | config/environments/test.rb | Ruby | mit | 1,512 |
/*=============================================================================
Copyright (c) 2001-2014 Joel de Guzman
Copyright (c) 2001-2011 Hartmut Kaiser
Copyright (c) 2010 Bryce Lelbach
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
================================================_==============================*/
#if !defined(BOOST_SPIRIT_X3_STRING_TRAITS_OCTOBER_2008_1252PM)
#define BOOST_SPIRIT_X3_STRING_TRAITS_OCTOBER_2008_1252PM
#include <string>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/identity.hpp>
namespace boost { namespace spirit { namespace x3 { namespace traits
{
///////////////////////////////////////////////////////////////////////////
// Determine if T is a character type
///////////////////////////////////////////////////////////////////////////
template <typename T>
struct is_char : mpl::false_ {};
template <typename T>
struct is_char<T const> : is_char<T> {};
template <>
struct is_char<char> : mpl::true_ {};
template <>
struct is_char<wchar_t> : mpl::true_ {};
///////////////////////////////////////////////////////////////////////////
// Determine if T is a string
///////////////////////////////////////////////////////////////////////////
template <typename T>
struct is_string : mpl::false_ {};
template <typename T>
struct is_string<T const> : is_string<T> {};
template <>
struct is_string<char const*> : mpl::true_ {};
template <>
struct is_string<wchar_t const*> : mpl::true_ {};
template <>
struct is_string<char*> : mpl::true_ {};
template <>
struct is_string<wchar_t*> : mpl::true_ {};
template <std::size_t N>
struct is_string<char[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<wchar_t[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<char const[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<wchar_t const[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<char(&)[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<wchar_t(&)[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<char const(&)[N]> : mpl::true_ {};
template <std::size_t N>
struct is_string<wchar_t const(&)[N]> : mpl::true_ {};
template <typename T, typename Traits, typename Allocator>
struct is_string<std::basic_string<T, Traits, Allocator> > : mpl::true_ {};
///////////////////////////////////////////////////////////////////////////
// Get the underlying char type of a string
///////////////////////////////////////////////////////////////////////////
template <typename T>
struct char_type_of;
template <typename T>
struct char_type_of<T const> : char_type_of<T> {};
template <>
struct char_type_of<char> : mpl::identity<char> {};
template <>
struct char_type_of<wchar_t> : mpl::identity<wchar_t> {};
template <>
struct char_type_of<char const*> : mpl::identity<char const> {};
template <>
struct char_type_of<wchar_t const*> : mpl::identity<wchar_t const> {};
template <>
struct char_type_of<char*> : mpl::identity<char> {};
template <>
struct char_type_of<wchar_t*> : mpl::identity<wchar_t> {};
template <std::size_t N>
struct char_type_of<char[N]> : mpl::identity<char> {};
template <std::size_t N>
struct char_type_of<wchar_t[N]> : mpl::identity<wchar_t> {};
template <std::size_t N>
struct char_type_of<char const[N]> : mpl::identity<char const> {};
template <std::size_t N>
struct char_type_of<wchar_t const[N]> : mpl::identity<wchar_t const> {};
template <std::size_t N>
struct char_type_of<char(&)[N]> : mpl::identity<char> {};
template <std::size_t N>
struct char_type_of<wchar_t(&)[N]> : mpl::identity<wchar_t> {};
template <std::size_t N>
struct char_type_of<char const(&)[N]> : mpl::identity<char const> {};
template <std::size_t N>
struct char_type_of<wchar_t const(&)[N]> : mpl::identity<wchar_t const> {};
template <typename T, typename Traits, typename Allocator>
struct char_type_of<std::basic_string<T, Traits, Allocator> >
: mpl::identity<T> {};
///////////////////////////////////////////////////////////////////////////
// Get the C string from a string
///////////////////////////////////////////////////////////////////////////
template <typename String>
struct extract_c_string;
template <typename String>
struct extract_c_string
{
typedef typename char_type_of<String>::type char_type;
template <typename T>
static T const* call (T* str)
{
return (T const*)str;
}
template <typename T>
static T const* call (T const* str)
{
return str;
}
};
// Forwarder that strips const
template <typename T>
struct extract_c_string<T const>
{
typedef typename extract_c_string<T>::char_type char_type;
static typename extract_c_string<T>::char_type const* call (T const str)
{
return extract_c_string<T>::call(str);
}
};
// Forwarder that strips references
template <typename T>
struct extract_c_string<T&>
{
typedef typename extract_c_string<T>::char_type char_type;
static typename extract_c_string<T>::char_type const* call (T& str)
{
return extract_c_string<T>::call(str);
}
};
// Forwarder that strips const references
template <typename T>
struct extract_c_string<T const&>
{
typedef typename extract_c_string<T>::char_type char_type;
static typename extract_c_string<T>::char_type const* call (T const& str)
{
return extract_c_string<T>::call(str);
}
};
template <typename T, typename Traits, typename Allocator>
struct extract_c_string<std::basic_string<T, Traits, Allocator> >
{
typedef T char_type;
typedef std::basic_string<T, Traits, Allocator> string;
static T const* call (string const& str)
{
return str.c_str();
}
};
template <typename T>
typename extract_c_string<T*>::char_type const*
get_c_string(T* str)
{
return extract_c_string<T*>::call(str);
}
template <typename T>
typename extract_c_string<T const*>::char_type const*
get_c_string(T const* str)
{
return extract_c_string<T const*>::call(str);
}
template <typename String>
typename extract_c_string<String>::char_type const*
get_c_string(String& str)
{
return extract_c_string<String>::call(str);
}
template <typename String>
typename extract_c_string<String>::char_type const*
get_c_string(String const& str)
{
return extract_c_string<String>::call(str);
}
///////////////////////////////////////////////////////////////////////////
// Get the begin/end iterators from a string
///////////////////////////////////////////////////////////////////////////
// Implementation for C-style strings.
template <typename T>
inline T const* get_string_begin(T const* str) { return str; }
template <typename T>
inline T* get_string_begin(T* str) { return str; }
template <typename T>
inline T const* get_string_end(T const* str)
{
T const* last = str;
while (*last)
last++;
return last;
}
template <typename T>
inline T* get_string_end(T* str)
{
T* last = str;
while (*last)
last++;
return last;
}
// Implementation for containers (includes basic_string).
template <typename T, typename Str>
inline typename Str::const_iterator get_string_begin(Str const& str)
{ return str.begin(); }
template <typename T, typename Str>
inline typename Str::iterator
get_string_begin(Str& str)
{ return str.begin(); }
template <typename T, typename Str>
inline typename Str::const_iterator get_string_end(Str const& str)
{ return str.end(); }
template <typename T, typename Str>
inline typename Str::iterator
get_string_end(Str& str)
{ return str.end(); }
}}}}
#endif
| nginnever/zogminer | tests/deps/boost/spirit/home/x3/support/traits/string_traits.hpp | C++ | mit | 8,750 |
function pointers
=================
syntax
------
C's syntax for function pointers is downright horrible.
void (*(*f())(void (*)(void)))(void);
That would be simply written in ooc as
f: func -> Func(Func) -> Func
ie. a function that returns a pointer to a function taking a function
and returning another function.
The difference between
f: func
and
f: Func
Is that the first defines an empty function, the latter defines
a pointer to a function. Apart from that, the syntax is pretty similar, ie.
let's say you have a
f: func (a, b: Int) -> Int
its type is
Func (Int, Int) -> Int
Generic type arguments are also legal, e.g.
print: func <K> (k: K)
which type is
Func <K> (K)
You can have variadic functions too, e.g.
print: func (fmt: String, ...) -> Int
which type is
Func (String, ...)
AST
---
'Func' declarations result in a FuncType.
For the following declaration:
Func <A, B> (C, D) -> E
A, B are its 'typeArgs' (of type VariableAccess)
C, D are its 'argTypes' (of type Type)
E is its 'returnType' (of type Type)
C typedefs
----------
In j/ooc we used to write the C syntax for function pointers in the generated
C code. But that was awful.
So now we just add typedefs like that:
#ifndef __FUNC___Int_Int_Int__DEFINE
#define __FUNC___Int_Int_Int__DEFINE
typedef lang_types__Int (*__FUNC___Int_Int_Int)(lang_types__Int, lang_types__Int);
#endif
The name '__FUNC___Int_Int_Int' is obtained via FuncType's toMangledString() method
| ooc-lang/rock | docs/internals/FuncType.md | Markdown | mit | 1,577 |
module.exports.twitter = function twitter(username) {
// Creates the canonical twitter URL without the '@'
return 'https://twitter.com/' + username.replace(/^@/, '');
};
module.exports.facebook = function facebook(username) {
// Handles a starting slash, this shouldn't happen, but just in case
return 'https://www.facebook.com/' + username.replace(/^\//, '');
};
| EdwardStudy/myghostblog | versions/2.16.4/core/server/lib/social/urls.js | JavaScript | mit | 381 |
# CentOS
CentOS Linux is a community-supported distribution derived from sources freely provided to the public by [Red Hat](ftp://ftp.redhat.com/pub/redhat/linux/enterprise/) for Red Hat Enterprise Linux (RHEL). As such, CentOS Linux aims to be functionally compatible with RHEL. The CentOS Project mainly changes packages to remove upstream vendor branding and artwork. CentOS Linux is no-cost and free to redistribute. Each CentOS Linux version is maintained for up to 10 years (by means of security updates -- the duration of the support interval by Red Hat has varied over time with respect to Sources released). A new CentOS Linux version is released approximately every 2 years and each CentOS Linux version is periodically updated (roughly every 6 months) to support newer hardware. This results in a secure, low-maintenance, reliable, predictable, and reproducible Linux environment.
> [wiki.centos.org](https://wiki.centos.org/FrontPage)
%%LOGO%%
# CentOS image documentation
The `%%IMAGE%%:latest` tag is always the most recent version currently available.
## Rolling builds
The CentOS Project offers regularly updated images for all active releases. These images will be updated monthly or as needed for emergency fixes. These rolling updates are tagged with the major version number only. For example: `docker pull %%IMAGE%%:6` or `docker pull %%IMAGE%%:7`
## Minor tags
Additionally, images with minor version tags that correspond to install media are also offered. **These images DO NOT receive updates** as they are intended to match installation iso contents. If you choose to use these images it is highly recommended that you include `RUN yum -y update && yum clean all` in your Dockerfile, or otherwise address any potential security concerns. To use these images, please specify the minor version tag:
For example: `docker pull %%IMAGE%%:5.11` or `docker pull %%IMAGE%%:6.6`
## Overlayfs and yum
Recent Docker versions support the [overlayfs](https://docs.docker.com/engine/userguide/storagedriver/overlayfs-driver/) backend, which is enabled by default on most distros supporting it from Docker 1.13 onwards. On Centos 6 and 7, **that backend requires yum-plugin-ovl to be installed and enabled**; while it is installed by default in recent %%IMAGE%% images, make it sure you retain the `plugins=1` option in `/etc/yum.conf` if you update that file; otherwise, you may encounter errors related to rpmdb checksum failure - see [Docker ticket 10180](https://github.com/docker/docker/issues/10180) for more details.
# Package documentation
By default, the CentOS containers are built using yum's `nodocs` option, which helps reduce the size of the image. If you install a package and discover files missing, please comment out the line `tsflags=nodocs` in `/etc/yum.conf` and reinstall your package.
# Systemd integration
Systemd is now included in both the %%IMAGE%%:7 and %%IMAGE%%:latest base containers, but it is not active by default. In order to use systemd, you will need to include text similar to the example Dockerfile below:
## Dockerfile for systemd base image
```dockerfile
FROM %%IMAGE%%:7
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/usr/sbin/init"]
```
This Dockerfile deletes a number of unit files which might cause issues. From here, you are ready to build your base image.
```console
$ docker build --rm -t local/c7-systemd .
```
## Example systemd enabled app container
In order to use the systemd enabled base container created above, you will need to create your `Dockerfile` similar to the one below.
```dockerfile
FROM local/c7-systemd
RUN yum -y install httpd; yum clean all; systemctl enable httpd.service
EXPOSE 80
CMD ["/usr/sbin/init"]
```
Build this image:
```console
$ docker build --rm -t local/c7-systemd-httpd .
```
## Running a systemd enabled app container
In order to run a container with systemd, you will need to mount the cgroups volumes from the host. Below is an example command that will run the systemd enabled httpd container created earlier.
```console
$ docker run -ti -v /sys/fs/cgroup:/sys/fs/cgroup:ro -p 80:80 local/c7-systemd-httpd
```
This container is running with systemd in a limited context, with the cgroups filesystem mounted. There have been reports that if you're using an Ubuntu host, you will need to add `-v /tmp/$(mktemp -d):/run` in addition to the cgroups mount.
## A note about vsyscall
CentOS 6 binaries and/or libraries are built to expect some system calls to be accessed via `vsyscall` mappings. Some linux distributions have opted to disable `vsyscall` entirely (opting exclusively for more secure `vdso` mappings), causing segmentation faults.
If running `docker run --rm -it centos:centos6.7 bash` immediately exits with status code `139`, check to see if your system has disabled vsyscall:
```console
$ cat /proc/self/maps | egrep 'vdso|vsyscall'
7fffccfcc000-7fffccfce000 r-xp 00000000 00:00 0 [vdso]
$
```
vs
```console
$ cat /proc/self/maps | egrep 'vdso|vsyscall'
7fffe03fe000-7fffe0400000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
```
If you do not see a `vsyscall` mapping, and you need to run a CentOS 6 container, try adding `vsyscall=emulated` to the kernel options in your bootloader
Further reading : [lwn.net](https://lwn.net/Articles/446528/)
| crate/docker-docs | centos/content.md | Markdown | mit | 5,914 |
var utils = exports;
var uglify = require('uglify-js');
utils.extend = function extend(target, source) {
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
};
utils.beautify = function beautify(code) {
var ast = uglify.parser.parse(code);
return uglify.uglify.gen_code(ast, { beautify: true });
};
utils.expressionify = function expressionify(code) {
try {
var ast = uglify.parser.parse('(function(){\n' + code + '\n})');
} catch(e) {
console.error(e.message + ' on ' + (e.line - 1) + ':' + e.pos);
console.error('in');
console.error(code);
throw e;
}
ast[1] = ast[1][0][1][3];
function traverse(ast) {
if (!Array.isArray(ast)) return ast;
switch (ast[0]) {
case 'toplevel':
if (ast[1].length === 1 && ast[1][0][0] !== 'block') {
return ast;
} else {
var children = ast[1][0][0] === 'block' ? ast[1][0][1] : ast[1];
return ['toplevel', [[
'call', [
'dot', [
'function', null, [],
children.map(function(child, i, children) {
return (i == children.length - 1) ? traverse(child) : child;
})
],
'call'
],
[ ['name', 'this'] ]
]]];
}
case 'block':
// Empty blocks can't be processed
if (ast[1].length <= 0) return ast;
var last = ast[1][ast[1].length - 1];
return [
ast[0],
ast[1].slice(0, -1).concat([traverse(last)])
];
case 'while':
case 'for':
case 'switch':
return ast;
case 'if':
return [
'if',
ast[1],
traverse(ast[2]),
traverse(ast[3])
];
case 'stat':
return [
'stat',
traverse(ast[1])
];
default:
if (ast[0] === 'return') return ast;
return [
'return',
ast
]
}
return ast;
}
return uglify.uglify.gen_code(traverse(ast)).replace(/;$/, '');
};
utils.localify = function localify(code, id) {
var ast = uglify.parser.parse(code);
if (ast[1].length !== 1 || ast[1][0][0] !== 'stat') {
throw new TypeError('Incorrect code for local: ' + code);
}
var vars = [],
set = [],
unset = [];
function traverse(node) {
if (node[0] === 'assign') {
if (node[1] !== true) {
throw new TypeError('Incorrect assignment in local');
}
if (node[2][0] === 'dot' || node[2][0] === 'sub') {
var host = ['name', '$l' + id++];
vars.push(host[1]);
set.push(['assign', true, host, node[2][1]]);
node[2][1] = host;
if (node[2][0] === 'sub') {
var property = ['name', '$l' + id++];
vars.push(property[1]);
set.push(['assign', true, property, node[2][2]]);
node[2][2] = property;
}
}
var target = ['name', '$l' + id++];
vars.push(target[1]);
set.push(['assign', true, target, node[2]]);
set.push(['assign', true, node[2], node[3]]);
unset.push(['assign', true, node[2], target]);
} else if (node[0] === 'seq') {
traverse(node[1]);
traverse(node[2]);
} else {
throw new TypeError(
'Incorrect code for local (' + node[0] + '): ' + code
);
}
}
traverse(ast[1][0][1]);
function generate(seqs) {
return uglify.uglify.gen_code(seqs.reduce(function (current, acc) {
return ['seq', current, acc];
}));
}
return {
vars: vars,
before: generate(set.concat([['name', 'true']])),
afterSuccess: generate(unset.concat([['name', 'true']])),
afterFail: generate(unset.concat([['name', 'false']]))
};
};
utils.merge = function merge(a, b) {
Object.keys(b).forEach(function(key) {
a[key] = b[key];
});
};
| CoderPuppy/loke-lang | node_modules/ometajs/lib/ometajs/utils.js | JavaScript | mit | 3,898 |
//
// header.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef HTTP_SERVER3_HEADER_HPP
#define HTTP_SERVER3_HEADER_HPP
#include <string>
namespace http {
namespace server3 {
struct header
{
std::string name;
std::string value;
};
} // namespace server3
} // namespace http
#endif // HTTP_SERVER3_HEADER_HPP
| vslavik/poedit | deps/boost/libs/asio/example/cpp03/http/server3/header.hpp | C++ | mit | 534 |
/* 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/. */
/*
* Plugin to hide series in flot graphs.
*
* To activate, set legend.hideable to true in the flot options object.
* To hide one or more series by default, set legend.hidden to an array of
* label strings.
*
* At the moment, this only works with line and point graphs.
*
* Example:
*
* var plotdata = [
* {
* data: [[1, 1], [2, 1], [3, 3], [4, 2], [5, 5]],
* label: "graph 1"
* },
* {
* data: [[1, 0], [2, 1], [3, 0], [4, 4], [5, 3]],
* label: "graph 2"
* }
* ];
*
* plot = $.plot($("#placeholder"), plotdata, {
* series: {
* points: { show: true },
* lines: { show: true }
* },
* legend: {
* hideable: true,
* hidden: ["graph 1", "graph 2"]
* }
* });
*
*/
(function ($) {
var options = { };
var drawnOnce = false;
function init(plot) {
function findPlotSeries(label) {
var plotdata = plot.getData();
for (var i = 0; i < plotdata.length; i++) {
if (plotdata[i].label == label) {
return plotdata[i];
}
}
return null;
}
function plotLabelClicked(label, mouseOut) {
var series = findPlotSeries(label);
if (!series) {
return;
}
var switchedOff = false;
if (typeof series.points.oldShow === "undefined") {
series.points.oldShow = false;
}
if (typeof series.lines.oldShow === "undefined") {
series.lines.oldShow = false;
}
if (series.points.show && !series.points.oldShow) {
series.points.show = false;
series.points.oldShow = true;
switchedOff = true;
}
if (series.lines.show && !series.lines.oldShow) {
series.lines.show = false;
series.lines.oldShow = true;
switchedOff = true;
}
if (switchedOff) {
series.oldColor = series.color;
series.color = "#fff";
} else {
var switchedOn = false;
if (!series.points.show && series.points.oldShow) {
series.points.show = true;
series.points.oldShow = false;
switchedOn = true;
}
if (!series.lines.show && series.lines.oldShow) {
series.lines.show = true;
series.lines.oldShow = false;
switchedOn = true;
}
if (switchedOn) {
series.color = series.oldColor;
}
}
// HACK: Reset the data, triggering recalculation of graph bounds
plot.setData(plot.getData());
plot.setupGrid();
plot.draw();
}
function plotLabelHandlers(plot, options) {
$(".graphlabel").mouseenter(function() { $(this).css("cursor", "pointer"); })
.mouseleave(function() { $(this).css("cursor", "default"); })
.unbind("click").click(function() { plotLabelClicked($(this).parent().text()); });
if (!drawnOnce) {
drawnOnce = true;
if (options.legend.hidden) {
for (var i = 0; i < options.legend.hidden.length; i++) {
plotLabelClicked(options.legend.hidden[i], true);
}
}
}
}
function checkOptions(plot, options) {
if (!options.legend.hideable) {
return;
}
options.legend.labelFormatter = function(label, series) {
return '<span class="graphlabel">' + label + '</span>';
};
// Really just needed for initial draw; the mouse-enter/leave
// functions will call plotLabelHandlers() directly, since they
// only call setupGrid().
plot.hooks.draw.push(function (plot, ctx) {
plotLabelHandlers(plot, options);
});
}
plot.hooks.processOptions.push(checkOptions);
function hideDatapointsIfNecessary(plot, s, datapoints) {
if (!plot.getOptions().legend.hideable) {
return;
}
if (!s.points.show && !s.lines.show) {
s.datapoints.format = [ null, null ];
}
}
plot.hooks.processDatapoints.push(hideDatapointsIfNecessary);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'hiddenGraphs',
version: '1.0'
});
})(jQuery);
| mehulsbhatt/torque | web/static/js/jquery.flot.hiddengraphs.js | JavaScript | mit | 5,081 |
module ActiveRecord
# = Active Record Through Association
module Associations
module ThroughAssociation #:nodoc:
delegate :source_reflection, :through_reflection, :to => :reflection
protected
# We merge in these scopes for two reasons:
#
# 1. To get the default_scope conditions for any of the other reflections in the chain
# 2. To get the type conditions for any STI models in the chain
def target_scope
scope = super
reflection.chain.drop(1).each do |reflection|
relation = reflection.klass.all
scope.merge!(
relation.except(:select, :create_with, :includes, :preload, :joins, :eager_load)
)
end
scope
end
private
# Construct attributes for :through pointing to owner and associate. This is used by the
# methods which create and delete records on the association.
#
# We only support indirectly modifying through associations which have a belongs_to source.
# This is the "has_many :tags, through: :taggings" situation, where the join model
# typically has a belongs_to on both side. In other words, associations which could also
# be represented as has_and_belongs_to_many associations.
#
# We do not support creating/deleting records on the association where the source has
# some other type, because this opens up a whole can of worms, and in basically any
# situation it is more natural for the user to just create or modify their join records
# directly as required.
def construct_join_attributes(*records)
ensure_mutable
if source_reflection.association_primary_key(reflection.klass) == reflection.klass.primary_key
join_attributes = { source_reflection.name => records }
else
join_attributes = {
source_reflection.foreign_key =>
records.map { |record|
record.send(source_reflection.association_primary_key(reflection.klass))
}
}
end
if options[:source_type]
join_attributes[source_reflection.foreign_type] =
records.map { |record| record.class.base_class.name }
end
if records.count == 1
Hash[join_attributes.map { |k, v| [k, v.first] }]
else
join_attributes
end
end
# Note: this does not capture all cases, for example it would be crazy to try to
# properly support stale-checking for nested associations.
def stale_state
if through_reflection.belongs_to?
owner[through_reflection.foreign_key] && owner[through_reflection.foreign_key].to_s
end
end
def foreign_key_present?
through_reflection.belongs_to? && !owner[through_reflection.foreign_key].nil?
end
def ensure_mutable
unless source_reflection.belongs_to?
if reflection.has_one?
raise HasOneThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection)
else
raise HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection)
end
end
end
def ensure_not_nested
if reflection.nested?
if reflection.has_one?
raise HasOneThroughNestedAssociationsAreReadonly.new(owner, reflection)
else
raise HasManyThroughNestedAssociationsAreReadonly.new(owner, reflection)
end
end
end
def build_record(attributes)
inverse = source_reflection.inverse_of
target = through_association.target
if inverse && target && !target.is_a?(Array)
attributes[inverse.foreign_key] = target.id
end
super(attributes)
end
end
end
end
| susancal/Waitr | vendor/cache/ruby/2.3.0/gems/activerecord-5.0.0/lib/active_record/associations/through_association.rb | Ruby | mit | 4,003 |
Param(
# comma- or semicolon-separated list of Chocolatey packages.
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[string] $packageList
)
Function Get-TempPassword() {
Param(
[int]$length=10,
[string[]]$sourcedata
)
For ($loop=1; $loop -le $length; $loop++) {
$tempPassword+=($sourcedata | GET-RANDOM)
}
return $tempPassword
}
$ascii=$NULL;For ($a=33;$a -le 126;$a++) {$ascii+=,[char][byte]$a }
$userName = "artifactInstaller"
$password = Get-TempPassword -length 43 -sourcedata $ascii
$cn = [ADSI]"WinNT://$env:ComputerName"
# Create user
$user = $cn.Create("User", $userName)
$user.SetPassword($password)
$user.SetInfo()
$user.description = "DevTestLab artifact installer"
$user.SetInfo()
# Add user to the Administrators group
$group = [ADSI]"WinNT://$env:ComputerName/Administrators,group"
$group.add("WinNT://$env:ComputerName/$userName")
$secPassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("$env:COMPUTERNAME\$($username)", $secPassword)
$command = $PSScriptRoot + "\ChocolateyPackageInstaller.ps1"
# Run Chocolatey as the artifactInstaller user
Enable-PSRemoting -Force -SkipNetworkProfileCheck
Invoke-Command -FilePath $command -Credential $credential -ComputerName $env:COMPUTERNAME -ArgumentList $packageList
Disable-PSRemoting -Force
# Delete the artifactInstaller user
$cn.Delete("User", $userName)
# Delete the artifactInstaller user profile
gwmi win32_userprofile | where { $_.LocalPath -like "*$userName*" } | foreach { $_.Delete() } | sogeti/AzureDevTestBrowserLabArtifacts | browserlabartifacts/windows-safari/startChocolatey.ps1 | PowerShell | mit | 1,618 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NSubstitute;
using Xunit;
using System.Threading.Tasks;
namespace Octokit.Tests.Clients
{
/// <summary>
/// Client tests mostly just need to make sure they call the IApiConnection with the correct
/// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs.
/// </summary>
public class SearchClientTests
{
public class TheConstructor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new SearchClient(null));
}
}
public class TheSearchUsersMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchUsers(new SearchUsersRequest("something"));
connection.Received().Get<SearchUsersResult>(Arg.Is<Uri>(u => u.ToString() == "search/users"), Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchUsers(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github"));
}
[Fact]
public void TestingTheAccountTypeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.AccountType = AccountSearchType.User;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+type:User"));
}
[Fact]
public void TestingTheAccountTypeQualifier_Org()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.AccountType = AccountSearchType.Org;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+type:Org"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get users where the fullname contains 'github'
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Fullname };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Fullname"));
}
[Fact]
public void TestingTheInQualifier_Email()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Email };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Email"));
}
[Fact]
public void TestingTheInQualifier_Username()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Username };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Username"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.In = new[] { UserInQualifier.Username, UserInQualifier.Fullname, UserInQualifier.Email };
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Username,Fullname,Email"));
}
[Fact]
public void TestingTheReposQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.GreaterThan(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:>5"));
}
[Fact]
public void TestingTheReposQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.GreaterThanOrEquals(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:>=5"));
}
[Fact]
public void TestingTheReposQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.LessThanOrEquals(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:<=5"));
}
[Fact]
public void TestingTheReposQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Repositories = Range.LessThan(5);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+repos:<5"));
}
[Fact]
public void TestingTheLocationQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Location = "San Francisco";
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+location:San Francisco"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get users who have mostly repos where language is Ruby
var request = new SearchUsersRequest("github");
request.Language = Language.Ruby;
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+language:Ruby"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_Between()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Created = DateRange.Between(new DateTime(2014, 1, 1), new DateTime(2014, 2, 1));
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:2014-01-01..2014-02-01"));
}
[Fact]
public void TestingTheFollowersQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.GreaterThan(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:>1"));
}
[Fact]
public void TestingTheFollowersQualifier_GreaterThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.GreaterThanOrEquals(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:>=1"));
}
[Fact]
public void TestingTheFollowersQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.LessThan(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:<1"));
}
[Fact]
public void TestingTheFollowersQualifier_LessThanOrEqualTo()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = Range.LessThanOrEquals(1);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:<=1"));
}
[Fact]
public void TestingTheFollowersQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchUsersRequest("github");
request.Followers = new Range(1, 1000);
client.SearchUsers(request);
connection.Received().Get<SearchUsersResult>(
Arg.Is<Uri>(u => u.ToString() == "search/users"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+followers:1..1000"));
}
}
public class TheSearchRepoMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchRepo(new SearchRepositoriesRequest("something"));
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchRepo(null));
}
[Fact]
public void TestingTheSizeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.Size = Range.GreaterThan(1);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+size:>1"));
}
[Fact]
public void TestingTheStarsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are greater than 500
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.GreaterThan(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:>500"));
}
[Fact]
public void TestingTheStarsQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are less than 500
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.LessThan(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:<500"));
}
[Fact]
public void TestingTheStarsQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos stargazers are less than 500 or equal to
var request = new SearchRepositoriesRequest("github");
request.Stars = Range.LessThanOrEquals(500);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+stars:<=500"));
}
[Fact]
public void TestingTheForksQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos which has forks that are greater than 50
var request = new SearchRepositoriesRequest("github");
request.Forks = Range.GreaterThan(50);
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+forks:>50"));
}
[Fact]
public void TestingTheForkQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//search repos that contains rails and forks are included in the search
var request = new SearchRepositoriesRequest("github");
request.Fork = ForkQualifier.IncludeForks;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+fork:IncludeForks"));
}
[Fact]
public void TestingTheLangaugeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos whos language is Ruby
var request = new SearchRepositoriesRequest("github");
request.Language = Language.Ruby;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+language:Ruby"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the Description contains the test 'github'
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Description };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Description"));
}
[Fact]
public void TestingTheInQualifier_Name()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Name };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Name"));
}
[Fact]
public void TestingTheInQualifier_Readme()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Readme };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Readme"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.In = new[] { InQualifier.Readme, InQualifier.Description, InQualifier.Name };
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+in:Readme,Description,Name"));
}
[Fact]
public void TestingTheCreatedQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.GreaterThan(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:>=2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.LessThan(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been created after year jan 1 2011
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.LessThanOrEquals(new DateTime(2011, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:<=2011-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_Between()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.Created = DateRange.Between(new DateTime(2011, 1, 1), new DateTime(2012, 11, 11));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+created:2011-01-01..2012-11-11"));
}
[Fact]
public void TestingTheUpdatedQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.GreaterThan(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:>2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.GreaterThanOrEquals(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:>=2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.LessThan(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:<2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where the search contains 'github' and has been pushed before year jan 1 2013
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.LessThanOrEquals(new DateTime(2013, 1, 1));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:<=2013-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_Between()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.Updated = DateRange.Between(new DateTime(2012, 4, 30), new DateTime(2012, 7, 4));
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+pushed:2012-04-30..2012-07-04"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
//get repos where search contains 'github' and user/org is 'github'
var request = new SearchRepositoriesRequest("github");
request.User = "rails";
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "github+user:rails"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest("github");
request.SortField = RepoSearchSort.Stars;
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "github" &&
d["sort"] == "stars"));
}
[Fact]
public void TestingTheSearchParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchRepositoriesRequest();
client.SearchRepo(request);
connection.Received().Get<SearchRepositoryResult>(
Arg.Is<Uri>(u => u.ToString() == "search/repositories"),
Arg.Is<Dictionary<string, string>>(d =>
String.IsNullOrEmpty(d["q"])));
}
}
public class TheSearchIssuesMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchIssues(new SearchIssuesRequest("something"));
connection.Received().Get<SearchIssuesResult>(Arg.Is<Uri>(u => u.ToString() == "search/issues"), Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchIssues(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("pub");
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "pub"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.SortField = IssueSearchSort.Comments;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "comments"));
}
[Fact]
public void TestingTheOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.SortField = IssueSearchSort.Updated;
request.Order = SortDirection.Ascending;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "updated" &&
d["order"] == "asc"));
}
[Fact]
public void TestingTheDefaultOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d =>
d["order"] == "desc"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.In = new[] { IssueInQualifier.Comment };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:comment"));
}
[Fact]
public void TestingTheInQualifiers_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.In = new[] { IssueInQualifier.Body, IssueInQualifier.Title };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:body,title"));
}
[Fact]
public void TestingTheTypeQualifier_Issue()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Type = IssueTypeQualifier.Issue;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+type:issue"));
}
[Fact]
public void TestingTheTypeQualifier_PR()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Type = IssueTypeQualifier.PR;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+type:pr"));
}
[Fact]
public void TestingTheAuthorQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Author = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+author:alfhenrik"));
}
[Fact]
public void TestingTheAssigneeQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Assignee = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+assignee:alfhenrik"));
}
[Fact]
public void TestingTheMentionsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Mentions = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+mentions:alfhenrik"));
}
[Fact]
public void TestingTheCommenterQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Commenter = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+commenter:alfhenrik"));
}
[Fact]
public void TestingTheInvolvesQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Involves = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+involves:alfhenrik"));
}
[Fact]
public void TestingTheStateQualifier_Open()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.State = ItemState.Open;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+state:open"));
}
[Fact]
public void TestingTheStateQualifier_Closed()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.State = ItemState.Closed;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+state:closed"));
}
[Fact]
public void TestingTheLabelsQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Labels = new[] { "bug" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug"));
}
[Fact]
public void TestingTheLabelsQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Labels = new[] { "bug", "feature" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+label:bug+label:feature"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Language = Language.CSharp;
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+language:CSharp"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:>2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:>=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:<2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:<=2014-01-01"));
}
[Fact]
public void TestingTheCreatedQualifier_Between()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Created = DateRange.Between(new DateTime(2014, 1, 1), new DateTime(2014, 2, 2));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+created:2014-01-01..2014-02-02"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.GreaterThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:>2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_GreaterThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.GreaterThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:>=2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.LessThan(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:<2014-01-01"));
}
[Fact]
public void TestingTheUpdatedQualifier_LessThanOrEquals()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Updated = DateRange.LessThanOrEquals(new DateTime(2014, 1, 1));
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+updated:<=2014-01-01"));
}
[Fact]
public void TestingTheCommentsQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.GreaterThan(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:>10"));
}
[Fact]
public void TestingTheCommentsQualifier_GreaterThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.GreaterThanOrEquals(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:>=10"));
}
[Fact]
public void TestingTheCommentsQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.LessThan(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:<10"));
}
[Fact]
public void TestingTheCommentsQualifier_LessThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = Range.LessThanOrEquals(10);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:<=10"));
}
[Fact]
public void TestingTheCommentsQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Comments = new Range(10, 20);
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+comments:10..20"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.User = "alfhenrik";
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+user:alfhenrik"));
}
[Fact]
public void TestingTheRepoQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Repos.Add("octokit", "octokit.net");
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit/octokit.net"));
}
[Fact]
public async Task ErrorOccursWhenSpecifyingInvalidFormatForRepos()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("windows");
request.Repos = new RepositoryCollection {
"haha-business"
};
request.SortField = IssueSearchSort.Created;
request.Order = SortDirection.Descending;
await Assert.ThrowsAsync<RepositoryFormatException>(
async () => await client.SearchIssues(request));
}
[Fact]
public void TestingTheRepoAndUserAndLabelQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchIssuesRequest("something");
request.Repos.Add("octokit/octokit.net");
request.User = "alfhenrik";
request.Labels = new[] { "bug" };
client.SearchIssues(request);
connection.Received().Get<SearchIssuesResult>(
Arg.Is<Uri>(u => u.ToString() == "search/issues"),
Arg.Is<Dictionary<string, string>>(d => d["q"] ==
"something+label:bug+user:alfhenrik+repo:octokit/octokit.net"));
}
}
public class TheSearchCodeMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
client.SearchCode(new SearchCodeRequest("something"));
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Any<Dictionary<string, string>>());
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new SearchClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.SearchCode(null));
}
[Fact]
public void TestingTheTermParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something"));
}
[Fact]
public void TestingTheSortParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.SortField = CodeSearchSort.Indexed;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["sort"] == "indexed"));
}
[Fact]
public void TestingTheOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.SortField = CodeSearchSort.Indexed;
request.Order = SortDirection.Ascending;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["sort"] == "indexed" &&
d["order"] == "asc"));
}
[Fact]
public void TestingTheDefaultOrderParameter()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["order"] == "desc"));
}
[Fact]
public void TestingTheInQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.In = new[] { CodeInQualifier.File };
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:file"));
}
[Fact]
public void TestingTheInQualifier_Multiple()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.In = new[] { CodeInQualifier.File, CodeInQualifier.Path };
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+in:file,path"));
}
[Fact]
public void TestingTheLanguageQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Language = Language.CSharp;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+language:C#"));
}
[Fact]
public void TestingTheForksQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Forks = true;
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+fork:true"));
}
[Fact]
public void TestingTheSizeQualifier_GreaterThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.GreaterThan(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:>10"));
}
[Fact]
public void TestingTheSizeQualifier_GreaterThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.GreaterThanOrEquals(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:>=10"));
}
[Fact]
public void TestingTheSizeQualifier_LessThan()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.LessThan(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:<10"));
}
[Fact]
public void TestingTheSizeQualifier_LessThanOrEqual()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = Range.LessThanOrEquals(10);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:<=10"));
}
[Fact]
public void TestingTheSizeQualifier_Range()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Size = new Range(10, 100);
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+size:10..100"));
}
[Fact]
public void TestingThePathQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Path = "app/public";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+path:app/public"));
}
[Fact]
public void TestingTheExtensionQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.Extension = "cs";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+extension:cs"));
}
[Fact]
public void TestingTheFileNameQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.FileName = "packages.config";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+filename:packages.config"));
}
[Fact]
public void TestingTheUserQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something");
request.User = "alfhenrik";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+user:alfhenrik"));
}
[Fact]
public void TestingTheRepoQualifier()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something", "octokit", "octokit.net");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d => d["q"] == "something+repo:octokit/octokit.net"));
}
[Fact]
public void TestingTheRepoQualifier_InConstructor()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something", "octokit", "octokit.net");
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "something+repo:octokit/octokit.net"));
}
[Fact]
public void TestingTheRepoAndPathAndExtensionQualifiers()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("something", "octokit", "octokit.net");
request.Path = "tools/FAKE.core";
request.Extension = "fs";
client.SearchCode(request);
connection.Received().Get<SearchCodeResult>(
Arg.Is<Uri>(u => u.ToString() == "search/code"),
Arg.Is<Dictionary<string, string>>(d =>
d["q"] == "something+path:tools/FAKE.core+extension:fs+repo:octokit/octokit.net"));
}
[Fact]
public async Task ErrorOccursWhenSpecifyingInvalidFormatForRepos()
{
var connection = Substitute.For<IApiConnection>();
var client = new SearchClient(connection);
var request = new SearchCodeRequest("windows");
request.Repos = new RepositoryCollection {
"haha-business"
};
request.Order = SortDirection.Descending;
await Assert.ThrowsAsync<RepositoryFormatException>(
async () => await client.SearchCode(request));
}
}
}
}
| hitesh97/octokit.net | Octokit.Tests/Clients/SearchClientTests.cs | C# | mit | 72,612 |
{% extends "layout.html" %}
{% block page_title %}
Apprenticeships
{% endblock %}
{% block content %}
<script>
var whereNow = function() {
var goToEmployer = JSON.parse(localStorage.getItem('commitments.isEmployer'));
if (goToEmployer == "yes") {
window.location.href='../provider-in-progress/provider-list';
} else {
window.location.href='employer-confirmation';
}
};
</script>
<style>
.people-nav a {
{% include "includes/nav-on-state-css.html" %}
}
</style>
<main id="content" role="main">
{% include "includes/phase_banner_beta_noNav.html" %}
{% include "includes/secondary-nav-provider.html" %}
<!--div class="breadcrumbs">
<ol role="breadcrumbs">
<li><a href="/{% include "includes/sprint-link.html" %}/balance">Access my funds</a></li>
</ol>
</div-->
<div class="breadcrumbs back-breadcrumb">
<ol role="breadcrumbs">
{% include "includes/breadcrumbs/register-back.html" %}
</ol>
</div>
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge" >Instructions for your training provider</h1>
<p class="lede">Let <span style="font-weight:700">Hackney Skills and Training Ltd</span> know which apprentices you'd like them to add.</p>
<form action="">
<fieldset>
<legend class="visuallyhidden">provider contact details and message - optional</legend>
<div class="form-group">
<label class="form-label-bold" for="message">Instructions</label>
<span class="form-hint">For example, please add the 12 admin level 2 apprentices and 13 engineering level 3 apprentices.</span>
<textarea class="form-control" id="message" type="text" style="width:100%" rows="5" ></textarea>
</div>
</fieldset>
<input class="button" id="Finish" onclick="whereNow()" type="button" value="Send">
</form>
<div style="margin-top:50px"></div>
<!-- template to pull in the start tabs so this doesn't get too messy - it is pulling in the tabs -->
<!-- {% include "includes/start-tabs.html" %} -->
</div>
<div class="column-one-third">
<!--aside class="related">
<h2 class="heading-medium" style="margin-top:10px">Existing account</h2>
<nav role="navigation">
<ul class="robSideNav">
<li>
<a href="../login">Sign in</a>
</li>
</ul>
</nav>
</aside-->
</div>
</div>
</main>
<script>
//jquery that runs the tabs. Uses the jquery.tabs.js from gov.uk
{% endblock %}
| SkillsFundingAgency/das-alpha-ui | app/views/programmeTwo/register/beta/spend/provider-contact.html | HTML | mit | 2,727 |
require 'spec_helper'
RSpec.configure do |c|
c.os = 'Gentoo'
end
describe kernel_module('lp') do
it { should be_loaded }
its(:command) { should eq "lsmod | grep ^lp" }
end
describe kernel_module('invalid-module') do
it { should_not be_loaded }
end
| kavanista/serverspec | spec/gentoo/kernel_module_spec.rb | Ruby | mit | 259 |
<TS language="af_ZA" version="2.0">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>Skep 'n nuwe adres</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Maak 'n kopie van die huidige adres na die stelsel klipbord</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Verwyder</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Wagfrase Dialoog</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Tik wagfrase in</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Nuwe wagfrase</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Herhaal nuwe wagfrase</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Enkripteer beursie</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Hierdie operasie benodig 'n wagwoord om die beursie oop te sluit.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Sluit beursie oop</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Hierdie operasie benodig 'n wagwoord om die beursie oop te sluit.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Sluit beursie oop</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Verander wagfrase</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Bevestig beursie enkripsie.</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Die beursie is nou bewaak</translation>
</message>
<message>
<source>Enter the old passphrase and new passphrase to the wallet.</source>
<translation>Tik in die ou wagfrase en die nuwe wagfrase vir die beursie.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Die beursie kon nie bewaak word nie</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Beursie bewaaking het misluk as gevolg van 'n interne fout. Die beursie is nie bewaak nie!</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Die wagfrase stem nie ooreen nie</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Beursie oopsluiting het misluk</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Die wagfrase wat ingetik was om die beursie oop te sluit, was verkeerd.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Beursie dekripsie het misluk</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Die beursie se wagfrase verandering was suksesvol.</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Synchronizing with network...</source>
<translation>Sinchroniseer met die netwerk ...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Oorsig</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Wys algemene oorsig van die beursie</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Transaksies</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Besoek transaksie geskiedenis</translation>
</message>
<message>
<source>E&xit</source>
<translation>S&luit af</translation>
</message>
<message>
<source>Quit application</source>
<translation>Sluit af</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Wys inligting oor Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Opsies</translation>
</message>
<message>
<source>Bitcoin</source>
<translation>Bitcoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Beursie</translation>
</message>
<message>
<source>&File</source>
<translation>&Lêer</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Instellings</translation>
</message>
<message>
<source>&Help</source>
<translation>&Hulp</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Blad nutsbalk</translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 agter</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Ontvangs van laaste blok is %1 terug.</translation>
</message>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
<message>
<source>Information</source>
<translation>Informasie</translation>
</message>
</context>
<context>
<name>ClientModel</name>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Copy address</source>
<translation>Maak kopie van adres</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<source>&Address</source>
<translation>&Adres</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Nuwe ontvangende adres</translation>
</message>
<message>
<source>New sending address</source>
<translation>Nuwe stuurende adres</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Wysig ontvangende adres</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Wysig stuurende adres</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Kon nie die beursie oopsluit nie.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Opsies</translation>
</message>
<message>
<source>W&allet</source>
<translation>&Beursie</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Vorm</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>&Information</source>
<translation>Informasie</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>&Bedrag:</translation>
</message>
<message>
<source>&Message:</source>
<translation>&Boodskap:</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Message</source>
<translation>Boodskap</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Message</source>
<translation>Boodskap</translation>
</message>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Stuur Munstukke</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Onvoldoende fondse</translation>
</message>
<message>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Transaksie fooi:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Stuur aan vele ontvangers op eens</translation>
</message>
<message>
<source>Balance:</source>
<translation>Balans:</translation>
</message>
<message>
<source>S&end</source>
<translation>S&tuur</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>&Bedrag:</translation>
</message>
<message>
<source>Message:</source>
<translation>Boodskap:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>&Sign Message</source>
<translation>&Teken boodskap</translation>
</message>
<message>
<source>Signature</source>
<translation>Handtekening</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Teken &Boodskap</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>From</source>
<translation>Van</translation>
</message>
<message>
<source>To</source>
<translation>Na</translation>
</message>
<message>
<source>own address</source>
<translation>eie adres</translation>
</message>
<message>
<source>label</source>
<translation>etiket</translation>
</message>
<message>
<source>Credit</source>
<translation>Krediet</translation>
</message>
<message>
<source>not accepted</source>
<translation>nie aanvaar nie</translation>
</message>
<message>
<source>Debit</source>
<translation>Debiet</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Transaksie fooi</translation>
</message>
<message>
<source>Net amount</source>
<translation>Netto bedrag</translation>
</message>
<message>
<source>Message</source>
<translation>Boodskap</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>Transaksie ID</translation>
</message>
<message>
<source>Transaction</source>
<translation>Transaksie</translation>
</message>
<message>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<source>true</source>
<translation>waar</translation>
</message>
<message>
<source>false</source>
<translation>onwaar</translation>
</message>
<message>
<source>unknown</source>
<translation>onbekend</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Type</source>
<translation>Tipe</translation>
</message>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Received with</source>
<translation>Ontvang met</translation>
</message>
<message>
<source>Received from</source>
<translation>Ontvang van</translation>
</message>
<message>
<source>Sent to</source>
<translation>Gestuur na</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Betalings Aan/na jouself</translation>
</message>
<message>
<source>Mined</source>
<translation>Gemyn</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(n.v.t)</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Datum en tyd wat die transaksie ontvang was.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Tipe transaksie.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Alles</translation>
</message>
<message>
<source>Today</source>
<translation>Vandag</translation>
</message>
<message>
<source>This week</source>
<translation>Hierdie week</translation>
</message>
<message>
<source>This month</source>
<translation>Hierdie maand</translation>
</message>
<message>
<source>Last month</source>
<translation>Verlede maand</translation>
</message>
<message>
<source>This year</source>
<translation>Hierdie jaar</translation>
</message>
<message>
<source>Range...</source>
<translation>Reeks...</translation>
</message>
<message>
<source>Received with</source>
<translation>Ontvang met</translation>
</message>
<message>
<source>Sent to</source>
<translation>Gestuur na</translation>
</message>
<message>
<source>To yourself</source>
<translation>Aan/na jouself</translation>
</message>
<message>
<source>Mined</source>
<translation>Gemyn</translation>
</message>
<message>
<source>Other</source>
<translation>Ander</translation>
</message>
<message>
<source>Min amount</source>
<translation>Min bedrag</translation>
</message>
<message>
<source>Copy address</source>
<translation>Maak kopie van adres</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<source>Type</source>
<translation>Tipe</translation>
</message>
<message>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>Range:</source>
<translation>Reeks:</translation>
</message>
<message>
<source>to</source>
<translation>aan</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Stuur Munstukke</translation>
</message>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Opsies:</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Fout: Hardeskyf spasie is baie laag!</translation>
</message>
<message>
<source>Information</source>
<translation>Informasie</translation>
</message>
<message>
<source>This help message</source>
<translation>Hierdie help boodskap</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>Laai adresse...</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Onvoldoende fondse</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Laai blok indeks...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Laai beursie...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Klaar gelaai</translation>
</message>
<message>
<source>Error</source>
<translation>Fout</translation>
</message>
</context>
</TS> | Bitcoin-com/BUcash | src/qt/locale/bitcoin_af_ZA.ts | TypeScript | mit | 20,485 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Orleans.Serialization;
namespace Orleans.Runtime.MembershipService
{
[Serializable]
internal class InMemoryMembershipTable
{
private readonly SerializationManager serializationManager;
private readonly Dictionary<SiloAddress, Tuple<MembershipEntry, string>> siloTable;
private TableVersion tableVersion;
private long lastETagCounter;
public InMemoryMembershipTable(SerializationManager serializationManager)
{
this.serializationManager = serializationManager;
siloTable = new Dictionary<SiloAddress, Tuple<MembershipEntry, string>>();
lastETagCounter = 0;
tableVersion = new TableVersion(0, NewETag());
}
public MembershipTableData Read(SiloAddress key)
{
return siloTable.ContainsKey(key) ?
new MembershipTableData((Tuple<MembershipEntry, string>)this.serializationManager.DeepCopy(siloTable[key]), tableVersion)
: new MembershipTableData(tableVersion);
}
public MembershipTableData ReadAll()
{
return new MembershipTableData(siloTable.Values.Select(tuple =>
new Tuple<MembershipEntry, string>((MembershipEntry)this.serializationManager.DeepCopy(tuple.Item1), tuple.Item2)).ToList(), tableVersion);
}
public TableVersion ReadTableVersion()
{
return tableVersion;
}
public bool Insert(MembershipEntry entry, TableVersion version)
{
Tuple<MembershipEntry, string> data;
siloTable.TryGetValue(entry.SiloAddress, out data);
if (data != null) return false;
if (!tableVersion.VersionEtag.Equals(version.VersionEtag)) return false;
siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>(
entry, lastETagCounter++.ToString(CultureInfo.InvariantCulture));
tableVersion = new TableVersion(version.Version, NewETag());
return true;
}
public bool Update(MembershipEntry entry, string etag, TableVersion version)
{
Tuple<MembershipEntry, string> data;
siloTable.TryGetValue(entry.SiloAddress, out data);
if (data == null) return false;
if (!data.Item2.Equals(etag) || !tableVersion.VersionEtag.Equals(version.VersionEtag)) return false;
siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>(
entry, lastETagCounter++.ToString(CultureInfo.InvariantCulture));
tableVersion = new TableVersion(version.Version, NewETag());
return true;
}
public void UpdateIAmAlive(MembershipEntry entry)
{
Tuple<MembershipEntry, string> data;
siloTable.TryGetValue(entry.SiloAddress, out data);
if (data == null) return;
data.Item1.IAmAliveTime = entry.IAmAliveTime;
siloTable[entry.SiloAddress] = new Tuple<MembershipEntry, string>(data.Item1, NewETag());
}
public override string ToString()
{
return String.Format("Table = {0}, ETagCounter={1}", ReadAll().ToString(), lastETagCounter);
}
private string NewETag()
{
return lastETagCounter++.ToString(CultureInfo.InvariantCulture);
}
}
}
| shlomiw/orleans | src/OrleansRuntime/MembershipService/InMemoryMembershipTable.cs | C# | mit | 3,500 |
///////////////////////////////////////////////////////////////////////////////
// moment.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_MOMENT_HPP_EAN_15_11_2005
#define BOOST_ACCUMULATORS_STATISTICS_MOMENT_HPP_EAN_15_11_2005
#include <boost/config/no_tr1/cmath.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
namespace boost { namespace numeric
{
/// INTERNAL ONLY
///
template<typename T>
T const &pow(T const &x, mpl::int_<1>)
{
return x;
}
/// INTERNAL ONLY
///
template<typename T, int N>
T pow(T const &x, mpl::int_<N>)
{
using namespace operators;
T y = numeric::pow(x, mpl::int_<N/2>());
T z = y * y;
return (N % 2) ? (z * x) : z;
}
}}
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// moment_impl
template<typename N, typename Sample>
struct moment_impl
: accumulator_base // TODO: also depends_on sum of powers
{
BOOST_MPL_ASSERT_RELATION(N::value, >, 0);
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
template<typename Args>
moment_impl(Args const &args)
: sum(args[sample | Sample()])
{
}
template<typename Args>
void operator ()(Args const &args)
{
this->sum += numeric::pow(args[sample], N());
}
template<typename Args>
result_type result(Args const &args) const
{
return numeric::fdiv(this->sum, count(args));
}
// make this accumulator serializeable
template<class Archive>
void serialize(Archive & ar, const unsigned int file_version)
{
ar & sum;
}
private:
Sample sum;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::moment
//
namespace tag
{
template<int N>
struct moment
: depends_on<count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::moment_impl<mpl::int_<N>, mpl::_1> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::moment
//
namespace extract
{
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, moment, (int))
}
using extract::moment;
// So that moment<N> can be automatically substituted with
// weighted_moment<N> when the weight parameter is non-void
template<int N>
struct as_weighted_feature<tag::moment<N> >
{
typedef tag::weighted_moment<N> type;
};
template<int N>
struct feature_of<tag::weighted_moment<N> >
: feature_of<tag::moment<N> >
{
};
}} // namespace boost::accumulators
#endif
| kumakoko/KumaGL | third_lib/boost/1.75.0/boost/accumulators/statistics/moment.hpp | C++ | mit | 3,436 |
/*
* W.J. van der Laan 2011-2012
*/
#include <QApplication>
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "paymentserver.h"
#include "splashscreen.h"
#include <QMessageBox>
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
#include <QLocale>
#include <QTimer>
#include <QTranslator>
#include <QLibraryInfo>
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Declare meta types used for QMetaObject::invokeMethod
Q_DECLARE_METATYPE(bool*)
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static SplashScreen *splashref;
static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(guiref, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
return false;
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired)
{
if(!guiref)
return false;
if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55));
qApp->processEvents();
}
printf("init message: %s\n", message.c_str());
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Dogecoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Command-line options take precedence:
ParseParameters(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Register meta types used for QMetaObject::invokeMethod
qRegisterMetaType< bool* >();
// Do this early as we don't want to bother initializing if we are just calling IPC
// ... but do it after creating app, so QCoreApplication::arguments is initialized:
if (PaymentServer::ipcSendCommandLine())
exit(0);
PaymentServer* paymentServer = new PaymentServer(&app);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// ... then bitcoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Dogecoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
QApplication::setOrganizationName("Dogecoin");
QApplication::setOrganizationDomain("dogecoin-noexist-domain.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
QApplication::setApplicationName("Dogecoin-Qt-testnet");
else
QApplication::setApplicationName("Dogecoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
#ifdef Q_OS_MAC
// on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange)
if(GetBoolArg("-testnet")) {
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
}
#endif
SplashScreen splash(QPixmap(), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
#if MAC_OSX
// QSplashScreen on Mac seems to always stay on top. Ugh.
splash.setWindowFlags(Qt::FramelessWindowHint);
#endif
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
#ifndef Q_OS_MAC
// Regenerate startup link, to fix links to old versions
// OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs)
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
#endif
boost::thread_group threadGroup;
BitcoinGUI window;
guiref = &window;
QTimer* pollShutdownTimer = new QTimer(guiref);
QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
if(AppInit2(threadGroup))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel *walletModel = 0;
if(pwalletMain)
walletModel = new WalletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
if(walletModel)
{
window.addWallet("~Default", walletModel);
window.setCurrentWallet("~Default");
}
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Now that initialization/startup is done, process any command-line
// bitcoin: URIs
QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
app.exec();
window.hide();
window.setClientModel(0);
window.removeAllWallets();
guiref = 0;
delete walletModel;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
}
else
{
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
| PoundCoinz/PoundCoinz | src/qt/bitcoin.cpp | C++ | mit | 10,783 |
//DO NOT DELETE THIS, this is in use...
angular.module('umbraco')
.controller("Umbraco.PropertyEditors.MacroContainerController",
function($scope, dialogService, entityResource, macroService){
$scope.renderModel = [];
$scope.allowOpenButton = true;
$scope.allowRemoveButton = true;
$scope.sortableOptions = {};
if($scope.model.value){
var macros = $scope.model.value.split('>');
angular.forEach(macros, function(syntax, key){
if(syntax && syntax.length > 10){
//re-add the char we split on
syntax = syntax + ">";
var parsed = macroService.parseMacroSyntax(syntax);
if(!parsed){
parsed = {};
}
parsed.syntax = syntax;
collectDetails(parsed);
$scope.renderModel.push(parsed);
setSortingState($scope.renderModel);
}
});
}
function collectDetails(macro){
macro.details = "";
macro.icon = "icon-settings-alt";
if(macro.macroParamsDictionary){
angular.forEach((macro.macroParamsDictionary), function(value, key){
macro.details += key + ": " + value + " ";
});
}
}
function openDialog(index){
var dialogData = {
allowedMacros: $scope.model.config.allowed
};
if(index !== null && $scope.renderModel[index]) {
var macro = $scope.renderModel[index];
dialogData["macroData"] = macro;
}
$scope.macroPickerOverlay = {};
$scope.macroPickerOverlay.view = "macropicker";
$scope.macroPickerOverlay.dialogData = dialogData;
$scope.macroPickerOverlay.show = true;
$scope.macroPickerOverlay.submit = function(model) {
var macroObject = macroService.collectValueData(model.selectedMacro, model.macroParams, dialogData.renderingEngine);
collectDetails(macroObject);
//update the raw syntax and the list...
if(index !== null && $scope.renderModel[index]) {
$scope.renderModel[index] = macroObject;
} else {
$scope.renderModel.push(macroObject);
}
setSortingState($scope.renderModel);
$scope.macroPickerOverlay.show = false;
$scope.macroPickerOverlay = null;
};
$scope.macroPickerOverlay.close = function(oldModel) {
$scope.macroPickerOverlay.show = false;
$scope.macroPickerOverlay = null;
};
}
$scope.edit =function(index){
openDialog(index);
};
$scope.add = function () {
if ($scope.model.config.max && $scope.model.config.max > 0 && $scope.renderModel.length >= $scope.model.config.max) {
//cannot add more than the max
return;
}
openDialog();
};
$scope.remove =function(index){
$scope.renderModel.splice(index, 1);
setSortingState($scope.renderModel);
};
$scope.clear = function() {
$scope.model.value = "";
$scope.renderModel = [];
};
var unsubscribe = $scope.$on("formSubmitting", function (ev, args) {
var syntax = [];
angular.forEach($scope.renderModel, function(value, key){
syntax.push(value.syntax);
});
$scope.model.value = syntax.join("");
});
//when the scope is destroyed we need to unsubscribe
$scope.$on('$destroy', function () {
unsubscribe();
});
function trim(str, chr) {
var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g');
return str.replace(rgxtrim, '');
}
function setSortingState(items) {
// disable sorting if the list only consist of one item
if(items.length > 1) {
$scope.sortableOptions.disabled = false;
} else {
$scope.sortableOptions.disabled = true;
}
}
});
| abryukhov/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/views/propertyeditors/macrocontainer/macrocontainer.controller.js | JavaScript | mit | 3,569 |
<a href='https://github.com/angular/angular.js/edit/v1.4.x/src/ngMessages/messages.js?message=docs(ngMessagesInclude)%3A%20describe%20your%20change...#L482' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.4.7/src/ngMessages/messages.js#L482' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">ngMessagesInclude</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- directive in module <a href="api/ngMessages">ngMessages</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p><code>ngMessagesInclude</code> is a directive with the purpose to import existing ngMessage template
code from a remote template and place the downloaded template code into the exact spot
that the ngMessagesInclude directive is placed within the ngMessages container. This allows
for a series of pre-defined messages to be reused and also allows for the developer to
determine what messages are overridden due to the placement of the ngMessagesInclude directive.</p>
</div>
<div>
<h2>Directive Info</h2>
<ul>
<li>This directive creates new scope.</li>
<li>This directive executes at priority level 0.</li>
</ul>
<h2 id="usage">Usage</h2>
<div class="usage">
<pre><code class="lang-html"><!-- using attribute directives -->
<ANY ng-messages="expression" role="alert">
<ANY ng-messages-include="remoteTplString">...</ANY>
</ANY>
<!-- or by using element directives -->
<ng-messages for="expression" role="alert">
<ng-messages-include src="expressionValue1">...</ng-messages-include>
</ng-messages>
</code></pre>
<p><a href="api/ngMessages">Click here</a> to learn more about <code>ngMessages</code> and <code>ngMessage</code>.</p>
</div>
<section class="api-section">
<h3>Arguments</h3>
<table class="variables-matrix input-arguments">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
ngMessagesInclude
| src
</td>
<td>
<a href="" class="label type-hint type-hint-string">string</a>
</td>
<td>
<p>a string value corresponding to the remote template.</p>
</td>
</tr>
</tbody>
</table>
</section>
</div>
| bdipaola/DiplomacyScoring | vendor/assets/javascripts/docs/partials/api/ngMessages/directive/ngMessagesInclude.html | HTML | mit | 2,671 |
/*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2010 University of Dundee. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.env.data.model;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import omero.IllegalArgumentException;
import org.openmicroscopy.shoola.env.data.login.UserCredentials;
import omero.gateway.model.ExperimenterData;
import omero.gateway.model.GroupData;
/**
* Holds information about the group, users to handle.
*
* @author Jean-Marie Burel
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @author Donald MacDonald
* <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a>
* @version 3.0
* @since 3.0-Beta4
*/
public class AdminObject
{
/** Indicates to create a group. */
public static final int CREATE_GROUP = 0;
/** Indicates to create a group. */
public static final int CREATE_EXPERIMENTER = 1;
/** Indicates to update a group. */
public static final int UPDATE_GROUP = 2;
/** Indicates to update experimenter. */
public static final int UPDATE_EXPERIMENTER = 3;
/** Indicates to reset the password. */
public static final int RESET_PASSWORD = 4;
/** Indicates to add experimenters to group. */
public static final int ADD_EXPERIMENTER_TO_GROUP = 5;
/** Indicates to reset the password. */
public static final int ACTIVATE_USER = 6;
/**
* Validates the index.
*
* @param index The value to control.
*/
private void checkIndex(int index)
{
switch (index) {
case CREATE_EXPERIMENTER:
case CREATE_GROUP:
case UPDATE_GROUP:
case UPDATE_EXPERIMENTER:
case RESET_PASSWORD:
case ADD_EXPERIMENTER_TO_GROUP:
case ACTIVATE_USER:
return;
default:
throw new IllegalArgumentException("Index not supported");
}
}
/**
* Can be the group to create or the group to add the experimenters to
* depending on the index.
*/
private GroupData group;
/** The collection of groups to create. */
private List<GroupData> groups;
/**
* Can be the owners of the group or the experimenters to create
* depending on the index.
*/
private Map<ExperimenterData, UserCredentials> experimenters;
/** One of the constants defined by this class. */
private int index;
/** Indicates the permissions associated to the group. */
private int permissions = -1;
/**
* Creates a new instance.
*
* @param group The group to handle.
* @param experimenters The experimenters to handle.
* @param index One of the constants defined by this class.
*/
public AdminObject(GroupData group, Map<ExperimenterData, UserCredentials>
experimenters, int index)
{
checkIndex(index);
this.group = group;
this.experimenters = experimenters;
this.index = index;
this.permissions = -1;
}
/**
* Creates a new instance.
*
* @param group The group to handle.
* @param values The experimenters to handle.
*/
public AdminObject(GroupData group, Collection<ExperimenterData> values)
{
if (values != null) {
Iterator<ExperimenterData> i = values.iterator();
experimenters = new HashMap<ExperimenterData, UserCredentials>();
while (i.hasNext()) {
experimenters.put(i.next(), null);
}
}
this.group = group;
this.index = ADD_EXPERIMENTER_TO_GROUP;
this.permissions = -1;
}
/**
* Creates a new instance.
*
* @param experimenters The experimenters to handle.
* @param index One of the constants defined by this class.
*/
public AdminObject(Map<ExperimenterData, UserCredentials> experimenters,
int index)
{
this(null, experimenters, index);
}
/**
* Sets the permissions associated to the group.
*
* @param permissions The value to set. One of the constants defined
* by this class.
*/
public void setPermissions(int permissions)
{
switch (permissions) {
case GroupData.PERMISSIONS_PRIVATE:
case GroupData.PERMISSIONS_GROUP_READ:
case GroupData.PERMISSIONS_GROUP_READ_LINK:
case GroupData.PERMISSIONS_GROUP_READ_WRITE:
case GroupData.PERMISSIONS_PUBLIC_READ:
case GroupData.PERMISSIONS_PUBLIC_READ_WRITE:
this.permissions = permissions;
break;
default:
this.permissions = GroupData.PERMISSIONS_PRIVATE;
}
}
/**
* Returns the permissions associated to the group.
*
* @return See above.
*/
public int getPermissions() { return permissions; }
/**
* Returns the experimenters to create.
*
* @return See above
*/
public Map<ExperimenterData, UserCredentials> getExperimenters()
{
return experimenters;
}
/**
* Returns the group to create or to add the experimenters to.
*
* @return See above.
*/
public GroupData getGroup() { return group; }
/**
* Sets the groups.
*
* @param groups The value to handle.
*/
public void setGroups(List<GroupData> groups) { this.groups = groups; }
/**
* Returns the groups to add the new users to.
*
* @return See above.
*/
public List<GroupData> getGroups() { return groups; }
/**
* Returns one of the constants defined by this class.
*
* @return See above.
*/
public int getIndex() { return index; }
}
| knabar/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/env/data/model/AdminObject.java | Java | gpl-2.0 | 6,106 |
<?php
/*
Widget Name: Editor
Description: A widget which allows editing of content using the TinyMCE editor.
Author: SiteOrigin
Author URI: https://siteorigin.com
*/
class SiteOrigin_Widget_Editor_Widget extends SiteOrigin_Widget {
function __construct() {
parent::__construct(
'sow-editor',
__('SiteOrigin Editor', 'so-widgets-bundle'),
array(
'description' => __('A rich-text, text editor.', 'so-widgets-bundle'),
'help' => 'https://siteorigin.com/widgets-bundle/editor-widget/'
),
array(),
false,
plugin_dir_path(__FILE__)
);
}
function initialize_form(){
return array(
'title' => array(
'type' => 'text',
'label' => __('Title', 'so-widgets-bundle'),
),
'text' => array(
'type' => 'tinymce',
'rows' => 20
),
'autop' => array(
'type' => 'checkbox',
'default' => true,
'label' => __('Automatically add paragraphs', 'so-widgets-bundle'),
),
);
}
function unwpautop($string) {
$string = str_replace("<p>", "", $string);
$string = str_replace(array("<br />", "<br>", "<br/>"), "\n", $string);
$string = str_replace("</p>", "\n\n", $string);
return $string;
}
public function get_template_variables( $instance, $args ) {
$instance = wp_parse_args(
$instance,
array( 'text' => '' )
);
$instance['text'] = $this->unwpautop( $instance['text'] );
$instance['text'] = apply_filters( 'widget_text', $instance['text'] );
// Run some known stuff
if( !empty($GLOBALS['wp_embed']) ) {
$instance['text'] = $GLOBALS['wp_embed']->autoembed( $instance['text'] );
}
if (function_exists('wp_make_content_images_responsive')) {
$instance['text'] = wp_make_content_images_responsive( $instance['text'] );
}
if( $instance['autop'] ) {
$instance['text'] = wpautop( $instance['text'] );
}
$instance['text'] = do_shortcode( shortcode_unautop( $instance['text'] ) );
return array(
'text' => $instance['text'],
);
}
function get_style_name($instance) {
// We're not using a style
return false;
}
}
siteorigin_widget_register( 'sow-editor', __FILE__, 'SiteOrigin_Widget_Editor_Widget' );
| Analytical-Engine-Interactive/loopylogic | wp-content/plugins/so-widgets-bundle/widgets/editor/editor.php | PHP | gpl-2.0 | 2,126 |
// -*- C++ -*-
//=============================================================================
/**
* @file Token_Manager.h
*
* $Id: Token_Manager.h 80826 2008-03-04 14:51:23Z wotte $
*
* @author Tim Harrison (harrison@cs.wustl.edu)
*/
//=============================================================================
#ifndef ACE_TOKEN_MANAGER_H
#define ACE_TOKEN_MANAGER_H
#include /**/ "ace/pre.h"
#include /**/ "ace/config-all.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "ace/Local_Tokens.h"
#if defined (ACE_HAS_TOKENS_LIBRARY)
#include "ace/Null_Mutex.h"
#include "ace/Map_Manager.h"
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
class ACE_Local_Mutex;
class ACE_Mutex_Token;
/**
* @class ACE_Token_Manager
*
* @brief Manages all tokens in a process space.
*
* Factory: Proxies use the token manager to obtain token
* references. This allows multiple proxies to reference the same
* logical token.
* Deadlock detection: Tokens use the manager to check for
* deadlock situations during acquires.
*/
class ACE_Export ACE_Token_Manager : public ACE_Cleanup
{
// To add a new type of token (e.g. semaphore), do the following
// steps: 1. Create a new derivation of ACE_Token. This class
// defines the semantics of the new Token. 2. Create a
// derivation of ACE_Token_Manager. You will only need to
// redefine make_mutex.
public:
ACE_Token_Manager (void);
virtual ~ACE_Token_Manager (void);
/// Get the pointer to token manager singleton.
static ACE_Token_Manager *instance (void);
/// Set the pointer to token manager singleton.
void instance (ACE_Token_Manager *);
/**
* The Token manager uses ACE_Token_Proxy::token_id_ to look for
* an existing token. If none is found, the Token Manager calls
* ACE_Token_Proxy::create_token to create a new one. When
* finished, sets ACE_Token_Proxy::token_. @a token_name uniquely
* id's the token name.
*/
void get_token (ACE_Token_Proxy *, const ACE_TCHAR *token_name);
/**
* Check whether acquire will cause deadlock or not.
* returns 1 if the acquire will _not_ cause deadlock.
* returns 0 if the acquire _will_ cause deadlock.
* This method ignores recursive acquisition. That is, it will not
* report deadlock if the client holding the token requests the
* token again. Thus, it assumes recursive mutexes.
*/
int check_deadlock (ACE_Token_Proxy *proxy);
int check_deadlock (ACE_Tokens *token, ACE_Token_Proxy *proxy);
/// Notify the token manager that a token has been released. If as a
/// result, there is no owner of the token, the token is deleted.
void release_token (ACE_Tokens *&token);
/**
* This is to allow Tokens to perform atomic transactions. The
* typical usage is to acquire this mutex, check for a safe_acquire,
* perform some queueing (if need be) and then release the lock.
* This is necessary since safe_acquire is implemented in terms of
* the Token queues.
*/
ACE_TOKEN_CONST::MUTEX &mutex (void);
/// Dump the state of the class.
void dump (void) const;
/// Turn debug mode on/off.
void debug (bool d);
private:
/// Whether to print debug messages or not.
bool debug_;
/// pointer to singleton token manager.
static ACE_Token_Manager *token_manager_;
/// Return the token that the given client_id is waiting for, if any
ACE_Tokens *token_waiting_for (const ACE_TCHAR *client_id);
/// ACE_Mutex_Token used to lock internal data structures.
ACE_TOKEN_CONST::MUTEX lock_;
/// This may be changed to a template type.
typedef ACE_Token_Name TOKEN_NAME;
/// COLLECTION maintains a mapping from token names to ACE_Tokens*
typedef ACE_Map_Manager<TOKEN_NAME, ACE_Tokens *, ACE_Null_Mutex>
COLLECTION;
/// Allows iterations through collection_
/**
* @deprecated Deprecated typedef. Use COLLECTION::ITERATOR trait
* instead.
*/
typedef COLLECTION::ITERATOR COLLECTION_ITERATOR;
/// Allows iterations through collection_
/**
* @deprecated Deprecated typedef. Use COLLECTION::ENTRY trait
* instead.
*/
typedef COLLECTION::ENTRY COLLECTION_ENTRY;
/// COLLECTION maintains a mapping from token names to ACE_Tokens*.
COLLECTION collection_;
};
ACE_END_VERSIONED_NAMESPACE_DECL
#if defined (__ACE_INLINE__)
#include "ace/Token_Manager.inl"
#endif /* __ACE_INLINE__ */
#endif /* ACE_HAS_TOKENS_LIBRARY */
#include /**/ "ace/post.h"
#endif /* ACE_TOKEN_MANAGER_H */
| skyne/NeoCore | dep/ACE_wrappers/ace/Token_Manager.h | C | gpl-2.0 | 4,507 |
// Copyright 2010 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
// ---------------------------------------------------------------------------------------------
// GC graphics pipeline
// ---------------------------------------------------------------------------------------------
// 3d commands are issued through the fifo. The GPU draws to the 2MB EFB.
// The efb can be copied back into ram in two forms: as textures or as XFB.
// The XFB is the region in RAM that the VI chip scans out to the television.
// So, after all rendering to EFB is done, the image is copied into one of two XFBs in RAM.
// Next frame, that one is scanned out and the other one gets the copy. = double buffering.
// ---------------------------------------------------------------------------------------------
#include <cinttypes>
#include <cmath>
#include <string>
#include "Common/Atomic.h"
#include "Common/Event.h"
#include "Common/Profiler.h"
#include "Common/StringUtil.h"
#include "Common/Timer.h"
#include "Core/ConfigManager.h"
#include "Core/Core.h"
#include "Core/Host.h"
#include "Core/Movie.h"
#include "Core/FifoPlayer/FifoRecorder.h"
#include "Core/HW/VideoInterface.h"
#include "VideoCommon/AVIDump.h"
#include "VideoCommon/BPMemory.h"
#include "VideoCommon/CommandProcessor.h"
#include "VideoCommon/CPMemory.h"
#include "VideoCommon/Debugger.h"
#include "VideoCommon/Fifo.h"
#include "VideoCommon/FPSCounter.h"
#include "VideoCommon/FramebufferManagerBase.h"
#include "VideoCommon/MainBase.h"
#include "VideoCommon/OpcodeDecoding.h"
#include "VideoCommon/RenderBase.h"
#include "VideoCommon/Statistics.h"
#include "VideoCommon/TextureCacheBase.h"
#include "VideoCommon/VideoConfig.h"
#include "VideoCommon/XFMemory.h"
// TODO: Move these out of here.
int frameCount;
int OSDChoice;
static int OSDTime;
Renderer *g_renderer = nullptr;
std::mutex Renderer::s_criticalScreenshot;
std::string Renderer::s_sScreenshotName;
Common::Event Renderer::s_screenshotCompleted;
volatile bool Renderer::s_bScreenshot;
// The framebuffer size
int Renderer::s_target_width;
int Renderer::s_target_height;
// TODO: Add functionality to reinit all the render targets when the window is resized.
int Renderer::s_backbuffer_width;
int Renderer::s_backbuffer_height;
PostProcessingShaderImplementation* Renderer::m_post_processor;
TargetRectangle Renderer::target_rc;
int Renderer::s_last_efb_scale;
bool Renderer::XFBWrited;
PEControl::PixelFormat Renderer::prev_efb_format = PEControl::INVALID_FMT;
unsigned int Renderer::efb_scale_numeratorX = 1;
unsigned int Renderer::efb_scale_numeratorY = 1;
unsigned int Renderer::efb_scale_denominatorX = 1;
unsigned int Renderer::efb_scale_denominatorY = 1;
Renderer::Renderer()
: frame_data()
, bLastFrameDumped(false)
{
UpdateActiveConfig();
TextureCache::OnConfigChanged(g_ActiveConfig);
#if defined _WIN32 || defined HAVE_LIBAV
bAVIDumping = false;
#endif
OSDChoice = 0;
OSDTime = 0;
}
Renderer::~Renderer()
{
// invalidate previous efb format
prev_efb_format = PEControl::INVALID_FMT;
efb_scale_numeratorX = efb_scale_numeratorY = efb_scale_denominatorX = efb_scale_denominatorY = 1;
#if defined _WIN32 || defined HAVE_LIBAV
if (SConfig::GetInstance().m_DumpFrames && bLastFrameDumped && bAVIDumping)
AVIDump::Stop();
#else
if (pFrameDump.IsOpen())
pFrameDump.Close();
#endif
}
void Renderer::RenderToXFB(u32 xfbAddr, const EFBRectangle& sourceRc, u32 fbStride, u32 fbHeight, float Gamma)
{
CheckFifoRecording();
if (!fbStride || !fbHeight)
return;
XFBWrited = true;
if (g_ActiveConfig.bUseXFB)
{
FramebufferManagerBase::CopyToXFB(xfbAddr, fbStride, fbHeight, sourceRc, Gamma);
}
else
{
// below div two to convert from bytes to pixels - it expects width, not stride
Swap(xfbAddr, fbStride/2, fbStride/2, fbHeight, sourceRc, Gamma);
}
}
int Renderer::EFBToScaledX(int x)
{
switch (g_ActiveConfig.iEFBScale)
{
case SCALE_AUTO: // fractional
return FramebufferManagerBase::ScaleToVirtualXfbWidth(x);
default:
return x * (int)efb_scale_numeratorX / (int)efb_scale_denominatorX;
};
}
int Renderer::EFBToScaledY(int y)
{
switch (g_ActiveConfig.iEFBScale)
{
case SCALE_AUTO: // fractional
return FramebufferManagerBase::ScaleToVirtualXfbHeight(y);
default:
return y * (int)efb_scale_numeratorY / (int)efb_scale_denominatorY;
};
}
void Renderer::CalculateTargetScale(int x, int y, int* scaledX, int* scaledY)
{
if (g_ActiveConfig.iEFBScale == SCALE_AUTO || g_ActiveConfig.iEFBScale == SCALE_AUTO_INTEGRAL)
{
*scaledX = x;
*scaledY = y;
}
else
{
*scaledX = x * (int)efb_scale_numeratorX / (int)efb_scale_denominatorX;
*scaledY = y * (int)efb_scale_numeratorY / (int)efb_scale_denominatorY;
}
}
// return true if target size changed
bool Renderer::CalculateTargetSize(unsigned int framebuffer_width, unsigned int framebuffer_height)
{
int newEFBWidth, newEFBHeight;
newEFBWidth = newEFBHeight = 0;
// TODO: Ugly. Clean up
switch (s_last_efb_scale)
{
case SCALE_AUTO:
case SCALE_AUTO_INTEGRAL:
newEFBWidth = FramebufferManagerBase::ScaleToVirtualXfbWidth(EFB_WIDTH);
newEFBHeight = FramebufferManagerBase::ScaleToVirtualXfbHeight(EFB_HEIGHT);
if (s_last_efb_scale == SCALE_AUTO_INTEGRAL)
{
newEFBWidth = ((newEFBWidth-1) / EFB_WIDTH + 1) * EFB_WIDTH;
newEFBHeight = ((newEFBHeight-1) / EFB_HEIGHT + 1) * EFB_HEIGHT;
}
efb_scale_numeratorX = newEFBWidth;
efb_scale_denominatorX = EFB_WIDTH;
efb_scale_numeratorY = newEFBHeight;
efb_scale_denominatorY = EFB_HEIGHT;
break;
case SCALE_1X:
efb_scale_numeratorX = efb_scale_numeratorY = 1;
efb_scale_denominatorX = efb_scale_denominatorY = 1;
break;
case SCALE_1_5X:
efb_scale_numeratorX = efb_scale_numeratorY = 3;
efb_scale_denominatorX = efb_scale_denominatorY = 2;
break;
case SCALE_2X:
efb_scale_numeratorX = efb_scale_numeratorY = 2;
efb_scale_denominatorX = efb_scale_denominatorY = 1;
break;
case SCALE_2_5X:
efb_scale_numeratorX = efb_scale_numeratorY = 5;
efb_scale_denominatorX = efb_scale_denominatorY = 2;
break;
default:
efb_scale_numeratorX = efb_scale_numeratorY = s_last_efb_scale - 3;
efb_scale_denominatorX = efb_scale_denominatorY = 1;
int maxSize;
maxSize = GetMaxTextureSize();
if ((unsigned)maxSize < EFB_WIDTH * efb_scale_numeratorX / efb_scale_denominatorX)
{
efb_scale_numeratorX = efb_scale_numeratorY = (maxSize / EFB_WIDTH);
efb_scale_denominatorX = efb_scale_denominatorY = 1;
}
break;
}
if (s_last_efb_scale > SCALE_AUTO_INTEGRAL)
CalculateTargetScale(EFB_WIDTH, EFB_HEIGHT, &newEFBWidth, &newEFBHeight);
if (newEFBWidth != s_target_width || newEFBHeight != s_target_height)
{
s_target_width = newEFBWidth;
s_target_height = newEFBHeight;
return true;
}
return false;
}
void Renderer::ConvertStereoRectangle(const TargetRectangle& rc, TargetRectangle& leftRc, TargetRectangle& rightRc)
{
// Resize target to half its original size
TargetRectangle drawRc = rc;
if (g_ActiveConfig.iStereoMode == STEREO_TAB)
{
// The height may be negative due to flipped rectangles
int height = rc.bottom - rc.top;
drawRc.top += height / 4;
drawRc.bottom -= height / 4;
}
else
{
int width = rc.right - rc.left;
drawRc.left += width / 4;
drawRc.right -= width / 4;
}
// Create two target rectangle offset to the sides of the backbuffer
leftRc = drawRc, rightRc = drawRc;
if (g_ActiveConfig.iStereoMode == STEREO_TAB)
{
leftRc.top -= s_backbuffer_height / 4;
leftRc.bottom -= s_backbuffer_height / 4;
rightRc.top += s_backbuffer_height / 4;
rightRc.bottom += s_backbuffer_height / 4;
}
else
{
leftRc.left -= s_backbuffer_width / 4;
leftRc.right -= s_backbuffer_width / 4;
rightRc.left += s_backbuffer_width / 4;
rightRc.right += s_backbuffer_width / 4;
}
}
void Renderer::SetScreenshot(const std::string& filename)
{
std::lock_guard<std::mutex> lk(s_criticalScreenshot);
s_sScreenshotName = filename;
s_bScreenshot = true;
}
// Create On-Screen-Messages
void Renderer::DrawDebugText()
{
std::string final_yellow, final_cyan;
if (g_ActiveConfig.bShowFPS || SConfig::GetInstance().m_ShowFrameCount)
{
if (g_ActiveConfig.bShowFPS)
final_cyan += StringFromFormat("FPS: %d", g_renderer->m_fps_counter.m_fps);
if (g_ActiveConfig.bShowFPS && SConfig::GetInstance().m_ShowFrameCount)
final_cyan += " - ";
if (SConfig::GetInstance().m_ShowFrameCount)
{
final_cyan += StringFromFormat("Frame: %llu", (unsigned long long) Movie::g_currentFrame);
if (Movie::IsPlayingInput())
final_cyan += StringFromFormat(" / %llu", (unsigned long long) Movie::g_totalFrames);
}
final_cyan += "\n";
final_yellow += "\n";
}
if (SConfig::GetInstance().m_ShowLag)
{
final_cyan += StringFromFormat("Lag: %" PRIu64 "\n", Movie::g_currentLagCount);
final_yellow += "\n";
}
if (SConfig::GetInstance().m_ShowInputDisplay)
{
final_cyan += Movie::GetInputDisplay();
final_yellow += "\n";
}
// OSD Menu messages
if (OSDChoice > 0)
{
OSDTime = Common::Timer::GetTimeMs() + 3000;
OSDChoice = -OSDChoice;
}
if ((u32)OSDTime > Common::Timer::GetTimeMs())
{
std::string res_text;
switch (g_ActiveConfig.iEFBScale)
{
case SCALE_AUTO:
res_text = "Auto (fractional)";
break;
case SCALE_AUTO_INTEGRAL:
res_text = "Auto (integral)";
break;
case SCALE_1X:
res_text = "Native";
break;
case SCALE_1_5X:
res_text = "1.5x";
break;
case SCALE_2X:
res_text = "2x";
break;
case SCALE_2_5X:
res_text = "2.5x";
break;
default:
res_text = StringFromFormat("%dx", g_ActiveConfig.iEFBScale - 3);
break;
}
const char* ar_text = "";
switch (g_ActiveConfig.iAspectRatio)
{
case ASPECT_AUTO:
ar_text = "Auto";
break;
case ASPECT_STRETCH:
ar_text = "Stretch";
break;
case ASPECT_ANALOG:
ar_text = "Force 4:3";
break;
case ASPECT_ANALOG_WIDE:
ar_text = "Force 16:9";
}
const char* const efbcopy_text = g_ActiveConfig.bSkipEFBCopyToRam ? "to Texture" : "to RAM";
// The rows
const std::string lines[] =
{
std::string("Internal Resolution: ") + res_text,
std::string("Aspect Ratio: ") + ar_text + (g_ActiveConfig.bCrop ? " (crop)" : ""),
std::string("Copy EFB: ") + efbcopy_text,
std::string("Fog: ") + (g_ActiveConfig.bDisableFog ? "Disabled" : "Enabled"),
};
enum { lines_count = sizeof(lines) / sizeof(*lines) };
// The latest changed setting in yellow
for (int i = 0; i != lines_count; ++i)
{
if (OSDChoice == -i - 1)
final_yellow += lines[i];
final_yellow += '\n';
}
// The other settings in cyan
for (int i = 0; i != lines_count; ++i)
{
if (OSDChoice != -i - 1)
final_cyan += lines[i];
final_cyan += '\n';
}
}
final_cyan += Common::Profiler::ToString();
if (g_ActiveConfig.bOverlayStats)
final_cyan += Statistics::ToString();
if (g_ActiveConfig.bOverlayProjStats)
final_cyan += Statistics::ToStringProj();
//and then the text
g_renderer->RenderText(final_cyan, 20, 20, 0xFF00FFFF);
g_renderer->RenderText(final_yellow, 20, 20, 0xFFFFFF00);
}
void Renderer::UpdateDrawRectangle(int backbuffer_width, int backbuffer_height)
{
float FloatGLWidth = (float)backbuffer_width;
float FloatGLHeight = (float)backbuffer_height;
float FloatXOffset = 0;
float FloatYOffset = 0;
// The rendering window size
const float WinWidth = FloatGLWidth;
const float WinHeight = FloatGLHeight;
// Update aspect ratio hack values
// Won't take effect until next frame
// Don't know if there is a better place for this code so there isn't a 1 frame delay
if (g_ActiveConfig.bWidescreenHack)
{
float source_aspect = VideoInterface::GetAspectRatio(g_aspect_wide);
float target_aspect;
switch (g_ActiveConfig.iAspectRatio)
{
case ASPECT_STRETCH:
target_aspect = WinWidth / WinHeight;
break;
case ASPECT_ANALOG:
target_aspect = VideoInterface::GetAspectRatio(false);
break;
case ASPECT_ANALOG_WIDE:
target_aspect = VideoInterface::GetAspectRatio(true);
break;
default:
// ASPECT_AUTO
target_aspect = source_aspect;
break;
}
float adjust = source_aspect / target_aspect;
if (adjust > 1)
{
// Vert+
g_Config.fAspectRatioHackW = 1;
g_Config.fAspectRatioHackH = 1 / adjust;
}
else
{
// Hor+
g_Config.fAspectRatioHackW = adjust;
g_Config.fAspectRatioHackH = 1;
}
}
else
{
// Hack is disabled
g_Config.fAspectRatioHackW = 1;
g_Config.fAspectRatioHackH = 1;
}
// Check for force-settings and override.
// The rendering window aspect ratio as a proportion of the 4:3 or 16:9 ratio
float Ratio;
switch (g_ActiveConfig.iAspectRatio)
{
case ASPECT_ANALOG_WIDE:
Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(true);
break;
case ASPECT_ANALOG:
Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(false);
break;
default:
Ratio = (WinWidth / WinHeight) / VideoInterface::GetAspectRatio(g_aspect_wide);
break;
}
if (g_ActiveConfig.iAspectRatio != ASPECT_STRETCH)
{
if (Ratio > 1.0f)
{
// Scale down and center in the X direction.
FloatGLWidth /= Ratio;
FloatXOffset = (WinWidth - FloatGLWidth) / 2.0f;
}
// The window is too high, we have to limit the height
else
{
// Scale down and center in the Y direction.
FloatGLHeight *= Ratio;
FloatYOffset = FloatYOffset + (WinHeight - FloatGLHeight) / 2.0f;
}
}
// -----------------------------------------------------------------------
// Crop the picture from Analog to 4:3 or from Analog (Wide) to 16:9.
// Output: FloatGLWidth, FloatGLHeight, FloatXOffset, FloatYOffset
// ------------------
if (g_ActiveConfig.iAspectRatio != ASPECT_STRETCH && g_ActiveConfig.bCrop)
{
switch (g_ActiveConfig.iAspectRatio)
{
case ASPECT_ANALOG_WIDE:
Ratio = (16.0f / 9.0f) / VideoInterface::GetAspectRatio(true);
break;
case ASPECT_ANALOG:
Ratio = (4.0f / 3.0f) / VideoInterface::GetAspectRatio(false);
break;
default:
Ratio = (!g_aspect_wide ? (4.0f / 3.0f) : (16.0f / 9.0f)) / VideoInterface::GetAspectRatio(g_aspect_wide);
break;
}
if (Ratio <= 1.0f)
{
Ratio = 1.0f / Ratio;
}
// The width and height we will add (calculate this before FloatGLWidth and FloatGLHeight is adjusted)
float IncreasedWidth = (Ratio - 1.0f) * FloatGLWidth;
float IncreasedHeight = (Ratio - 1.0f) * FloatGLHeight;
// The new width and height
FloatGLWidth = FloatGLWidth * Ratio;
FloatGLHeight = FloatGLHeight * Ratio;
// Adjust the X and Y offset
FloatXOffset = FloatXOffset - (IncreasedWidth * 0.5f);
FloatYOffset = FloatYOffset - (IncreasedHeight * 0.5f);
}
int XOffset = (int)(FloatXOffset + 0.5f);
int YOffset = (int)(FloatYOffset + 0.5f);
int iWhidth = (int)ceil(FloatGLWidth);
int iHeight = (int)ceil(FloatGLHeight);
iWhidth -= iWhidth % 4; // ensure divisibility by 4 to make it compatible with all the video encoders
iHeight -= iHeight % 4;
target_rc.left = XOffset;
target_rc.top = YOffset;
target_rc.right = XOffset + iWhidth;
target_rc.bottom = YOffset + iHeight;
}
void Renderer::SetWindowSize(int width, int height)
{
if (width < 1)
width = 1;
if (height < 1)
height = 1;
// Scale the window size by the EFB scale.
CalculateTargetScale(width, height, &width, &height);
Host_RequestRenderWindowSize(width, height);
}
void Renderer::CheckFifoRecording()
{
bool wasRecording = g_bRecordFifoData;
g_bRecordFifoData = FifoRecorder::GetInstance().IsRecording();
if (g_bRecordFifoData)
{
if (!wasRecording)
{
RecordVideoMemory();
}
FifoRecorder::GetInstance().EndFrame(CommandProcessor::fifo.CPBase, CommandProcessor::fifo.CPEnd);
}
}
void Renderer::RecordVideoMemory()
{
u32 *bpmem_ptr = (u32*)&bpmem;
u32 cpmem[256];
// The FIFO recording format splits XF memory into xfmem and xfregs; follow
// that split here.
u32 *xfmem_ptr = (u32*)&xfmem;
u32 *xfregs_ptr = (u32*)&xfmem + FifoDataFile::XF_MEM_SIZE;
u32 xfregs_size = sizeof(XFMemory) / 4 - FifoDataFile::XF_MEM_SIZE;
memset(cpmem, 0, 256 * 4);
FillCPMemoryArray(cpmem);
FifoRecorder::GetInstance().SetVideoMemory(bpmem_ptr, cpmem, xfmem_ptr, xfregs_ptr, xfregs_size);
}
void Renderer::Swap(u32 xfbAddr, u32 fbWidth, u32 fbStride, u32 fbHeight, const EFBRectangle& rc, float Gamma)
{
// TODO: merge more generic parts into VideoCommon
g_renderer->SwapImpl(xfbAddr, fbWidth, fbStride, fbHeight, rc, Gamma);
if (XFBWrited)
g_renderer->m_fps_counter.Update();
frameCount++;
GFX_DEBUGGER_PAUSE_AT(NEXT_FRAME, true);
// Begin new frame
// Set default viewport and scissor, for the clear to work correctly
// New frame
stats.ResetFrame();
Core::Callback_VideoCopiedToXFB(XFBWrited || (g_ActiveConfig.bUseXFB && g_ActiveConfig.bUseRealXFB));
XFBWrited = false;
}
void Renderer::PokeEFB(EFBAccessType type, const std::vector<EfbPokeData>& data)
{
for (EfbPokeData poke : data)
{
AccessEFB(type, poke.x, poke.y, poke.data);
}
}
| aroulin/dolphin | Source/Core/VideoCommon/RenderBase.cpp | C++ | gpl-2.0 | 17,004 |
/* This testcase is part of GDB, the GNU debugger.
Copyright 2014-2016 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 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/>. */
extern int shlib_1_func (void);
int
main ()
{
/* We need a reference to shlib_1_func to make sure its shlib is
not discarded from the link. This happens on windows. */
int x = shlib_1_func ();
return 0;
}
| swigger/gdb-ios | gdb/testsuite/gdb.base/symtab-search-order.c | C | gpl-2.0 | 974 |
<?php
wp_enqueue_script( 'pods' );
wp_enqueue_style( 'pods-form' );
if ( empty( $fields ) || !is_array( $fields ) )
$fields = $obj->pod->fields;
if ( !isset( $duplicate ) )
$duplicate = false;
else
$duplicate = (boolean) $duplicate;
$groups = PodsInit::$meta->groups_get( $pod->pod_data[ 'type' ], $pod->pod_data[ 'name' ], $fields );
$group_fields = array();
$submittable_fields = array();
foreach ( $groups as $g => $group ) {
// unset fields
foreach ( $group[ 'fields' ] as $k => $field ) {
if ( in_array( $field[ 'name' ], array( 'created', 'modified' ) ) ) {
unset( $group[ 'fields' ][ $k ] );
continue;
}
elseif ( false === PodsForm::permission( $field[ 'type' ], $field[ 'name' ], $field[ 'options' ], $group[ 'fields' ], $pod, $pod->id() ) ) {
if ( pods_var( 'hidden', $field[ 'options' ], false ) ) {
$group[ 'fields' ][ $k ][ 'type' ] = 'hidden';
}
elseif ( pods_var( 'read_only', $field[ 'options' ], false ) ) {
$group[ 'fields' ][ $k ][ 'readonly' ] = true;
}
else {
unset( $group[ 'fields' ][ $k ] );
continue;
}
}
elseif ( !pods_has_permissions( $field[ 'options' ] ) ) {
if ( pods_var( 'hidden', $field[ 'options' ], false ) ) {
$group[ 'fields' ][ $k ][ 'type' ] = 'hidden';
}
elseif ( pods_var( 'read_only', $field[ 'options' ], false ) ) {
$group[ 'fields' ][ $k ][ 'readonly' ] = true;
}
}
if ( !pods_var( 'readonly', $field, false ) ) {
$submittable_fields[ $field[ 'name' ]] = $group[ 'fields' ][ $k ];
}
$group_fields[ $field[ 'name' ] ] = $group[ 'fields' ][ $k ];
}
$groups[ $g ] = $group;
}
if ( !isset( $thank_you_alt ) )
$thank_you_alt = $thank_you;
$uri_hash = wp_create_nonce( 'pods_uri_' . $_SERVER[ 'REQUEST_URI' ] );
$field_hash = wp_create_nonce( 'pods_fields_' . implode( ',', array_keys( $submittable_fields ) ) );
$uid = @session_id();
if ( is_user_logged_in() )
$uid = 'user_' . get_current_user_id();
$nonce = wp_create_nonce( 'pods_form_' . $pod->pod . '_' . $uid . '_' . ( $duplicate ? 0 : $pod->id() ) . '_' . $uri_hash . '_' . $field_hash );
if ( isset( $_POST[ '_pods_nonce' ] ) ) {
$action = __( 'saved', 'pods' );
if ( 'create' == pods_var_raw( 'do', 'post', 'save' ) )
$action = __( 'created', 'pods' );
elseif ( 'duplicate' == pods_var_raw( 'do', 'get', 'save' ) )
$action = __( 'duplicated', 'pods' );
try {
$params = pods_unslash( (array) $_POST );
$id = $pod->api->process_form( $params, $pod, $submittable_fields, $thank_you );
$message = sprintf( __( '<strong>Success!</strong> %s %s successfully.', 'pods' ), $obj->item, $action );
if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) )
$message .= ' <a target="_blank" href="' . $pod->field( 'detail_url' ) . '">' . sprintf( __( 'View %s', 'pods' ), $obj->item ) . '</a>';
$error = sprintf( __( '<strong>Error:</strong> %s %s successfully.', 'pods' ), $obj->item, $action );
if ( 0 < $id )
echo $obj->message( $message );
else
echo $obj->error( $error );
}
catch ( Exception $e ) {
echo $obj->error( $e->getMessage() );
}
}
elseif ( isset( $_GET[ 'do' ] ) ) {
$action = __( 'saved', 'pods' );
if ( 'create' == pods_var_raw( 'do', 'get', 'save' ) )
$action = __( 'created', 'pods' );
elseif ( 'duplicate' == pods_var_raw( 'do', 'get', 'save' ) )
$action = __( 'duplicated', 'pods' );
$message = sprintf( __( '<strong>Success!</strong> %s %s successfully.', 'pods' ), $obj->item, $action );
if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) )
$message .= ' <a target="_blank" href="' . $pod->field( 'detail_url' ) . '">' . sprintf( __( 'View %s', 'pods' ), $obj->item ) . '</a>';
$error = sprintf( __( '<strong>Error:</strong> %s not %s.', 'pods' ), $obj->item, $action );
if ( 0 < $pod->id() )
echo $obj->message( $message );
else
echo $obj->error( $error );
}
if ( !isset( $label ) )
$label = __( 'Save', 'pods' );
$do = 'create';
if ( 0 < $pod->id() ) {
if ( $duplicate )
$do = 'duplicate';
else
$do = 'save';
}
?>
<form action="" method="post" class="pods-submittable pods-form pods-form-pod-<?php echo $pod->pod; ?> pods-submittable-ajax">
<div class="pods-submittable-fields">
<?php
echo PodsForm::field( 'action', 'pods_admin', 'hidden' );
echo PodsForm::field( 'method', 'process_form', 'hidden' );
echo PodsForm::field( 'do', $do, 'hidden' );
echo PodsForm::field( '_pods_nonce', $nonce, 'hidden' );
echo PodsForm::field( '_pods_pod', $pod->pod, 'hidden' );
echo PodsForm::field( '_pods_id', ( $duplicate ? 0 : $pod->id() ), 'hidden' );
echo PodsForm::field( '_pods_uri', $uri_hash, 'hidden' );
echo PodsForm::field( '_pods_form', implode( ',', array_keys( $submittable_fields ) ), 'hidden' );
echo PodsForm::field( '_pods_location', $_SERVER[ 'REQUEST_URI' ], 'hidden' );
foreach ( $group_fields as $field ) {
if ( 'hidden' != $field[ 'type' ] )
continue;
echo PodsForm::field( 'pods_field_' . $field[ 'name' ], $pod->field( array( 'name' => $field[ 'name' ], 'in_form' => true ) ), 'hidden' );
}
/**
* Action that runs before the meta boxes for an Advanced Content Type
*
* Occurs at the top of #poststuff
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
do_action( 'pods_meta_box_pre', $pod, $obj );
?>
<div id="poststuff" class="metabox-holder has-right-sidebar"> <!-- class "has-right-sidebar" preps for a sidebar... always present? -->
<div id="side-info-column" class="inner-sidebar">
<?php
/**
* Action that runs before the sidebar of the editor for an Advanced Content Type
*
* Occurs at the top of #side-info-column
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_before_sidebar', $pod, $obj );
?>
<div id="side-sortables" class="meta-box-sortables ui-sortable">
<!-- BEGIN PUBLISH DIV -->
<div id="submitdiv" class="postbox">
<div class="handlediv" title="Click to toggle"><br /></div>
<h3 class="hndle"><span><?php _e( 'Manage', 'pods' ); ?></span></h3>
<div class="inside">
<div class="submitbox" id="submitpost">
<?php
if ( 0 < $pod->id() && ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) || isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) || 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) ) ) {
?>
<div id="minor-publishing">
<?php
if ( 0 < strlen( pods_var( 'detail_url', $pod->pod_data[ 'options' ] ) ) ) {
?>
<div id="minor-publishing-actions">
<div id="preview-action">
<a class="button" href="<?php echo $pod->field( 'detail_url' ); ?>" target="_blank"><?php echo sprintf( __( 'View %s', 'pods' ), $obj->item ); ?></a>
</div>
<div class="clear"></div>
</div>
<?php
}
if ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) || isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) ) {
?>
<div id="misc-publishing-actions">
<?php
$datef = __( 'M j, Y @ G:i' );
if ( isset( $pod->pod_data[ 'fields' ][ 'created' ] ) ) {
$date = date_i18n( $datef, strtotime( $pod->field( 'created' ) ) );
?>
<div class="misc-pub-section curtime">
<span id="timestamp"><?php _e( 'Created on', 'pods' ); ?>: <b><?php echo $date; ?></b></span>
</div>
<?php
}
if ( isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) && $pod->display( 'created' ) != $pod->display( 'modified' ) ) {
$date = date_i18n( $datef, strtotime( $pod->field( 'modified' ) ) );
?>
<div class="misc-pub-section curtime">
<span id="timestamp"><?php _e( 'Last Modified', 'pods' ); ?>: <b><?php echo $date; ?></b></span>
</div>
<?php
}
?>
<?php
/**
* Action that runs after the misc publish actions area for an Advanced Content Type
*
* Occurs at the end of #misc-publishing-actions
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
do_action( 'pods_ui_form_misc_pub_actions', $pod, $obj );
?>
</div>
<?php
}
?>
</div>
<!-- /#minor-publishing -->
<?php
}
?>
<div id="major-publishing-actions">
<?php
if ( pods_is_admin( array( 'pods', 'pods_delete_' . $pod->pod ) ) && null !== $pod->id() && !$duplicate && !in_array( 'delete', (array) $obj->actions_disabled ) && !in_array( 'delete', (array) $obj->actions_hidden ) ) {
?>
<div id="delete-action">
<a class="submitdelete deletion" href="<?php echo pods_var_update( array( 'action' => 'delete' ) ) ?>" onclick="return confirm('You are about to permanently delete this item\n Choose \'Cancel\' to stop, \'OK\' to delete.');"><?php _e( 'Delete', 'pods' ); ?></a>
</div>
<!-- /#delete-action -->
<?php } ?>
<div id="publishing-action">
<img class="waiting" src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" alt="" />
<input type="submit" name="publish" id="publish" class="button button-primary button-large" value="<?php echo esc_attr( $label ); ?>" accesskey="p" />
<?php
/**
* Action that runs after the publish button for an Advanced Content Type
*
* Occurs at the end of #publishing-action
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
do_action( 'pods_ui_form_submit_area', $pod, $obj );
?>
</div>
<!-- /#publishing-action -->
<div class="clear"></div>
</div>
<?php
/**
* Action that runs after the publish area for an Advanced Content Type
*
* Occurs at the end of #submitpost
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
do_action( 'pods_ui_form_publish_area', $pod, $obj );
?>
<!-- /#major-publishing-actions -->
</div>
<!-- /#submitpost -->
</div>
<!-- /.inside -->
</div>
<!-- /#submitdiv --><!-- END PUBLISH DIV --><!-- TODO: minor column fields -->
<?php
if ( pods_var_raw( 'action' ) == 'edit' && !$duplicate && !in_array( 'navigate', (array) $obj->actions_disabled ) && !in_array( 'navigate', (array) $obj->actions_hidden ) ) {
if ( !isset( $singular_label ) )
$singular_label = ucwords( str_replace( '_', ' ', $pod->pod_data[ 'name' ] ) );
$singular_label = pods_var_raw( 'label', $pod->pod_data[ 'options' ], $singular_label, null, true );
$singular_label = pods_var_raw( 'label_singular', $pod->pod_data[ 'options' ], $singular_label, null, true );
$pod->params = $obj->get_params( null, 'manage' );
$prev_next = apply_filters( 'pods_ui_prev_next_ids', array(), $pod, $obj );
if ( empty( $prev_next ) ) {
$prev_next = array(
'prev' => $pod->prev_id(),
'next' => $pod->next_id()
);
}
$prev = $prev_next[ 'prev' ];
$next = $prev_next[ 'next' ];
if ( 0 < $prev || 0 < $next ) {
?>
<div id="navigatediv" class="postbox">
<?php
/**
* Action that runs before the post navagiation in the editor for an Advanced Content Type
*
* Occurs at the top of #navigatediv
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_before_navigation', $pod, $obj );
?>
<div class="handlediv" title="Click to toggle"><br /></div>
<h3 class="hndle"><span><?php _e( 'Navigate', 'pods' ); ?></span></h3>
<div class="inside">
<div class="pods-admin" id="navigatebox">
<div id="navigation-actions">
<?php
if ( 0 < $prev ) {
?>
<a class="previous-item" href="<?php echo pods_var_update( array( 'id' => $prev ), null, 'do' ); ?>">
<span>«</span>
<?php echo sprintf( __( 'Previous %s', 'pods' ), $singular_label ); ?>
</a>
<?php
}
if ( 0 < $next ) {
?>
<a class="next-item" href="<?php echo pods_var_update( array( 'id' => $next ), null, 'do' ); ?>">
<?php echo sprintf( __( 'Next %s', 'pods' ), $singular_label ); ?>
<span>»</span>
</a>
<?php
}
?>
<div class="clear"></div>
</div>
<!-- /#navigation-actions -->
</div>
<!-- /#navigatebox -->
</div>
<!-- /.inside -->
<?php
/**
* Action that runs after the post navagiation in the editor for an Advanced Content Type
*
* Occurs at the bottom of #navigatediv
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_after_navigation', $pod, $obj );
?>
</div> <!-- /#navigatediv -->
<?php
}
}
?>
</div>
<!-- /#side-sortables -->
<?php
/**
* Action that runs after the sidebar of the editor for an Advanced Content Type
*
* Occurs at the bottom of #side-info-column
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_after_sidebar', $pod, $obj );
?>
</div>
<!-- /#side-info-column -->
<div id="post-body">
<div id="post-body-content">
<?php
$more = false;
if ( $pod->pod_data[ 'field_index' ] != $pod->pod_data[ 'field_id' ] ) {
foreach ( $group_fields as $field ) {
if ( $pod->pod_data[ 'field_index' ] != $field[ 'name' ] || 'text' != $field[ 'type' ] )
continue;
$more = true;
$extra = '';
$max_length = (int) pods_var( 'maxlength', $field[ 'options' ], pods_var( $field[ 'type' ] . '_max_length', $field[ 'options' ], 0 ), null, true );
if ( 0 < $max_length )
$extra .= ' maxlength="' . $max_length . '"';
/**
* Filter that lets you make the title field readonly
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.5
*/
if ( pods_v( 'readonly', $field[ 'options' ], pods_v( 'readonly', $field, false ) ) || apply_filters( 'pods_ui_form_title_readonly', false, $pod, $obj ) ) {
?>
<div id="titlediv">
<div id="titlewrap">
<h3><?php echo esc_html( $pod->index() ); ?></h3>
<input type="hidden" name="pods_field_<?php echo $pod->pod_data[ 'field_index' ]; ?>" data-name-clean="pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" id="title" size="30" tabindex="1" value="<?php echo esc_attr( htmlspecialchars( $pod->index() ) ); ?>" class="pods-form-ui-field-name-pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" autocomplete="off"<?php echo $extra; ?> />
</div>
<!-- /#titlewrap -->
</div>
<!-- /#titlediv -->
<?php
}
else {
?>
<div id="titlediv">
<?php
/**
* Action that runs before the title field of the editor for an Advanced Content Type
*
* Occurs at the top of #titlediv
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_before_title', $pod, $obj );
?>
<div id="titlewrap">
<label class="screen-reader-text" id="title-prompt-text" for="title"><?php echo apply_filters( 'pods_enter_name_here', __( 'Enter name here', 'pods' ), $pod, $fields ); ?></label>
<input type="text" name="pods_field_<?php echo $pod->pod_data[ 'field_index' ]; ?>" data-name-clean="pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" id="title" size="30" tabindex="1" value="<?php echo esc_attr( htmlspecialchars( $pod->index() ) ); ?>" class="pods-form-ui-field-name-pods-field-<?php echo $pod->pod_data[ 'field_index' ]; ?>" autocomplete="off"<?php echo $extra; ?> />
<?php
/**
* Action that runs after the title field of the editor for an Advanced Content Type
*
* Occurs at the bottom of #titlediv
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_after_title', $pod, $obj );
?>
</div>
<!-- /#titlewrap -->
<div class="inside">
<div id="edit-slug-box">
</div>
<!-- /#edit-slug-box -->
</div>
<!-- /.inside -->
</div>
<!-- /#titlediv -->
<?php
}
unset( $group_fields[ $field[ 'name' ] ] );
}
}
if ( 0 < count( $groups ) ) {
if ( $more && 1 == count( $groups ) ) {
$first_group = current( $groups );
if ( 1 == count( $first_group[ 'fields' ] ) && isset( $first_group[ 'fields' ][ $pod->pod_data[ 'field_index' ] ] ) ) {
$groups = array();
}
}
if ( 0 < count( $groups ) ) {
?>
<div id="normal-sortables" class="meta-box-sortables ui-sortable">
<?php
foreach ( $groups as $group ) {
if ( empty( $group[ 'fields' ] ) ) {
continue;
}
/**
* Action that runs before the main fields metabox in the editor for an Advanced Content Type
*
* Occurs at the top of #normal-sortables
*
* @param obj $pod Current Pods object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_before_metabox', $pod );
?>
<div id="pods-meta-box-<?php echo sanitize_title( $group[ 'label' ] ); ?>" class="postbox" style="">
<div class="handlediv" title="Click to toggle"><br /></div>
<h3 class="hndle">
<span>
<?php
if ( ! $more && 1 == count( $groups ) ) {
$title = __( 'Fields', 'pods' );
}
else {
$title = $group[ 'label' ];
}
/** This filter is documented in classes/PodsMeta.php */
echo apply_filters( 'pods_meta_default_box_title', $title, $pod, $fields, $pod->api->pod_data[ 'type' ], $pod->pod );
?>
</span>
</h3>
<div class="inside">
<?php
if ( false === apply_filters( 'pods_meta_box_override', false, $pod, $group, $obj ) ) {
?>
<table class="form-table pods-metabox">
<?php
foreach ( $group[ 'fields' ] as $field ) {
if ( 'hidden' == $field[ 'type' ] || $more === $field[ 'name' ] || !isset( $group_fields[ $field[ 'name' ] ] ) )
continue;
?>
<tr class="form-field pods-field pods-field-input <?php echo 'pods-form-ui-row-type-' . $field[ 'type' ] . ' pods-form-ui-row-name-' . PodsForm::clean( $field[ 'name' ], true ); ?>">
<th scope="row" valign="top"><?php echo PodsForm::label( 'pods_field_' . $field[ 'name' ], $field[ 'label' ], $field[ 'help' ], $field ); ?></th>
<td>
<?php echo PodsForm::field( 'pods_field_' . $field[ 'name' ], $pod->field( array( 'name' => $field[ 'name' ], 'in_form' => true ) ), $field[ 'type' ], $field, $pod, $pod->id() ); ?>
<?php echo PodsForm::comment( 'pods_field_' . $field[ 'name' ], $field[ 'description' ], $field ); ?>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
</div>
<!-- /.inside -->
</div>
<!-- /#pods-meta-box -->
<?php
}
/**
* Action that runs after the main fields metabox in the editor for an Advanced Content Type
*
* Occurs at the bottom of #normal-sortables
*
* @param Pods $pod Current Pods object.
* @param PodsUI $obj Current PodsUI object.
*
* @since 2.4.1
*/
do_action( 'pods_act_editor_after_metabox', $pod, $obj );
?>
</div>
<!-- /#normal-sortables -->
<?php
}
}
?>
<!--<div id="advanced-sortables" class="meta-box-sortables ui-sortable">
</div>
/#advanced-sortables -->
</div>
<!-- /#post-body-content -->
<br class="clear" />
</div>
<!-- /#post-body -->
<br class="clear" />
</div>
<!-- /#poststuff -->
</div>
</form>
<!-- /#pods-record -->
<script type="text/javascript">
if ( 'undefined' == typeof ajaxurl ) {
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
}
jQuery( function ( $ ) {
$( document ).Pods( 'validate' );
$( document ).Pods( 'submit' );
$( document ).Pods( 'dependency' );
$( document ).Pods( 'confirm' );
$( document ).Pods( 'exit_confirm' );
} );
if ( 'undefined' == typeof pods_form_thank_you ) {
var pods_form_thank_you = null;
}
var pods_admin_submit_callback = function ( id ) {
id = parseInt( id );
var thank_you = '<?php echo pods_slash( $thank_you ); ?>';
var thank_you_alt = '<?php echo pods_slash( $thank_you_alt ); ?>';
if ( 'undefined' != typeof pods_form_thank_you && null !== pods_form_thank_you ) {
thank_you = pods_form_thank_you;
}
if ( 'NaN' == id )
document.location = thank_you_alt.replace( 'X_ID_X', 0 );
else
document.location = thank_you.replace( 'X_ID_X', id );
}
</script>
| nbrouse-deep/chefmatefrontburner_com | wp-content/plugins/pods/ui/admin/form.php | PHP | gpl-2.0 | 30,874 |
/**
* Colors
*/
/**
* Breakpoints & Media Queries
*/
/**
* SCSS Variables.
*
* Please use variables from this sheet to ensure consistency across the UI.
* Don't add to this sheet unless you're pretty sure the value will be reused in many places.
* For example, don't add rules to this sheet that affect block visuals. It's purely for UI.
*/
/**
* Colors
*/
/**
* Fonts & basic variables.
*/
/**
* Grid System.
* https://make.wordpress.org/design/2019/10/31/proposal-a-consistent-spacing-system-for-wordpress/
*/
/**
* Dimensions.
*/
/**
* Shadows.
*/
/**
* Editor widths.
*/
/**
* Block & Editor UI.
*/
/**
* Block paddings.
*/
/**
* React Native specific.
* These variables do not appear to be used anywhere else.
*/
/**
* Breakpoint mixins
*/
/**
* Long content fade mixin
*
* Creates a fading overlay to signify that the content is longer
* than the space allows.
*/
/**
* Focus styles.
*/
/**
* Applies editor left position to the selector passed as argument
*/
/**
* Styles that are reused verbatim in a few places
*/
/**
* Allows users to opt-out of animations via OS-level preferences.
*/
/**
* Reset default styles for JavaScript UI based pages.
* This is a WP-admin agnostic reset
*/
/**
* Reset the WP Admin page styles for Gutenberg-like pages.
*/
ol.wp-block-latest-comments {
margin-left: 0;
}
.wp-block-latest-comments .wp-block-latest-comments {
padding-left: 0;
}
.wp-block-latest-comments__comment {
line-height: 1.1;
list-style: none;
margin-bottom: 1em;
}
.has-avatars .wp-block-latest-comments__comment {
min-height: 2.25em;
list-style: none;
}
.has-avatars .wp-block-latest-comments__comment .wp-block-latest-comments__comment-meta,
.has-avatars .wp-block-latest-comments__comment .wp-block-latest-comments__comment-excerpt {
margin-left: 3.25em;
}
.has-dates .wp-block-latest-comments__comment, .has-excerpts .wp-block-latest-comments__comment {
line-height: 1.5;
}
.wp-block-latest-comments__comment-excerpt p {
font-size: 0.875em;
line-height: 1.8;
margin: 0.36em 0 1.4em;
}
.wp-block-latest-comments__comment-date {
display: block;
font-size: 0.75em;
}
.wp-block-latest-comments .avatar,
.wp-block-latest-comments__comment-avatar {
border-radius: 1.5em;
display: block;
float: left;
height: 2.5em;
margin-right: 0.75em;
width: 2.5em;
} | CityOfPhiladelphia/phila.gov | wp/wp-includes/blocks/latest-comments/style.css | CSS | gpl-2.0 | 2,355 |
/*
* Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Death_knight_darkreaver
SD%Complete: 100
SDComment:
SDCategory: Scholomance
EndScriptData */
#include "ScriptPCH.h"
class boss_death_knight_darkreaver : public CreatureScript
{
public:
boss_death_knight_darkreaver() : CreatureScript("boss_death_knight_darkreaver") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_death_knight_darkreaverAI (pCreature);
}
struct boss_death_knight_darkreaverAI : public ScriptedAI
{
boss_death_knight_darkreaverAI(Creature *c) : ScriptedAI(c) {}
void Reset()
{
}
void DamageTaken(Unit * /*done_by*/, uint32 &damage)
{
if (me->GetHealth() <= damage)
DoCast(me, 23261, true); //Summon Darkreaver's Fallen Charger
}
void EnterCombat(Unit * /*who*/)
{
}
};
};
void AddSC_boss_death_knight_darkreaver()
{
new boss_death_knight_darkreaver();
}
| sureandrew/trinitycore | src/server/scripts/EasternKingdoms/Scholomance/boss_death_knight_darkreaver.cpp | C++ | gpl-2.0 | 1,778 |
//
// Copyright(C) 1993-1996 Id Software, Inc.
// Copyright(C) 2005-2014 Simon Howard
//
// 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.
//
// DESCRIPTION:
// Mission begin melt/wipe screen special effect.
//
#include <string.h>
#include "z_zone.h"
#include "i_video.h"
#include "v_video.h"
#include "m_random.h"
#include "doomtype.h"
#include "f_wipe.h"
//
// SCREEN WIPE PACKAGE
//
// when zero, stop the wipe
static boolean go = 0;
static byte* wipe_scr_start;
static byte* wipe_scr_end;
static byte* wipe_scr;
void
wipe_shittyColMajorXform
( short* array,
int width,
int height )
{
int x;
int y;
short* dest;
dest = (short*) Z_Malloc(width*height*2, PU_STATIC, 0);
for(y=0;y<height;y++)
for(x=0;x<width;x++)
dest[x*height+y] = array[y*width+x];
memcpy(array, dest, width*height*2);
Z_Free(dest);
}
int
wipe_initColorXForm
( int width,
int height,
int ticks )
{
memcpy(wipe_scr, wipe_scr_start, width*height);
return 0;
}
int
wipe_doColorXForm
( int width,
int height,
int ticks )
{
boolean changed;
byte* w;
byte* e;
int newval;
changed = false;
w = wipe_scr;
e = wipe_scr_end;
while (w!=wipe_scr+width*height)
{
if (*w != *e)
{
if (*w > *e)
{
newval = *w - ticks;
if (newval < *e)
*w = *e;
else
*w = newval;
changed = true;
}
else if (*w < *e)
{
newval = *w + ticks;
if (newval > *e)
*w = *e;
else
*w = newval;
changed = true;
}
}
w++;
e++;
}
return !changed;
}
int
wipe_exitColorXForm
( int width,
int height,
int ticks )
{
return 0;
}
static int* y;
int
wipe_initMelt
( int width,
int height,
int ticks )
{
int i, r;
// copy start screen to main screen
memcpy(wipe_scr, wipe_scr_start, width*height);
// makes this wipe faster (in theory)
// to have stuff in column-major format
wipe_shittyColMajorXform((short*)wipe_scr_start, width/2, height);
wipe_shittyColMajorXform((short*)wipe_scr_end, width/2, height);
// setup initial column positions
// (y<0 => not ready to scroll yet)
y = (int *) Z_Malloc(width*sizeof(int), PU_STATIC, 0);
y[0] = -(M_Random()%16);
for (i=1;i<width;i++)
{
r = (M_Random()%3) - 1;
y[i] = y[i-1] + r;
if (y[i] > 0) y[i] = 0;
else if (y[i] == -16) y[i] = -15;
}
return 0;
}
int
wipe_doMelt
( int width,
int height,
int ticks )
{
int i;
int j;
int dy;
int idx;
short* s;
short* d;
boolean done = true;
width/=2;
while (ticks--)
{
for (i=0;i<width;i++)
{
if (y[i]<0)
{
y[i]++; done = false;
}
else if (y[i] < height)
{
dy = (y[i] < 16) ? y[i]+1 : 8;
if (y[i]+dy >= height) dy = height - y[i];
s = &((short *)wipe_scr_end)[i*height+y[i]];
d = &((short *)wipe_scr)[y[i]*width+i];
idx = 0;
for (j=dy;j;j--)
{
d[idx] = *(s++);
idx += width;
}
y[i] += dy;
s = &((short *)wipe_scr_start)[i*height];
d = &((short *)wipe_scr)[y[i]*width+i];
idx = 0;
for (j=height-y[i];j;j--)
{
d[idx] = *(s++);
idx += width;
}
done = false;
}
}
}
return done;
}
int
wipe_exitMelt
( int width,
int height,
int ticks )
{
Z_Free(y);
Z_Free(wipe_scr_start);
Z_Free(wipe_scr_end);
return 0;
}
int
wipe_StartScreen
( int x,
int y,
int width,
int height )
{
wipe_scr_start = Z_Malloc(SCREENWIDTH * SCREENHEIGHT, PU_STATIC, NULL);
I_ReadScreen(wipe_scr_start);
return 0;
}
int
wipe_EndScreen
( int x,
int y,
int width,
int height )
{
wipe_scr_end = Z_Malloc(SCREENWIDTH * SCREENHEIGHT, PU_STATIC, NULL);
I_ReadScreen(wipe_scr_end);
V_DrawBlock(x, y, width, height, wipe_scr_start); // restore start scr.
return 0;
}
int
wipe_ScreenWipe
( int wipeno,
int x,
int y,
int width,
int height,
int ticks )
{
int rc;
static int (*wipes[])(int, int, int) =
{
wipe_initColorXForm, wipe_doColorXForm, wipe_exitColorXForm,
wipe_initMelt, wipe_doMelt, wipe_exitMelt
};
// initial stuff
if (!go)
{
go = 1;
// wipe_scr = (byte *) Z_Malloc(width*height, PU_STATIC, 0); // DEBUG
wipe_scr = I_VideoBuffer;
(*wipes[wipeno*3])(width, height, ticks);
}
// do a piece of wipe-in
V_MarkRect(0, 0, width, height);
rc = (*wipes[wipeno*3+1])(width, height, ticks);
// V_DrawBlock(x, y, 0, width, height, wipe_scr); // DEBUG
// final stuff
if (rc)
{
go = 0;
(*wipes[wipeno*3+2])(width, height, ticks);
}
return !go;
}
| WarlockD/crispy-doom | stm32/chocolate/chocdoom/f_wipe.c | C | gpl-2.0 | 5,076 |
/*
* tg3.c: Broadcom Tigon3 ethernet driver.
*
* Copyright (C) 2001, 2002, 2003, 2004 David S. Miller (davem@redhat.com)
* Copyright (C) 2001, 2002, 2003 Jeff Garzik (jgarzik@pobox.com)
* Copyright (C) 2004 Sun Microsystems Inc.
* Copyright (C) 2005-2014 Broadcom Corporation.
*
* Firmware is:
* Derived from proprietary unpublished source code,
* Copyright (C) 2000-2003 Broadcom Corporation.
*
* Permission is hereby granted for the distribution of this firmware
* data in hexadecimal or equivalent format, provided this copyright
* notice is accompanying it.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/stringify.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/compiler.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/in.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <linux/mdio.h>
#include <linux/mii.h>
#include <linux/phy.h>
#include <linux/brcmphy.h>
#include <linux/if.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/workqueue.h>
#include <linux/prefetch.h>
#include <linux/dma-mapping.h>
#include <linux/firmware.h>
#include <linux/ssb/ssb_driver_gige.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <net/checksum.h>
#include <net/ip.h>
#include <linux/io.h>
#include <asm/byteorder.h>
#include <linux/uaccess.h>
#include <uapi/linux/net_tstamp.h>
#include <linux/ptp_clock_kernel.h>
#ifdef CONFIG_SPARC
#include <asm/idprom.h>
#include <asm/prom.h>
#endif
#define BAR_0 0
#define BAR_2 2
#include "tg3.h"
/* Functions & macros to verify TG3_FLAGS types */
static inline int _tg3_flag(enum TG3_FLAGS flag, unsigned long *bits)
{
return test_bit(flag, bits);
}
static inline void _tg3_flag_set(enum TG3_FLAGS flag, unsigned long *bits)
{
set_bit(flag, bits);
}
static inline void _tg3_flag_clear(enum TG3_FLAGS flag, unsigned long *bits)
{
clear_bit(flag, bits);
}
#define tg3_flag(tp, flag) \
_tg3_flag(TG3_FLAG_##flag, (tp)->tg3_flags)
#define tg3_flag_set(tp, flag) \
_tg3_flag_set(TG3_FLAG_##flag, (tp)->tg3_flags)
#define tg3_flag_clear(tp, flag) \
_tg3_flag_clear(TG3_FLAG_##flag, (tp)->tg3_flags)
#define DRV_MODULE_NAME "tg3"
#define TG3_MAJ_NUM 3
#define TG3_MIN_NUM 137
#define DRV_MODULE_VERSION \
__stringify(TG3_MAJ_NUM) "." __stringify(TG3_MIN_NUM)
#define DRV_MODULE_RELDATE "May 11, 2014"
#define RESET_KIND_SHUTDOWN 0
#define RESET_KIND_INIT 1
#define RESET_KIND_SUSPEND 2
#define TG3_DEF_RX_MODE 0
#define TG3_DEF_TX_MODE 0
#define TG3_DEF_MSG_ENABLE \
(NETIF_MSG_DRV | \
NETIF_MSG_PROBE | \
NETIF_MSG_LINK | \
NETIF_MSG_TIMER | \
NETIF_MSG_IFDOWN | \
NETIF_MSG_IFUP | \
NETIF_MSG_RX_ERR | \
NETIF_MSG_TX_ERR)
#define TG3_GRC_LCLCTL_PWRSW_DELAY 100
/* length of time before we decide the hardware is borked,
* and dev->tx_timeout() should be called to fix the problem
*/
#define TG3_TX_TIMEOUT (5 * HZ)
/* hardware minimum and maximum for a single frame's data payload */
#define TG3_MIN_MTU 60
#define TG3_MAX_MTU(tp) \
(tg3_flag(tp, JUMBO_CAPABLE) ? 9000 : 1500)
/* These numbers seem to be hard coded in the NIC firmware somehow.
* You can't change the ring sizes, but you can change where you place
* them in the NIC onboard memory.
*/
#define TG3_RX_STD_RING_SIZE(tp) \
(tg3_flag(tp, LRG_PROD_RING_CAP) ? \
TG3_RX_STD_MAX_SIZE_5717 : TG3_RX_STD_MAX_SIZE_5700)
#define TG3_DEF_RX_RING_PENDING 200
#define TG3_RX_JMB_RING_SIZE(tp) \
(tg3_flag(tp, LRG_PROD_RING_CAP) ? \
TG3_RX_JMB_MAX_SIZE_5717 : TG3_RX_JMB_MAX_SIZE_5700)
#define TG3_DEF_RX_JUMBO_RING_PENDING 100
/* Do not place this n-ring entries value into the tp struct itself,
* we really want to expose these constants to GCC so that modulo et
* al. operations are done with shifts and masks instead of with
* hw multiply/modulo instructions. Another solution would be to
* replace things like '% foo' with '& (foo - 1)'.
*/
#define TG3_TX_RING_SIZE 512
#define TG3_DEF_TX_RING_PENDING (TG3_TX_RING_SIZE - 1)
#define TG3_RX_STD_RING_BYTES(tp) \
(sizeof(struct tg3_rx_buffer_desc) * TG3_RX_STD_RING_SIZE(tp))
#define TG3_RX_JMB_RING_BYTES(tp) \
(sizeof(struct tg3_ext_rx_buffer_desc) * TG3_RX_JMB_RING_SIZE(tp))
#define TG3_RX_RCB_RING_BYTES(tp) \
(sizeof(struct tg3_rx_buffer_desc) * (tp->rx_ret_ring_mask + 1))
#define TG3_TX_RING_BYTES (sizeof(struct tg3_tx_buffer_desc) * \
TG3_TX_RING_SIZE)
#define NEXT_TX(N) (((N) + 1) & (TG3_TX_RING_SIZE - 1))
#define TG3_DMA_BYTE_ENAB 64
#define TG3_RX_STD_DMA_SZ 1536
#define TG3_RX_JMB_DMA_SZ 9046
#define TG3_RX_DMA_TO_MAP_SZ(x) ((x) + TG3_DMA_BYTE_ENAB)
#define TG3_RX_STD_MAP_SZ TG3_RX_DMA_TO_MAP_SZ(TG3_RX_STD_DMA_SZ)
#define TG3_RX_JMB_MAP_SZ TG3_RX_DMA_TO_MAP_SZ(TG3_RX_JMB_DMA_SZ)
#define TG3_RX_STD_BUFF_RING_SIZE(tp) \
(sizeof(struct ring_info) * TG3_RX_STD_RING_SIZE(tp))
#define TG3_RX_JMB_BUFF_RING_SIZE(tp) \
(sizeof(struct ring_info) * TG3_RX_JMB_RING_SIZE(tp))
/* Due to a hardware bug, the 5701 can only DMA to memory addresses
* that are at least dword aligned when used in PCIX mode. The driver
* works around this bug by double copying the packet. This workaround
* is built into the normal double copy length check for efficiency.
*
* However, the double copy is only necessary on those architectures
* where unaligned memory accesses are inefficient. For those architectures
* where unaligned memory accesses incur little penalty, we can reintegrate
* the 5701 in the normal rx path. Doing so saves a device structure
* dereference by hardcoding the double copy threshold in place.
*/
#define TG3_RX_COPY_THRESHOLD 256
#if NET_IP_ALIGN == 0 || defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
#define TG3_RX_COPY_THRESH(tp) TG3_RX_COPY_THRESHOLD
#else
#define TG3_RX_COPY_THRESH(tp) ((tp)->rx_copy_thresh)
#endif
#if (NET_IP_ALIGN != 0)
#define TG3_RX_OFFSET(tp) ((tp)->rx_offset)
#else
#define TG3_RX_OFFSET(tp) (NET_SKB_PAD)
#endif
/* minimum number of free TX descriptors required to wake up TX process */
#define TG3_TX_WAKEUP_THRESH(tnapi) ((tnapi)->tx_pending / 4)
#define TG3_TX_BD_DMA_MAX_2K 2048
#define TG3_TX_BD_DMA_MAX_4K 4096
#define TG3_RAW_IP_ALIGN 2
#define TG3_MAX_UCAST_ADDR(tp) (tg3_flag((tp), ENABLE_ASF) ? 2 : 3)
#define TG3_UCAST_ADDR_IDX(tp) (tg3_flag((tp), ENABLE_ASF) ? 2 : 1)
#define TG3_FW_UPDATE_TIMEOUT_SEC 5
#define TG3_FW_UPDATE_FREQ_SEC (TG3_FW_UPDATE_TIMEOUT_SEC / 2)
#define FIRMWARE_TG3 "tigon/tg3.bin"
#define FIRMWARE_TG357766 "tigon/tg357766.bin"
#define FIRMWARE_TG3TSO "tigon/tg3_tso.bin"
#define FIRMWARE_TG3TSO5 "tigon/tg3_tso5.bin"
static char version[] =
DRV_MODULE_NAME ".c:v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")";
MODULE_AUTHOR("David S. Miller (davem@redhat.com) and Jeff Garzik (jgarzik@pobox.com)");
MODULE_DESCRIPTION("Broadcom Tigon3 ethernet driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_MODULE_VERSION);
MODULE_FIRMWARE(FIRMWARE_TG3);
MODULE_FIRMWARE(FIRMWARE_TG3TSO);
MODULE_FIRMWARE(FIRMWARE_TG3TSO5);
static int tg3_debug = -1; /* -1 == use TG3_DEF_MSG_ENABLE as value */
module_param(tg3_debug, int, 0);
MODULE_PARM_DESC(tg3_debug, "Tigon3 bitmapped debugging message enable value");
#define TG3_DRV_DATA_FLAG_10_100_ONLY 0x0001
#define TG3_DRV_DATA_FLAG_5705_10_100 0x0002
static DEFINE_PCI_DEVICE_TABLE(tg3_pci_tbl) = {
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5700)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5701)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702FE)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705_2)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705M_2)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702X)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703X)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702A3)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703A3)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5782)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5788)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5789)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5901),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY |
TG3_DRV_DATA_FLAG_5705_10_100},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5901_2),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY |
TG3_DRV_DATA_FLAG_5705_10_100},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704S_2)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705F),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY |
TG3_DRV_DATA_FLAG_5705_10_100},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5721)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5722)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5750)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751F),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5752)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5752M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753F),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5754)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5754M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5755)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5755M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5756)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5786)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787)},
{PCI_DEVICE_SUB(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5787M,
PCI_VENDOR_ID_LENOVO,
TG3PCI_SUBDEVICE_ID_LENOVO_5787M),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787F),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5714)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5714S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5715)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5715S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5780)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5780S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5781)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5906)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5906M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5784)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5764)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5723)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5761)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5761E)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5761S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5761SE)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5785_G)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5785_F)},
{PCI_DEVICE_SUB(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57780,
PCI_VENDOR_ID_AI, TG3PCI_SUBDEVICE_ID_ACER_57780_A),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE_SUB(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57780,
PCI_VENDOR_ID_AI, TG3PCI_SUBDEVICE_ID_ACER_57780_B),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57780)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57760)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57790),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57788)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5717)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5717_C)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5718)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57781)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57785)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57761)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57765)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57791),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57795),
.driver_data = TG3_DRV_DATA_FLAG_10_100_ONLY},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5719)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5720)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57762)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57766)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5762)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5725)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5727)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57764)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57767)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57787)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57782)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57786)},
{PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, PCI_DEVICE_ID_SYSKONNECT_9DXX)},
{PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, PCI_DEVICE_ID_SYSKONNECT_9MXX)},
{PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1000)},
{PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1001)},
{PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1003)},
{PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC9100)},
{PCI_DEVICE(PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_TIGON3)},
{PCI_DEVICE(0x10cf, 0x11a2)}, /* Fujitsu 1000base-SX with BCM5703SKHB */
{}
};
MODULE_DEVICE_TABLE(pci, tg3_pci_tbl);
static const struct {
const char string[ETH_GSTRING_LEN];
} ethtool_stats_keys[] = {
{ "rx_octets" },
{ "rx_fragments" },
{ "rx_ucast_packets" },
{ "rx_mcast_packets" },
{ "rx_bcast_packets" },
{ "rx_fcs_errors" },
{ "rx_align_errors" },
{ "rx_xon_pause_rcvd" },
{ "rx_xoff_pause_rcvd" },
{ "rx_mac_ctrl_rcvd" },
{ "rx_xoff_entered" },
{ "rx_frame_too_long_errors" },
{ "rx_jabbers" },
{ "rx_undersize_packets" },
{ "rx_in_length_errors" },
{ "rx_out_length_errors" },
{ "rx_64_or_less_octet_packets" },
{ "rx_65_to_127_octet_packets" },
{ "rx_128_to_255_octet_packets" },
{ "rx_256_to_511_octet_packets" },
{ "rx_512_to_1023_octet_packets" },
{ "rx_1024_to_1522_octet_packets" },
{ "rx_1523_to_2047_octet_packets" },
{ "rx_2048_to_4095_octet_packets" },
{ "rx_4096_to_8191_octet_packets" },
{ "rx_8192_to_9022_octet_packets" },
{ "tx_octets" },
{ "tx_collisions" },
{ "tx_xon_sent" },
{ "tx_xoff_sent" },
{ "tx_flow_control" },
{ "tx_mac_errors" },
{ "tx_single_collisions" },
{ "tx_mult_collisions" },
{ "tx_deferred" },
{ "tx_excessive_collisions" },
{ "tx_late_collisions" },
{ "tx_collide_2times" },
{ "tx_collide_3times" },
{ "tx_collide_4times" },
{ "tx_collide_5times" },
{ "tx_collide_6times" },
{ "tx_collide_7times" },
{ "tx_collide_8times" },
{ "tx_collide_9times" },
{ "tx_collide_10times" },
{ "tx_collide_11times" },
{ "tx_collide_12times" },
{ "tx_collide_13times" },
{ "tx_collide_14times" },
{ "tx_collide_15times" },
{ "tx_ucast_packets" },
{ "tx_mcast_packets" },
{ "tx_bcast_packets" },
{ "tx_carrier_sense_errors" },
{ "tx_discards" },
{ "tx_errors" },
{ "dma_writeq_full" },
{ "dma_write_prioq_full" },
{ "rxbds_empty" },
{ "rx_discards" },
{ "rx_errors" },
{ "rx_threshold_hit" },
{ "dma_readq_full" },
{ "dma_read_prioq_full" },
{ "tx_comp_queue_full" },
{ "ring_set_send_prod_index" },
{ "ring_status_update" },
{ "nic_irqs" },
{ "nic_avoided_irqs" },
{ "nic_tx_threshold_hit" },
{ "mbuf_lwm_thresh_hit" },
};
#define TG3_NUM_STATS ARRAY_SIZE(ethtool_stats_keys)
#define TG3_NVRAM_TEST 0
#define TG3_LINK_TEST 1
#define TG3_REGISTER_TEST 2
#define TG3_MEMORY_TEST 3
#define TG3_MAC_LOOPB_TEST 4
#define TG3_PHY_LOOPB_TEST 5
#define TG3_EXT_LOOPB_TEST 6
#define TG3_INTERRUPT_TEST 7
static const struct {
const char string[ETH_GSTRING_LEN];
} ethtool_test_keys[] = {
[TG3_NVRAM_TEST] = { "nvram test (online) " },
[TG3_LINK_TEST] = { "link test (online) " },
[TG3_REGISTER_TEST] = { "register test (offline)" },
[TG3_MEMORY_TEST] = { "memory test (offline)" },
[TG3_MAC_LOOPB_TEST] = { "mac loopback test (offline)" },
[TG3_PHY_LOOPB_TEST] = { "phy loopback test (offline)" },
[TG3_EXT_LOOPB_TEST] = { "ext loopback test (offline)" },
[TG3_INTERRUPT_TEST] = { "interrupt test (offline)" },
};
#define TG3_NUM_TEST ARRAY_SIZE(ethtool_test_keys)
static void tg3_write32(struct tg3 *tp, u32 off, u32 val)
{
writel(val, tp->regs + off);
}
static u32 tg3_read32(struct tg3 *tp, u32 off)
{
return readl(tp->regs + off);
}
static void tg3_ape_write32(struct tg3 *tp, u32 off, u32 val)
{
writel(val, tp->aperegs + off);
}
static u32 tg3_ape_read32(struct tg3 *tp, u32 off)
{
return readl(tp->aperegs + off);
}
static void tg3_write_indirect_reg32(struct tg3 *tp, u32 off, u32 val)
{
unsigned long flags;
spin_lock_irqsave(&tp->indirect_lock, flags);
pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off);
pci_write_config_dword(tp->pdev, TG3PCI_REG_DATA, val);
spin_unlock_irqrestore(&tp->indirect_lock, flags);
}
static void tg3_write_flush_reg32(struct tg3 *tp, u32 off, u32 val)
{
writel(val, tp->regs + off);
readl(tp->regs + off);
}
static u32 tg3_read_indirect_reg32(struct tg3 *tp, u32 off)
{
unsigned long flags;
u32 val;
spin_lock_irqsave(&tp->indirect_lock, flags);
pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off);
pci_read_config_dword(tp->pdev, TG3PCI_REG_DATA, &val);
spin_unlock_irqrestore(&tp->indirect_lock, flags);
return val;
}
static void tg3_write_indirect_mbox(struct tg3 *tp, u32 off, u32 val)
{
unsigned long flags;
if (off == (MAILBOX_RCVRET_CON_IDX_0 + TG3_64BIT_REG_LOW)) {
pci_write_config_dword(tp->pdev, TG3PCI_RCV_RET_RING_CON_IDX +
TG3_64BIT_REG_LOW, val);
return;
}
if (off == TG3_RX_STD_PROD_IDX_REG) {
pci_write_config_dword(tp->pdev, TG3PCI_STD_RING_PROD_IDX +
TG3_64BIT_REG_LOW, val);
return;
}
spin_lock_irqsave(&tp->indirect_lock, flags);
pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off + 0x5600);
pci_write_config_dword(tp->pdev, TG3PCI_REG_DATA, val);
spin_unlock_irqrestore(&tp->indirect_lock, flags);
/* In indirect mode when disabling interrupts, we also need
* to clear the interrupt bit in the GRC local ctrl register.
*/
if ((off == (MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW)) &&
(val == 0x1)) {
pci_write_config_dword(tp->pdev, TG3PCI_MISC_LOCAL_CTRL,
tp->grc_local_ctrl|GRC_LCLCTRL_CLEARINT);
}
}
static u32 tg3_read_indirect_mbox(struct tg3 *tp, u32 off)
{
unsigned long flags;
u32 val;
spin_lock_irqsave(&tp->indirect_lock, flags);
pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off + 0x5600);
pci_read_config_dword(tp->pdev, TG3PCI_REG_DATA, &val);
spin_unlock_irqrestore(&tp->indirect_lock, flags);
return val;
}
/* usec_wait specifies the wait time in usec when writing to certain registers
* where it is unsafe to read back the register without some delay.
* GRC_LOCAL_CTRL is one example if the GPIOs are toggled to switch power.
* TG3PCI_CLOCK_CTRL is another example if the clock frequencies are changed.
*/
static void _tw32_flush(struct tg3 *tp, u32 off, u32 val, u32 usec_wait)
{
if (tg3_flag(tp, PCIX_TARGET_HWBUG) || tg3_flag(tp, ICH_WORKAROUND))
/* Non-posted methods */
tp->write32(tp, off, val);
else {
/* Posted method */
tg3_write32(tp, off, val);
if (usec_wait)
udelay(usec_wait);
tp->read32(tp, off);
}
/* Wait again after the read for the posted method to guarantee that
* the wait time is met.
*/
if (usec_wait)
udelay(usec_wait);
}
static inline void tw32_mailbox_flush(struct tg3 *tp, u32 off, u32 val)
{
tp->write32_mbox(tp, off, val);
if (tg3_flag(tp, FLUSH_POSTED_WRITES) ||
(!tg3_flag(tp, MBOX_WRITE_REORDER) &&
!tg3_flag(tp, ICH_WORKAROUND)))
tp->read32_mbox(tp, off);
}
static void tg3_write32_tx_mbox(struct tg3 *tp, u32 off, u32 val)
{
void __iomem *mbox = tp->regs + off;
writel(val, mbox);
if (tg3_flag(tp, TXD_MBOX_HWBUG))
writel(val, mbox);
if (tg3_flag(tp, MBOX_WRITE_REORDER) ||
tg3_flag(tp, FLUSH_POSTED_WRITES))
readl(mbox);
}
static u32 tg3_read32_mbox_5906(struct tg3 *tp, u32 off)
{
return readl(tp->regs + off + GRCMBOX_BASE);
}
static void tg3_write32_mbox_5906(struct tg3 *tp, u32 off, u32 val)
{
writel(val, tp->regs + off + GRCMBOX_BASE);
}
#define tw32_mailbox(reg, val) tp->write32_mbox(tp, reg, val)
#define tw32_mailbox_f(reg, val) tw32_mailbox_flush(tp, (reg), (val))
#define tw32_rx_mbox(reg, val) tp->write32_rx_mbox(tp, reg, val)
#define tw32_tx_mbox(reg, val) tp->write32_tx_mbox(tp, reg, val)
#define tr32_mailbox(reg) tp->read32_mbox(tp, reg)
#define tw32(reg, val) tp->write32(tp, reg, val)
#define tw32_f(reg, val) _tw32_flush(tp, (reg), (val), 0)
#define tw32_wait_f(reg, val, us) _tw32_flush(tp, (reg), (val), (us))
#define tr32(reg) tp->read32(tp, reg)
static void tg3_write_mem(struct tg3 *tp, u32 off, u32 val)
{
unsigned long flags;
if (tg3_asic_rev(tp) == ASIC_REV_5906 &&
(off >= NIC_SRAM_STATS_BLK) && (off < NIC_SRAM_TX_BUFFER_DESC))
return;
spin_lock_irqsave(&tp->indirect_lock, flags);
if (tg3_flag(tp, SRAM_USE_CONFIG)) {
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, off);
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val);
/* Always leave this as zero. */
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0);
} else {
tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, off);
tw32_f(TG3PCI_MEM_WIN_DATA, val);
/* Always leave this as zero. */
tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, 0);
}
spin_unlock_irqrestore(&tp->indirect_lock, flags);
}
static void tg3_read_mem(struct tg3 *tp, u32 off, u32 *val)
{
unsigned long flags;
if (tg3_asic_rev(tp) == ASIC_REV_5906 &&
(off >= NIC_SRAM_STATS_BLK) && (off < NIC_SRAM_TX_BUFFER_DESC)) {
*val = 0;
return;
}
spin_lock_irqsave(&tp->indirect_lock, flags);
if (tg3_flag(tp, SRAM_USE_CONFIG)) {
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, off);
pci_read_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val);
/* Always leave this as zero. */
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0);
} else {
tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, off);
*val = tr32(TG3PCI_MEM_WIN_DATA);
/* Always leave this as zero. */
tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, 0);
}
spin_unlock_irqrestore(&tp->indirect_lock, flags);
}
static void tg3_ape_lock_init(struct tg3 *tp)
{
int i;
u32 regbase, bit;
if (tg3_asic_rev(tp) == ASIC_REV_5761)
regbase = TG3_APE_LOCK_GRANT;
else
regbase = TG3_APE_PER_LOCK_GRANT;
/* Make sure the driver hasn't any stale locks. */
for (i = TG3_APE_LOCK_PHY0; i <= TG3_APE_LOCK_GPIO; i++) {
switch (i) {
case TG3_APE_LOCK_PHY0:
case TG3_APE_LOCK_PHY1:
case TG3_APE_LOCK_PHY2:
case TG3_APE_LOCK_PHY3:
bit = APE_LOCK_GRANT_DRIVER;
break;
default:
if (!tp->pci_fn)
bit = APE_LOCK_GRANT_DRIVER;
else
bit = 1 << tp->pci_fn;
}
tg3_ape_write32(tp, regbase + 4 * i, bit);
}
}
static int tg3_ape_lock(struct tg3 *tp, int locknum)
{
int i, off;
int ret = 0;
u32 status, req, gnt, bit;
if (!tg3_flag(tp, ENABLE_APE))
return 0;
switch (locknum) {
case TG3_APE_LOCK_GPIO:
if (tg3_asic_rev(tp) == ASIC_REV_5761)
return 0;
case TG3_APE_LOCK_GRC:
case TG3_APE_LOCK_MEM:
if (!tp->pci_fn)
bit = APE_LOCK_REQ_DRIVER;
else
bit = 1 << tp->pci_fn;
break;
case TG3_APE_LOCK_PHY0:
case TG3_APE_LOCK_PHY1:
case TG3_APE_LOCK_PHY2:
case TG3_APE_LOCK_PHY3:
bit = APE_LOCK_REQ_DRIVER;
break;
default:
return -EINVAL;
}
if (tg3_asic_rev(tp) == ASIC_REV_5761) {
req = TG3_APE_LOCK_REQ;
gnt = TG3_APE_LOCK_GRANT;
} else {
req = TG3_APE_PER_LOCK_REQ;
gnt = TG3_APE_PER_LOCK_GRANT;
}
off = 4 * locknum;
tg3_ape_write32(tp, req + off, bit);
/* Wait for up to 1 millisecond to acquire lock. */
for (i = 0; i < 100; i++) {
status = tg3_ape_read32(tp, gnt + off);
if (status == bit)
break;
if (pci_channel_offline(tp->pdev))
break;
udelay(10);
}
if (status != bit) {
/* Revoke the lock request. */
tg3_ape_write32(tp, gnt + off, bit);
ret = -EBUSY;
}
return ret;
}
static void tg3_ape_unlock(struct tg3 *tp, int locknum)
{
u32 gnt, bit;
if (!tg3_flag(tp, ENABLE_APE))
return;
switch (locknum) {
case TG3_APE_LOCK_GPIO:
if (tg3_asic_rev(tp) == ASIC_REV_5761)
return;
case TG3_APE_LOCK_GRC:
case TG3_APE_LOCK_MEM:
if (!tp->pci_fn)
bit = APE_LOCK_GRANT_DRIVER;
else
bit = 1 << tp->pci_fn;
break;
case TG3_APE_LOCK_PHY0:
case TG3_APE_LOCK_PHY1:
case TG3_APE_LOCK_PHY2:
case TG3_APE_LOCK_PHY3:
bit = APE_LOCK_GRANT_DRIVER;
break;
default:
return;
}
if (tg3_asic_rev(tp) == ASIC_REV_5761)
gnt = TG3_APE_LOCK_GRANT;
else
gnt = TG3_APE_PER_LOCK_GRANT;
tg3_ape_write32(tp, gnt + 4 * locknum, bit);
}
static int tg3_ape_event_lock(struct tg3 *tp, u32 timeout_us)
{
u32 apedata;
while (timeout_us) {
if (tg3_ape_lock(tp, TG3_APE_LOCK_MEM))
return -EBUSY;
apedata = tg3_ape_read32(tp, TG3_APE_EVENT_STATUS);
if (!(apedata & APE_EVENT_STATUS_EVENT_PENDING))
break;
tg3_ape_unlock(tp, TG3_APE_LOCK_MEM);
udelay(10);
timeout_us -= (timeout_us > 10) ? 10 : timeout_us;
}
return timeout_us ? 0 : -EBUSY;
}
static int tg3_ape_wait_for_event(struct tg3 *tp, u32 timeout_us)
{
u32 i, apedata;
for (i = 0; i < timeout_us / 10; i++) {
apedata = tg3_ape_read32(tp, TG3_APE_EVENT_STATUS);
if (!(apedata & APE_EVENT_STATUS_EVENT_PENDING))
break;
udelay(10);
}
return i == timeout_us / 10;
}
static int tg3_ape_scratchpad_read(struct tg3 *tp, u32 *data, u32 base_off,
u32 len)
{
int err;
u32 i, bufoff, msgoff, maxlen, apedata;
if (!tg3_flag(tp, APE_HAS_NCSI))
return 0;
apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG);
if (apedata != APE_SEG_SIG_MAGIC)
return -ENODEV;
apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS);
if (!(apedata & APE_FW_STATUS_READY))
return -EAGAIN;
bufoff = tg3_ape_read32(tp, TG3_APE_SEG_MSG_BUF_OFF) +
TG3_APE_SHMEM_BASE;
msgoff = bufoff + 2 * sizeof(u32);
maxlen = tg3_ape_read32(tp, TG3_APE_SEG_MSG_BUF_LEN);
while (len) {
u32 length;
/* Cap xfer sizes to scratchpad limits. */
length = (len > maxlen) ? maxlen : len;
len -= length;
apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS);
if (!(apedata & APE_FW_STATUS_READY))
return -EAGAIN;
/* Wait for up to 1 msec for APE to service previous event. */
err = tg3_ape_event_lock(tp, 1000);
if (err)
return err;
apedata = APE_EVENT_STATUS_DRIVER_EVNT |
APE_EVENT_STATUS_SCRTCHPD_READ |
APE_EVENT_STATUS_EVENT_PENDING;
tg3_ape_write32(tp, TG3_APE_EVENT_STATUS, apedata);
tg3_ape_write32(tp, bufoff, base_off);
tg3_ape_write32(tp, bufoff + sizeof(u32), length);
tg3_ape_unlock(tp, TG3_APE_LOCK_MEM);
tg3_ape_write32(tp, TG3_APE_EVENT, APE_EVENT_1);
base_off += length;
if (tg3_ape_wait_for_event(tp, 30000))
return -EAGAIN;
for (i = 0; length; i += 4, length -= 4) {
u32 val = tg3_ape_read32(tp, msgoff + i);
memcpy(data, &val, sizeof(u32));
data++;
}
}
return 0;
}
static int tg3_ape_send_event(struct tg3 *tp, u32 event)
{
int err;
u32 apedata;
apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG);
if (apedata != APE_SEG_SIG_MAGIC)
return -EAGAIN;
apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS);
if (!(apedata & APE_FW_STATUS_READY))
return -EAGAIN;
/* Wait for up to 1 millisecond for APE to service previous event. */
err = tg3_ape_event_lock(tp, 1000);
if (err)
return err;
tg3_ape_write32(tp, TG3_APE_EVENT_STATUS,
event | APE_EVENT_STATUS_EVENT_PENDING);
tg3_ape_unlock(tp, TG3_APE_LOCK_MEM);
tg3_ape_write32(tp, TG3_APE_EVENT, APE_EVENT_1);
return 0;
}
static void tg3_ape_driver_state_change(struct tg3 *tp, int kind)
{
u32 event;
u32 apedata;
if (!tg3_flag(tp, ENABLE_APE))
return;
switch (kind) {
case RESET_KIND_INIT:
tg3_ape_write32(tp, TG3_APE_HOST_SEG_SIG,
APE_HOST_SEG_SIG_MAGIC);
tg3_ape_write32(tp, TG3_APE_HOST_SEG_LEN,
APE_HOST_SEG_LEN_MAGIC);
apedata = tg3_ape_read32(tp, TG3_APE_HOST_INIT_COUNT);
tg3_ape_write32(tp, TG3_APE_HOST_INIT_COUNT, ++apedata);
tg3_ape_write32(tp, TG3_APE_HOST_DRIVER_ID,
APE_HOST_DRIVER_ID_MAGIC(TG3_MAJ_NUM, TG3_MIN_NUM));
tg3_ape_write32(tp, TG3_APE_HOST_BEHAVIOR,
APE_HOST_BEHAV_NO_PHYLOCK);
tg3_ape_write32(tp, TG3_APE_HOST_DRVR_STATE,
TG3_APE_HOST_DRVR_STATE_START);
event = APE_EVENT_STATUS_STATE_START;
break;
case RESET_KIND_SHUTDOWN:
/* With the interface we are currently using,
* APE does not track driver state. Wiping
* out the HOST SEGMENT SIGNATURE forces
* the APE to assume OS absent status.
*/
tg3_ape_write32(tp, TG3_APE_HOST_SEG_SIG, 0x0);
if (device_may_wakeup(&tp->pdev->dev) &&
tg3_flag(tp, WOL_ENABLE)) {
tg3_ape_write32(tp, TG3_APE_HOST_WOL_SPEED,
TG3_APE_HOST_WOL_SPEED_AUTO);
apedata = TG3_APE_HOST_DRVR_STATE_WOL;
} else
apedata = TG3_APE_HOST_DRVR_STATE_UNLOAD;
tg3_ape_write32(tp, TG3_APE_HOST_DRVR_STATE, apedata);
event = APE_EVENT_STATUS_STATE_UNLOAD;
break;
default:
return;
}
event |= APE_EVENT_STATUS_DRIVER_EVNT | APE_EVENT_STATUS_STATE_CHNGE;
tg3_ape_send_event(tp, event);
}
static void tg3_disable_ints(struct tg3 *tp)
{
int i;
tw32(TG3PCI_MISC_HOST_CTRL,
(tp->misc_host_ctrl | MISC_HOST_CTRL_MASK_PCI_INT));
for (i = 0; i < tp->irq_max; i++)
tw32_mailbox_f(tp->napi[i].int_mbox, 0x00000001);
}
static void tg3_enable_ints(struct tg3 *tp)
{
int i;
tp->irq_sync = 0;
wmb();
tw32(TG3PCI_MISC_HOST_CTRL,
(tp->misc_host_ctrl & ~MISC_HOST_CTRL_MASK_PCI_INT));
tp->coal_now = tp->coalesce_mode | HOSTCC_MODE_ENABLE;
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24);
if (tg3_flag(tp, 1SHOT_MSI))
tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24);
tp->coal_now |= tnapi->coal_now;
}
/* Force an initial interrupt */
if (!tg3_flag(tp, TAGGED_STATUS) &&
(tp->napi[0].hw_status->status & SD_STATUS_UPDATED))
tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl | GRC_LCLCTRL_SETINT);
else
tw32(HOSTCC_MODE, tp->coal_now);
tp->coal_now &= ~(tp->napi[0].coal_now | tp->napi[1].coal_now);
}
static inline unsigned int tg3_has_work(struct tg3_napi *tnapi)
{
struct tg3 *tp = tnapi->tp;
struct tg3_hw_status *sblk = tnapi->hw_status;
unsigned int work_exists = 0;
/* check for phy events */
if (!(tg3_flag(tp, USE_LINKCHG_REG) || tg3_flag(tp, POLL_SERDES))) {
if (sblk->status & SD_STATUS_LINK_CHG)
work_exists = 1;
}
/* check for TX work to do */
if (sblk->idx[0].tx_consumer != tnapi->tx_cons)
work_exists = 1;
/* check for RX work to do */
if (tnapi->rx_rcb_prod_idx &&
*(tnapi->rx_rcb_prod_idx) != tnapi->rx_rcb_ptr)
work_exists = 1;
return work_exists;
}
/* tg3_int_reenable
* similar to tg3_enable_ints, but it accurately determines whether there
* is new work pending and can return without flushing the PIO write
* which reenables interrupts
*/
static void tg3_int_reenable(struct tg3_napi *tnapi)
{
struct tg3 *tp = tnapi->tp;
tw32_mailbox(tnapi->int_mbox, tnapi->last_tag << 24);
mmiowb();
/* When doing tagged status, this work check is unnecessary.
* The last_tag we write above tells the chip which piece of
* work we've completed.
*/
if (!tg3_flag(tp, TAGGED_STATUS) && tg3_has_work(tnapi))
tw32(HOSTCC_MODE, tp->coalesce_mode |
HOSTCC_MODE_ENABLE | tnapi->coal_now);
}
static void tg3_switch_clocks(struct tg3 *tp)
{
u32 clock_ctrl;
u32 orig_clock_ctrl;
if (tg3_flag(tp, CPMU_PRESENT) || tg3_flag(tp, 5780_CLASS))
return;
clock_ctrl = tr32(TG3PCI_CLOCK_CTRL);
orig_clock_ctrl = clock_ctrl;
clock_ctrl &= (CLOCK_CTRL_FORCE_CLKRUN |
CLOCK_CTRL_CLKRUN_OENABLE |
0x1f);
tp->pci_clock_ctrl = clock_ctrl;
if (tg3_flag(tp, 5705_PLUS)) {
if (orig_clock_ctrl & CLOCK_CTRL_625_CORE) {
tw32_wait_f(TG3PCI_CLOCK_CTRL,
clock_ctrl | CLOCK_CTRL_625_CORE, 40);
}
} else if ((orig_clock_ctrl & CLOCK_CTRL_44MHZ_CORE) != 0) {
tw32_wait_f(TG3PCI_CLOCK_CTRL,
clock_ctrl |
(CLOCK_CTRL_44MHZ_CORE | CLOCK_CTRL_ALTCLK),
40);
tw32_wait_f(TG3PCI_CLOCK_CTRL,
clock_ctrl | (CLOCK_CTRL_ALTCLK),
40);
}
tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl, 40);
}
#define PHY_BUSY_LOOPS 5000
static int __tg3_readphy(struct tg3 *tp, unsigned int phy_addr, int reg,
u32 *val)
{
u32 frame_val;
unsigned int loops;
int ret;
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE,
(tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL));
udelay(80);
}
tg3_ape_lock(tp, tp->phy_ape_lock);
*val = 0x0;
frame_val = ((phy_addr << MI_COM_PHY_ADDR_SHIFT) &
MI_COM_PHY_ADDR_MASK);
frame_val |= ((reg << MI_COM_REG_ADDR_SHIFT) &
MI_COM_REG_ADDR_MASK);
frame_val |= (MI_COM_CMD_READ | MI_COM_START);
tw32_f(MAC_MI_COM, frame_val);
loops = PHY_BUSY_LOOPS;
while (loops != 0) {
udelay(10);
frame_val = tr32(MAC_MI_COM);
if ((frame_val & MI_COM_BUSY) == 0) {
udelay(5);
frame_val = tr32(MAC_MI_COM);
break;
}
loops -= 1;
}
ret = -EBUSY;
if (loops != 0) {
*val = frame_val & MI_COM_DATA_MASK;
ret = 0;
}
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE, tp->mi_mode);
udelay(80);
}
tg3_ape_unlock(tp, tp->phy_ape_lock);
return ret;
}
static int tg3_readphy(struct tg3 *tp, int reg, u32 *val)
{
return __tg3_readphy(tp, tp->phy_addr, reg, val);
}
static int __tg3_writephy(struct tg3 *tp, unsigned int phy_addr, int reg,
u32 val)
{
u32 frame_val;
unsigned int loops;
int ret;
if ((tp->phy_flags & TG3_PHYFLG_IS_FET) &&
(reg == MII_CTRL1000 || reg == MII_TG3_AUX_CTRL))
return 0;
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE,
(tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL));
udelay(80);
}
tg3_ape_lock(tp, tp->phy_ape_lock);
frame_val = ((phy_addr << MI_COM_PHY_ADDR_SHIFT) &
MI_COM_PHY_ADDR_MASK);
frame_val |= ((reg << MI_COM_REG_ADDR_SHIFT) &
MI_COM_REG_ADDR_MASK);
frame_val |= (val & MI_COM_DATA_MASK);
frame_val |= (MI_COM_CMD_WRITE | MI_COM_START);
tw32_f(MAC_MI_COM, frame_val);
loops = PHY_BUSY_LOOPS;
while (loops != 0) {
udelay(10);
frame_val = tr32(MAC_MI_COM);
if ((frame_val & MI_COM_BUSY) == 0) {
udelay(5);
frame_val = tr32(MAC_MI_COM);
break;
}
loops -= 1;
}
ret = -EBUSY;
if (loops != 0)
ret = 0;
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE, tp->mi_mode);
udelay(80);
}
tg3_ape_unlock(tp, tp->phy_ape_lock);
return ret;
}
static int tg3_writephy(struct tg3 *tp, int reg, u32 val)
{
return __tg3_writephy(tp, tp->phy_addr, reg, val);
}
static int tg3_phy_cl45_write(struct tg3 *tp, u32 devad, u32 addr, u32 val)
{
int err;
err = tg3_writephy(tp, MII_TG3_MMD_CTRL, devad);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, addr);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_CTRL,
MII_TG3_MMD_CTRL_DATA_NOINC | devad);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, val);
done:
return err;
}
static int tg3_phy_cl45_read(struct tg3 *tp, u32 devad, u32 addr, u32 *val)
{
int err;
err = tg3_writephy(tp, MII_TG3_MMD_CTRL, devad);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, addr);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_CTRL,
MII_TG3_MMD_CTRL_DATA_NOINC | devad);
if (err)
goto done;
err = tg3_readphy(tp, MII_TG3_MMD_ADDRESS, val);
done:
return err;
}
static int tg3_phydsp_read(struct tg3 *tp, u32 reg, u32 *val)
{
int err;
err = tg3_writephy(tp, MII_TG3_DSP_ADDRESS, reg);
if (!err)
err = tg3_readphy(tp, MII_TG3_DSP_RW_PORT, val);
return err;
}
static int tg3_phydsp_write(struct tg3 *tp, u32 reg, u32 val)
{
int err;
err = tg3_writephy(tp, MII_TG3_DSP_ADDRESS, reg);
if (!err)
err = tg3_writephy(tp, MII_TG3_DSP_RW_PORT, val);
return err;
}
static int tg3_phy_auxctl_read(struct tg3 *tp, int reg, u32 *val)
{
int err;
err = tg3_writephy(tp, MII_TG3_AUX_CTRL,
(reg << MII_TG3_AUXCTL_MISC_RDSEL_SHIFT) |
MII_TG3_AUXCTL_SHDWSEL_MISC);
if (!err)
err = tg3_readphy(tp, MII_TG3_AUX_CTRL, val);
return err;
}
static int tg3_phy_auxctl_write(struct tg3 *tp, int reg, u32 set)
{
if (reg == MII_TG3_AUXCTL_SHDWSEL_MISC)
set |= MII_TG3_AUXCTL_MISC_WREN;
return tg3_writephy(tp, MII_TG3_AUX_CTRL, set | reg);
}
static int tg3_phy_toggle_auxctl_smdsp(struct tg3 *tp, bool enable)
{
u32 val;
int err;
err = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, &val);
if (err)
return err;
if (enable)
val |= MII_TG3_AUXCTL_ACTL_SMDSP_ENA;
else
val &= ~MII_TG3_AUXCTL_ACTL_SMDSP_ENA;
err = tg3_phy_auxctl_write((tp), MII_TG3_AUXCTL_SHDWSEL_AUXCTL,
val | MII_TG3_AUXCTL_ACTL_TX_6DB);
return err;
}
static int tg3_phy_shdw_write(struct tg3 *tp, int reg, u32 val)
{
return tg3_writephy(tp, MII_TG3_MISC_SHDW,
reg | val | MII_TG3_MISC_SHDW_WREN);
}
static int tg3_bmcr_reset(struct tg3 *tp)
{
u32 phy_control;
int limit, err;
/* OK, reset it, and poll the BMCR_RESET bit until it
* clears or we time out.
*/
phy_control = BMCR_RESET;
err = tg3_writephy(tp, MII_BMCR, phy_control);
if (err != 0)
return -EBUSY;
limit = 5000;
while (limit--) {
err = tg3_readphy(tp, MII_BMCR, &phy_control);
if (err != 0)
return -EBUSY;
if ((phy_control & BMCR_RESET) == 0) {
udelay(40);
break;
}
udelay(10);
}
if (limit < 0)
return -EBUSY;
return 0;
}
static int tg3_mdio_read(struct mii_bus *bp, int mii_id, int reg)
{
struct tg3 *tp = bp->priv;
u32 val;
spin_lock_bh(&tp->lock);
if (__tg3_readphy(tp, mii_id, reg, &val))
val = -EIO;
spin_unlock_bh(&tp->lock);
return val;
}
static int tg3_mdio_write(struct mii_bus *bp, int mii_id, int reg, u16 val)
{
struct tg3 *tp = bp->priv;
u32 ret = 0;
spin_lock_bh(&tp->lock);
if (__tg3_writephy(tp, mii_id, reg, val))
ret = -EIO;
spin_unlock_bh(&tp->lock);
return ret;
}
static void tg3_mdio_config_5785(struct tg3 *tp)
{
u32 val;
struct phy_device *phydev;
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) {
case PHY_ID_BCM50610:
case PHY_ID_BCM50610M:
val = MAC_PHYCFG2_50610_LED_MODES;
break;
case PHY_ID_BCMAC131:
val = MAC_PHYCFG2_AC131_LED_MODES;
break;
case PHY_ID_RTL8211C:
val = MAC_PHYCFG2_RTL8211C_LED_MODES;
break;
case PHY_ID_RTL8201E:
val = MAC_PHYCFG2_RTL8201E_LED_MODES;
break;
default:
return;
}
if (phydev->interface != PHY_INTERFACE_MODE_RGMII) {
tw32(MAC_PHYCFG2, val);
val = tr32(MAC_PHYCFG1);
val &= ~(MAC_PHYCFG1_RGMII_INT |
MAC_PHYCFG1_RXCLK_TO_MASK | MAC_PHYCFG1_TXCLK_TO_MASK);
val |= MAC_PHYCFG1_RXCLK_TIMEOUT | MAC_PHYCFG1_TXCLK_TIMEOUT;
tw32(MAC_PHYCFG1, val);
return;
}
if (!tg3_flag(tp, RGMII_INBAND_DISABLE))
val |= MAC_PHYCFG2_EMODE_MASK_MASK |
MAC_PHYCFG2_FMODE_MASK_MASK |
MAC_PHYCFG2_GMODE_MASK_MASK |
MAC_PHYCFG2_ACT_MASK_MASK |
MAC_PHYCFG2_QUAL_MASK_MASK |
MAC_PHYCFG2_INBAND_ENABLE;
tw32(MAC_PHYCFG2, val);
val = tr32(MAC_PHYCFG1);
val &= ~(MAC_PHYCFG1_RXCLK_TO_MASK | MAC_PHYCFG1_TXCLK_TO_MASK |
MAC_PHYCFG1_RGMII_EXT_RX_DEC | MAC_PHYCFG1_RGMII_SND_STAT_EN);
if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) {
if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN))
val |= MAC_PHYCFG1_RGMII_EXT_RX_DEC;
if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN))
val |= MAC_PHYCFG1_RGMII_SND_STAT_EN;
}
val |= MAC_PHYCFG1_RXCLK_TIMEOUT | MAC_PHYCFG1_TXCLK_TIMEOUT |
MAC_PHYCFG1_RGMII_INT | MAC_PHYCFG1_TXC_DRV;
tw32(MAC_PHYCFG1, val);
val = tr32(MAC_EXT_RGMII_MODE);
val &= ~(MAC_RGMII_MODE_RX_INT_B |
MAC_RGMII_MODE_RX_QUALITY |
MAC_RGMII_MODE_RX_ACTIVITY |
MAC_RGMII_MODE_RX_ENG_DET |
MAC_RGMII_MODE_TX_ENABLE |
MAC_RGMII_MODE_TX_LOWPWR |
MAC_RGMII_MODE_TX_RESET);
if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) {
if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN))
val |= MAC_RGMII_MODE_RX_INT_B |
MAC_RGMII_MODE_RX_QUALITY |
MAC_RGMII_MODE_RX_ACTIVITY |
MAC_RGMII_MODE_RX_ENG_DET;
if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN))
val |= MAC_RGMII_MODE_TX_ENABLE |
MAC_RGMII_MODE_TX_LOWPWR |
MAC_RGMII_MODE_TX_RESET;
}
tw32(MAC_EXT_RGMII_MODE, val);
}
static void tg3_mdio_start(struct tg3 *tp)
{
tp->mi_mode &= ~MAC_MI_MODE_AUTO_POLL;
tw32_f(MAC_MI_MODE, tp->mi_mode);
udelay(80);
if (tg3_flag(tp, MDIOBUS_INITED) &&
tg3_asic_rev(tp) == ASIC_REV_5785)
tg3_mdio_config_5785(tp);
}
static int tg3_mdio_init(struct tg3 *tp)
{
int i;
u32 reg;
struct phy_device *phydev;
if (tg3_flag(tp, 5717_PLUS)) {
u32 is_serdes;
tp->phy_addr = tp->pci_fn + 1;
if (tg3_chip_rev_id(tp) != CHIPREV_ID_5717_A0)
is_serdes = tr32(SG_DIG_STATUS) & SG_DIG_IS_SERDES;
else
is_serdes = tr32(TG3_CPMU_PHY_STRAP) &
TG3_CPMU_PHY_STRAP_IS_SERDES;
if (is_serdes)
tp->phy_addr += 7;
} else if (tg3_flag(tp, IS_SSB_CORE) && tg3_flag(tp, ROBOSWITCH)) {
int addr;
addr = ssb_gige_get_phyaddr(tp->pdev);
if (addr < 0)
return addr;
tp->phy_addr = addr;
} else
tp->phy_addr = TG3_PHY_MII_ADDR;
tg3_mdio_start(tp);
if (!tg3_flag(tp, USE_PHYLIB) || tg3_flag(tp, MDIOBUS_INITED))
return 0;
tp->mdio_bus = mdiobus_alloc();
if (tp->mdio_bus == NULL)
return -ENOMEM;
tp->mdio_bus->name = "tg3 mdio bus";
snprintf(tp->mdio_bus->id, MII_BUS_ID_SIZE, "%x",
(tp->pdev->bus->number << 8) | tp->pdev->devfn);
tp->mdio_bus->priv = tp;
tp->mdio_bus->parent = &tp->pdev->dev;
tp->mdio_bus->read = &tg3_mdio_read;
tp->mdio_bus->write = &tg3_mdio_write;
tp->mdio_bus->phy_mask = ~(1 << tp->phy_addr);
tp->mdio_bus->irq = &tp->mdio_irq[0];
for (i = 0; i < PHY_MAX_ADDR; i++)
tp->mdio_bus->irq[i] = PHY_POLL;
/* The bus registration will look for all the PHYs on the mdio bus.
* Unfortunately, it does not ensure the PHY is powered up before
* accessing the PHY ID registers. A chip reset is the
* quickest way to bring the device back to an operational state..
*/
if (tg3_readphy(tp, MII_BMCR, ®) || (reg & BMCR_PDOWN))
tg3_bmcr_reset(tp);
i = mdiobus_register(tp->mdio_bus);
if (i) {
dev_warn(&tp->pdev->dev, "mdiobus_reg failed (0x%x)\n", i);
mdiobus_free(tp->mdio_bus);
return i;
}
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
if (!phydev || !phydev->drv) {
dev_warn(&tp->pdev->dev, "No PHY devices\n");
mdiobus_unregister(tp->mdio_bus);
mdiobus_free(tp->mdio_bus);
return -ENODEV;
}
switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) {
case PHY_ID_BCM57780:
phydev->interface = PHY_INTERFACE_MODE_GMII;
phydev->dev_flags |= PHY_BRCM_AUTO_PWRDWN_ENABLE;
break;
case PHY_ID_BCM50610:
case PHY_ID_BCM50610M:
phydev->dev_flags |= PHY_BRCM_CLEAR_RGMII_MODE |
PHY_BRCM_RX_REFCLK_UNUSED |
PHY_BRCM_DIS_TXCRXC_NOENRGY |
PHY_BRCM_AUTO_PWRDWN_ENABLE;
if (tg3_flag(tp, RGMII_INBAND_DISABLE))
phydev->dev_flags |= PHY_BRCM_STD_IBND_DISABLE;
if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN))
phydev->dev_flags |= PHY_BRCM_EXT_IBND_RX_ENABLE;
if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN))
phydev->dev_flags |= PHY_BRCM_EXT_IBND_TX_ENABLE;
/* fallthru */
case PHY_ID_RTL8211C:
phydev->interface = PHY_INTERFACE_MODE_RGMII;
break;
case PHY_ID_RTL8201E:
case PHY_ID_BCMAC131:
phydev->interface = PHY_INTERFACE_MODE_MII;
phydev->dev_flags |= PHY_BRCM_AUTO_PWRDWN_ENABLE;
tp->phy_flags |= TG3_PHYFLG_IS_FET;
break;
}
tg3_flag_set(tp, MDIOBUS_INITED);
if (tg3_asic_rev(tp) == ASIC_REV_5785)
tg3_mdio_config_5785(tp);
return 0;
}
static void tg3_mdio_fini(struct tg3 *tp)
{
if (tg3_flag(tp, MDIOBUS_INITED)) {
tg3_flag_clear(tp, MDIOBUS_INITED);
mdiobus_unregister(tp->mdio_bus);
mdiobus_free(tp->mdio_bus);
}
}
/* tp->lock is held. */
static inline void tg3_generate_fw_event(struct tg3 *tp)
{
u32 val;
val = tr32(GRC_RX_CPU_EVENT);
val |= GRC_RX_CPU_DRIVER_EVENT;
tw32_f(GRC_RX_CPU_EVENT, val);
tp->last_event_jiffies = jiffies;
}
#define TG3_FW_EVENT_TIMEOUT_USEC 2500
/* tp->lock is held. */
static void tg3_wait_for_event_ack(struct tg3 *tp)
{
int i;
unsigned int delay_cnt;
long time_remain;
/* If enough time has passed, no wait is necessary. */
time_remain = (long)(tp->last_event_jiffies + 1 +
usecs_to_jiffies(TG3_FW_EVENT_TIMEOUT_USEC)) -
(long)jiffies;
if (time_remain < 0)
return;
/* Check if we can shorten the wait time. */
delay_cnt = jiffies_to_usecs(time_remain);
if (delay_cnt > TG3_FW_EVENT_TIMEOUT_USEC)
delay_cnt = TG3_FW_EVENT_TIMEOUT_USEC;
delay_cnt = (delay_cnt >> 3) + 1;
for (i = 0; i < delay_cnt; i++) {
if (!(tr32(GRC_RX_CPU_EVENT) & GRC_RX_CPU_DRIVER_EVENT))
break;
if (pci_channel_offline(tp->pdev))
break;
udelay(8);
}
}
/* tp->lock is held. */
static void tg3_phy_gather_ump_data(struct tg3 *tp, u32 *data)
{
u32 reg, val;
val = 0;
if (!tg3_readphy(tp, MII_BMCR, ®))
val = reg << 16;
if (!tg3_readphy(tp, MII_BMSR, ®))
val |= (reg & 0xffff);
*data++ = val;
val = 0;
if (!tg3_readphy(tp, MII_ADVERTISE, ®))
val = reg << 16;
if (!tg3_readphy(tp, MII_LPA, ®))
val |= (reg & 0xffff);
*data++ = val;
val = 0;
if (!(tp->phy_flags & TG3_PHYFLG_MII_SERDES)) {
if (!tg3_readphy(tp, MII_CTRL1000, ®))
val = reg << 16;
if (!tg3_readphy(tp, MII_STAT1000, ®))
val |= (reg & 0xffff);
}
*data++ = val;
if (!tg3_readphy(tp, MII_PHYADDR, ®))
val = reg << 16;
else
val = 0;
*data++ = val;
}
/* tp->lock is held. */
static void tg3_ump_link_report(struct tg3 *tp)
{
u32 data[4];
if (!tg3_flag(tp, 5780_CLASS) || !tg3_flag(tp, ENABLE_ASF))
return;
tg3_phy_gather_ump_data(tp, data);
tg3_wait_for_event_ack(tp);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX, FWCMD_NICDRV_LINK_UPDATE);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_LEN_MBOX, 14);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x0, data[0]);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x4, data[1]);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x8, data[2]);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0xc, data[3]);
tg3_generate_fw_event(tp);
}
/* tp->lock is held. */
static void tg3_stop_fw(struct tg3 *tp)
{
if (tg3_flag(tp, ENABLE_ASF) && !tg3_flag(tp, ENABLE_APE)) {
/* Wait for RX cpu to ACK the previous event. */
tg3_wait_for_event_ack(tp);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX, FWCMD_NICDRV_PAUSE_FW);
tg3_generate_fw_event(tp);
/* Wait for RX cpu to ACK this event. */
tg3_wait_for_event_ack(tp);
}
}
/* tp->lock is held. */
static void tg3_write_sig_pre_reset(struct tg3 *tp, int kind)
{
tg3_write_mem(tp, NIC_SRAM_FIRMWARE_MBOX,
NIC_SRAM_FIRMWARE_MBOX_MAGIC1);
if (tg3_flag(tp, ASF_NEW_HANDSHAKE)) {
switch (kind) {
case RESET_KIND_INIT:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_START);
break;
case RESET_KIND_SHUTDOWN:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_UNLOAD);
break;
case RESET_KIND_SUSPEND:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_SUSPEND);
break;
default:
break;
}
}
}
/* tp->lock is held. */
static void tg3_write_sig_post_reset(struct tg3 *tp, int kind)
{
if (tg3_flag(tp, ASF_NEW_HANDSHAKE)) {
switch (kind) {
case RESET_KIND_INIT:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_START_DONE);
break;
case RESET_KIND_SHUTDOWN:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_UNLOAD_DONE);
break;
default:
break;
}
}
}
/* tp->lock is held. */
static void tg3_write_sig_legacy(struct tg3 *tp, int kind)
{
if (tg3_flag(tp, ENABLE_ASF)) {
switch (kind) {
case RESET_KIND_INIT:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_START);
break;
case RESET_KIND_SHUTDOWN:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_UNLOAD);
break;
case RESET_KIND_SUSPEND:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_SUSPEND);
break;
default:
break;
}
}
}
static int tg3_poll_fw(struct tg3 *tp)
{
int i;
u32 val;
if (tg3_flag(tp, NO_FWARE_REPORTED))
return 0;
if (tg3_flag(tp, IS_SSB_CORE)) {
/* We don't use firmware. */
return 0;
}
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
/* Wait up to 20ms for init done. */
for (i = 0; i < 200; i++) {
if (tr32(VCPU_STATUS) & VCPU_STATUS_INIT_DONE)
return 0;
if (pci_channel_offline(tp->pdev))
return -ENODEV;
udelay(100);
}
return -ENODEV;
}
/* Wait for firmware initialization to complete. */
for (i = 0; i < 100000; i++) {
tg3_read_mem(tp, NIC_SRAM_FIRMWARE_MBOX, &val);
if (val == ~NIC_SRAM_FIRMWARE_MBOX_MAGIC1)
break;
if (pci_channel_offline(tp->pdev)) {
if (!tg3_flag(tp, NO_FWARE_REPORTED)) {
tg3_flag_set(tp, NO_FWARE_REPORTED);
netdev_info(tp->dev, "No firmware running\n");
}
break;
}
udelay(10);
}
/* Chip might not be fitted with firmware. Some Sun onboard
* parts are configured like that. So don't signal the timeout
* of the above loop as an error, but do report the lack of
* running firmware once.
*/
if (i >= 100000 && !tg3_flag(tp, NO_FWARE_REPORTED)) {
tg3_flag_set(tp, NO_FWARE_REPORTED);
netdev_info(tp->dev, "No firmware running\n");
}
if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) {
/* The 57765 A0 needs a little more
* time to do some important work.
*/
mdelay(10);
}
return 0;
}
static void tg3_link_report(struct tg3 *tp)
{
if (!netif_carrier_ok(tp->dev)) {
netif_info(tp, link, tp->dev, "Link is down\n");
tg3_ump_link_report(tp);
} else if (netif_msg_link(tp)) {
netdev_info(tp->dev, "Link is up at %d Mbps, %s duplex\n",
(tp->link_config.active_speed == SPEED_1000 ?
1000 :
(tp->link_config.active_speed == SPEED_100 ?
100 : 10)),
(tp->link_config.active_duplex == DUPLEX_FULL ?
"full" : "half"));
netdev_info(tp->dev, "Flow control is %s for TX and %s for RX\n",
(tp->link_config.active_flowctrl & FLOW_CTRL_TX) ?
"on" : "off",
(tp->link_config.active_flowctrl & FLOW_CTRL_RX) ?
"on" : "off");
if (tp->phy_flags & TG3_PHYFLG_EEE_CAP)
netdev_info(tp->dev, "EEE is %s\n",
tp->setlpicnt ? "enabled" : "disabled");
tg3_ump_link_report(tp);
}
tp->link_up = netif_carrier_ok(tp->dev);
}
static u32 tg3_decode_flowctrl_1000T(u32 adv)
{
u32 flowctrl = 0;
if (adv & ADVERTISE_PAUSE_CAP) {
flowctrl |= FLOW_CTRL_RX;
if (!(adv & ADVERTISE_PAUSE_ASYM))
flowctrl |= FLOW_CTRL_TX;
} else if (adv & ADVERTISE_PAUSE_ASYM)
flowctrl |= FLOW_CTRL_TX;
return flowctrl;
}
static u16 tg3_advert_flowctrl_1000X(u8 flow_ctrl)
{
u16 miireg;
if ((flow_ctrl & FLOW_CTRL_TX) && (flow_ctrl & FLOW_CTRL_RX))
miireg = ADVERTISE_1000XPAUSE;
else if (flow_ctrl & FLOW_CTRL_TX)
miireg = ADVERTISE_1000XPSE_ASYM;
else if (flow_ctrl & FLOW_CTRL_RX)
miireg = ADVERTISE_1000XPAUSE | ADVERTISE_1000XPSE_ASYM;
else
miireg = 0;
return miireg;
}
static u32 tg3_decode_flowctrl_1000X(u32 adv)
{
u32 flowctrl = 0;
if (adv & ADVERTISE_1000XPAUSE) {
flowctrl |= FLOW_CTRL_RX;
if (!(adv & ADVERTISE_1000XPSE_ASYM))
flowctrl |= FLOW_CTRL_TX;
} else if (adv & ADVERTISE_1000XPSE_ASYM)
flowctrl |= FLOW_CTRL_TX;
return flowctrl;
}
static u8 tg3_resolve_flowctrl_1000X(u16 lcladv, u16 rmtadv)
{
u8 cap = 0;
if (lcladv & rmtadv & ADVERTISE_1000XPAUSE) {
cap = FLOW_CTRL_TX | FLOW_CTRL_RX;
} else if (lcladv & rmtadv & ADVERTISE_1000XPSE_ASYM) {
if (lcladv & ADVERTISE_1000XPAUSE)
cap = FLOW_CTRL_RX;
if (rmtadv & ADVERTISE_1000XPAUSE)
cap = FLOW_CTRL_TX;
}
return cap;
}
static void tg3_setup_flow_control(struct tg3 *tp, u32 lcladv, u32 rmtadv)
{
u8 autoneg;
u8 flowctrl = 0;
u32 old_rx_mode = tp->rx_mode;
u32 old_tx_mode = tp->tx_mode;
if (tg3_flag(tp, USE_PHYLIB))
autoneg = tp->mdio_bus->phy_map[tp->phy_addr]->autoneg;
else
autoneg = tp->link_config.autoneg;
if (autoneg == AUTONEG_ENABLE && tg3_flag(tp, PAUSE_AUTONEG)) {
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)
flowctrl = tg3_resolve_flowctrl_1000X(lcladv, rmtadv);
else
flowctrl = mii_resolve_flowctrl_fdx(lcladv, rmtadv);
} else
flowctrl = tp->link_config.flowctrl;
tp->link_config.active_flowctrl = flowctrl;
if (flowctrl & FLOW_CTRL_RX)
tp->rx_mode |= RX_MODE_FLOW_CTRL_ENABLE;
else
tp->rx_mode &= ~RX_MODE_FLOW_CTRL_ENABLE;
if (old_rx_mode != tp->rx_mode)
tw32_f(MAC_RX_MODE, tp->rx_mode);
if (flowctrl & FLOW_CTRL_TX)
tp->tx_mode |= TX_MODE_FLOW_CTRL_ENABLE;
else
tp->tx_mode &= ~TX_MODE_FLOW_CTRL_ENABLE;
if (old_tx_mode != tp->tx_mode)
tw32_f(MAC_TX_MODE, tp->tx_mode);
}
static void tg3_adjust_link(struct net_device *dev)
{
u8 oldflowctrl, linkmesg = 0;
u32 mac_mode, lcl_adv, rmt_adv;
struct tg3 *tp = netdev_priv(dev);
struct phy_device *phydev = tp->mdio_bus->phy_map[tp->phy_addr];
spin_lock_bh(&tp->lock);
mac_mode = tp->mac_mode & ~(MAC_MODE_PORT_MODE_MASK |
MAC_MODE_HALF_DUPLEX);
oldflowctrl = tp->link_config.active_flowctrl;
if (phydev->link) {
lcl_adv = 0;
rmt_adv = 0;
if (phydev->speed == SPEED_100 || phydev->speed == SPEED_10)
mac_mode |= MAC_MODE_PORT_MODE_MII;
else if (phydev->speed == SPEED_1000 ||
tg3_asic_rev(tp) != ASIC_REV_5785)
mac_mode |= MAC_MODE_PORT_MODE_GMII;
else
mac_mode |= MAC_MODE_PORT_MODE_MII;
if (phydev->duplex == DUPLEX_HALF)
mac_mode |= MAC_MODE_HALF_DUPLEX;
else {
lcl_adv = mii_advertise_flowctrl(
tp->link_config.flowctrl);
if (phydev->pause)
rmt_adv = LPA_PAUSE_CAP;
if (phydev->asym_pause)
rmt_adv |= LPA_PAUSE_ASYM;
}
tg3_setup_flow_control(tp, lcl_adv, rmt_adv);
} else
mac_mode |= MAC_MODE_PORT_MODE_GMII;
if (mac_mode != tp->mac_mode) {
tp->mac_mode = mac_mode;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
}
if (tg3_asic_rev(tp) == ASIC_REV_5785) {
if (phydev->speed == SPEED_10)
tw32(MAC_MI_STAT,
MAC_MI_STAT_10MBPS_MODE |
MAC_MI_STAT_LNKSTAT_ATTN_ENAB);
else
tw32(MAC_MI_STAT, MAC_MI_STAT_LNKSTAT_ATTN_ENAB);
}
if (phydev->speed == SPEED_1000 && phydev->duplex == DUPLEX_HALF)
tw32(MAC_TX_LENGTHS,
((2 << TX_LENGTHS_IPG_CRS_SHIFT) |
(6 << TX_LENGTHS_IPG_SHIFT) |
(0xff << TX_LENGTHS_SLOT_TIME_SHIFT)));
else
tw32(MAC_TX_LENGTHS,
((2 << TX_LENGTHS_IPG_CRS_SHIFT) |
(6 << TX_LENGTHS_IPG_SHIFT) |
(32 << TX_LENGTHS_SLOT_TIME_SHIFT)));
if (phydev->link != tp->old_link ||
phydev->speed != tp->link_config.active_speed ||
phydev->duplex != tp->link_config.active_duplex ||
oldflowctrl != tp->link_config.active_flowctrl)
linkmesg = 1;
tp->old_link = phydev->link;
tp->link_config.active_speed = phydev->speed;
tp->link_config.active_duplex = phydev->duplex;
spin_unlock_bh(&tp->lock);
if (linkmesg)
tg3_link_report(tp);
}
static int tg3_phy_init(struct tg3 *tp)
{
struct phy_device *phydev;
if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED)
return 0;
/* Bring the PHY back to a known state. */
tg3_bmcr_reset(tp);
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
/* Attach the MAC to the PHY. */
phydev = phy_connect(tp->dev, dev_name(&phydev->dev),
tg3_adjust_link, phydev->interface);
if (IS_ERR(phydev)) {
dev_err(&tp->pdev->dev, "Could not attach to PHY\n");
return PTR_ERR(phydev);
}
/* Mask with MAC supported features. */
switch (phydev->interface) {
case PHY_INTERFACE_MODE_GMII:
case PHY_INTERFACE_MODE_RGMII:
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
phydev->supported &= (PHY_GBIT_FEATURES |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
}
/* fallthru */
case PHY_INTERFACE_MODE_MII:
phydev->supported &= (PHY_BASIC_FEATURES |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
default:
phy_disconnect(tp->mdio_bus->phy_map[tp->phy_addr]);
return -EINVAL;
}
tp->phy_flags |= TG3_PHYFLG_IS_CONNECTED;
phydev->advertising = phydev->supported;
return 0;
}
static void tg3_phy_start(struct tg3 *tp)
{
struct phy_device *phydev;
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return;
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) {
tp->phy_flags &= ~TG3_PHYFLG_IS_LOW_POWER;
phydev->speed = tp->link_config.speed;
phydev->duplex = tp->link_config.duplex;
phydev->autoneg = tp->link_config.autoneg;
phydev->advertising = tp->link_config.advertising;
}
phy_start(phydev);
phy_start_aneg(phydev);
}
static void tg3_phy_stop(struct tg3 *tp)
{
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return;
phy_stop(tp->mdio_bus->phy_map[tp->phy_addr]);
}
static void tg3_phy_fini(struct tg3 *tp)
{
if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) {
phy_disconnect(tp->mdio_bus->phy_map[tp->phy_addr]);
tp->phy_flags &= ~TG3_PHYFLG_IS_CONNECTED;
}
}
static int tg3_phy_set_extloopbk(struct tg3 *tp)
{
int err;
u32 val;
if (tp->phy_flags & TG3_PHYFLG_IS_FET)
return 0;
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) {
/* Cannot do read-modify-write on 5401 */
err = tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_AUXCTL,
MII_TG3_AUXCTL_ACTL_EXTLOOPBK |
0x4c20);
goto done;
}
err = tg3_phy_auxctl_read(tp,
MII_TG3_AUXCTL_SHDWSEL_AUXCTL, &val);
if (err)
return err;
val |= MII_TG3_AUXCTL_ACTL_EXTLOOPBK;
err = tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_AUXCTL, val);
done:
return err;
}
static void tg3_phy_fet_toggle_apd(struct tg3 *tp, bool enable)
{
u32 phytest;
if (!tg3_readphy(tp, MII_TG3_FET_TEST, &phytest)) {
u32 phy;
tg3_writephy(tp, MII_TG3_FET_TEST,
phytest | MII_TG3_FET_SHADOW_EN);
if (!tg3_readphy(tp, MII_TG3_FET_SHDW_AUXSTAT2, &phy)) {
if (enable)
phy |= MII_TG3_FET_SHDW_AUXSTAT2_APD;
else
phy &= ~MII_TG3_FET_SHDW_AUXSTAT2_APD;
tg3_writephy(tp, MII_TG3_FET_SHDW_AUXSTAT2, phy);
}
tg3_writephy(tp, MII_TG3_FET_TEST, phytest);
}
}
static void tg3_phy_toggle_apd(struct tg3 *tp, bool enable)
{
u32 reg;
if (!tg3_flag(tp, 5705_PLUS) ||
(tg3_flag(tp, 5717_PLUS) &&
(tp->phy_flags & TG3_PHYFLG_MII_SERDES)))
return;
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
tg3_phy_fet_toggle_apd(tp, enable);
return;
}
reg = MII_TG3_MISC_SHDW_SCR5_LPED |
MII_TG3_MISC_SHDW_SCR5_DLPTLM |
MII_TG3_MISC_SHDW_SCR5_SDTL |
MII_TG3_MISC_SHDW_SCR5_C125OE;
if (tg3_asic_rev(tp) != ASIC_REV_5784 || !enable)
reg |= MII_TG3_MISC_SHDW_SCR5_DLLAPD;
tg3_phy_shdw_write(tp, MII_TG3_MISC_SHDW_SCR5_SEL, reg);
reg = MII_TG3_MISC_SHDW_APD_WKTM_84MS;
if (enable)
reg |= MII_TG3_MISC_SHDW_APD_ENABLE;
tg3_phy_shdw_write(tp, MII_TG3_MISC_SHDW_APD_SEL, reg);
}
static void tg3_phy_toggle_automdix(struct tg3 *tp, bool enable)
{
u32 phy;
if (!tg3_flag(tp, 5705_PLUS) ||
(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
return;
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
u32 ephy;
if (!tg3_readphy(tp, MII_TG3_FET_TEST, &ephy)) {
u32 reg = MII_TG3_FET_SHDW_MISCCTRL;
tg3_writephy(tp, MII_TG3_FET_TEST,
ephy | MII_TG3_FET_SHADOW_EN);
if (!tg3_readphy(tp, reg, &phy)) {
if (enable)
phy |= MII_TG3_FET_SHDW_MISCCTRL_MDIX;
else
phy &= ~MII_TG3_FET_SHDW_MISCCTRL_MDIX;
tg3_writephy(tp, reg, phy);
}
tg3_writephy(tp, MII_TG3_FET_TEST, ephy);
}
} else {
int ret;
ret = tg3_phy_auxctl_read(tp,
MII_TG3_AUXCTL_SHDWSEL_MISC, &phy);
if (!ret) {
if (enable)
phy |= MII_TG3_AUXCTL_MISC_FORCE_AMDIX;
else
phy &= ~MII_TG3_AUXCTL_MISC_FORCE_AMDIX;
tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_MISC, phy);
}
}
}
static void tg3_phy_set_wirespeed(struct tg3 *tp)
{
int ret;
u32 val;
if (tp->phy_flags & TG3_PHYFLG_NO_ETH_WIRE_SPEED)
return;
ret = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_MISC, &val);
if (!ret)
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_MISC,
val | MII_TG3_AUXCTL_MISC_WIRESPD_EN);
}
static void tg3_phy_apply_otp(struct tg3 *tp)
{
u32 otp, phy;
if (!tp->phy_otp)
return;
otp = tp->phy_otp;
if (tg3_phy_toggle_auxctl_smdsp(tp, true))
return;
phy = ((otp & TG3_OTP_AGCTGT_MASK) >> TG3_OTP_AGCTGT_SHIFT);
phy |= MII_TG3_DSP_TAP1_AGCTGT_DFLT;
tg3_phydsp_write(tp, MII_TG3_DSP_TAP1, phy);
phy = ((otp & TG3_OTP_HPFFLTR_MASK) >> TG3_OTP_HPFFLTR_SHIFT) |
((otp & TG3_OTP_HPFOVER_MASK) >> TG3_OTP_HPFOVER_SHIFT);
tg3_phydsp_write(tp, MII_TG3_DSP_AADJ1CH0, phy);
phy = ((otp & TG3_OTP_LPFDIS_MASK) >> TG3_OTP_LPFDIS_SHIFT);
phy |= MII_TG3_DSP_AADJ1CH3_ADCCKADJ;
tg3_phydsp_write(tp, MII_TG3_DSP_AADJ1CH3, phy);
phy = ((otp & TG3_OTP_VDAC_MASK) >> TG3_OTP_VDAC_SHIFT);
tg3_phydsp_write(tp, MII_TG3_DSP_EXP75, phy);
phy = ((otp & TG3_OTP_10BTAMP_MASK) >> TG3_OTP_10BTAMP_SHIFT);
tg3_phydsp_write(tp, MII_TG3_DSP_EXP96, phy);
phy = ((otp & TG3_OTP_ROFF_MASK) >> TG3_OTP_ROFF_SHIFT) |
((otp & TG3_OTP_RCOFF_MASK) >> TG3_OTP_RCOFF_SHIFT);
tg3_phydsp_write(tp, MII_TG3_DSP_EXP97, phy);
tg3_phy_toggle_auxctl_smdsp(tp, false);
}
static void tg3_eee_pull_config(struct tg3 *tp, struct ethtool_eee *eee)
{
u32 val;
struct ethtool_eee *dest = &tp->eee;
if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP))
return;
if (eee)
dest = eee;
if (tg3_phy_cl45_read(tp, MDIO_MMD_AN, TG3_CL45_D7_EEERES_STAT, &val))
return;
/* Pull eee_active */
if (val == TG3_CL45_D7_EEERES_STAT_LP_1000T ||
val == TG3_CL45_D7_EEERES_STAT_LP_100TX) {
dest->eee_active = 1;
} else
dest->eee_active = 0;
/* Pull lp advertised settings */
if (tg3_phy_cl45_read(tp, MDIO_MMD_AN, MDIO_AN_EEE_LPABLE, &val))
return;
dest->lp_advertised = mmd_eee_adv_to_ethtool_adv_t(val);
/* Pull advertised and eee_enabled settings */
if (tg3_phy_cl45_read(tp, MDIO_MMD_AN, MDIO_AN_EEE_ADV, &val))
return;
dest->eee_enabled = !!val;
dest->advertised = mmd_eee_adv_to_ethtool_adv_t(val);
/* Pull tx_lpi_enabled */
val = tr32(TG3_CPMU_EEE_MODE);
dest->tx_lpi_enabled = !!(val & TG3_CPMU_EEEMD_LPI_IN_TX);
/* Pull lpi timer value */
dest->tx_lpi_timer = tr32(TG3_CPMU_EEE_DBTMR1) & 0xffff;
}
static void tg3_phy_eee_adjust(struct tg3 *tp, bool current_link_up)
{
u32 val;
if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP))
return;
tp->setlpicnt = 0;
if (tp->link_config.autoneg == AUTONEG_ENABLE &&
current_link_up &&
tp->link_config.active_duplex == DUPLEX_FULL &&
(tp->link_config.active_speed == SPEED_100 ||
tp->link_config.active_speed == SPEED_1000)) {
u32 eeectl;
if (tp->link_config.active_speed == SPEED_1000)
eeectl = TG3_CPMU_EEE_CTRL_EXIT_16_5_US;
else
eeectl = TG3_CPMU_EEE_CTRL_EXIT_36_US;
tw32(TG3_CPMU_EEE_CTRL, eeectl);
tg3_eee_pull_config(tp, NULL);
if (tp->eee.eee_active)
tp->setlpicnt = 2;
}
if (!tp->setlpicnt) {
if (current_link_up &&
!tg3_phy_toggle_auxctl_smdsp(tp, true)) {
tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, 0x0000);
tg3_phy_toggle_auxctl_smdsp(tp, false);
}
val = tr32(TG3_CPMU_EEE_MODE);
tw32(TG3_CPMU_EEE_MODE, val & ~TG3_CPMU_EEEMD_LPI_ENABLE);
}
}
static void tg3_phy_eee_enable(struct tg3 *tp)
{
u32 val;
if (tp->link_config.active_speed == SPEED_1000 &&
(tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_flag(tp, 57765_CLASS)) &&
!tg3_phy_toggle_auxctl_smdsp(tp, true)) {
val = MII_TG3_DSP_TAP26_ALNOKO |
MII_TG3_DSP_TAP26_RMRXSTO;
tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, val);
tg3_phy_toggle_auxctl_smdsp(tp, false);
}
val = tr32(TG3_CPMU_EEE_MODE);
tw32(TG3_CPMU_EEE_MODE, val | TG3_CPMU_EEEMD_LPI_ENABLE);
}
static int tg3_wait_macro_done(struct tg3 *tp)
{
int limit = 100;
while (limit--) {
u32 tmp32;
if (!tg3_readphy(tp, MII_TG3_DSP_CONTROL, &tmp32)) {
if ((tmp32 & 0x1000) == 0)
break;
}
}
if (limit < 0)
return -EBUSY;
return 0;
}
static int tg3_phy_write_and_check_testpat(struct tg3 *tp, int *resetp)
{
static const u32 test_pat[4][6] = {
{ 0x00005555, 0x00000005, 0x00002aaa, 0x0000000a, 0x00003456, 0x00000003 },
{ 0x00002aaa, 0x0000000a, 0x00003333, 0x00000003, 0x0000789a, 0x00000005 },
{ 0x00005a5a, 0x00000005, 0x00002a6a, 0x0000000a, 0x00001bcd, 0x00000003 },
{ 0x00002a5a, 0x0000000a, 0x000033c3, 0x00000003, 0x00002ef1, 0x00000005 }
};
int chan;
for (chan = 0; chan < 4; chan++) {
int i;
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
(chan * 0x2000) | 0x0200);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0002);
for (i = 0; i < 6; i++)
tg3_writephy(tp, MII_TG3_DSP_RW_PORT,
test_pat[chan][i]);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0202);
if (tg3_wait_macro_done(tp)) {
*resetp = 1;
return -EBUSY;
}
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
(chan * 0x2000) | 0x0200);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0082);
if (tg3_wait_macro_done(tp)) {
*resetp = 1;
return -EBUSY;
}
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0802);
if (tg3_wait_macro_done(tp)) {
*resetp = 1;
return -EBUSY;
}
for (i = 0; i < 6; i += 2) {
u32 low, high;
if (tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &low) ||
tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &high) ||
tg3_wait_macro_done(tp)) {
*resetp = 1;
return -EBUSY;
}
low &= 0x7fff;
high &= 0x000f;
if (low != test_pat[chan][i] ||
high != test_pat[chan][i+1]) {
tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x000b);
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x4001);
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x4005);
return -EBUSY;
}
}
}
return 0;
}
static int tg3_phy_reset_chanpat(struct tg3 *tp)
{
int chan;
for (chan = 0; chan < 4; chan++) {
int i;
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
(chan * 0x2000) | 0x0200);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0002);
for (i = 0; i < 6; i++)
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x000);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0202);
if (tg3_wait_macro_done(tp))
return -EBUSY;
}
return 0;
}
static int tg3_phy_reset_5703_4_5(struct tg3 *tp)
{
u32 reg32, phy9_orig;
int retries, do_phy_reset, err;
retries = 10;
do_phy_reset = 1;
do {
if (do_phy_reset) {
err = tg3_bmcr_reset(tp);
if (err)
return err;
do_phy_reset = 0;
}
/* Disable transmitter and interrupt. */
if (tg3_readphy(tp, MII_TG3_EXT_CTRL, ®32))
continue;
reg32 |= 0x3000;
tg3_writephy(tp, MII_TG3_EXT_CTRL, reg32);
/* Set full-duplex, 1000 mbps. */
tg3_writephy(tp, MII_BMCR,
BMCR_FULLDPLX | BMCR_SPEED1000);
/* Set to master mode. */
if (tg3_readphy(tp, MII_CTRL1000, &phy9_orig))
continue;
tg3_writephy(tp, MII_CTRL1000,
CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER);
err = tg3_phy_toggle_auxctl_smdsp(tp, true);
if (err)
return err;
/* Block the PHY control access. */
tg3_phydsp_write(tp, 0x8005, 0x0800);
err = tg3_phy_write_and_check_testpat(tp, &do_phy_reset);
if (!err)
break;
} while (--retries);
err = tg3_phy_reset_chanpat(tp);
if (err)
return err;
tg3_phydsp_write(tp, 0x8005, 0x0000);
tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x8200);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0000);
tg3_phy_toggle_auxctl_smdsp(tp, false);
tg3_writephy(tp, MII_CTRL1000, phy9_orig);
err = tg3_readphy(tp, MII_TG3_EXT_CTRL, ®32);
if (err)
return err;
reg32 &= ~0x3000;
tg3_writephy(tp, MII_TG3_EXT_CTRL, reg32);
return 0;
}
static void tg3_carrier_off(struct tg3 *tp)
{
netif_carrier_off(tp->dev);
tp->link_up = false;
}
static void tg3_warn_mgmt_link_flap(struct tg3 *tp)
{
if (tg3_flag(tp, ENABLE_ASF))
netdev_warn(tp->dev,
"Management side-band traffic will be interrupted during phy settings change\n");
}
/* This will reset the tigon3 PHY if there is no valid
* link unless the FORCE argument is non-zero.
*/
static int tg3_phy_reset(struct tg3 *tp)
{
u32 val, cpmuctrl;
int err;
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
val = tr32(GRC_MISC_CFG);
tw32_f(GRC_MISC_CFG, val & ~GRC_MISC_CFG_EPHY_IDDQ);
udelay(40);
}
err = tg3_readphy(tp, MII_BMSR, &val);
err |= tg3_readphy(tp, MII_BMSR, &val);
if (err != 0)
return -EBUSY;
if (netif_running(tp->dev) && tp->link_up) {
netif_carrier_off(tp->dev);
tg3_link_report(tp);
}
if (tg3_asic_rev(tp) == ASIC_REV_5703 ||
tg3_asic_rev(tp) == ASIC_REV_5704 ||
tg3_asic_rev(tp) == ASIC_REV_5705) {
err = tg3_phy_reset_5703_4_5(tp);
if (err)
return err;
goto out;
}
cpmuctrl = 0;
if (tg3_asic_rev(tp) == ASIC_REV_5784 &&
tg3_chip_rev(tp) != CHIPREV_5784_AX) {
cpmuctrl = tr32(TG3_CPMU_CTRL);
if (cpmuctrl & CPMU_CTRL_GPHY_10MB_RXONLY)
tw32(TG3_CPMU_CTRL,
cpmuctrl & ~CPMU_CTRL_GPHY_10MB_RXONLY);
}
err = tg3_bmcr_reset(tp);
if (err)
return err;
if (cpmuctrl & CPMU_CTRL_GPHY_10MB_RXONLY) {
val = MII_TG3_DSP_EXP8_AEDW | MII_TG3_DSP_EXP8_REJ2MHz;
tg3_phydsp_write(tp, MII_TG3_DSP_EXP8, val);
tw32(TG3_CPMU_CTRL, cpmuctrl);
}
if (tg3_chip_rev(tp) == CHIPREV_5784_AX ||
tg3_chip_rev(tp) == CHIPREV_5761_AX) {
val = tr32(TG3_CPMU_LSPD_1000MB_CLK);
if ((val & CPMU_LSPD_1000MB_MACCLK_MASK) ==
CPMU_LSPD_1000MB_MACCLK_12_5) {
val &= ~CPMU_LSPD_1000MB_MACCLK_MASK;
udelay(40);
tw32_f(TG3_CPMU_LSPD_1000MB_CLK, val);
}
}
if (tg3_flag(tp, 5717_PLUS) &&
(tp->phy_flags & TG3_PHYFLG_MII_SERDES))
return 0;
tg3_phy_apply_otp(tp);
if (tp->phy_flags & TG3_PHYFLG_ENABLE_APD)
tg3_phy_toggle_apd(tp, true);
else
tg3_phy_toggle_apd(tp, false);
out:
if ((tp->phy_flags & TG3_PHYFLG_ADC_BUG) &&
!tg3_phy_toggle_auxctl_smdsp(tp, true)) {
tg3_phydsp_write(tp, 0x201f, 0x2aaa);
tg3_phydsp_write(tp, 0x000a, 0x0323);
tg3_phy_toggle_auxctl_smdsp(tp, false);
}
if (tp->phy_flags & TG3_PHYFLG_5704_A0_BUG) {
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68);
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68);
}
if (tp->phy_flags & TG3_PHYFLG_BER_BUG) {
if (!tg3_phy_toggle_auxctl_smdsp(tp, true)) {
tg3_phydsp_write(tp, 0x000a, 0x310b);
tg3_phydsp_write(tp, 0x201f, 0x9506);
tg3_phydsp_write(tp, 0x401f, 0x14e2);
tg3_phy_toggle_auxctl_smdsp(tp, false);
}
} else if (tp->phy_flags & TG3_PHYFLG_JITTER_BUG) {
if (!tg3_phy_toggle_auxctl_smdsp(tp, true)) {
tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x000a);
if (tp->phy_flags & TG3_PHYFLG_ADJUST_TRIM) {
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x110b);
tg3_writephy(tp, MII_TG3_TEST1,
MII_TG3_TEST1_TRIM_EN | 0x4);
} else
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x010b);
tg3_phy_toggle_auxctl_smdsp(tp, false);
}
}
/* Set Extended packet length bit (bit 14) on all chips that */
/* support jumbo frames */
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) {
/* Cannot do read-modify-write on 5401 */
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, 0x4c20);
} else if (tg3_flag(tp, JUMBO_CAPABLE)) {
/* Set bit 14 with read-modify-write to preserve other bits */
err = tg3_phy_auxctl_read(tp,
MII_TG3_AUXCTL_SHDWSEL_AUXCTL, &val);
if (!err)
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL,
val | MII_TG3_AUXCTL_ACTL_EXTPKTLEN);
}
/* Set phy register 0x10 bit 0 to high fifo elasticity to support
* jumbo frames transmission.
*/
if (tg3_flag(tp, JUMBO_CAPABLE)) {
if (!tg3_readphy(tp, MII_TG3_EXT_CTRL, &val))
tg3_writephy(tp, MII_TG3_EXT_CTRL,
val | MII_TG3_EXT_CTRL_FIFO_ELASTIC);
}
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
/* adjust output voltage */
tg3_writephy(tp, MII_TG3_FET_PTEST, 0x12);
}
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5762_A0)
tg3_phydsp_write(tp, 0xffb, 0x4000);
tg3_phy_toggle_automdix(tp, true);
tg3_phy_set_wirespeed(tp);
return 0;
}
#define TG3_GPIO_MSG_DRVR_PRES 0x00000001
#define TG3_GPIO_MSG_NEED_VAUX 0x00000002
#define TG3_GPIO_MSG_MASK (TG3_GPIO_MSG_DRVR_PRES | \
TG3_GPIO_MSG_NEED_VAUX)
#define TG3_GPIO_MSG_ALL_DRVR_PRES_MASK \
((TG3_GPIO_MSG_DRVR_PRES << 0) | \
(TG3_GPIO_MSG_DRVR_PRES << 4) | \
(TG3_GPIO_MSG_DRVR_PRES << 8) | \
(TG3_GPIO_MSG_DRVR_PRES << 12))
#define TG3_GPIO_MSG_ALL_NEED_VAUX_MASK \
((TG3_GPIO_MSG_NEED_VAUX << 0) | \
(TG3_GPIO_MSG_NEED_VAUX << 4) | \
(TG3_GPIO_MSG_NEED_VAUX << 8) | \
(TG3_GPIO_MSG_NEED_VAUX << 12))
static inline u32 tg3_set_function_status(struct tg3 *tp, u32 newstat)
{
u32 status, shift;
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719)
status = tg3_ape_read32(tp, TG3_APE_GPIO_MSG);
else
status = tr32(TG3_CPMU_DRV_STATUS);
shift = TG3_APE_GPIO_MSG_SHIFT + 4 * tp->pci_fn;
status &= ~(TG3_GPIO_MSG_MASK << shift);
status |= (newstat << shift);
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719)
tg3_ape_write32(tp, TG3_APE_GPIO_MSG, status);
else
tw32(TG3_CPMU_DRV_STATUS, status);
return status >> TG3_APE_GPIO_MSG_SHIFT;
}
static inline int tg3_pwrsrc_switch_to_vmain(struct tg3 *tp)
{
if (!tg3_flag(tp, IS_NIC))
return 0;
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720) {
if (tg3_ape_lock(tp, TG3_APE_LOCK_GPIO))
return -EIO;
tg3_set_function_status(tp, TG3_GPIO_MSG_DRVR_PRES);
tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
tg3_ape_unlock(tp, TG3_APE_LOCK_GPIO);
} else {
tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
}
return 0;
}
static void tg3_pwrsrc_die_with_vmain(struct tg3 *tp)
{
u32 grc_local_ctrl;
if (!tg3_flag(tp, IS_NIC) ||
tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701)
return;
grc_local_ctrl = tp->grc_local_ctrl | GRC_LCLCTRL_GPIO_OE1;
tw32_wait_f(GRC_LOCAL_CTRL,
grc_local_ctrl | GRC_LCLCTRL_GPIO_OUTPUT1,
TG3_GRC_LCLCTL_PWRSW_DELAY);
tw32_wait_f(GRC_LOCAL_CTRL,
grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
tw32_wait_f(GRC_LOCAL_CTRL,
grc_local_ctrl | GRC_LCLCTRL_GPIO_OUTPUT1,
TG3_GRC_LCLCTL_PWRSW_DELAY);
}
static void tg3_pwrsrc_switch_to_vaux(struct tg3 *tp)
{
if (!tg3_flag(tp, IS_NIC))
return;
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701) {
tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl |
(GRC_LCLCTRL_GPIO_OE0 |
GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OE2 |
GRC_LCLCTRL_GPIO_OUTPUT0 |
GRC_LCLCTRL_GPIO_OUTPUT1),
TG3_GRC_LCLCTL_PWRSW_DELAY);
} else if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S) {
/* The 5761 non-e device swaps GPIO 0 and GPIO 2. */
u32 grc_local_ctrl = GRC_LCLCTRL_GPIO_OE0 |
GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OE2 |
GRC_LCLCTRL_GPIO_OUTPUT0 |
GRC_LCLCTRL_GPIO_OUTPUT1 |
tp->grc_local_ctrl;
tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
grc_local_ctrl |= GRC_LCLCTRL_GPIO_OUTPUT2;
tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
grc_local_ctrl &= ~GRC_LCLCTRL_GPIO_OUTPUT0;
tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
} else {
u32 no_gpio2;
u32 grc_local_ctrl = 0;
/* Workaround to prevent overdrawing Amps. */
if (tg3_asic_rev(tp) == ASIC_REV_5714) {
grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE3;
tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl |
grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
}
/* On 5753 and variants, GPIO2 cannot be used. */
no_gpio2 = tp->nic_sram_data_cfg &
NIC_SRAM_DATA_CFG_NO_GPIO2;
grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE0 |
GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OE2 |
GRC_LCLCTRL_GPIO_OUTPUT1 |
GRC_LCLCTRL_GPIO_OUTPUT2;
if (no_gpio2) {
grc_local_ctrl &= ~(GRC_LCLCTRL_GPIO_OE2 |
GRC_LCLCTRL_GPIO_OUTPUT2);
}
tw32_wait_f(GRC_LOCAL_CTRL,
tp->grc_local_ctrl | grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
grc_local_ctrl |= GRC_LCLCTRL_GPIO_OUTPUT0;
tw32_wait_f(GRC_LOCAL_CTRL,
tp->grc_local_ctrl | grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
if (!no_gpio2) {
grc_local_ctrl &= ~GRC_LCLCTRL_GPIO_OUTPUT2;
tw32_wait_f(GRC_LOCAL_CTRL,
tp->grc_local_ctrl | grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
}
}
}
static void tg3_frob_aux_power_5717(struct tg3 *tp, bool wol_enable)
{
u32 msg = 0;
/* Serialize power state transitions */
if (tg3_ape_lock(tp, TG3_APE_LOCK_GPIO))
return;
if (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE) || wol_enable)
msg = TG3_GPIO_MSG_NEED_VAUX;
msg = tg3_set_function_status(tp, msg);
if (msg & TG3_GPIO_MSG_ALL_DRVR_PRES_MASK)
goto done;
if (msg & TG3_GPIO_MSG_ALL_NEED_VAUX_MASK)
tg3_pwrsrc_switch_to_vaux(tp);
else
tg3_pwrsrc_die_with_vmain(tp);
done:
tg3_ape_unlock(tp, TG3_APE_LOCK_GPIO);
}
static void tg3_frob_aux_power(struct tg3 *tp, bool include_wol)
{
bool need_vaux = false;
/* The GPIOs do something completely different on 57765. */
if (!tg3_flag(tp, IS_NIC) || tg3_flag(tp, 57765_CLASS))
return;
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720) {
tg3_frob_aux_power_5717(tp, include_wol ?
tg3_flag(tp, WOL_ENABLE) != 0 : 0);
return;
}
if (tp->pdev_peer && tp->pdev_peer != tp->pdev) {
struct net_device *dev_peer;
dev_peer = pci_get_drvdata(tp->pdev_peer);
/* remove_one() may have been run on the peer. */
if (dev_peer) {
struct tg3 *tp_peer = netdev_priv(dev_peer);
if (tg3_flag(tp_peer, INIT_COMPLETE))
return;
if ((include_wol && tg3_flag(tp_peer, WOL_ENABLE)) ||
tg3_flag(tp_peer, ENABLE_ASF))
need_vaux = true;
}
}
if ((include_wol && tg3_flag(tp, WOL_ENABLE)) ||
tg3_flag(tp, ENABLE_ASF))
need_vaux = true;
if (need_vaux)
tg3_pwrsrc_switch_to_vaux(tp);
else
tg3_pwrsrc_die_with_vmain(tp);
}
static int tg3_5700_link_polarity(struct tg3 *tp, u32 speed)
{
if (tp->led_ctrl == LED_CTRL_MODE_PHY_2)
return 1;
else if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5411) {
if (speed != SPEED_10)
return 1;
} else if (speed == SPEED_10)
return 1;
return 0;
}
static bool tg3_phy_power_bug(struct tg3 *tp)
{
switch (tg3_asic_rev(tp)) {
case ASIC_REV_5700:
case ASIC_REV_5704:
return true;
case ASIC_REV_5780:
if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
return true;
return false;
case ASIC_REV_5717:
if (!tp->pci_fn)
return true;
return false;
case ASIC_REV_5719:
case ASIC_REV_5720:
if ((tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
!tp->pci_fn)
return true;
return false;
}
return false;
}
static bool tg3_phy_led_bug(struct tg3 *tp)
{
switch (tg3_asic_rev(tp)) {
case ASIC_REV_5719:
case ASIC_REV_5720:
if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) &&
!tp->pci_fn)
return true;
return false;
}
return false;
}
static void tg3_power_down_phy(struct tg3 *tp, bool do_low_power)
{
u32 val;
if (tp->phy_flags & TG3_PHYFLG_KEEP_LINK_ON_PWRDN)
return;
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
if (tg3_asic_rev(tp) == ASIC_REV_5704) {
u32 sg_dig_ctrl = tr32(SG_DIG_CTRL);
u32 serdes_cfg = tr32(MAC_SERDES_CFG);
sg_dig_ctrl |=
SG_DIG_USING_HW_AUTONEG | SG_DIG_SOFT_RESET;
tw32(SG_DIG_CTRL, sg_dig_ctrl);
tw32(MAC_SERDES_CFG, serdes_cfg | (1 << 15));
}
return;
}
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
tg3_bmcr_reset(tp);
val = tr32(GRC_MISC_CFG);
tw32_f(GRC_MISC_CFG, val | GRC_MISC_CFG_EPHY_IDDQ);
udelay(40);
return;
} else if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
u32 phytest;
if (!tg3_readphy(tp, MII_TG3_FET_TEST, &phytest)) {
u32 phy;
tg3_writephy(tp, MII_ADVERTISE, 0);
tg3_writephy(tp, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART);
tg3_writephy(tp, MII_TG3_FET_TEST,
phytest | MII_TG3_FET_SHADOW_EN);
if (!tg3_readphy(tp, MII_TG3_FET_SHDW_AUXMODE4, &phy)) {
phy |= MII_TG3_FET_SHDW_AUXMODE4_SBPD;
tg3_writephy(tp,
MII_TG3_FET_SHDW_AUXMODE4,
phy);
}
tg3_writephy(tp, MII_TG3_FET_TEST, phytest);
}
return;
} else if (do_low_power) {
if (!tg3_phy_led_bug(tp))
tg3_writephy(tp, MII_TG3_EXT_CTRL,
MII_TG3_EXT_CTRL_FORCE_LED_OFF);
val = MII_TG3_AUXCTL_PCTL_100TX_LPWR |
MII_TG3_AUXCTL_PCTL_SPR_ISOLATE |
MII_TG3_AUXCTL_PCTL_VREG_11V;
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_PWRCTL, val);
}
/* The PHY should not be powered down on some chips because
* of bugs.
*/
if (tg3_phy_power_bug(tp))
return;
if (tg3_chip_rev(tp) == CHIPREV_5784_AX ||
tg3_chip_rev(tp) == CHIPREV_5761_AX) {
val = tr32(TG3_CPMU_LSPD_1000MB_CLK);
val &= ~CPMU_LSPD_1000MB_MACCLK_MASK;
val |= CPMU_LSPD_1000MB_MACCLK_12_5;
tw32_f(TG3_CPMU_LSPD_1000MB_CLK, val);
}
tg3_writephy(tp, MII_BMCR, BMCR_PDOWN);
}
/* tp->lock is held. */
static int tg3_nvram_lock(struct tg3 *tp)
{
if (tg3_flag(tp, NVRAM)) {
int i;
if (tp->nvram_lock_cnt == 0) {
tw32(NVRAM_SWARB, SWARB_REQ_SET1);
for (i = 0; i < 8000; i++) {
if (tr32(NVRAM_SWARB) & SWARB_GNT1)
break;
udelay(20);
}
if (i == 8000) {
tw32(NVRAM_SWARB, SWARB_REQ_CLR1);
return -ENODEV;
}
}
tp->nvram_lock_cnt++;
}
return 0;
}
/* tp->lock is held. */
static void tg3_nvram_unlock(struct tg3 *tp)
{
if (tg3_flag(tp, NVRAM)) {
if (tp->nvram_lock_cnt > 0)
tp->nvram_lock_cnt--;
if (tp->nvram_lock_cnt == 0)
tw32_f(NVRAM_SWARB, SWARB_REQ_CLR1);
}
}
/* tp->lock is held. */
static void tg3_enable_nvram_access(struct tg3 *tp)
{
if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) {
u32 nvaccess = tr32(NVRAM_ACCESS);
tw32(NVRAM_ACCESS, nvaccess | ACCESS_ENABLE);
}
}
/* tp->lock is held. */
static void tg3_disable_nvram_access(struct tg3 *tp)
{
if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) {
u32 nvaccess = tr32(NVRAM_ACCESS);
tw32(NVRAM_ACCESS, nvaccess & ~ACCESS_ENABLE);
}
}
static int tg3_nvram_read_using_eeprom(struct tg3 *tp,
u32 offset, u32 *val)
{
u32 tmp;
int i;
if (offset > EEPROM_ADDR_ADDR_MASK || (offset % 4) != 0)
return -EINVAL;
tmp = tr32(GRC_EEPROM_ADDR) & ~(EEPROM_ADDR_ADDR_MASK |
EEPROM_ADDR_DEVID_MASK |
EEPROM_ADDR_READ);
tw32(GRC_EEPROM_ADDR,
tmp |
(0 << EEPROM_ADDR_DEVID_SHIFT) |
((offset << EEPROM_ADDR_ADDR_SHIFT) &
EEPROM_ADDR_ADDR_MASK) |
EEPROM_ADDR_READ | EEPROM_ADDR_START);
for (i = 0; i < 1000; i++) {
tmp = tr32(GRC_EEPROM_ADDR);
if (tmp & EEPROM_ADDR_COMPLETE)
break;
msleep(1);
}
if (!(tmp & EEPROM_ADDR_COMPLETE))
return -EBUSY;
tmp = tr32(GRC_EEPROM_DATA);
/*
* The data will always be opposite the native endian
* format. Perform a blind byteswap to compensate.
*/
*val = swab32(tmp);
return 0;
}
#define NVRAM_CMD_TIMEOUT 100
static int tg3_nvram_exec_cmd(struct tg3 *tp, u32 nvram_cmd)
{
int i;
tw32(NVRAM_CMD, nvram_cmd);
for (i = 0; i < NVRAM_CMD_TIMEOUT; i++) {
udelay(10);
if (tr32(NVRAM_CMD) & NVRAM_CMD_DONE) {
udelay(10);
break;
}
}
if (i == NVRAM_CMD_TIMEOUT)
return -EBUSY;
return 0;
}
static u32 tg3_nvram_phys_addr(struct tg3 *tp, u32 addr)
{
if (tg3_flag(tp, NVRAM) &&
tg3_flag(tp, NVRAM_BUFFERED) &&
tg3_flag(tp, FLASH) &&
!tg3_flag(tp, NO_NVRAM_ADDR_TRANS) &&
(tp->nvram_jedecnum == JEDEC_ATMEL))
addr = ((addr / tp->nvram_pagesize) <<
ATMEL_AT45DB0X1B_PAGE_POS) +
(addr % tp->nvram_pagesize);
return addr;
}
static u32 tg3_nvram_logical_addr(struct tg3 *tp, u32 addr)
{
if (tg3_flag(tp, NVRAM) &&
tg3_flag(tp, NVRAM_BUFFERED) &&
tg3_flag(tp, FLASH) &&
!tg3_flag(tp, NO_NVRAM_ADDR_TRANS) &&
(tp->nvram_jedecnum == JEDEC_ATMEL))
addr = ((addr >> ATMEL_AT45DB0X1B_PAGE_POS) *
tp->nvram_pagesize) +
(addr & ((1 << ATMEL_AT45DB0X1B_PAGE_POS) - 1));
return addr;
}
/* NOTE: Data read in from NVRAM is byteswapped according to
* the byteswapping settings for all other register accesses.
* tg3 devices are BE devices, so on a BE machine, the data
* returned will be exactly as it is seen in NVRAM. On a LE
* machine, the 32-bit value will be byteswapped.
*/
static int tg3_nvram_read(struct tg3 *tp, u32 offset, u32 *val)
{
int ret;
if (!tg3_flag(tp, NVRAM))
return tg3_nvram_read_using_eeprom(tp, offset, val);
offset = tg3_nvram_phys_addr(tp, offset);
if (offset > NVRAM_ADDR_MSK)
return -EINVAL;
ret = tg3_nvram_lock(tp);
if (ret)
return ret;
tg3_enable_nvram_access(tp);
tw32(NVRAM_ADDR, offset);
ret = tg3_nvram_exec_cmd(tp, NVRAM_CMD_RD | NVRAM_CMD_GO |
NVRAM_CMD_FIRST | NVRAM_CMD_LAST | NVRAM_CMD_DONE);
if (ret == 0)
*val = tr32(NVRAM_RDDATA);
tg3_disable_nvram_access(tp);
tg3_nvram_unlock(tp);
return ret;
}
/* Ensures NVRAM data is in bytestream format. */
static int tg3_nvram_read_be32(struct tg3 *tp, u32 offset, __be32 *val)
{
u32 v;
int res = tg3_nvram_read(tp, offset, &v);
if (!res)
*val = cpu_to_be32(v);
return res;
}
static int tg3_nvram_write_block_using_eeprom(struct tg3 *tp,
u32 offset, u32 len, u8 *buf)
{
int i, j, rc = 0;
u32 val;
for (i = 0; i < len; i += 4) {
u32 addr;
__be32 data;
addr = offset + i;
memcpy(&data, buf + i, 4);
/*
* The SEEPROM interface expects the data to always be opposite
* the native endian format. We accomplish this by reversing
* all the operations that would have been performed on the
* data from a call to tg3_nvram_read_be32().
*/
tw32(GRC_EEPROM_DATA, swab32(be32_to_cpu(data)));
val = tr32(GRC_EEPROM_ADDR);
tw32(GRC_EEPROM_ADDR, val | EEPROM_ADDR_COMPLETE);
val &= ~(EEPROM_ADDR_ADDR_MASK | EEPROM_ADDR_DEVID_MASK |
EEPROM_ADDR_READ);
tw32(GRC_EEPROM_ADDR, val |
(0 << EEPROM_ADDR_DEVID_SHIFT) |
(addr & EEPROM_ADDR_ADDR_MASK) |
EEPROM_ADDR_START |
EEPROM_ADDR_WRITE);
for (j = 0; j < 1000; j++) {
val = tr32(GRC_EEPROM_ADDR);
if (val & EEPROM_ADDR_COMPLETE)
break;
msleep(1);
}
if (!(val & EEPROM_ADDR_COMPLETE)) {
rc = -EBUSY;
break;
}
}
return rc;
}
/* offset and length are dword aligned */
static int tg3_nvram_write_block_unbuffered(struct tg3 *tp, u32 offset, u32 len,
u8 *buf)
{
int ret = 0;
u32 pagesize = tp->nvram_pagesize;
u32 pagemask = pagesize - 1;
u32 nvram_cmd;
u8 *tmp;
tmp = kmalloc(pagesize, GFP_KERNEL);
if (tmp == NULL)
return -ENOMEM;
while (len) {
int j;
u32 phy_addr, page_off, size;
phy_addr = offset & ~pagemask;
for (j = 0; j < pagesize; j += 4) {
ret = tg3_nvram_read_be32(tp, phy_addr + j,
(__be32 *) (tmp + j));
if (ret)
break;
}
if (ret)
break;
page_off = offset & pagemask;
size = pagesize;
if (len < size)
size = len;
len -= size;
memcpy(tmp + page_off, buf, size);
offset = offset + (pagesize - page_off);
tg3_enable_nvram_access(tp);
/*
* Before we can erase the flash page, we need
* to issue a special "write enable" command.
*/
nvram_cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE;
if (tg3_nvram_exec_cmd(tp, nvram_cmd))
break;
/* Erase the target page */
tw32(NVRAM_ADDR, phy_addr);
nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR |
NVRAM_CMD_FIRST | NVRAM_CMD_LAST | NVRAM_CMD_ERASE;
if (tg3_nvram_exec_cmd(tp, nvram_cmd))
break;
/* Issue another write enable to start the write. */
nvram_cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE;
if (tg3_nvram_exec_cmd(tp, nvram_cmd))
break;
for (j = 0; j < pagesize; j += 4) {
__be32 data;
data = *((__be32 *) (tmp + j));
tw32(NVRAM_WRDATA, be32_to_cpu(data));
tw32(NVRAM_ADDR, phy_addr + j);
nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE |
NVRAM_CMD_WR;
if (j == 0)
nvram_cmd |= NVRAM_CMD_FIRST;
else if (j == (pagesize - 4))
nvram_cmd |= NVRAM_CMD_LAST;
ret = tg3_nvram_exec_cmd(tp, nvram_cmd);
if (ret)
break;
}
if (ret)
break;
}
nvram_cmd = NVRAM_CMD_WRDI | NVRAM_CMD_GO | NVRAM_CMD_DONE;
tg3_nvram_exec_cmd(tp, nvram_cmd);
kfree(tmp);
return ret;
}
/* offset and length are dword aligned */
static int tg3_nvram_write_block_buffered(struct tg3 *tp, u32 offset, u32 len,
u8 *buf)
{
int i, ret = 0;
for (i = 0; i < len; i += 4, offset += 4) {
u32 page_off, phy_addr, nvram_cmd;
__be32 data;
memcpy(&data, buf + i, 4);
tw32(NVRAM_WRDATA, be32_to_cpu(data));
page_off = offset % tp->nvram_pagesize;
phy_addr = tg3_nvram_phys_addr(tp, offset);
nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR;
if (page_off == 0 || i == 0)
nvram_cmd |= NVRAM_CMD_FIRST;
if (page_off == (tp->nvram_pagesize - 4))
nvram_cmd |= NVRAM_CMD_LAST;
if (i == (len - 4))
nvram_cmd |= NVRAM_CMD_LAST;
if ((nvram_cmd & NVRAM_CMD_FIRST) ||
!tg3_flag(tp, FLASH) ||
!tg3_flag(tp, 57765_PLUS))
tw32(NVRAM_ADDR, phy_addr);
if (tg3_asic_rev(tp) != ASIC_REV_5752 &&
!tg3_flag(tp, 5755_PLUS) &&
(tp->nvram_jedecnum == JEDEC_ST) &&
(nvram_cmd & NVRAM_CMD_FIRST)) {
u32 cmd;
cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE;
ret = tg3_nvram_exec_cmd(tp, cmd);
if (ret)
break;
}
if (!tg3_flag(tp, FLASH)) {
/* We always do complete word writes to eeprom. */
nvram_cmd |= (NVRAM_CMD_FIRST | NVRAM_CMD_LAST);
}
ret = tg3_nvram_exec_cmd(tp, nvram_cmd);
if (ret)
break;
}
return ret;
}
/* offset and length are dword aligned */
static int tg3_nvram_write_block(struct tg3 *tp, u32 offset, u32 len, u8 *buf)
{
int ret;
if (tg3_flag(tp, EEPROM_WRITE_PROT)) {
tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl &
~GRC_LCLCTRL_GPIO_OUTPUT1);
udelay(40);
}
if (!tg3_flag(tp, NVRAM)) {
ret = tg3_nvram_write_block_using_eeprom(tp, offset, len, buf);
} else {
u32 grc_mode;
ret = tg3_nvram_lock(tp);
if (ret)
return ret;
tg3_enable_nvram_access(tp);
if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM))
tw32(NVRAM_WRITE1, 0x406);
grc_mode = tr32(GRC_MODE);
tw32(GRC_MODE, grc_mode | GRC_MODE_NVRAM_WR_ENABLE);
if (tg3_flag(tp, NVRAM_BUFFERED) || !tg3_flag(tp, FLASH)) {
ret = tg3_nvram_write_block_buffered(tp, offset, len,
buf);
} else {
ret = tg3_nvram_write_block_unbuffered(tp, offset, len,
buf);
}
grc_mode = tr32(GRC_MODE);
tw32(GRC_MODE, grc_mode & ~GRC_MODE_NVRAM_WR_ENABLE);
tg3_disable_nvram_access(tp);
tg3_nvram_unlock(tp);
}
if (tg3_flag(tp, EEPROM_WRITE_PROT)) {
tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl);
udelay(40);
}
return ret;
}
#define RX_CPU_SCRATCH_BASE 0x30000
#define RX_CPU_SCRATCH_SIZE 0x04000
#define TX_CPU_SCRATCH_BASE 0x34000
#define TX_CPU_SCRATCH_SIZE 0x04000
/* tp->lock is held. */
static int tg3_pause_cpu(struct tg3 *tp, u32 cpu_base)
{
int i;
const int iters = 10000;
for (i = 0; i < iters; i++) {
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32(cpu_base + CPU_MODE, CPU_MODE_HALT);
if (tr32(cpu_base + CPU_MODE) & CPU_MODE_HALT)
break;
if (pci_channel_offline(tp->pdev))
return -EBUSY;
}
return (i == iters) ? -EBUSY : 0;
}
/* tp->lock is held. */
static int tg3_rxcpu_pause(struct tg3 *tp)
{
int rc = tg3_pause_cpu(tp, RX_CPU_BASE);
tw32(RX_CPU_BASE + CPU_STATE, 0xffffffff);
tw32_f(RX_CPU_BASE + CPU_MODE, CPU_MODE_HALT);
udelay(10);
return rc;
}
/* tp->lock is held. */
static int tg3_txcpu_pause(struct tg3 *tp)
{
return tg3_pause_cpu(tp, TX_CPU_BASE);
}
/* tp->lock is held. */
static void tg3_resume_cpu(struct tg3 *tp, u32 cpu_base)
{
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32_f(cpu_base + CPU_MODE, 0x00000000);
}
/* tp->lock is held. */
static void tg3_rxcpu_resume(struct tg3 *tp)
{
tg3_resume_cpu(tp, RX_CPU_BASE);
}
/* tp->lock is held. */
static int tg3_halt_cpu(struct tg3 *tp, u32 cpu_base)
{
int rc;
BUG_ON(cpu_base == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS));
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
u32 val = tr32(GRC_VCPU_EXT_CTRL);
tw32(GRC_VCPU_EXT_CTRL, val | GRC_VCPU_EXT_CTRL_HALT_CPU);
return 0;
}
if (cpu_base == RX_CPU_BASE) {
rc = tg3_rxcpu_pause(tp);
} else {
/*
* There is only an Rx CPU for the 5750 derivative in the
* BCM4785.
*/
if (tg3_flag(tp, IS_SSB_CORE))
return 0;
rc = tg3_txcpu_pause(tp);
}
if (rc) {
netdev_err(tp->dev, "%s timed out, %s CPU\n",
__func__, cpu_base == RX_CPU_BASE ? "RX" : "TX");
return -ENODEV;
}
/* Clear firmware's nvram arbitration. */
if (tg3_flag(tp, NVRAM))
tw32(NVRAM_SWARB, SWARB_REQ_CLR0);
return 0;
}
static int tg3_fw_data_len(struct tg3 *tp,
const struct tg3_firmware_hdr *fw_hdr)
{
int fw_len;
/* Non fragmented firmware have one firmware header followed by a
* contiguous chunk of data to be written. The length field in that
* header is not the length of data to be written but the complete
* length of the bss. The data length is determined based on
* tp->fw->size minus headers.
*
* Fragmented firmware have a main header followed by multiple
* fragments. Each fragment is identical to non fragmented firmware
* with a firmware header followed by a contiguous chunk of data. In
* the main header, the length field is unused and set to 0xffffffff.
* In each fragment header the length is the entire size of that
* fragment i.e. fragment data + header length. Data length is
* therefore length field in the header minus TG3_FW_HDR_LEN.
*/
if (tp->fw_len == 0xffffffff)
fw_len = be32_to_cpu(fw_hdr->len);
else
fw_len = tp->fw->size;
return (fw_len - TG3_FW_HDR_LEN) / sizeof(u32);
}
/* tp->lock is held. */
static int tg3_load_firmware_cpu(struct tg3 *tp, u32 cpu_base,
u32 cpu_scratch_base, int cpu_scratch_size,
const struct tg3_firmware_hdr *fw_hdr)
{
int err, i;
void (*write_op)(struct tg3 *, u32, u32);
int total_len = tp->fw->size;
if (cpu_base == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS)) {
netdev_err(tp->dev,
"%s: Trying to load TX cpu firmware which is 5705\n",
__func__);
return -EINVAL;
}
if (tg3_flag(tp, 5705_PLUS) && tg3_asic_rev(tp) != ASIC_REV_57766)
write_op = tg3_write_mem;
else
write_op = tg3_write_indirect_reg32;
if (tg3_asic_rev(tp) != ASIC_REV_57766) {
/* It is possible that bootcode is still loading at this point.
* Get the nvram lock first before halting the cpu.
*/
int lock_err = tg3_nvram_lock(tp);
err = tg3_halt_cpu(tp, cpu_base);
if (!lock_err)
tg3_nvram_unlock(tp);
if (err)
goto out;
for (i = 0; i < cpu_scratch_size; i += sizeof(u32))
write_op(tp, cpu_scratch_base + i, 0);
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32(cpu_base + CPU_MODE,
tr32(cpu_base + CPU_MODE) | CPU_MODE_HALT);
} else {
/* Subtract additional main header for fragmented firmware and
* advance to the first fragment
*/
total_len -= TG3_FW_HDR_LEN;
fw_hdr++;
}
do {
u32 *fw_data = (u32 *)(fw_hdr + 1);
for (i = 0; i < tg3_fw_data_len(tp, fw_hdr); i++)
write_op(tp, cpu_scratch_base +
(be32_to_cpu(fw_hdr->base_addr) & 0xffff) +
(i * sizeof(u32)),
be32_to_cpu(fw_data[i]));
total_len -= be32_to_cpu(fw_hdr->len);
/* Advance to next fragment */
fw_hdr = (struct tg3_firmware_hdr *)
((void *)fw_hdr + be32_to_cpu(fw_hdr->len));
} while (total_len > 0);
err = 0;
out:
return err;
}
/* tp->lock is held. */
static int tg3_pause_cpu_and_set_pc(struct tg3 *tp, u32 cpu_base, u32 pc)
{
int i;
const int iters = 5;
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32_f(cpu_base + CPU_PC, pc);
for (i = 0; i < iters; i++) {
if (tr32(cpu_base + CPU_PC) == pc)
break;
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32(cpu_base + CPU_MODE, CPU_MODE_HALT);
tw32_f(cpu_base + CPU_PC, pc);
udelay(1000);
}
return (i == iters) ? -EBUSY : 0;
}
/* tp->lock is held. */
static int tg3_load_5701_a0_firmware_fix(struct tg3 *tp)
{
const struct tg3_firmware_hdr *fw_hdr;
int err;
fw_hdr = (struct tg3_firmware_hdr *)tp->fw->data;
/* Firmware blob starts with version numbers, followed by
start address and length. We are setting complete length.
length = end_address_of_bss - start_address_of_text.
Remainder is the blob to be loaded contiguously
from start address. */
err = tg3_load_firmware_cpu(tp, RX_CPU_BASE,
RX_CPU_SCRATCH_BASE, RX_CPU_SCRATCH_SIZE,
fw_hdr);
if (err)
return err;
err = tg3_load_firmware_cpu(tp, TX_CPU_BASE,
TX_CPU_SCRATCH_BASE, TX_CPU_SCRATCH_SIZE,
fw_hdr);
if (err)
return err;
/* Now startup only the RX cpu. */
err = tg3_pause_cpu_and_set_pc(tp, RX_CPU_BASE,
be32_to_cpu(fw_hdr->base_addr));
if (err) {
netdev_err(tp->dev, "%s fails to set RX CPU PC, is %08x "
"should be %08x\n", __func__,
tr32(RX_CPU_BASE + CPU_PC),
be32_to_cpu(fw_hdr->base_addr));
return -ENODEV;
}
tg3_rxcpu_resume(tp);
return 0;
}
static int tg3_validate_rxcpu_state(struct tg3 *tp)
{
const int iters = 1000;
int i;
u32 val;
/* Wait for boot code to complete initialization and enter service
* loop. It is then safe to download service patches
*/
for (i = 0; i < iters; i++) {
if (tr32(RX_CPU_HWBKPT) == TG3_SBROM_IN_SERVICE_LOOP)
break;
udelay(10);
}
if (i == iters) {
netdev_err(tp->dev, "Boot code not ready for service patches\n");
return -EBUSY;
}
val = tg3_read_indirect_reg32(tp, TG3_57766_FW_HANDSHAKE);
if (val & 0xff) {
netdev_warn(tp->dev,
"Other patches exist. Not downloading EEE patch\n");
return -EEXIST;
}
return 0;
}
/* tp->lock is held. */
static void tg3_load_57766_firmware(struct tg3 *tp)
{
struct tg3_firmware_hdr *fw_hdr;
if (!tg3_flag(tp, NO_NVRAM))
return;
if (tg3_validate_rxcpu_state(tp))
return;
if (!tp->fw)
return;
/* This firmware blob has a different format than older firmware
* releases as given below. The main difference is we have fragmented
* data to be written to non-contiguous locations.
*
* In the beginning we have a firmware header identical to other
* firmware which consists of version, base addr and length. The length
* here is unused and set to 0xffffffff.
*
* This is followed by a series of firmware fragments which are
* individually identical to previous firmware. i.e. they have the
* firmware header and followed by data for that fragment. The version
* field of the individual fragment header is unused.
*/
fw_hdr = (struct tg3_firmware_hdr *)tp->fw->data;
if (be32_to_cpu(fw_hdr->base_addr) != TG3_57766_FW_BASE_ADDR)
return;
if (tg3_rxcpu_pause(tp))
return;
/* tg3_load_firmware_cpu() will always succeed for the 57766 */
tg3_load_firmware_cpu(tp, 0, TG3_57766_FW_BASE_ADDR, 0, fw_hdr);
tg3_rxcpu_resume(tp);
}
/* tp->lock is held. */
static int tg3_load_tso_firmware(struct tg3 *tp)
{
const struct tg3_firmware_hdr *fw_hdr;
unsigned long cpu_base, cpu_scratch_base, cpu_scratch_size;
int err;
if (!tg3_flag(tp, FW_TSO))
return 0;
fw_hdr = (struct tg3_firmware_hdr *)tp->fw->data;
/* Firmware blob starts with version numbers, followed by
start address and length. We are setting complete length.
length = end_address_of_bss - start_address_of_text.
Remainder is the blob to be loaded contiguously
from start address. */
cpu_scratch_size = tp->fw_len;
if (tg3_asic_rev(tp) == ASIC_REV_5705) {
cpu_base = RX_CPU_BASE;
cpu_scratch_base = NIC_SRAM_MBUF_POOL_BASE5705;
} else {
cpu_base = TX_CPU_BASE;
cpu_scratch_base = TX_CPU_SCRATCH_BASE;
cpu_scratch_size = TX_CPU_SCRATCH_SIZE;
}
err = tg3_load_firmware_cpu(tp, cpu_base,
cpu_scratch_base, cpu_scratch_size,
fw_hdr);
if (err)
return err;
/* Now startup the cpu. */
err = tg3_pause_cpu_and_set_pc(tp, cpu_base,
be32_to_cpu(fw_hdr->base_addr));
if (err) {
netdev_err(tp->dev,
"%s fails to set CPU PC, is %08x should be %08x\n",
__func__, tr32(cpu_base + CPU_PC),
be32_to_cpu(fw_hdr->base_addr));
return -ENODEV;
}
tg3_resume_cpu(tp, cpu_base);
return 0;
}
/* tp->lock is held. */
static void __tg3_set_one_mac_addr(struct tg3 *tp, u8 *mac_addr, int index)
{
u32 addr_high, addr_low;
addr_high = ((mac_addr[0] << 8) | mac_addr[1]);
addr_low = ((mac_addr[2] << 24) | (mac_addr[3] << 16) |
(mac_addr[4] << 8) | mac_addr[5]);
if (index < 4) {
tw32(MAC_ADDR_0_HIGH + (index * 8), addr_high);
tw32(MAC_ADDR_0_LOW + (index * 8), addr_low);
} else {
index -= 4;
tw32(MAC_EXTADDR_0_HIGH + (index * 8), addr_high);
tw32(MAC_EXTADDR_0_LOW + (index * 8), addr_low);
}
}
/* tp->lock is held. */
static void __tg3_set_mac_addr(struct tg3 *tp, bool skip_mac_1)
{
u32 addr_high;
int i;
for (i = 0; i < 4; i++) {
if (i == 1 && skip_mac_1)
continue;
__tg3_set_one_mac_addr(tp, tp->dev->dev_addr, i);
}
if (tg3_asic_rev(tp) == ASIC_REV_5703 ||
tg3_asic_rev(tp) == ASIC_REV_5704) {
for (i = 4; i < 16; i++)
__tg3_set_one_mac_addr(tp, tp->dev->dev_addr, i);
}
addr_high = (tp->dev->dev_addr[0] +
tp->dev->dev_addr[1] +
tp->dev->dev_addr[2] +
tp->dev->dev_addr[3] +
tp->dev->dev_addr[4] +
tp->dev->dev_addr[5]) &
TX_BACKOFF_SEED_MASK;
tw32(MAC_TX_BACKOFF_SEED, addr_high);
}
static void tg3_enable_register_access(struct tg3 *tp)
{
/*
* Make sure register accesses (indirect or otherwise) will function
* correctly.
*/
pci_write_config_dword(tp->pdev,
TG3PCI_MISC_HOST_CTRL, tp->misc_host_ctrl);
}
static int tg3_power_up(struct tg3 *tp)
{
int err;
tg3_enable_register_access(tp);
err = pci_set_power_state(tp->pdev, PCI_D0);
if (!err) {
/* Switch out of Vaux if it is a NIC */
tg3_pwrsrc_switch_to_vmain(tp);
} else {
netdev_err(tp->dev, "Transition to D0 failed\n");
}
return err;
}
static int tg3_setup_phy(struct tg3 *, bool);
static int tg3_power_down_prepare(struct tg3 *tp)
{
u32 misc_host_ctrl;
bool device_should_wake, do_low_power;
tg3_enable_register_access(tp);
/* Restore the CLKREQ setting. */
if (tg3_flag(tp, CLKREQ_BUG))
pcie_capability_set_word(tp->pdev, PCI_EXP_LNKCTL,
PCI_EXP_LNKCTL_CLKREQ_EN);
misc_host_ctrl = tr32(TG3PCI_MISC_HOST_CTRL);
tw32(TG3PCI_MISC_HOST_CTRL,
misc_host_ctrl | MISC_HOST_CTRL_MASK_PCI_INT);
device_should_wake = device_may_wakeup(&tp->pdev->dev) &&
tg3_flag(tp, WOL_ENABLE);
if (tg3_flag(tp, USE_PHYLIB)) {
do_low_power = false;
if ((tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) &&
!(tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) {
struct phy_device *phydev;
u32 phyid, advertising;
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
tp->phy_flags |= TG3_PHYFLG_IS_LOW_POWER;
tp->link_config.speed = phydev->speed;
tp->link_config.duplex = phydev->duplex;
tp->link_config.autoneg = phydev->autoneg;
tp->link_config.advertising = phydev->advertising;
advertising = ADVERTISED_TP |
ADVERTISED_Pause |
ADVERTISED_Autoneg |
ADVERTISED_10baseT_Half;
if (tg3_flag(tp, ENABLE_ASF) || device_should_wake) {
if (tg3_flag(tp, WOL_SPEED_100MB))
advertising |=
ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Full;
else
advertising |= ADVERTISED_10baseT_Full;
}
phydev->advertising = advertising;
phy_start_aneg(phydev);
phyid = phydev->drv->phy_id & phydev->drv->phy_id_mask;
if (phyid != PHY_ID_BCMAC131) {
phyid &= PHY_BCM_OUI_MASK;
if (phyid == PHY_BCM_OUI_1 ||
phyid == PHY_BCM_OUI_2 ||
phyid == PHY_BCM_OUI_3)
do_low_power = true;
}
}
} else {
do_low_power = true;
if (!(tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER))
tp->phy_flags |= TG3_PHYFLG_IS_LOW_POWER;
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
tg3_setup_phy(tp, false);
}
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
u32 val;
val = tr32(GRC_VCPU_EXT_CTRL);
tw32(GRC_VCPU_EXT_CTRL, val | GRC_VCPU_EXT_CTRL_DISABLE_WOL);
} else if (!tg3_flag(tp, ENABLE_ASF)) {
int i;
u32 val;
for (i = 0; i < 200; i++) {
tg3_read_mem(tp, NIC_SRAM_FW_ASF_STATUS_MBOX, &val);
if (val == ~NIC_SRAM_FIRMWARE_MBOX_MAGIC1)
break;
msleep(1);
}
}
if (tg3_flag(tp, WOL_CAP))
tg3_write_mem(tp, NIC_SRAM_WOL_MBOX, WOL_SIGNATURE |
WOL_DRV_STATE_SHUTDOWN |
WOL_DRV_WOL |
WOL_SET_MAGIC_PKT);
if (device_should_wake) {
u32 mac_mode;
if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) {
if (do_low_power &&
!(tp->phy_flags & TG3_PHYFLG_IS_FET)) {
tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_PWRCTL,
MII_TG3_AUXCTL_PCTL_WOL_EN |
MII_TG3_AUXCTL_PCTL_100TX_LPWR |
MII_TG3_AUXCTL_PCTL_CL_AB_TXDAC);
udelay(40);
}
if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
mac_mode = MAC_MODE_PORT_MODE_GMII;
else if (tp->phy_flags &
TG3_PHYFLG_KEEP_LINK_ON_PWRDN) {
if (tp->link_config.active_speed == SPEED_1000)
mac_mode = MAC_MODE_PORT_MODE_GMII;
else
mac_mode = MAC_MODE_PORT_MODE_MII;
} else
mac_mode = MAC_MODE_PORT_MODE_MII;
mac_mode |= tp->mac_mode & MAC_MODE_LINK_POLARITY;
if (tg3_asic_rev(tp) == ASIC_REV_5700) {
u32 speed = tg3_flag(tp, WOL_SPEED_100MB) ?
SPEED_100 : SPEED_10;
if (tg3_5700_link_polarity(tp, speed))
mac_mode |= MAC_MODE_LINK_POLARITY;
else
mac_mode &= ~MAC_MODE_LINK_POLARITY;
}
} else {
mac_mode = MAC_MODE_PORT_MODE_TBI;
}
if (!tg3_flag(tp, 5750_PLUS))
tw32(MAC_LED_CTRL, tp->led_ctrl);
mac_mode |= MAC_MODE_MAGIC_PKT_ENABLE;
if ((tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, 5780_CLASS)) &&
(tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE)))
mac_mode |= MAC_MODE_KEEP_FRAME_IN_WOL;
if (tg3_flag(tp, ENABLE_APE))
mac_mode |= MAC_MODE_APE_TX_EN |
MAC_MODE_APE_RX_EN |
MAC_MODE_TDE_ENABLE;
tw32_f(MAC_MODE, mac_mode);
udelay(100);
tw32_f(MAC_RX_MODE, RX_MODE_ENABLE);
udelay(10);
}
if (!tg3_flag(tp, WOL_SPEED_100MB) &&
(tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701)) {
u32 base_val;
base_val = tp->pci_clock_ctrl;
base_val |= (CLOCK_CTRL_RXCLK_DISABLE |
CLOCK_CTRL_TXCLK_DISABLE);
tw32_wait_f(TG3PCI_CLOCK_CTRL, base_val | CLOCK_CTRL_ALTCLK |
CLOCK_CTRL_PWRDOWN_PLL133, 40);
} else if (tg3_flag(tp, 5780_CLASS) ||
tg3_flag(tp, CPMU_PRESENT) ||
tg3_asic_rev(tp) == ASIC_REV_5906) {
/* do nothing */
} else if (!(tg3_flag(tp, 5750_PLUS) && tg3_flag(tp, ENABLE_ASF))) {
u32 newbits1, newbits2;
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701) {
newbits1 = (CLOCK_CTRL_RXCLK_DISABLE |
CLOCK_CTRL_TXCLK_DISABLE |
CLOCK_CTRL_ALTCLK);
newbits2 = newbits1 | CLOCK_CTRL_44MHZ_CORE;
} else if (tg3_flag(tp, 5705_PLUS)) {
newbits1 = CLOCK_CTRL_625_CORE;
newbits2 = newbits1 | CLOCK_CTRL_ALTCLK;
} else {
newbits1 = CLOCK_CTRL_ALTCLK;
newbits2 = newbits1 | CLOCK_CTRL_44MHZ_CORE;
}
tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits1,
40);
tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits2,
40);
if (!tg3_flag(tp, 5705_PLUS)) {
u32 newbits3;
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701) {
newbits3 = (CLOCK_CTRL_RXCLK_DISABLE |
CLOCK_CTRL_TXCLK_DISABLE |
CLOCK_CTRL_44MHZ_CORE);
} else {
newbits3 = CLOCK_CTRL_44MHZ_CORE;
}
tw32_wait_f(TG3PCI_CLOCK_CTRL,
tp->pci_clock_ctrl | newbits3, 40);
}
}
if (!(device_should_wake) && !tg3_flag(tp, ENABLE_ASF))
tg3_power_down_phy(tp, do_low_power);
tg3_frob_aux_power(tp, true);
/* Workaround for unstable PLL clock */
if ((!tg3_flag(tp, IS_SSB_CORE)) &&
((tg3_chip_rev(tp) == CHIPREV_5750_AX) ||
(tg3_chip_rev(tp) == CHIPREV_5750_BX))) {
u32 val = tr32(0x7d00);
val &= ~((1 << 16) | (1 << 4) | (1 << 2) | (1 << 1) | 1);
tw32(0x7d00, val);
if (!tg3_flag(tp, ENABLE_ASF)) {
int err;
err = tg3_nvram_lock(tp);
tg3_halt_cpu(tp, RX_CPU_BASE);
if (!err)
tg3_nvram_unlock(tp);
}
}
tg3_write_sig_post_reset(tp, RESET_KIND_SHUTDOWN);
tg3_ape_driver_state_change(tp, RESET_KIND_SHUTDOWN);
return 0;
}
static void tg3_power_down(struct tg3 *tp)
{
pci_wake_from_d3(tp->pdev, tg3_flag(tp, WOL_ENABLE));
pci_set_power_state(tp->pdev, PCI_D3hot);
}
static void tg3_aux_stat_to_speed_duplex(struct tg3 *tp, u32 val, u16 *speed, u8 *duplex)
{
switch (val & MII_TG3_AUX_STAT_SPDMASK) {
case MII_TG3_AUX_STAT_10HALF:
*speed = SPEED_10;
*duplex = DUPLEX_HALF;
break;
case MII_TG3_AUX_STAT_10FULL:
*speed = SPEED_10;
*duplex = DUPLEX_FULL;
break;
case MII_TG3_AUX_STAT_100HALF:
*speed = SPEED_100;
*duplex = DUPLEX_HALF;
break;
case MII_TG3_AUX_STAT_100FULL:
*speed = SPEED_100;
*duplex = DUPLEX_FULL;
break;
case MII_TG3_AUX_STAT_1000HALF:
*speed = SPEED_1000;
*duplex = DUPLEX_HALF;
break;
case MII_TG3_AUX_STAT_1000FULL:
*speed = SPEED_1000;
*duplex = DUPLEX_FULL;
break;
default:
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
*speed = (val & MII_TG3_AUX_STAT_100) ? SPEED_100 :
SPEED_10;
*duplex = (val & MII_TG3_AUX_STAT_FULL) ? DUPLEX_FULL :
DUPLEX_HALF;
break;
}
*speed = SPEED_UNKNOWN;
*duplex = DUPLEX_UNKNOWN;
break;
}
}
static int tg3_phy_autoneg_cfg(struct tg3 *tp, u32 advertise, u32 flowctrl)
{
int err = 0;
u32 val, new_adv;
new_adv = ADVERTISE_CSMA;
new_adv |= ethtool_adv_to_mii_adv_t(advertise) & ADVERTISE_ALL;
new_adv |= mii_advertise_flowctrl(flowctrl);
err = tg3_writephy(tp, MII_ADVERTISE, new_adv);
if (err)
goto done;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
new_adv = ethtool_adv_to_mii_ctrl1000_t(advertise);
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0)
new_adv |= CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER;
err = tg3_writephy(tp, MII_CTRL1000, new_adv);
if (err)
goto done;
}
if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP))
goto done;
tw32(TG3_CPMU_EEE_MODE,
tr32(TG3_CPMU_EEE_MODE) & ~TG3_CPMU_EEEMD_LPI_ENABLE);
err = tg3_phy_toggle_auxctl_smdsp(tp, true);
if (!err) {
u32 err2;
val = 0;
/* Advertise 100-BaseTX EEE ability */
if (advertise & ADVERTISED_100baseT_Full)
val |= MDIO_AN_EEE_ADV_100TX;
/* Advertise 1000-BaseT EEE ability */
if (advertise & ADVERTISED_1000baseT_Full)
val |= MDIO_AN_EEE_ADV_1000T;
if (!tp->eee.eee_enabled) {
val = 0;
tp->eee.advertised = 0;
} else {
tp->eee.advertised = advertise &
(ADVERTISED_100baseT_Full |
ADVERTISED_1000baseT_Full);
}
err = tg3_phy_cl45_write(tp, MDIO_MMD_AN, MDIO_AN_EEE_ADV, val);
if (err)
val = 0;
switch (tg3_asic_rev(tp)) {
case ASIC_REV_5717:
case ASIC_REV_57765:
case ASIC_REV_57766:
case ASIC_REV_5719:
/* If we advertised any eee advertisements above... */
if (val)
val = MII_TG3_DSP_TAP26_ALNOKO |
MII_TG3_DSP_TAP26_RMRXSTO |
MII_TG3_DSP_TAP26_OPCSINPT;
tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, val);
/* Fall through */
case ASIC_REV_5720:
case ASIC_REV_5762:
if (!tg3_phydsp_read(tp, MII_TG3_DSP_CH34TP2, &val))
tg3_phydsp_write(tp, MII_TG3_DSP_CH34TP2, val |
MII_TG3_DSP_CH34TP2_HIBW01);
}
err2 = tg3_phy_toggle_auxctl_smdsp(tp, false);
if (!err)
err = err2;
}
done:
return err;
}
static void tg3_phy_copper_begin(struct tg3 *tp)
{
if (tp->link_config.autoneg == AUTONEG_ENABLE ||
(tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) {
u32 adv, fc;
if ((tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) &&
!(tp->phy_flags & TG3_PHYFLG_KEEP_LINK_ON_PWRDN)) {
adv = ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full;
if (tg3_flag(tp, WOL_SPEED_100MB))
adv |= ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full;
if (tp->phy_flags & TG3_PHYFLG_1G_ON_VAUX_OK) {
if (!(tp->phy_flags &
TG3_PHYFLG_DISABLE_1G_HD_ADV))
adv |= ADVERTISED_1000baseT_Half;
adv |= ADVERTISED_1000baseT_Full;
}
fc = FLOW_CTRL_TX | FLOW_CTRL_RX;
} else {
adv = tp->link_config.advertising;
if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY)
adv &= ~(ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full);
fc = tp->link_config.flowctrl;
}
tg3_phy_autoneg_cfg(tp, adv, fc);
if ((tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) &&
(tp->phy_flags & TG3_PHYFLG_KEEP_LINK_ON_PWRDN)) {
/* Normally during power down we want to autonegotiate
* the lowest possible speed for WOL. However, to avoid
* link flap, we leave it untouched.
*/
return;
}
tg3_writephy(tp, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART);
} else {
int i;
u32 bmcr, orig_bmcr;
tp->link_config.active_speed = tp->link_config.speed;
tp->link_config.active_duplex = tp->link_config.duplex;
if (tg3_asic_rev(tp) == ASIC_REV_5714) {
/* With autoneg disabled, 5715 only links up when the
* advertisement register has the configured speed
* enabled.
*/
tg3_writephy(tp, MII_ADVERTISE, ADVERTISE_ALL);
}
bmcr = 0;
switch (tp->link_config.speed) {
default:
case SPEED_10:
break;
case SPEED_100:
bmcr |= BMCR_SPEED100;
break;
case SPEED_1000:
bmcr |= BMCR_SPEED1000;
break;
}
if (tp->link_config.duplex == DUPLEX_FULL)
bmcr |= BMCR_FULLDPLX;
if (!tg3_readphy(tp, MII_BMCR, &orig_bmcr) &&
(bmcr != orig_bmcr)) {
tg3_writephy(tp, MII_BMCR, BMCR_LOOPBACK);
for (i = 0; i < 1500; i++) {
u32 tmp;
udelay(10);
if (tg3_readphy(tp, MII_BMSR, &tmp) ||
tg3_readphy(tp, MII_BMSR, &tmp))
continue;
if (!(tmp & BMSR_LSTATUS)) {
udelay(40);
break;
}
}
tg3_writephy(tp, MII_BMCR, bmcr);
udelay(40);
}
}
}
static int tg3_phy_pull_config(struct tg3 *tp)
{
int err;
u32 val;
err = tg3_readphy(tp, MII_BMCR, &val);
if (err)
goto done;
if (!(val & BMCR_ANENABLE)) {
tp->link_config.autoneg = AUTONEG_DISABLE;
tp->link_config.advertising = 0;
tg3_flag_clear(tp, PAUSE_AUTONEG);
err = -EIO;
switch (val & (BMCR_SPEED1000 | BMCR_SPEED100)) {
case 0:
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)
goto done;
tp->link_config.speed = SPEED_10;
break;
case BMCR_SPEED100:
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)
goto done;
tp->link_config.speed = SPEED_100;
break;
case BMCR_SPEED1000:
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
tp->link_config.speed = SPEED_1000;
break;
}
/* Fall through */
default:
goto done;
}
if (val & BMCR_FULLDPLX)
tp->link_config.duplex = DUPLEX_FULL;
else
tp->link_config.duplex = DUPLEX_HALF;
tp->link_config.flowctrl = FLOW_CTRL_RX | FLOW_CTRL_TX;
err = 0;
goto done;
}
tp->link_config.autoneg = AUTONEG_ENABLE;
tp->link_config.advertising = ADVERTISED_Autoneg;
tg3_flag_set(tp, PAUSE_AUTONEG);
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) {
u32 adv;
err = tg3_readphy(tp, MII_ADVERTISE, &val);
if (err)
goto done;
adv = mii_adv_to_ethtool_adv_t(val & ADVERTISE_ALL);
tp->link_config.advertising |= adv | ADVERTISED_TP;
tp->link_config.flowctrl = tg3_decode_flowctrl_1000T(val);
} else {
tp->link_config.advertising |= ADVERTISED_FIBRE;
}
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
u32 adv;
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) {
err = tg3_readphy(tp, MII_CTRL1000, &val);
if (err)
goto done;
adv = mii_ctrl1000_to_ethtool_adv_t(val);
} else {
err = tg3_readphy(tp, MII_ADVERTISE, &val);
if (err)
goto done;
adv = tg3_decode_flowctrl_1000X(val);
tp->link_config.flowctrl = adv;
val &= (ADVERTISE_1000XHALF | ADVERTISE_1000XFULL);
adv = mii_adv_to_ethtool_adv_x(val);
}
tp->link_config.advertising |= adv;
}
done:
return err;
}
static int tg3_init_5401phy_dsp(struct tg3 *tp)
{
int err;
/* Turn off tap power management. */
/* Set Extended packet length bit */
err = tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, 0x4c20);
err |= tg3_phydsp_write(tp, 0x0012, 0x1804);
err |= tg3_phydsp_write(tp, 0x0013, 0x1204);
err |= tg3_phydsp_write(tp, 0x8006, 0x0132);
err |= tg3_phydsp_write(tp, 0x8006, 0x0232);
err |= tg3_phydsp_write(tp, 0x201f, 0x0a20);
udelay(40);
return err;
}
static bool tg3_phy_eee_config_ok(struct tg3 *tp)
{
struct ethtool_eee eee;
if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP))
return true;
tg3_eee_pull_config(tp, &eee);
if (tp->eee.eee_enabled) {
if (tp->eee.advertised != eee.advertised ||
tp->eee.tx_lpi_timer != eee.tx_lpi_timer ||
tp->eee.tx_lpi_enabled != eee.tx_lpi_enabled)
return false;
} else {
/* EEE is disabled but we're advertising */
if (eee.advertised)
return false;
}
return true;
}
static bool tg3_phy_copper_an_config_ok(struct tg3 *tp, u32 *lcladv)
{
u32 advmsk, tgtadv, advertising;
advertising = tp->link_config.advertising;
tgtadv = ethtool_adv_to_mii_adv_t(advertising) & ADVERTISE_ALL;
advmsk = ADVERTISE_ALL;
if (tp->link_config.active_duplex == DUPLEX_FULL) {
tgtadv |= mii_advertise_flowctrl(tp->link_config.flowctrl);
advmsk |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM;
}
if (tg3_readphy(tp, MII_ADVERTISE, lcladv))
return false;
if ((*lcladv & advmsk) != tgtadv)
return false;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
u32 tg3_ctrl;
tgtadv = ethtool_adv_to_mii_ctrl1000_t(advertising);
if (tg3_readphy(tp, MII_CTRL1000, &tg3_ctrl))
return false;
if (tgtadv &&
(tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0)) {
tgtadv |= CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER;
tg3_ctrl &= (ADVERTISE_1000HALF | ADVERTISE_1000FULL |
CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER);
} else {
tg3_ctrl &= (ADVERTISE_1000HALF | ADVERTISE_1000FULL);
}
if (tg3_ctrl != tgtadv)
return false;
}
return true;
}
static bool tg3_phy_copper_fetch_rmtadv(struct tg3 *tp, u32 *rmtadv)
{
u32 lpeth = 0;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
u32 val;
if (tg3_readphy(tp, MII_STAT1000, &val))
return false;
lpeth = mii_stat1000_to_ethtool_lpa_t(val);
}
if (tg3_readphy(tp, MII_LPA, rmtadv))
return false;
lpeth |= mii_lpa_to_ethtool_lpa_t(*rmtadv);
tp->link_config.rmt_adv = lpeth;
return true;
}
static bool tg3_test_and_report_link_chg(struct tg3 *tp, bool curr_link_up)
{
if (curr_link_up != tp->link_up) {
if (curr_link_up) {
netif_carrier_on(tp->dev);
} else {
netif_carrier_off(tp->dev);
if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
}
tg3_link_report(tp);
return true;
}
return false;
}
static void tg3_clear_mac_status(struct tg3 *tp)
{
tw32(MAC_EVENT, 0);
tw32_f(MAC_STATUS,
MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_MI_COMPLETION |
MAC_STATUS_LNKSTATE_CHANGED);
udelay(40);
}
static void tg3_setup_eee(struct tg3 *tp)
{
u32 val;
val = TG3_CPMU_EEE_LNKIDL_PCIE_NL0 |
TG3_CPMU_EEE_LNKIDL_UART_IDL;
if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0)
val |= TG3_CPMU_EEE_LNKIDL_APE_TX_MT;
tw32_f(TG3_CPMU_EEE_LNKIDL_CTRL, val);
tw32_f(TG3_CPMU_EEE_CTRL,
TG3_CPMU_EEE_CTRL_EXIT_20_1_US);
val = TG3_CPMU_EEEMD_ERLY_L1_XIT_DET |
(tp->eee.tx_lpi_enabled ? TG3_CPMU_EEEMD_LPI_IN_TX : 0) |
TG3_CPMU_EEEMD_LPI_IN_RX |
TG3_CPMU_EEEMD_EEE_ENABLE;
if (tg3_asic_rev(tp) != ASIC_REV_5717)
val |= TG3_CPMU_EEEMD_SND_IDX_DET_EN;
if (tg3_flag(tp, ENABLE_APE))
val |= TG3_CPMU_EEEMD_APE_TX_DET_EN;
tw32_f(TG3_CPMU_EEE_MODE, tp->eee.eee_enabled ? val : 0);
tw32_f(TG3_CPMU_EEE_DBTMR1,
TG3_CPMU_DBTMR1_PCIEXIT_2047US |
(tp->eee.tx_lpi_timer & 0xffff));
tw32_f(TG3_CPMU_EEE_DBTMR2,
TG3_CPMU_DBTMR2_APE_TX_2047US |
TG3_CPMU_DBTMR2_TXIDXEQ_2047US);
}
static int tg3_setup_copper_phy(struct tg3 *tp, bool force_reset)
{
bool current_link_up;
u32 bmsr, val;
u32 lcl_adv, rmt_adv;
u16 current_speed;
u8 current_duplex;
int i, err;
tg3_clear_mac_status(tp);
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE,
(tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL));
udelay(80);
}
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_PWRCTL, 0);
/* Some third-party PHYs need to be reset on link going
* down.
*/
if ((tg3_asic_rev(tp) == ASIC_REV_5703 ||
tg3_asic_rev(tp) == ASIC_REV_5704 ||
tg3_asic_rev(tp) == ASIC_REV_5705) &&
tp->link_up) {
tg3_readphy(tp, MII_BMSR, &bmsr);
if (!tg3_readphy(tp, MII_BMSR, &bmsr) &&
!(bmsr & BMSR_LSTATUS))
force_reset = true;
}
if (force_reset)
tg3_phy_reset(tp);
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) {
tg3_readphy(tp, MII_BMSR, &bmsr);
if (tg3_readphy(tp, MII_BMSR, &bmsr) ||
!tg3_flag(tp, INIT_COMPLETE))
bmsr = 0;
if (!(bmsr & BMSR_LSTATUS)) {
err = tg3_init_5401phy_dsp(tp);
if (err)
return err;
tg3_readphy(tp, MII_BMSR, &bmsr);
for (i = 0; i < 1000; i++) {
udelay(10);
if (!tg3_readphy(tp, MII_BMSR, &bmsr) &&
(bmsr & BMSR_LSTATUS)) {
udelay(40);
break;
}
}
if ((tp->phy_id & TG3_PHY_ID_REV_MASK) ==
TG3_PHY_REV_BCM5401_B0 &&
!(bmsr & BMSR_LSTATUS) &&
tp->link_config.active_speed == SPEED_1000) {
err = tg3_phy_reset(tp);
if (!err)
err = tg3_init_5401phy_dsp(tp);
if (err)
return err;
}
}
} else if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0) {
/* 5701 {A0,B0} CRC bug workaround */
tg3_writephy(tp, 0x15, 0x0a75);
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8c68);
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68);
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8c68);
}
/* Clear pending interrupts... */
tg3_readphy(tp, MII_TG3_ISTAT, &val);
tg3_readphy(tp, MII_TG3_ISTAT, &val);
if (tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT)
tg3_writephy(tp, MII_TG3_IMASK, ~MII_TG3_INT_LINKCHG);
else if (!(tp->phy_flags & TG3_PHYFLG_IS_FET))
tg3_writephy(tp, MII_TG3_IMASK, ~0);
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701) {
if (tp->led_ctrl == LED_CTRL_MODE_PHY_1)
tg3_writephy(tp, MII_TG3_EXT_CTRL,
MII_TG3_EXT_CTRL_LNK3_LED_MODE);
else
tg3_writephy(tp, MII_TG3_EXT_CTRL, 0);
}
current_link_up = false;
current_speed = SPEED_UNKNOWN;
current_duplex = DUPLEX_UNKNOWN;
tp->phy_flags &= ~TG3_PHYFLG_MDIX_STATE;
tp->link_config.rmt_adv = 0;
if (tp->phy_flags & TG3_PHYFLG_CAPACITIVE_COUPLING) {
err = tg3_phy_auxctl_read(tp,
MII_TG3_AUXCTL_SHDWSEL_MISCTEST,
&val);
if (!err && !(val & (1 << 10))) {
tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_MISCTEST,
val | (1 << 10));
goto relink;
}
}
bmsr = 0;
for (i = 0; i < 100; i++) {
tg3_readphy(tp, MII_BMSR, &bmsr);
if (!tg3_readphy(tp, MII_BMSR, &bmsr) &&
(bmsr & BMSR_LSTATUS))
break;
udelay(40);
}
if (bmsr & BMSR_LSTATUS) {
u32 aux_stat, bmcr;
tg3_readphy(tp, MII_TG3_AUX_STAT, &aux_stat);
for (i = 0; i < 2000; i++) {
udelay(10);
if (!tg3_readphy(tp, MII_TG3_AUX_STAT, &aux_stat) &&
aux_stat)
break;
}
tg3_aux_stat_to_speed_duplex(tp, aux_stat,
¤t_speed,
¤t_duplex);
bmcr = 0;
for (i = 0; i < 200; i++) {
tg3_readphy(tp, MII_BMCR, &bmcr);
if (tg3_readphy(tp, MII_BMCR, &bmcr))
continue;
if (bmcr && bmcr != 0x7fff)
break;
udelay(10);
}
lcl_adv = 0;
rmt_adv = 0;
tp->link_config.active_speed = current_speed;
tp->link_config.active_duplex = current_duplex;
if (tp->link_config.autoneg == AUTONEG_ENABLE) {
bool eee_config_ok = tg3_phy_eee_config_ok(tp);
if ((bmcr & BMCR_ANENABLE) &&
eee_config_ok &&
tg3_phy_copper_an_config_ok(tp, &lcl_adv) &&
tg3_phy_copper_fetch_rmtadv(tp, &rmt_adv))
current_link_up = true;
/* EEE settings changes take effect only after a phy
* reset. If we have skipped a reset due to Link Flap
* Avoidance being enabled, do it now.
*/
if (!eee_config_ok &&
(tp->phy_flags & TG3_PHYFLG_KEEP_LINK_ON_PWRDN) &&
!force_reset) {
tg3_setup_eee(tp);
tg3_phy_reset(tp);
}
} else {
if (!(bmcr & BMCR_ANENABLE) &&
tp->link_config.speed == current_speed &&
tp->link_config.duplex == current_duplex) {
current_link_up = true;
}
}
if (current_link_up &&
tp->link_config.active_duplex == DUPLEX_FULL) {
u32 reg, bit;
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
reg = MII_TG3_FET_GEN_STAT;
bit = MII_TG3_FET_GEN_STAT_MDIXSTAT;
} else {
reg = MII_TG3_EXT_STAT;
bit = MII_TG3_EXT_STAT_MDIX;
}
if (!tg3_readphy(tp, reg, &val) && (val & bit))
tp->phy_flags |= TG3_PHYFLG_MDIX_STATE;
tg3_setup_flow_control(tp, lcl_adv, rmt_adv);
}
}
relink:
if (!current_link_up || (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) {
tg3_phy_copper_begin(tp);
if (tg3_flag(tp, ROBOSWITCH)) {
current_link_up = true;
/* FIXME: when BCM5325 switch is used use 100 MBit/s */
current_speed = SPEED_1000;
current_duplex = DUPLEX_FULL;
tp->link_config.active_speed = current_speed;
tp->link_config.active_duplex = current_duplex;
}
tg3_readphy(tp, MII_BMSR, &bmsr);
if ((!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) ||
(tp->mac_mode & MAC_MODE_PORT_INT_LPBACK))
current_link_up = true;
}
tp->mac_mode &= ~MAC_MODE_PORT_MODE_MASK;
if (current_link_up) {
if (tp->link_config.active_speed == SPEED_100 ||
tp->link_config.active_speed == SPEED_10)
tp->mac_mode |= MAC_MODE_PORT_MODE_MII;
else
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
} else if (tp->phy_flags & TG3_PHYFLG_IS_FET)
tp->mac_mode |= MAC_MODE_PORT_MODE_MII;
else
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
/* In order for the 5750 core in BCM4785 chip to work properly
* in RGMII mode, the Led Control Register must be set up.
*/
if (tg3_flag(tp, RGMII_MODE)) {
u32 led_ctrl = tr32(MAC_LED_CTRL);
led_ctrl &= ~(LED_CTRL_1000MBPS_ON | LED_CTRL_100MBPS_ON);
if (tp->link_config.active_speed == SPEED_10)
led_ctrl |= LED_CTRL_LNKLED_OVERRIDE;
else if (tp->link_config.active_speed == SPEED_100)
led_ctrl |= (LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_100MBPS_ON);
else if (tp->link_config.active_speed == SPEED_1000)
led_ctrl |= (LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_1000MBPS_ON);
tw32(MAC_LED_CTRL, led_ctrl);
udelay(40);
}
tp->mac_mode &= ~MAC_MODE_HALF_DUPLEX;
if (tp->link_config.active_duplex == DUPLEX_HALF)
tp->mac_mode |= MAC_MODE_HALF_DUPLEX;
if (tg3_asic_rev(tp) == ASIC_REV_5700) {
if (current_link_up &&
tg3_5700_link_polarity(tp, tp->link_config.active_speed))
tp->mac_mode |= MAC_MODE_LINK_POLARITY;
else
tp->mac_mode &= ~MAC_MODE_LINK_POLARITY;
}
/* ??? Without this setting Netgear GA302T PHY does not
* ??? send/receive packets...
*/
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5411 &&
tg3_chip_rev_id(tp) == CHIPREV_ID_5700_ALTIMA) {
tp->mi_mode |= MAC_MI_MODE_AUTO_POLL;
tw32_f(MAC_MI_MODE, tp->mi_mode);
udelay(80);
}
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tg3_phy_eee_adjust(tp, current_link_up);
if (tg3_flag(tp, USE_LINKCHG_REG)) {
/* Polled via timer. */
tw32_f(MAC_EVENT, 0);
} else {
tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED);
}
udelay(40);
if (tg3_asic_rev(tp) == ASIC_REV_5700 &&
current_link_up &&
tp->link_config.active_speed == SPEED_1000 &&
(tg3_flag(tp, PCIX_MODE) || tg3_flag(tp, PCI_HIGH_SPEED))) {
udelay(120);
tw32_f(MAC_STATUS,
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED));
udelay(40);
tg3_write_mem(tp,
NIC_SRAM_FIRMWARE_MBOX,
NIC_SRAM_FIRMWARE_MBOX_MAGIC2);
}
/* Prevent send BD corruption. */
if (tg3_flag(tp, CLKREQ_BUG)) {
if (tp->link_config.active_speed == SPEED_100 ||
tp->link_config.active_speed == SPEED_10)
pcie_capability_clear_word(tp->pdev, PCI_EXP_LNKCTL,
PCI_EXP_LNKCTL_CLKREQ_EN);
else
pcie_capability_set_word(tp->pdev, PCI_EXP_LNKCTL,
PCI_EXP_LNKCTL_CLKREQ_EN);
}
tg3_test_and_report_link_chg(tp, current_link_up);
return 0;
}
struct tg3_fiber_aneginfo {
int state;
#define ANEG_STATE_UNKNOWN 0
#define ANEG_STATE_AN_ENABLE 1
#define ANEG_STATE_RESTART_INIT 2
#define ANEG_STATE_RESTART 3
#define ANEG_STATE_DISABLE_LINK_OK 4
#define ANEG_STATE_ABILITY_DETECT_INIT 5
#define ANEG_STATE_ABILITY_DETECT 6
#define ANEG_STATE_ACK_DETECT_INIT 7
#define ANEG_STATE_ACK_DETECT 8
#define ANEG_STATE_COMPLETE_ACK_INIT 9
#define ANEG_STATE_COMPLETE_ACK 10
#define ANEG_STATE_IDLE_DETECT_INIT 11
#define ANEG_STATE_IDLE_DETECT 12
#define ANEG_STATE_LINK_OK 13
#define ANEG_STATE_NEXT_PAGE_WAIT_INIT 14
#define ANEG_STATE_NEXT_PAGE_WAIT 15
u32 flags;
#define MR_AN_ENABLE 0x00000001
#define MR_RESTART_AN 0x00000002
#define MR_AN_COMPLETE 0x00000004
#define MR_PAGE_RX 0x00000008
#define MR_NP_LOADED 0x00000010
#define MR_TOGGLE_TX 0x00000020
#define MR_LP_ADV_FULL_DUPLEX 0x00000040
#define MR_LP_ADV_HALF_DUPLEX 0x00000080
#define MR_LP_ADV_SYM_PAUSE 0x00000100
#define MR_LP_ADV_ASYM_PAUSE 0x00000200
#define MR_LP_ADV_REMOTE_FAULT1 0x00000400
#define MR_LP_ADV_REMOTE_FAULT2 0x00000800
#define MR_LP_ADV_NEXT_PAGE 0x00001000
#define MR_TOGGLE_RX 0x00002000
#define MR_NP_RX 0x00004000
#define MR_LINK_OK 0x80000000
unsigned long link_time, cur_time;
u32 ability_match_cfg;
int ability_match_count;
char ability_match, idle_match, ack_match;
u32 txconfig, rxconfig;
#define ANEG_CFG_NP 0x00000080
#define ANEG_CFG_ACK 0x00000040
#define ANEG_CFG_RF2 0x00000020
#define ANEG_CFG_RF1 0x00000010
#define ANEG_CFG_PS2 0x00000001
#define ANEG_CFG_PS1 0x00008000
#define ANEG_CFG_HD 0x00004000
#define ANEG_CFG_FD 0x00002000
#define ANEG_CFG_INVAL 0x00001f06
};
#define ANEG_OK 0
#define ANEG_DONE 1
#define ANEG_TIMER_ENAB 2
#define ANEG_FAILED -1
#define ANEG_STATE_SETTLE_TIME 10000
static int tg3_fiber_aneg_smachine(struct tg3 *tp,
struct tg3_fiber_aneginfo *ap)
{
u16 flowctrl;
unsigned long delta;
u32 rx_cfg_reg;
int ret;
if (ap->state == ANEG_STATE_UNKNOWN) {
ap->rxconfig = 0;
ap->link_time = 0;
ap->cur_time = 0;
ap->ability_match_cfg = 0;
ap->ability_match_count = 0;
ap->ability_match = 0;
ap->idle_match = 0;
ap->ack_match = 0;
}
ap->cur_time++;
if (tr32(MAC_STATUS) & MAC_STATUS_RCVD_CFG) {
rx_cfg_reg = tr32(MAC_RX_AUTO_NEG);
if (rx_cfg_reg != ap->ability_match_cfg) {
ap->ability_match_cfg = rx_cfg_reg;
ap->ability_match = 0;
ap->ability_match_count = 0;
} else {
if (++ap->ability_match_count > 1) {
ap->ability_match = 1;
ap->ability_match_cfg = rx_cfg_reg;
}
}
if (rx_cfg_reg & ANEG_CFG_ACK)
ap->ack_match = 1;
else
ap->ack_match = 0;
ap->idle_match = 0;
} else {
ap->idle_match = 1;
ap->ability_match_cfg = 0;
ap->ability_match_count = 0;
ap->ability_match = 0;
ap->ack_match = 0;
rx_cfg_reg = 0;
}
ap->rxconfig = rx_cfg_reg;
ret = ANEG_OK;
switch (ap->state) {
case ANEG_STATE_UNKNOWN:
if (ap->flags & (MR_AN_ENABLE | MR_RESTART_AN))
ap->state = ANEG_STATE_AN_ENABLE;
/* fallthru */
case ANEG_STATE_AN_ENABLE:
ap->flags &= ~(MR_AN_COMPLETE | MR_PAGE_RX);
if (ap->flags & MR_AN_ENABLE) {
ap->link_time = 0;
ap->cur_time = 0;
ap->ability_match_cfg = 0;
ap->ability_match_count = 0;
ap->ability_match = 0;
ap->idle_match = 0;
ap->ack_match = 0;
ap->state = ANEG_STATE_RESTART_INIT;
} else {
ap->state = ANEG_STATE_DISABLE_LINK_OK;
}
break;
case ANEG_STATE_RESTART_INIT:
ap->link_time = ap->cur_time;
ap->flags &= ~(MR_NP_LOADED);
ap->txconfig = 0;
tw32(MAC_TX_AUTO_NEG, 0);
tp->mac_mode |= MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
ret = ANEG_TIMER_ENAB;
ap->state = ANEG_STATE_RESTART;
/* fallthru */
case ANEG_STATE_RESTART:
delta = ap->cur_time - ap->link_time;
if (delta > ANEG_STATE_SETTLE_TIME)
ap->state = ANEG_STATE_ABILITY_DETECT_INIT;
else
ret = ANEG_TIMER_ENAB;
break;
case ANEG_STATE_DISABLE_LINK_OK:
ret = ANEG_DONE;
break;
case ANEG_STATE_ABILITY_DETECT_INIT:
ap->flags &= ~(MR_TOGGLE_TX);
ap->txconfig = ANEG_CFG_FD;
flowctrl = tg3_advert_flowctrl_1000X(tp->link_config.flowctrl);
if (flowctrl & ADVERTISE_1000XPAUSE)
ap->txconfig |= ANEG_CFG_PS1;
if (flowctrl & ADVERTISE_1000XPSE_ASYM)
ap->txconfig |= ANEG_CFG_PS2;
tw32(MAC_TX_AUTO_NEG, ap->txconfig);
tp->mac_mode |= MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
ap->state = ANEG_STATE_ABILITY_DETECT;
break;
case ANEG_STATE_ABILITY_DETECT:
if (ap->ability_match != 0 && ap->rxconfig != 0)
ap->state = ANEG_STATE_ACK_DETECT_INIT;
break;
case ANEG_STATE_ACK_DETECT_INIT:
ap->txconfig |= ANEG_CFG_ACK;
tw32(MAC_TX_AUTO_NEG, ap->txconfig);
tp->mac_mode |= MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
ap->state = ANEG_STATE_ACK_DETECT;
/* fallthru */
case ANEG_STATE_ACK_DETECT:
if (ap->ack_match != 0) {
if ((ap->rxconfig & ~ANEG_CFG_ACK) ==
(ap->ability_match_cfg & ~ANEG_CFG_ACK)) {
ap->state = ANEG_STATE_COMPLETE_ACK_INIT;
} else {
ap->state = ANEG_STATE_AN_ENABLE;
}
} else if (ap->ability_match != 0 &&
ap->rxconfig == 0) {
ap->state = ANEG_STATE_AN_ENABLE;
}
break;
case ANEG_STATE_COMPLETE_ACK_INIT:
if (ap->rxconfig & ANEG_CFG_INVAL) {
ret = ANEG_FAILED;
break;
}
ap->flags &= ~(MR_LP_ADV_FULL_DUPLEX |
MR_LP_ADV_HALF_DUPLEX |
MR_LP_ADV_SYM_PAUSE |
MR_LP_ADV_ASYM_PAUSE |
MR_LP_ADV_REMOTE_FAULT1 |
MR_LP_ADV_REMOTE_FAULT2 |
MR_LP_ADV_NEXT_PAGE |
MR_TOGGLE_RX |
MR_NP_RX);
if (ap->rxconfig & ANEG_CFG_FD)
ap->flags |= MR_LP_ADV_FULL_DUPLEX;
if (ap->rxconfig & ANEG_CFG_HD)
ap->flags |= MR_LP_ADV_HALF_DUPLEX;
if (ap->rxconfig & ANEG_CFG_PS1)
ap->flags |= MR_LP_ADV_SYM_PAUSE;
if (ap->rxconfig & ANEG_CFG_PS2)
ap->flags |= MR_LP_ADV_ASYM_PAUSE;
if (ap->rxconfig & ANEG_CFG_RF1)
ap->flags |= MR_LP_ADV_REMOTE_FAULT1;
if (ap->rxconfig & ANEG_CFG_RF2)
ap->flags |= MR_LP_ADV_REMOTE_FAULT2;
if (ap->rxconfig & ANEG_CFG_NP)
ap->flags |= MR_LP_ADV_NEXT_PAGE;
ap->link_time = ap->cur_time;
ap->flags ^= (MR_TOGGLE_TX);
if (ap->rxconfig & 0x0008)
ap->flags |= MR_TOGGLE_RX;
if (ap->rxconfig & ANEG_CFG_NP)
ap->flags |= MR_NP_RX;
ap->flags |= MR_PAGE_RX;
ap->state = ANEG_STATE_COMPLETE_ACK;
ret = ANEG_TIMER_ENAB;
break;
case ANEG_STATE_COMPLETE_ACK:
if (ap->ability_match != 0 &&
ap->rxconfig == 0) {
ap->state = ANEG_STATE_AN_ENABLE;
break;
}
delta = ap->cur_time - ap->link_time;
if (delta > ANEG_STATE_SETTLE_TIME) {
if (!(ap->flags & (MR_LP_ADV_NEXT_PAGE))) {
ap->state = ANEG_STATE_IDLE_DETECT_INIT;
} else {
if ((ap->txconfig & ANEG_CFG_NP) == 0 &&
!(ap->flags & MR_NP_RX)) {
ap->state = ANEG_STATE_IDLE_DETECT_INIT;
} else {
ret = ANEG_FAILED;
}
}
}
break;
case ANEG_STATE_IDLE_DETECT_INIT:
ap->link_time = ap->cur_time;
tp->mac_mode &= ~MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
ap->state = ANEG_STATE_IDLE_DETECT;
ret = ANEG_TIMER_ENAB;
break;
case ANEG_STATE_IDLE_DETECT:
if (ap->ability_match != 0 &&
ap->rxconfig == 0) {
ap->state = ANEG_STATE_AN_ENABLE;
break;
}
delta = ap->cur_time - ap->link_time;
if (delta > ANEG_STATE_SETTLE_TIME) {
/* XXX another gem from the Broadcom driver :( */
ap->state = ANEG_STATE_LINK_OK;
}
break;
case ANEG_STATE_LINK_OK:
ap->flags |= (MR_AN_COMPLETE | MR_LINK_OK);
ret = ANEG_DONE;
break;
case ANEG_STATE_NEXT_PAGE_WAIT_INIT:
/* ??? unimplemented */
break;
case ANEG_STATE_NEXT_PAGE_WAIT:
/* ??? unimplemented */
break;
default:
ret = ANEG_FAILED;
break;
}
return ret;
}
static int fiber_autoneg(struct tg3 *tp, u32 *txflags, u32 *rxflags)
{
int res = 0;
struct tg3_fiber_aneginfo aninfo;
int status = ANEG_FAILED;
unsigned int tick;
u32 tmp;
tw32_f(MAC_TX_AUTO_NEG, 0);
tmp = tp->mac_mode & ~MAC_MODE_PORT_MODE_MASK;
tw32_f(MAC_MODE, tmp | MAC_MODE_PORT_MODE_GMII);
udelay(40);
tw32_f(MAC_MODE, tp->mac_mode | MAC_MODE_SEND_CONFIGS);
udelay(40);
memset(&aninfo, 0, sizeof(aninfo));
aninfo.flags |= MR_AN_ENABLE;
aninfo.state = ANEG_STATE_UNKNOWN;
aninfo.cur_time = 0;
tick = 0;
while (++tick < 195000) {
status = tg3_fiber_aneg_smachine(tp, &aninfo);
if (status == ANEG_DONE || status == ANEG_FAILED)
break;
udelay(1);
}
tp->mac_mode &= ~MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
*txflags = aninfo.txconfig;
*rxflags = aninfo.flags;
if (status == ANEG_DONE &&
(aninfo.flags & (MR_AN_COMPLETE | MR_LINK_OK |
MR_LP_ADV_FULL_DUPLEX)))
res = 1;
return res;
}
static void tg3_init_bcm8002(struct tg3 *tp)
{
u32 mac_status = tr32(MAC_STATUS);
int i;
/* Reset when initting first time or we have a link. */
if (tg3_flag(tp, INIT_COMPLETE) &&
!(mac_status & MAC_STATUS_PCS_SYNCED))
return;
/* Set PLL lock range. */
tg3_writephy(tp, 0x16, 0x8007);
/* SW reset */
tg3_writephy(tp, MII_BMCR, BMCR_RESET);
/* Wait for reset to complete. */
/* XXX schedule_timeout() ... */
for (i = 0; i < 500; i++)
udelay(10);
/* Config mode; select PMA/Ch 1 regs. */
tg3_writephy(tp, 0x10, 0x8411);
/* Enable auto-lock and comdet, select txclk for tx. */
tg3_writephy(tp, 0x11, 0x0a10);
tg3_writephy(tp, 0x18, 0x00a0);
tg3_writephy(tp, 0x16, 0x41ff);
/* Assert and deassert POR. */
tg3_writephy(tp, 0x13, 0x0400);
udelay(40);
tg3_writephy(tp, 0x13, 0x0000);
tg3_writephy(tp, 0x11, 0x0a50);
udelay(40);
tg3_writephy(tp, 0x11, 0x0a10);
/* Wait for signal to stabilize */
/* XXX schedule_timeout() ... */
for (i = 0; i < 15000; i++)
udelay(10);
/* Deselect the channel register so we can read the PHYID
* later.
*/
tg3_writephy(tp, 0x10, 0x8011);
}
static bool tg3_setup_fiber_hw_autoneg(struct tg3 *tp, u32 mac_status)
{
u16 flowctrl;
bool current_link_up;
u32 sg_dig_ctrl, sg_dig_status;
u32 serdes_cfg, expected_sg_dig_ctrl;
int workaround, port_a;
serdes_cfg = 0;
expected_sg_dig_ctrl = 0;
workaround = 0;
port_a = 1;
current_link_up = false;
if (tg3_chip_rev_id(tp) != CHIPREV_ID_5704_A0 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5704_A1) {
workaround = 1;
if (tr32(TG3PCI_DUAL_MAC_CTRL) & DUAL_MAC_CTRL_ID)
port_a = 0;
/* preserve bits 0-11,13,14 for signal pre-emphasis */
/* preserve bits 20-23 for voltage regulator */
serdes_cfg = tr32(MAC_SERDES_CFG) & 0x00f06fff;
}
sg_dig_ctrl = tr32(SG_DIG_CTRL);
if (tp->link_config.autoneg != AUTONEG_ENABLE) {
if (sg_dig_ctrl & SG_DIG_USING_HW_AUTONEG) {
if (workaround) {
u32 val = serdes_cfg;
if (port_a)
val |= 0xc010000;
else
val |= 0x4010000;
tw32_f(MAC_SERDES_CFG, val);
}
tw32_f(SG_DIG_CTRL, SG_DIG_COMMON_SETUP);
}
if (mac_status & MAC_STATUS_PCS_SYNCED) {
tg3_setup_flow_control(tp, 0, 0);
current_link_up = true;
}
goto out;
}
/* Want auto-negotiation. */
expected_sg_dig_ctrl = SG_DIG_USING_HW_AUTONEG | SG_DIG_COMMON_SETUP;
flowctrl = tg3_advert_flowctrl_1000X(tp->link_config.flowctrl);
if (flowctrl & ADVERTISE_1000XPAUSE)
expected_sg_dig_ctrl |= SG_DIG_PAUSE_CAP;
if (flowctrl & ADVERTISE_1000XPSE_ASYM)
expected_sg_dig_ctrl |= SG_DIG_ASYM_PAUSE;
if (sg_dig_ctrl != expected_sg_dig_ctrl) {
if ((tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT) &&
tp->serdes_counter &&
((mac_status & (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_RCVD_CFG)) ==
MAC_STATUS_PCS_SYNCED)) {
tp->serdes_counter--;
current_link_up = true;
goto out;
}
restart_autoneg:
if (workaround)
tw32_f(MAC_SERDES_CFG, serdes_cfg | 0xc011000);
tw32_f(SG_DIG_CTRL, expected_sg_dig_ctrl | SG_DIG_SOFT_RESET);
udelay(5);
tw32_f(SG_DIG_CTRL, expected_sg_dig_ctrl);
tp->serdes_counter = SERDES_AN_TIMEOUT_5704S;
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
} else if (mac_status & (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_SIGNAL_DET)) {
sg_dig_status = tr32(SG_DIG_STATUS);
mac_status = tr32(MAC_STATUS);
if ((sg_dig_status & SG_DIG_AUTONEG_COMPLETE) &&
(mac_status & MAC_STATUS_PCS_SYNCED)) {
u32 local_adv = 0, remote_adv = 0;
if (sg_dig_ctrl & SG_DIG_PAUSE_CAP)
local_adv |= ADVERTISE_1000XPAUSE;
if (sg_dig_ctrl & SG_DIG_ASYM_PAUSE)
local_adv |= ADVERTISE_1000XPSE_ASYM;
if (sg_dig_status & SG_DIG_PARTNER_PAUSE_CAPABLE)
remote_adv |= LPA_1000XPAUSE;
if (sg_dig_status & SG_DIG_PARTNER_ASYM_PAUSE)
remote_adv |= LPA_1000XPAUSE_ASYM;
tp->link_config.rmt_adv =
mii_adv_to_ethtool_adv_x(remote_adv);
tg3_setup_flow_control(tp, local_adv, remote_adv);
current_link_up = true;
tp->serdes_counter = 0;
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
} else if (!(sg_dig_status & SG_DIG_AUTONEG_COMPLETE)) {
if (tp->serdes_counter)
tp->serdes_counter--;
else {
if (workaround) {
u32 val = serdes_cfg;
if (port_a)
val |= 0xc010000;
else
val |= 0x4010000;
tw32_f(MAC_SERDES_CFG, val);
}
tw32_f(SG_DIG_CTRL, SG_DIG_COMMON_SETUP);
udelay(40);
/* Link parallel detection - link is up */
/* only if we have PCS_SYNC and not */
/* receiving config code words */
mac_status = tr32(MAC_STATUS);
if ((mac_status & MAC_STATUS_PCS_SYNCED) &&
!(mac_status & MAC_STATUS_RCVD_CFG)) {
tg3_setup_flow_control(tp, 0, 0);
current_link_up = true;
tp->phy_flags |=
TG3_PHYFLG_PARALLEL_DETECT;
tp->serdes_counter =
SERDES_PARALLEL_DET_TIMEOUT;
} else
goto restart_autoneg;
}
}
} else {
tp->serdes_counter = SERDES_AN_TIMEOUT_5704S;
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
}
out:
return current_link_up;
}
static bool tg3_setup_fiber_by_hand(struct tg3 *tp, u32 mac_status)
{
bool current_link_up = false;
if (!(mac_status & MAC_STATUS_PCS_SYNCED))
goto out;
if (tp->link_config.autoneg == AUTONEG_ENABLE) {
u32 txflags, rxflags;
int i;
if (fiber_autoneg(tp, &txflags, &rxflags)) {
u32 local_adv = 0, remote_adv = 0;
if (txflags & ANEG_CFG_PS1)
local_adv |= ADVERTISE_1000XPAUSE;
if (txflags & ANEG_CFG_PS2)
local_adv |= ADVERTISE_1000XPSE_ASYM;
if (rxflags & MR_LP_ADV_SYM_PAUSE)
remote_adv |= LPA_1000XPAUSE;
if (rxflags & MR_LP_ADV_ASYM_PAUSE)
remote_adv |= LPA_1000XPAUSE_ASYM;
tp->link_config.rmt_adv =
mii_adv_to_ethtool_adv_x(remote_adv);
tg3_setup_flow_control(tp, local_adv, remote_adv);
current_link_up = true;
}
for (i = 0; i < 30; i++) {
udelay(20);
tw32_f(MAC_STATUS,
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED));
udelay(40);
if ((tr32(MAC_STATUS) &
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED)) == 0)
break;
}
mac_status = tr32(MAC_STATUS);
if (!current_link_up &&
(mac_status & MAC_STATUS_PCS_SYNCED) &&
!(mac_status & MAC_STATUS_RCVD_CFG))
current_link_up = true;
} else {
tg3_setup_flow_control(tp, 0, 0);
/* Forcing 1000FD link up. */
current_link_up = true;
tw32_f(MAC_MODE, (tp->mac_mode | MAC_MODE_SEND_CONFIGS));
udelay(40);
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
}
out:
return current_link_up;
}
static int tg3_setup_fiber_phy(struct tg3 *tp, bool force_reset)
{
u32 orig_pause_cfg;
u16 orig_active_speed;
u8 orig_active_duplex;
u32 mac_status;
bool current_link_up;
int i;
orig_pause_cfg = tp->link_config.active_flowctrl;
orig_active_speed = tp->link_config.active_speed;
orig_active_duplex = tp->link_config.active_duplex;
if (!tg3_flag(tp, HW_AUTONEG) &&
tp->link_up &&
tg3_flag(tp, INIT_COMPLETE)) {
mac_status = tr32(MAC_STATUS);
mac_status &= (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_SIGNAL_DET |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_RCVD_CFG);
if (mac_status == (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_SIGNAL_DET)) {
tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED));
return 0;
}
}
tw32_f(MAC_TX_AUTO_NEG, 0);
tp->mac_mode &= ~(MAC_MODE_PORT_MODE_MASK | MAC_MODE_HALF_DUPLEX);
tp->mac_mode |= MAC_MODE_PORT_MODE_TBI;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
if (tp->phy_id == TG3_PHY_ID_BCM8002)
tg3_init_bcm8002(tp);
/* Enable link change event even when serdes polling. */
tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED);
udelay(40);
current_link_up = false;
tp->link_config.rmt_adv = 0;
mac_status = tr32(MAC_STATUS);
if (tg3_flag(tp, HW_AUTONEG))
current_link_up = tg3_setup_fiber_hw_autoneg(tp, mac_status);
else
current_link_up = tg3_setup_fiber_by_hand(tp, mac_status);
tp->napi[0].hw_status->status =
(SD_STATUS_UPDATED |
(tp->napi[0].hw_status->status & ~SD_STATUS_LINK_CHG));
for (i = 0; i < 100; i++) {
tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED));
udelay(5);
if ((tr32(MAC_STATUS) & (MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_LNKSTATE_CHANGED)) == 0)
break;
}
mac_status = tr32(MAC_STATUS);
if ((mac_status & MAC_STATUS_PCS_SYNCED) == 0) {
current_link_up = false;
if (tp->link_config.autoneg == AUTONEG_ENABLE &&
tp->serdes_counter == 0) {
tw32_f(MAC_MODE, (tp->mac_mode |
MAC_MODE_SEND_CONFIGS));
udelay(1);
tw32_f(MAC_MODE, tp->mac_mode);
}
}
if (current_link_up) {
tp->link_config.active_speed = SPEED_1000;
tp->link_config.active_duplex = DUPLEX_FULL;
tw32(MAC_LED_CTRL, (tp->led_ctrl |
LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_1000MBPS_ON));
} else {
tp->link_config.active_speed = SPEED_UNKNOWN;
tp->link_config.active_duplex = DUPLEX_UNKNOWN;
tw32(MAC_LED_CTRL, (tp->led_ctrl |
LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_TRAFFIC_OVERRIDE));
}
if (!tg3_test_and_report_link_chg(tp, current_link_up)) {
u32 now_pause_cfg = tp->link_config.active_flowctrl;
if (orig_pause_cfg != now_pause_cfg ||
orig_active_speed != tp->link_config.active_speed ||
orig_active_duplex != tp->link_config.active_duplex)
tg3_link_report(tp);
}
return 0;
}
static int tg3_setup_fiber_mii_phy(struct tg3 *tp, bool force_reset)
{
int err = 0;
u32 bmsr, bmcr;
u16 current_speed = SPEED_UNKNOWN;
u8 current_duplex = DUPLEX_UNKNOWN;
bool current_link_up = false;
u32 local_adv, remote_adv, sgsr;
if ((tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720) &&
!tg3_readphy(tp, SERDES_TG3_1000X_STATUS, &sgsr) &&
(sgsr & SERDES_TG3_SGMII_MODE)) {
if (force_reset)
tg3_phy_reset(tp);
tp->mac_mode &= ~MAC_MODE_PORT_MODE_MASK;
if (!(sgsr & SERDES_TG3_LINK_UP)) {
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
} else {
current_link_up = true;
if (sgsr & SERDES_TG3_SPEED_1000) {
current_speed = SPEED_1000;
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
} else if (sgsr & SERDES_TG3_SPEED_100) {
current_speed = SPEED_100;
tp->mac_mode |= MAC_MODE_PORT_MODE_MII;
} else {
current_speed = SPEED_10;
tp->mac_mode |= MAC_MODE_PORT_MODE_MII;
}
if (sgsr & SERDES_TG3_FULL_DUPLEX)
current_duplex = DUPLEX_FULL;
else
current_duplex = DUPLEX_HALF;
}
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tg3_clear_mac_status(tp);
goto fiber_setup_done;
}
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tg3_clear_mac_status(tp);
if (force_reset)
tg3_phy_reset(tp);
tp->link_config.rmt_adv = 0;
err |= tg3_readphy(tp, MII_BMSR, &bmsr);
err |= tg3_readphy(tp, MII_BMSR, &bmsr);
if (tg3_asic_rev(tp) == ASIC_REV_5714) {
if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP)
bmsr |= BMSR_LSTATUS;
else
bmsr &= ~BMSR_LSTATUS;
}
err |= tg3_readphy(tp, MII_BMCR, &bmcr);
if ((tp->link_config.autoneg == AUTONEG_ENABLE) && !force_reset &&
(tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT)) {
/* do nothing, just check for link up at the end */
} else if (tp->link_config.autoneg == AUTONEG_ENABLE) {
u32 adv, newadv;
err |= tg3_readphy(tp, MII_ADVERTISE, &adv);
newadv = adv & ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF |
ADVERTISE_1000XPAUSE |
ADVERTISE_1000XPSE_ASYM |
ADVERTISE_SLCT);
newadv |= tg3_advert_flowctrl_1000X(tp->link_config.flowctrl);
newadv |= ethtool_adv_to_mii_adv_x(tp->link_config.advertising);
if ((newadv != adv) || !(bmcr & BMCR_ANENABLE)) {
tg3_writephy(tp, MII_ADVERTISE, newadv);
bmcr |= BMCR_ANENABLE | BMCR_ANRESTART;
tg3_writephy(tp, MII_BMCR, bmcr);
tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED);
tp->serdes_counter = SERDES_AN_TIMEOUT_5714S;
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
return err;
}
} else {
u32 new_bmcr;
bmcr &= ~BMCR_SPEED1000;
new_bmcr = bmcr & ~(BMCR_ANENABLE | BMCR_FULLDPLX);
if (tp->link_config.duplex == DUPLEX_FULL)
new_bmcr |= BMCR_FULLDPLX;
if (new_bmcr != bmcr) {
/* BMCR_SPEED1000 is a reserved bit that needs
* to be set on write.
*/
new_bmcr |= BMCR_SPEED1000;
/* Force a linkdown */
if (tp->link_up) {
u32 adv;
err |= tg3_readphy(tp, MII_ADVERTISE, &adv);
adv &= ~(ADVERTISE_1000XFULL |
ADVERTISE_1000XHALF |
ADVERTISE_SLCT);
tg3_writephy(tp, MII_ADVERTISE, adv);
tg3_writephy(tp, MII_BMCR, bmcr |
BMCR_ANRESTART |
BMCR_ANENABLE);
udelay(10);
tg3_carrier_off(tp);
}
tg3_writephy(tp, MII_BMCR, new_bmcr);
bmcr = new_bmcr;
err |= tg3_readphy(tp, MII_BMSR, &bmsr);
err |= tg3_readphy(tp, MII_BMSR, &bmsr);
if (tg3_asic_rev(tp) == ASIC_REV_5714) {
if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP)
bmsr |= BMSR_LSTATUS;
else
bmsr &= ~BMSR_LSTATUS;
}
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
}
}
if (bmsr & BMSR_LSTATUS) {
current_speed = SPEED_1000;
current_link_up = true;
if (bmcr & BMCR_FULLDPLX)
current_duplex = DUPLEX_FULL;
else
current_duplex = DUPLEX_HALF;
local_adv = 0;
remote_adv = 0;
if (bmcr & BMCR_ANENABLE) {
u32 common;
err |= tg3_readphy(tp, MII_ADVERTISE, &local_adv);
err |= tg3_readphy(tp, MII_LPA, &remote_adv);
common = local_adv & remote_adv;
if (common & (ADVERTISE_1000XHALF |
ADVERTISE_1000XFULL)) {
if (common & ADVERTISE_1000XFULL)
current_duplex = DUPLEX_FULL;
else
current_duplex = DUPLEX_HALF;
tp->link_config.rmt_adv =
mii_adv_to_ethtool_adv_x(remote_adv);
} else if (!tg3_flag(tp, 5780_CLASS)) {
/* Link is up via parallel detect */
} else {
current_link_up = false;
}
}
}
fiber_setup_done:
if (current_link_up && current_duplex == DUPLEX_FULL)
tg3_setup_flow_control(tp, local_adv, remote_adv);
tp->mac_mode &= ~MAC_MODE_HALF_DUPLEX;
if (tp->link_config.active_duplex == DUPLEX_HALF)
tp->mac_mode |= MAC_MODE_HALF_DUPLEX;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED);
tp->link_config.active_speed = current_speed;
tp->link_config.active_duplex = current_duplex;
tg3_test_and_report_link_chg(tp, current_link_up);
return err;
}
static void tg3_serdes_parallel_detect(struct tg3 *tp)
{
if (tp->serdes_counter) {
/* Give autoneg time to complete. */
tp->serdes_counter--;
return;
}
if (!tp->link_up &&
(tp->link_config.autoneg == AUTONEG_ENABLE)) {
u32 bmcr;
tg3_readphy(tp, MII_BMCR, &bmcr);
if (bmcr & BMCR_ANENABLE) {
u32 phy1, phy2;
/* Select shadow register 0x1f */
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x7c00);
tg3_readphy(tp, MII_TG3_MISC_SHDW, &phy1);
/* Select expansion interrupt status register */
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
MII_TG3_DSP_EXP1_INT_STAT);
tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2);
tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2);
if ((phy1 & 0x10) && !(phy2 & 0x20)) {
/* We have signal detect and not receiving
* config code words, link is up by parallel
* detection.
*/
bmcr &= ~BMCR_ANENABLE;
bmcr |= BMCR_SPEED1000 | BMCR_FULLDPLX;
tg3_writephy(tp, MII_BMCR, bmcr);
tp->phy_flags |= TG3_PHYFLG_PARALLEL_DETECT;
}
}
} else if (tp->link_up &&
(tp->link_config.autoneg == AUTONEG_ENABLE) &&
(tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT)) {
u32 phy2;
/* Select expansion interrupt status register */
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
MII_TG3_DSP_EXP1_INT_STAT);
tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2);
if (phy2 & 0x20) {
u32 bmcr;
/* Config code words received, turn on autoneg. */
tg3_readphy(tp, MII_BMCR, &bmcr);
tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANENABLE);
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
}
}
}
static int tg3_setup_phy(struct tg3 *tp, bool force_reset)
{
u32 val;
int err;
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
err = tg3_setup_fiber_phy(tp, force_reset);
else if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
err = tg3_setup_fiber_mii_phy(tp, force_reset);
else
err = tg3_setup_copper_phy(tp, force_reset);
if (tg3_chip_rev(tp) == CHIPREV_5784_AX) {
u32 scale;
val = tr32(TG3_CPMU_CLCK_STAT) & CPMU_CLCK_STAT_MAC_CLCK_MASK;
if (val == CPMU_CLCK_STAT_MAC_CLCK_62_5)
scale = 65;
else if (val == CPMU_CLCK_STAT_MAC_CLCK_6_25)
scale = 6;
else
scale = 12;
val = tr32(GRC_MISC_CFG) & ~GRC_MISC_CFG_PRESCALAR_MASK;
val |= (scale << GRC_MISC_CFG_PRESCALAR_SHIFT);
tw32(GRC_MISC_CFG, val);
}
val = (2 << TX_LENGTHS_IPG_CRS_SHIFT) |
(6 << TX_LENGTHS_IPG_SHIFT);
if (tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762)
val |= tr32(MAC_TX_LENGTHS) &
(TX_LENGTHS_JMB_FRM_LEN_MSK |
TX_LENGTHS_CNT_DWN_VAL_MSK);
if (tp->link_config.active_speed == SPEED_1000 &&
tp->link_config.active_duplex == DUPLEX_HALF)
tw32(MAC_TX_LENGTHS, val |
(0xff << TX_LENGTHS_SLOT_TIME_SHIFT));
else
tw32(MAC_TX_LENGTHS, val |
(32 << TX_LENGTHS_SLOT_TIME_SHIFT));
if (!tg3_flag(tp, 5705_PLUS)) {
if (tp->link_up) {
tw32(HOSTCC_STAT_COAL_TICKS,
tp->coal.stats_block_coalesce_usecs);
} else {
tw32(HOSTCC_STAT_COAL_TICKS, 0);
}
}
if (tg3_flag(tp, ASPM_WORKAROUND)) {
val = tr32(PCIE_PWR_MGMT_THRESH);
if (!tp->link_up)
val = (val & ~PCIE_PWR_MGMT_L1_THRESH_MSK) |
tp->pwrmgmt_thresh;
else
val |= PCIE_PWR_MGMT_L1_THRESH_MSK;
tw32(PCIE_PWR_MGMT_THRESH, val);
}
return err;
}
/* tp->lock must be held */
static u64 tg3_refclk_read(struct tg3 *tp)
{
u64 stamp = tr32(TG3_EAV_REF_CLCK_LSB);
return stamp | (u64)tr32(TG3_EAV_REF_CLCK_MSB) << 32;
}
/* tp->lock must be held */
static void tg3_refclk_write(struct tg3 *tp, u64 newval)
{
u32 clock_ctl = tr32(TG3_EAV_REF_CLCK_CTL);
tw32(TG3_EAV_REF_CLCK_CTL, clock_ctl | TG3_EAV_REF_CLCK_CTL_STOP);
tw32(TG3_EAV_REF_CLCK_LSB, newval & 0xffffffff);
tw32(TG3_EAV_REF_CLCK_MSB, newval >> 32);
tw32_f(TG3_EAV_REF_CLCK_CTL, clock_ctl | TG3_EAV_REF_CLCK_CTL_RESUME);
}
static inline void tg3_full_lock(struct tg3 *tp, int irq_sync);
static inline void tg3_full_unlock(struct tg3 *tp);
static int tg3_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info)
{
struct tg3 *tp = netdev_priv(dev);
info->so_timestamping = SOF_TIMESTAMPING_TX_SOFTWARE |
SOF_TIMESTAMPING_RX_SOFTWARE |
SOF_TIMESTAMPING_SOFTWARE;
if (tg3_flag(tp, PTP_CAPABLE)) {
info->so_timestamping |= SOF_TIMESTAMPING_TX_HARDWARE |
SOF_TIMESTAMPING_RX_HARDWARE |
SOF_TIMESTAMPING_RAW_HARDWARE;
}
if (tp->ptp_clock)
info->phc_index = ptp_clock_index(tp->ptp_clock);
else
info->phc_index = -1;
info->tx_types = (1 << HWTSTAMP_TX_OFF) | (1 << HWTSTAMP_TX_ON);
info->rx_filters = (1 << HWTSTAMP_FILTER_NONE) |
(1 << HWTSTAMP_FILTER_PTP_V1_L4_EVENT) |
(1 << HWTSTAMP_FILTER_PTP_V2_L2_EVENT) |
(1 << HWTSTAMP_FILTER_PTP_V2_L4_EVENT);
return 0;
}
static int tg3_ptp_adjfreq(struct ptp_clock_info *ptp, s32 ppb)
{
struct tg3 *tp = container_of(ptp, struct tg3, ptp_info);
bool neg_adj = false;
u32 correction = 0;
if (ppb < 0) {
neg_adj = true;
ppb = -ppb;
}
/* Frequency adjustment is performed using hardware with a 24 bit
* accumulator and a programmable correction value. On each clk, the
* correction value gets added to the accumulator and when it
* overflows, the time counter is incremented/decremented.
*
* So conversion from ppb to correction value is
* ppb * (1 << 24) / 1000000000
*/
correction = div_u64((u64)ppb * (1 << 24), 1000000000ULL) &
TG3_EAV_REF_CLK_CORRECT_MASK;
tg3_full_lock(tp, 0);
if (correction)
tw32(TG3_EAV_REF_CLK_CORRECT_CTL,
TG3_EAV_REF_CLK_CORRECT_EN |
(neg_adj ? TG3_EAV_REF_CLK_CORRECT_NEG : 0) | correction);
else
tw32(TG3_EAV_REF_CLK_CORRECT_CTL, 0);
tg3_full_unlock(tp);
return 0;
}
static int tg3_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta)
{
struct tg3 *tp = container_of(ptp, struct tg3, ptp_info);
tg3_full_lock(tp, 0);
tp->ptp_adjust += delta;
tg3_full_unlock(tp);
return 0;
}
static int tg3_ptp_gettime(struct ptp_clock_info *ptp, struct timespec *ts)
{
u64 ns;
u32 remainder;
struct tg3 *tp = container_of(ptp, struct tg3, ptp_info);
tg3_full_lock(tp, 0);
ns = tg3_refclk_read(tp);
ns += tp->ptp_adjust;
tg3_full_unlock(tp);
ts->tv_sec = div_u64_rem(ns, 1000000000, &remainder);
ts->tv_nsec = remainder;
return 0;
}
static int tg3_ptp_settime(struct ptp_clock_info *ptp,
const struct timespec *ts)
{
u64 ns;
struct tg3 *tp = container_of(ptp, struct tg3, ptp_info);
ns = timespec_to_ns(ts);
tg3_full_lock(tp, 0);
tg3_refclk_write(tp, ns);
tp->ptp_adjust = 0;
tg3_full_unlock(tp);
return 0;
}
static int tg3_ptp_enable(struct ptp_clock_info *ptp,
struct ptp_clock_request *rq, int on)
{
struct tg3 *tp = container_of(ptp, struct tg3, ptp_info);
u32 clock_ctl;
int rval = 0;
switch (rq->type) {
case PTP_CLK_REQ_PEROUT:
if (rq->perout.index != 0)
return -EINVAL;
tg3_full_lock(tp, 0);
clock_ctl = tr32(TG3_EAV_REF_CLCK_CTL);
clock_ctl &= ~TG3_EAV_CTL_TSYNC_GPIO_MASK;
if (on) {
u64 nsec;
nsec = rq->perout.start.sec * 1000000000ULL +
rq->perout.start.nsec;
if (rq->perout.period.sec || rq->perout.period.nsec) {
netdev_warn(tp->dev,
"Device supports only a one-shot timesync output, period must be 0\n");
rval = -EINVAL;
goto err_out;
}
if (nsec & (1ULL << 63)) {
netdev_warn(tp->dev,
"Start value (nsec) is over limit. Maximum size of start is only 63 bits\n");
rval = -EINVAL;
goto err_out;
}
tw32(TG3_EAV_WATCHDOG0_LSB, (nsec & 0xffffffff));
tw32(TG3_EAV_WATCHDOG0_MSB,
TG3_EAV_WATCHDOG0_EN |
((nsec >> 32) & TG3_EAV_WATCHDOG_MSB_MASK));
tw32(TG3_EAV_REF_CLCK_CTL,
clock_ctl | TG3_EAV_CTL_TSYNC_WDOG0);
} else {
tw32(TG3_EAV_WATCHDOG0_MSB, 0);
tw32(TG3_EAV_REF_CLCK_CTL, clock_ctl);
}
err_out:
tg3_full_unlock(tp);
return rval;
default:
break;
}
return -EOPNOTSUPP;
}
static const struct ptp_clock_info tg3_ptp_caps = {
.owner = THIS_MODULE,
.name = "tg3 clock",
.max_adj = 250000000,
.n_alarm = 0,
.n_ext_ts = 0,
.n_per_out = 1,
.n_pins = 0,
.pps = 0,
.adjfreq = tg3_ptp_adjfreq,
.adjtime = tg3_ptp_adjtime,
.gettime = tg3_ptp_gettime,
.settime = tg3_ptp_settime,
.enable = tg3_ptp_enable,
};
static void tg3_hwclock_to_timestamp(struct tg3 *tp, u64 hwclock,
struct skb_shared_hwtstamps *timestamp)
{
memset(timestamp, 0, sizeof(struct skb_shared_hwtstamps));
timestamp->hwtstamp = ns_to_ktime((hwclock & TG3_TSTAMP_MASK) +
tp->ptp_adjust);
}
/* tp->lock must be held */
static void tg3_ptp_init(struct tg3 *tp)
{
if (!tg3_flag(tp, PTP_CAPABLE))
return;
/* Initialize the hardware clock to the system time. */
tg3_refclk_write(tp, ktime_to_ns(ktime_get_real()));
tp->ptp_adjust = 0;
tp->ptp_info = tg3_ptp_caps;
}
/* tp->lock must be held */
static void tg3_ptp_resume(struct tg3 *tp)
{
if (!tg3_flag(tp, PTP_CAPABLE))
return;
tg3_refclk_write(tp, ktime_to_ns(ktime_get_real()) + tp->ptp_adjust);
tp->ptp_adjust = 0;
}
static void tg3_ptp_fini(struct tg3 *tp)
{
if (!tg3_flag(tp, PTP_CAPABLE) || !tp->ptp_clock)
return;
ptp_clock_unregister(tp->ptp_clock);
tp->ptp_clock = NULL;
tp->ptp_adjust = 0;
}
static inline int tg3_irq_sync(struct tg3 *tp)
{
return tp->irq_sync;
}
static inline void tg3_rd32_loop(struct tg3 *tp, u32 *dst, u32 off, u32 len)
{
int i;
dst = (u32 *)((u8 *)dst + off);
for (i = 0; i < len; i += sizeof(u32))
*dst++ = tr32(off + i);
}
static void tg3_dump_legacy_regs(struct tg3 *tp, u32 *regs)
{
tg3_rd32_loop(tp, regs, TG3PCI_VENDOR, 0xb0);
tg3_rd32_loop(tp, regs, MAILBOX_INTERRUPT_0, 0x200);
tg3_rd32_loop(tp, regs, MAC_MODE, 0x4f0);
tg3_rd32_loop(tp, regs, SNDDATAI_MODE, 0xe0);
tg3_rd32_loop(tp, regs, SNDDATAC_MODE, 0x04);
tg3_rd32_loop(tp, regs, SNDBDS_MODE, 0x80);
tg3_rd32_loop(tp, regs, SNDBDI_MODE, 0x48);
tg3_rd32_loop(tp, regs, SNDBDC_MODE, 0x04);
tg3_rd32_loop(tp, regs, RCVLPC_MODE, 0x20);
tg3_rd32_loop(tp, regs, RCVLPC_SELLST_BASE, 0x15c);
tg3_rd32_loop(tp, regs, RCVDBDI_MODE, 0x0c);
tg3_rd32_loop(tp, regs, RCVDBDI_JUMBO_BD, 0x3c);
tg3_rd32_loop(tp, regs, RCVDBDI_BD_PROD_IDX_0, 0x44);
tg3_rd32_loop(tp, regs, RCVDCC_MODE, 0x04);
tg3_rd32_loop(tp, regs, RCVBDI_MODE, 0x20);
tg3_rd32_loop(tp, regs, RCVCC_MODE, 0x14);
tg3_rd32_loop(tp, regs, RCVLSC_MODE, 0x08);
tg3_rd32_loop(tp, regs, MBFREE_MODE, 0x08);
tg3_rd32_loop(tp, regs, HOSTCC_MODE, 0x100);
if (tg3_flag(tp, SUPPORT_MSIX))
tg3_rd32_loop(tp, regs, HOSTCC_RXCOL_TICKS_VEC1, 0x180);
tg3_rd32_loop(tp, regs, MEMARB_MODE, 0x10);
tg3_rd32_loop(tp, regs, BUFMGR_MODE, 0x58);
tg3_rd32_loop(tp, regs, RDMAC_MODE, 0x08);
tg3_rd32_loop(tp, regs, WDMAC_MODE, 0x08);
tg3_rd32_loop(tp, regs, RX_CPU_MODE, 0x04);
tg3_rd32_loop(tp, regs, RX_CPU_STATE, 0x04);
tg3_rd32_loop(tp, regs, RX_CPU_PGMCTR, 0x04);
tg3_rd32_loop(tp, regs, RX_CPU_HWBKPT, 0x04);
if (!tg3_flag(tp, 5705_PLUS)) {
tg3_rd32_loop(tp, regs, TX_CPU_MODE, 0x04);
tg3_rd32_loop(tp, regs, TX_CPU_STATE, 0x04);
tg3_rd32_loop(tp, regs, TX_CPU_PGMCTR, 0x04);
}
tg3_rd32_loop(tp, regs, GRCMBOX_INTERRUPT_0, 0x110);
tg3_rd32_loop(tp, regs, FTQ_RESET, 0x120);
tg3_rd32_loop(tp, regs, MSGINT_MODE, 0x0c);
tg3_rd32_loop(tp, regs, DMAC_MODE, 0x04);
tg3_rd32_loop(tp, regs, GRC_MODE, 0x4c);
if (tg3_flag(tp, NVRAM))
tg3_rd32_loop(tp, regs, NVRAM_CMD, 0x24);
}
static void tg3_dump_state(struct tg3 *tp)
{
int i;
u32 *regs;
regs = kzalloc(TG3_REG_BLK_SIZE, GFP_ATOMIC);
if (!regs)
return;
if (tg3_flag(tp, PCI_EXPRESS)) {
/* Read up to but not including private PCI registers */
for (i = 0; i < TG3_PCIE_TLDLPL_PORT; i += sizeof(u32))
regs[i / sizeof(u32)] = tr32(i);
} else
tg3_dump_legacy_regs(tp, regs);
for (i = 0; i < TG3_REG_BLK_SIZE / sizeof(u32); i += 4) {
if (!regs[i + 0] && !regs[i + 1] &&
!regs[i + 2] && !regs[i + 3])
continue;
netdev_err(tp->dev, "0x%08x: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
i * 4,
regs[i + 0], regs[i + 1], regs[i + 2], regs[i + 3]);
}
kfree(regs);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
/* SW status block */
netdev_err(tp->dev,
"%d: Host status block [%08x:%08x:(%04x:%04x:%04x):(%04x:%04x)]\n",
i,
tnapi->hw_status->status,
tnapi->hw_status->status_tag,
tnapi->hw_status->rx_jumbo_consumer,
tnapi->hw_status->rx_consumer,
tnapi->hw_status->rx_mini_consumer,
tnapi->hw_status->idx[0].rx_producer,
tnapi->hw_status->idx[0].tx_consumer);
netdev_err(tp->dev,
"%d: NAPI info [%08x:%08x:(%04x:%04x:%04x):%04x:(%04x:%04x:%04x:%04x)]\n",
i,
tnapi->last_tag, tnapi->last_irq_tag,
tnapi->tx_prod, tnapi->tx_cons, tnapi->tx_pending,
tnapi->rx_rcb_ptr,
tnapi->prodring.rx_std_prod_idx,
tnapi->prodring.rx_std_cons_idx,
tnapi->prodring.rx_jmb_prod_idx,
tnapi->prodring.rx_jmb_cons_idx);
}
}
/* This is called whenever we suspect that the system chipset is re-
* ordering the sequence of MMIO to the tx send mailbox. The symptom
* is bogus tx completions. We try to recover by setting the
* TG3_FLAG_MBOX_WRITE_REORDER flag and resetting the chip later
* in the workqueue.
*/
static void tg3_tx_recover(struct tg3 *tp)
{
BUG_ON(tg3_flag(tp, MBOX_WRITE_REORDER) ||
tp->write32_tx_mbox == tg3_write_indirect_mbox);
netdev_warn(tp->dev,
"The system may be re-ordering memory-mapped I/O "
"cycles to the network device, attempting to recover. "
"Please report the problem to the driver maintainer "
"and include system chipset information.\n");
tg3_flag_set(tp, TX_RECOVERY_PENDING);
}
static inline u32 tg3_tx_avail(struct tg3_napi *tnapi)
{
/* Tell compiler to fetch tx indices from memory. */
barrier();
return tnapi->tx_pending -
((tnapi->tx_prod - tnapi->tx_cons) & (TG3_TX_RING_SIZE - 1));
}
/* Tigon3 never reports partial packet sends. So we do not
* need special logic to handle SKBs that have not had all
* of their frags sent yet, like SunGEM does.
*/
static void tg3_tx(struct tg3_napi *tnapi)
{
struct tg3 *tp = tnapi->tp;
u32 hw_idx = tnapi->hw_status->idx[0].tx_consumer;
u32 sw_idx = tnapi->tx_cons;
struct netdev_queue *txq;
int index = tnapi - tp->napi;
unsigned int pkts_compl = 0, bytes_compl = 0;
if (tg3_flag(tp, ENABLE_TSS))
index--;
txq = netdev_get_tx_queue(tp->dev, index);
while (sw_idx != hw_idx) {
struct tg3_tx_ring_info *ri = &tnapi->tx_buffers[sw_idx];
struct sk_buff *skb = ri->skb;
int i, tx_bug = 0;
if (unlikely(skb == NULL)) {
tg3_tx_recover(tp);
return;
}
if (tnapi->tx_ring[sw_idx].len_flags & TXD_FLAG_HWTSTAMP) {
struct skb_shared_hwtstamps timestamp;
u64 hwclock = tr32(TG3_TX_TSTAMP_LSB);
hwclock |= (u64)tr32(TG3_TX_TSTAMP_MSB) << 32;
tg3_hwclock_to_timestamp(tp, hwclock, ×tamp);
skb_tstamp_tx(skb, ×tamp);
}
pci_unmap_single(tp->pdev,
dma_unmap_addr(ri, mapping),
skb_headlen(skb),
PCI_DMA_TODEVICE);
ri->skb = NULL;
while (ri->fragmented) {
ri->fragmented = false;
sw_idx = NEXT_TX(sw_idx);
ri = &tnapi->tx_buffers[sw_idx];
}
sw_idx = NEXT_TX(sw_idx);
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
ri = &tnapi->tx_buffers[sw_idx];
if (unlikely(ri->skb != NULL || sw_idx == hw_idx))
tx_bug = 1;
pci_unmap_page(tp->pdev,
dma_unmap_addr(ri, mapping),
skb_frag_size(&skb_shinfo(skb)->frags[i]),
PCI_DMA_TODEVICE);
while (ri->fragmented) {
ri->fragmented = false;
sw_idx = NEXT_TX(sw_idx);
ri = &tnapi->tx_buffers[sw_idx];
}
sw_idx = NEXT_TX(sw_idx);
}
pkts_compl++;
bytes_compl += skb->len;
dev_kfree_skb_any(skb);
if (unlikely(tx_bug)) {
tg3_tx_recover(tp);
return;
}
}
netdev_tx_completed_queue(txq, pkts_compl, bytes_compl);
tnapi->tx_cons = sw_idx;
/* Need to make the tx_cons update visible to tg3_start_xmit()
* before checking for netif_queue_stopped(). Without the
* memory barrier, there is a small possibility that tg3_start_xmit()
* will miss it and cause the queue to be stopped forever.
*/
smp_mb();
if (unlikely(netif_tx_queue_stopped(txq) &&
(tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi)))) {
__netif_tx_lock(txq, smp_processor_id());
if (netif_tx_queue_stopped(txq) &&
(tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi)))
netif_tx_wake_queue(txq);
__netif_tx_unlock(txq);
}
}
static void tg3_frag_free(bool is_frag, void *data)
{
if (is_frag)
put_page(virt_to_head_page(data));
else
kfree(data);
}
static void tg3_rx_data_free(struct tg3 *tp, struct ring_info *ri, u32 map_sz)
{
unsigned int skb_size = SKB_DATA_ALIGN(map_sz + TG3_RX_OFFSET(tp)) +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
if (!ri->data)
return;
pci_unmap_single(tp->pdev, dma_unmap_addr(ri, mapping),
map_sz, PCI_DMA_FROMDEVICE);
tg3_frag_free(skb_size <= PAGE_SIZE, ri->data);
ri->data = NULL;
}
/* Returns size of skb allocated or < 0 on error.
*
* We only need to fill in the address because the other members
* of the RX descriptor are invariant, see tg3_init_rings.
*
* Note the purposeful assymetry of cpu vs. chip accesses. For
* posting buffers we only dirty the first cache line of the RX
* descriptor (containing the address). Whereas for the RX status
* buffers the cpu only reads the last cacheline of the RX descriptor
* (to fetch the error flags, vlan tag, checksum, and opaque cookie).
*/
static int tg3_alloc_rx_data(struct tg3 *tp, struct tg3_rx_prodring_set *tpr,
u32 opaque_key, u32 dest_idx_unmasked,
unsigned int *frag_size)
{
struct tg3_rx_buffer_desc *desc;
struct ring_info *map;
u8 *data;
dma_addr_t mapping;
int skb_size, data_size, dest_idx;
switch (opaque_key) {
case RXD_OPAQUE_RING_STD:
dest_idx = dest_idx_unmasked & tp->rx_std_ring_mask;
desc = &tpr->rx_std[dest_idx];
map = &tpr->rx_std_buffers[dest_idx];
data_size = tp->rx_pkt_map_sz;
break;
case RXD_OPAQUE_RING_JUMBO:
dest_idx = dest_idx_unmasked & tp->rx_jmb_ring_mask;
desc = &tpr->rx_jmb[dest_idx].std;
map = &tpr->rx_jmb_buffers[dest_idx];
data_size = TG3_RX_JMB_MAP_SZ;
break;
default:
return -EINVAL;
}
/* Do not overwrite any of the map or rp information
* until we are sure we can commit to a new buffer.
*
* Callers depend upon this behavior and assume that
* we leave everything unchanged if we fail.
*/
skb_size = SKB_DATA_ALIGN(data_size + TG3_RX_OFFSET(tp)) +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
if (skb_size <= PAGE_SIZE) {
data = netdev_alloc_frag(skb_size);
*frag_size = skb_size;
} else {
data = kmalloc(skb_size, GFP_ATOMIC);
*frag_size = 0;
}
if (!data)
return -ENOMEM;
mapping = pci_map_single(tp->pdev,
data + TG3_RX_OFFSET(tp),
data_size,
PCI_DMA_FROMDEVICE);
if (unlikely(pci_dma_mapping_error(tp->pdev, mapping))) {
tg3_frag_free(skb_size <= PAGE_SIZE, data);
return -EIO;
}
map->data = data;
dma_unmap_addr_set(map, mapping, mapping);
desc->addr_hi = ((u64)mapping >> 32);
desc->addr_lo = ((u64)mapping & 0xffffffff);
return data_size;
}
/* We only need to move over in the address because the other
* members of the RX descriptor are invariant. See notes above
* tg3_alloc_rx_data for full details.
*/
static void tg3_recycle_rx(struct tg3_napi *tnapi,
struct tg3_rx_prodring_set *dpr,
u32 opaque_key, int src_idx,
u32 dest_idx_unmasked)
{
struct tg3 *tp = tnapi->tp;
struct tg3_rx_buffer_desc *src_desc, *dest_desc;
struct ring_info *src_map, *dest_map;
struct tg3_rx_prodring_set *spr = &tp->napi[0].prodring;
int dest_idx;
switch (opaque_key) {
case RXD_OPAQUE_RING_STD:
dest_idx = dest_idx_unmasked & tp->rx_std_ring_mask;
dest_desc = &dpr->rx_std[dest_idx];
dest_map = &dpr->rx_std_buffers[dest_idx];
src_desc = &spr->rx_std[src_idx];
src_map = &spr->rx_std_buffers[src_idx];
break;
case RXD_OPAQUE_RING_JUMBO:
dest_idx = dest_idx_unmasked & tp->rx_jmb_ring_mask;
dest_desc = &dpr->rx_jmb[dest_idx].std;
dest_map = &dpr->rx_jmb_buffers[dest_idx];
src_desc = &spr->rx_jmb[src_idx].std;
src_map = &spr->rx_jmb_buffers[src_idx];
break;
default:
return;
}
dest_map->data = src_map->data;
dma_unmap_addr_set(dest_map, mapping,
dma_unmap_addr(src_map, mapping));
dest_desc->addr_hi = src_desc->addr_hi;
dest_desc->addr_lo = src_desc->addr_lo;
/* Ensure that the update to the skb happens after the physical
* addresses have been transferred to the new BD location.
*/
smp_wmb();
src_map->data = NULL;
}
/* The RX ring scheme is composed of multiple rings which post fresh
* buffers to the chip, and one special ring the chip uses to report
* status back to the host.
*
* The special ring reports the status of received packets to the
* host. The chip does not write into the original descriptor the
* RX buffer was obtained from. The chip simply takes the original
* descriptor as provided by the host, updates the status and length
* field, then writes this into the next status ring entry.
*
* Each ring the host uses to post buffers to the chip is described
* by a TG3_BDINFO entry in the chips SRAM area. When a packet arrives,
* it is first placed into the on-chip ram. When the packet's length
* is known, it walks down the TG3_BDINFO entries to select the ring.
* Each TG3_BDINFO specifies a MAXLEN field and the first TG3_BDINFO
* which is within the range of the new packet's length is chosen.
*
* The "separate ring for rx status" scheme may sound queer, but it makes
* sense from a cache coherency perspective. If only the host writes
* to the buffer post rings, and only the chip writes to the rx status
* rings, then cache lines never move beyond shared-modified state.
* If both the host and chip were to write into the same ring, cache line
* eviction could occur since both entities want it in an exclusive state.
*/
static int tg3_rx(struct tg3_napi *tnapi, int budget)
{
struct tg3 *tp = tnapi->tp;
u32 work_mask, rx_std_posted = 0;
u32 std_prod_idx, jmb_prod_idx;
u32 sw_idx = tnapi->rx_rcb_ptr;
u16 hw_idx;
int received;
struct tg3_rx_prodring_set *tpr = &tnapi->prodring;
hw_idx = *(tnapi->rx_rcb_prod_idx);
/*
* We need to order the read of hw_idx and the read of
* the opaque cookie.
*/
rmb();
work_mask = 0;
received = 0;
std_prod_idx = tpr->rx_std_prod_idx;
jmb_prod_idx = tpr->rx_jmb_prod_idx;
while (sw_idx != hw_idx && budget > 0) {
struct ring_info *ri;
struct tg3_rx_buffer_desc *desc = &tnapi->rx_rcb[sw_idx];
unsigned int len;
struct sk_buff *skb;
dma_addr_t dma_addr;
u32 opaque_key, desc_idx, *post_ptr;
u8 *data;
u64 tstamp = 0;
desc_idx = desc->opaque & RXD_OPAQUE_INDEX_MASK;
opaque_key = desc->opaque & RXD_OPAQUE_RING_MASK;
if (opaque_key == RXD_OPAQUE_RING_STD) {
ri = &tp->napi[0].prodring.rx_std_buffers[desc_idx];
dma_addr = dma_unmap_addr(ri, mapping);
data = ri->data;
post_ptr = &std_prod_idx;
rx_std_posted++;
} else if (opaque_key == RXD_OPAQUE_RING_JUMBO) {
ri = &tp->napi[0].prodring.rx_jmb_buffers[desc_idx];
dma_addr = dma_unmap_addr(ri, mapping);
data = ri->data;
post_ptr = &jmb_prod_idx;
} else
goto next_pkt_nopost;
work_mask |= opaque_key;
if (desc->err_vlan & RXD_ERR_MASK) {
drop_it:
tg3_recycle_rx(tnapi, tpr, opaque_key,
desc_idx, *post_ptr);
drop_it_no_recycle:
/* Other statistics kept track of by card. */
tp->rx_dropped++;
goto next_pkt;
}
prefetch(data + TG3_RX_OFFSET(tp));
len = ((desc->idx_len & RXD_LEN_MASK) >> RXD_LEN_SHIFT) -
ETH_FCS_LEN;
if ((desc->type_flags & RXD_FLAG_PTPSTAT_MASK) ==
RXD_FLAG_PTPSTAT_PTPV1 ||
(desc->type_flags & RXD_FLAG_PTPSTAT_MASK) ==
RXD_FLAG_PTPSTAT_PTPV2) {
tstamp = tr32(TG3_RX_TSTAMP_LSB);
tstamp |= (u64)tr32(TG3_RX_TSTAMP_MSB) << 32;
}
if (len > TG3_RX_COPY_THRESH(tp)) {
int skb_size;
unsigned int frag_size;
skb_size = tg3_alloc_rx_data(tp, tpr, opaque_key,
*post_ptr, &frag_size);
if (skb_size < 0)
goto drop_it;
pci_unmap_single(tp->pdev, dma_addr, skb_size,
PCI_DMA_FROMDEVICE);
/* Ensure that the update to the data happens
* after the usage of the old DMA mapping.
*/
smp_wmb();
ri->data = NULL;
skb = build_skb(data, frag_size);
if (!skb) {
tg3_frag_free(frag_size != 0, data);
goto drop_it_no_recycle;
}
skb_reserve(skb, TG3_RX_OFFSET(tp));
} else {
tg3_recycle_rx(tnapi, tpr, opaque_key,
desc_idx, *post_ptr);
skb = netdev_alloc_skb(tp->dev,
len + TG3_RAW_IP_ALIGN);
if (skb == NULL)
goto drop_it_no_recycle;
skb_reserve(skb, TG3_RAW_IP_ALIGN);
pci_dma_sync_single_for_cpu(tp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE);
memcpy(skb->data,
data + TG3_RX_OFFSET(tp),
len);
pci_dma_sync_single_for_device(tp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE);
}
skb_put(skb, len);
if (tstamp)
tg3_hwclock_to_timestamp(tp, tstamp,
skb_hwtstamps(skb));
if ((tp->dev->features & NETIF_F_RXCSUM) &&
(desc->type_flags & RXD_FLAG_TCPUDP_CSUM) &&
(((desc->ip_tcp_csum & RXD_TCPCSUM_MASK)
>> RXD_TCPCSUM_SHIFT) == 0xffff))
skb->ip_summed = CHECKSUM_UNNECESSARY;
else
skb_checksum_none_assert(skb);
skb->protocol = eth_type_trans(skb, tp->dev);
if (len > (tp->dev->mtu + ETH_HLEN) &&
skb->protocol != htons(ETH_P_8021Q)) {
dev_kfree_skb_any(skb);
goto drop_it_no_recycle;
}
if (desc->type_flags & RXD_FLAG_VLAN &&
!(tp->rx_mode & RX_MODE_KEEP_VLAN_TAG))
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q),
desc->err_vlan & RXD_VLAN_MASK);
napi_gro_receive(&tnapi->napi, skb);
received++;
budget--;
next_pkt:
(*post_ptr)++;
if (unlikely(rx_std_posted >= tp->rx_std_max_post)) {
tpr->rx_std_prod_idx = std_prod_idx &
tp->rx_std_ring_mask;
tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG,
tpr->rx_std_prod_idx);
work_mask &= ~RXD_OPAQUE_RING_STD;
rx_std_posted = 0;
}
next_pkt_nopost:
sw_idx++;
sw_idx &= tp->rx_ret_ring_mask;
/* Refresh hw_idx to see if there is new work */
if (sw_idx == hw_idx) {
hw_idx = *(tnapi->rx_rcb_prod_idx);
rmb();
}
}
/* ACK the status ring. */
tnapi->rx_rcb_ptr = sw_idx;
tw32_rx_mbox(tnapi->consmbox, sw_idx);
/* Refill RX ring(s). */
if (!tg3_flag(tp, ENABLE_RSS)) {
/* Sync BD data before updating mailbox */
wmb();
if (work_mask & RXD_OPAQUE_RING_STD) {
tpr->rx_std_prod_idx = std_prod_idx &
tp->rx_std_ring_mask;
tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG,
tpr->rx_std_prod_idx);
}
if (work_mask & RXD_OPAQUE_RING_JUMBO) {
tpr->rx_jmb_prod_idx = jmb_prod_idx &
tp->rx_jmb_ring_mask;
tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG,
tpr->rx_jmb_prod_idx);
}
mmiowb();
} else if (work_mask) {
/* rx_std_buffers[] and rx_jmb_buffers[] entries must be
* updated before the producer indices can be updated.
*/
smp_wmb();
tpr->rx_std_prod_idx = std_prod_idx & tp->rx_std_ring_mask;
tpr->rx_jmb_prod_idx = jmb_prod_idx & tp->rx_jmb_ring_mask;
if (tnapi != &tp->napi[1]) {
tp->rx_refill = true;
napi_schedule(&tp->napi[1].napi);
}
}
return received;
}
static void tg3_poll_link(struct tg3 *tp)
{
/* handle link change and other phy events */
if (!(tg3_flag(tp, USE_LINKCHG_REG) || tg3_flag(tp, POLL_SERDES))) {
struct tg3_hw_status *sblk = tp->napi[0].hw_status;
if (sblk->status & SD_STATUS_LINK_CHG) {
sblk->status = SD_STATUS_UPDATED |
(sblk->status & ~SD_STATUS_LINK_CHG);
spin_lock(&tp->lock);
if (tg3_flag(tp, USE_PHYLIB)) {
tw32_f(MAC_STATUS,
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_MI_COMPLETION |
MAC_STATUS_LNKSTATE_CHANGED));
udelay(40);
} else
tg3_setup_phy(tp, false);
spin_unlock(&tp->lock);
}
}
}
static int tg3_rx_prodring_xfer(struct tg3 *tp,
struct tg3_rx_prodring_set *dpr,
struct tg3_rx_prodring_set *spr)
{
u32 si, di, cpycnt, src_prod_idx;
int i, err = 0;
while (1) {
src_prod_idx = spr->rx_std_prod_idx;
/* Make sure updates to the rx_std_buffers[] entries and the
* standard producer index are seen in the correct order.
*/
smp_rmb();
if (spr->rx_std_cons_idx == src_prod_idx)
break;
if (spr->rx_std_cons_idx < src_prod_idx)
cpycnt = src_prod_idx - spr->rx_std_cons_idx;
else
cpycnt = tp->rx_std_ring_mask + 1 -
spr->rx_std_cons_idx;
cpycnt = min(cpycnt,
tp->rx_std_ring_mask + 1 - dpr->rx_std_prod_idx);
si = spr->rx_std_cons_idx;
di = dpr->rx_std_prod_idx;
for (i = di; i < di + cpycnt; i++) {
if (dpr->rx_std_buffers[i].data) {
cpycnt = i - di;
err = -ENOSPC;
break;
}
}
if (!cpycnt)
break;
/* Ensure that updates to the rx_std_buffers ring and the
* shadowed hardware producer ring from tg3_recycle_skb() are
* ordered correctly WRT the skb check above.
*/
smp_rmb();
memcpy(&dpr->rx_std_buffers[di],
&spr->rx_std_buffers[si],
cpycnt * sizeof(struct ring_info));
for (i = 0; i < cpycnt; i++, di++, si++) {
struct tg3_rx_buffer_desc *sbd, *dbd;
sbd = &spr->rx_std[si];
dbd = &dpr->rx_std[di];
dbd->addr_hi = sbd->addr_hi;
dbd->addr_lo = sbd->addr_lo;
}
spr->rx_std_cons_idx = (spr->rx_std_cons_idx + cpycnt) &
tp->rx_std_ring_mask;
dpr->rx_std_prod_idx = (dpr->rx_std_prod_idx + cpycnt) &
tp->rx_std_ring_mask;
}
while (1) {
src_prod_idx = spr->rx_jmb_prod_idx;
/* Make sure updates to the rx_jmb_buffers[] entries and
* the jumbo producer index are seen in the correct order.
*/
smp_rmb();
if (spr->rx_jmb_cons_idx == src_prod_idx)
break;
if (spr->rx_jmb_cons_idx < src_prod_idx)
cpycnt = src_prod_idx - spr->rx_jmb_cons_idx;
else
cpycnt = tp->rx_jmb_ring_mask + 1 -
spr->rx_jmb_cons_idx;
cpycnt = min(cpycnt,
tp->rx_jmb_ring_mask + 1 - dpr->rx_jmb_prod_idx);
si = spr->rx_jmb_cons_idx;
di = dpr->rx_jmb_prod_idx;
for (i = di; i < di + cpycnt; i++) {
if (dpr->rx_jmb_buffers[i].data) {
cpycnt = i - di;
err = -ENOSPC;
break;
}
}
if (!cpycnt)
break;
/* Ensure that updates to the rx_jmb_buffers ring and the
* shadowed hardware producer ring from tg3_recycle_skb() are
* ordered correctly WRT the skb check above.
*/
smp_rmb();
memcpy(&dpr->rx_jmb_buffers[di],
&spr->rx_jmb_buffers[si],
cpycnt * sizeof(struct ring_info));
for (i = 0; i < cpycnt; i++, di++, si++) {
struct tg3_rx_buffer_desc *sbd, *dbd;
sbd = &spr->rx_jmb[si].std;
dbd = &dpr->rx_jmb[di].std;
dbd->addr_hi = sbd->addr_hi;
dbd->addr_lo = sbd->addr_lo;
}
spr->rx_jmb_cons_idx = (spr->rx_jmb_cons_idx + cpycnt) &
tp->rx_jmb_ring_mask;
dpr->rx_jmb_prod_idx = (dpr->rx_jmb_prod_idx + cpycnt) &
tp->rx_jmb_ring_mask;
}
return err;
}
static int tg3_poll_work(struct tg3_napi *tnapi, int work_done, int budget)
{
struct tg3 *tp = tnapi->tp;
/* run TX completion thread */
if (tnapi->hw_status->idx[0].tx_consumer != tnapi->tx_cons) {
tg3_tx(tnapi);
if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING)))
return work_done;
}
if (!tnapi->rx_rcb_prod_idx)
return work_done;
/* run RX thread, within the bounds set by NAPI.
* All RX "locking" is done by ensuring outside
* code synchronizes with tg3->napi.poll()
*/
if (*(tnapi->rx_rcb_prod_idx) != tnapi->rx_rcb_ptr)
work_done += tg3_rx(tnapi, budget - work_done);
if (tg3_flag(tp, ENABLE_RSS) && tnapi == &tp->napi[1]) {
struct tg3_rx_prodring_set *dpr = &tp->napi[0].prodring;
int i, err = 0;
u32 std_prod_idx = dpr->rx_std_prod_idx;
u32 jmb_prod_idx = dpr->rx_jmb_prod_idx;
tp->rx_refill = false;
for (i = 1; i <= tp->rxq_cnt; i++)
err |= tg3_rx_prodring_xfer(tp, dpr,
&tp->napi[i].prodring);
wmb();
if (std_prod_idx != dpr->rx_std_prod_idx)
tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG,
dpr->rx_std_prod_idx);
if (jmb_prod_idx != dpr->rx_jmb_prod_idx)
tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG,
dpr->rx_jmb_prod_idx);
mmiowb();
if (err)
tw32_f(HOSTCC_MODE, tp->coal_now);
}
return work_done;
}
static inline void tg3_reset_task_schedule(struct tg3 *tp)
{
if (!test_and_set_bit(TG3_FLAG_RESET_TASK_PENDING, tp->tg3_flags))
schedule_work(&tp->reset_task);
}
static inline void tg3_reset_task_cancel(struct tg3 *tp)
{
cancel_work_sync(&tp->reset_task);
tg3_flag_clear(tp, RESET_TASK_PENDING);
tg3_flag_clear(tp, TX_RECOVERY_PENDING);
}
static int tg3_poll_msix(struct napi_struct *napi, int budget)
{
struct tg3_napi *tnapi = container_of(napi, struct tg3_napi, napi);
struct tg3 *tp = tnapi->tp;
int work_done = 0;
struct tg3_hw_status *sblk = tnapi->hw_status;
while (1) {
work_done = tg3_poll_work(tnapi, work_done, budget);
if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING)))
goto tx_recovery;
if (unlikely(work_done >= budget))
break;
/* tp->last_tag is used in tg3_int_reenable() below
* to tell the hw how much work has been processed,
* so we must read it before checking for more work.
*/
tnapi->last_tag = sblk->status_tag;
tnapi->last_irq_tag = tnapi->last_tag;
rmb();
/* check for RX/TX work to do */
if (likely(sblk->idx[0].tx_consumer == tnapi->tx_cons &&
*(tnapi->rx_rcb_prod_idx) == tnapi->rx_rcb_ptr)) {
/* This test here is not race free, but will reduce
* the number of interrupts by looping again.
*/
if (tnapi == &tp->napi[1] && tp->rx_refill)
continue;
napi_complete(napi);
/* Reenable interrupts. */
tw32_mailbox(tnapi->int_mbox, tnapi->last_tag << 24);
/* This test here is synchronized by napi_schedule()
* and napi_complete() to close the race condition.
*/
if (unlikely(tnapi == &tp->napi[1] && tp->rx_refill)) {
tw32(HOSTCC_MODE, tp->coalesce_mode |
HOSTCC_MODE_ENABLE |
tnapi->coal_now);
}
mmiowb();
break;
}
}
return work_done;
tx_recovery:
/* work_done is guaranteed to be less than budget. */
napi_complete(napi);
tg3_reset_task_schedule(tp);
return work_done;
}
static void tg3_process_error(struct tg3 *tp)
{
u32 val;
bool real_error = false;
if (tg3_flag(tp, ERROR_PROCESSED))
return;
/* Check Flow Attention register */
val = tr32(HOSTCC_FLOW_ATTN);
if (val & ~HOSTCC_FLOW_ATTN_MBUF_LWM) {
netdev_err(tp->dev, "FLOW Attention error. Resetting chip.\n");
real_error = true;
}
if (tr32(MSGINT_STATUS) & ~MSGINT_STATUS_MSI_REQ) {
netdev_err(tp->dev, "MSI Status error. Resetting chip.\n");
real_error = true;
}
if (tr32(RDMAC_STATUS) || tr32(WDMAC_STATUS)) {
netdev_err(tp->dev, "DMA Status error. Resetting chip.\n");
real_error = true;
}
if (!real_error)
return;
tg3_dump_state(tp);
tg3_flag_set(tp, ERROR_PROCESSED);
tg3_reset_task_schedule(tp);
}
static int tg3_poll(struct napi_struct *napi, int budget)
{
struct tg3_napi *tnapi = container_of(napi, struct tg3_napi, napi);
struct tg3 *tp = tnapi->tp;
int work_done = 0;
struct tg3_hw_status *sblk = tnapi->hw_status;
while (1) {
if (sblk->status & SD_STATUS_ERROR)
tg3_process_error(tp);
tg3_poll_link(tp);
work_done = tg3_poll_work(tnapi, work_done, budget);
if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING)))
goto tx_recovery;
if (unlikely(work_done >= budget))
break;
if (tg3_flag(tp, TAGGED_STATUS)) {
/* tp->last_tag is used in tg3_int_reenable() below
* to tell the hw how much work has been processed,
* so we must read it before checking for more work.
*/
tnapi->last_tag = sblk->status_tag;
tnapi->last_irq_tag = tnapi->last_tag;
rmb();
} else
sblk->status &= ~SD_STATUS_UPDATED;
if (likely(!tg3_has_work(tnapi))) {
napi_complete(napi);
tg3_int_reenable(tnapi);
break;
}
}
return work_done;
tx_recovery:
/* work_done is guaranteed to be less than budget. */
napi_complete(napi);
tg3_reset_task_schedule(tp);
return work_done;
}
static void tg3_napi_disable(struct tg3 *tp)
{
int i;
for (i = tp->irq_cnt - 1; i >= 0; i--)
napi_disable(&tp->napi[i].napi);
}
static void tg3_napi_enable(struct tg3 *tp)
{
int i;
for (i = 0; i < tp->irq_cnt; i++)
napi_enable(&tp->napi[i].napi);
}
static void tg3_napi_init(struct tg3 *tp)
{
int i;
netif_napi_add(tp->dev, &tp->napi[0].napi, tg3_poll, 64);
for (i = 1; i < tp->irq_cnt; i++)
netif_napi_add(tp->dev, &tp->napi[i].napi, tg3_poll_msix, 64);
}
static void tg3_napi_fini(struct tg3 *tp)
{
int i;
for (i = 0; i < tp->irq_cnt; i++)
netif_napi_del(&tp->napi[i].napi);
}
static inline void tg3_netif_stop(struct tg3 *tp)
{
tp->dev->trans_start = jiffies; /* prevent tx timeout */
tg3_napi_disable(tp);
netif_carrier_off(tp->dev);
netif_tx_disable(tp->dev);
}
/* tp->lock must be held */
static inline void tg3_netif_start(struct tg3 *tp)
{
tg3_ptp_resume(tp);
/* NOTE: unconditional netif_tx_wake_all_queues is only
* appropriate so long as all callers are assured to
* have free tx slots (such as after tg3_init_hw)
*/
netif_tx_wake_all_queues(tp->dev);
if (tp->link_up)
netif_carrier_on(tp->dev);
tg3_napi_enable(tp);
tp->napi[0].hw_status->status |= SD_STATUS_UPDATED;
tg3_enable_ints(tp);
}
static void tg3_irq_quiesce(struct tg3 *tp)
{
int i;
BUG_ON(tp->irq_sync);
tp->irq_sync = 1;
smp_mb();
for (i = 0; i < tp->irq_cnt; i++)
synchronize_irq(tp->napi[i].irq_vec);
}
/* Fully shutdown all tg3 driver activity elsewhere in the system.
* If irq_sync is non-zero, then the IRQ handler must be synchronized
* with as well. Most of the time, this is not necessary except when
* shutting down the device.
*/
static inline void tg3_full_lock(struct tg3 *tp, int irq_sync)
{
spin_lock_bh(&tp->lock);
if (irq_sync)
tg3_irq_quiesce(tp);
}
static inline void tg3_full_unlock(struct tg3 *tp)
{
spin_unlock_bh(&tp->lock);
}
/* One-shot MSI handler - Chip automatically disables interrupt
* after sending MSI so driver doesn't have to do it.
*/
static irqreturn_t tg3_msi_1shot(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
prefetch(tnapi->hw_status);
if (tnapi->rx_rcb)
prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]);
if (likely(!tg3_irq_sync(tp)))
napi_schedule(&tnapi->napi);
return IRQ_HANDLED;
}
/* MSI ISR - No need to check for interrupt sharing and no need to
* flush status block and interrupt mailbox. PCI ordering rules
* guarantee that MSI will arrive after the status block.
*/
static irqreturn_t tg3_msi(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
prefetch(tnapi->hw_status);
if (tnapi->rx_rcb)
prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]);
/*
* Writing any value to intr-mbox-0 clears PCI INTA# and
* chip-internal interrupt pending events.
* Writing non-zero to intr-mbox-0 additional tells the
* NIC to stop sending us irqs, engaging "in-intr-handler"
* event coalescing.
*/
tw32_mailbox(tnapi->int_mbox, 0x00000001);
if (likely(!tg3_irq_sync(tp)))
napi_schedule(&tnapi->napi);
return IRQ_RETVAL(1);
}
static irqreturn_t tg3_interrupt(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
struct tg3_hw_status *sblk = tnapi->hw_status;
unsigned int handled = 1;
/* In INTx mode, it is possible for the interrupt to arrive at
* the CPU before the status block posted prior to the interrupt.
* Reading the PCI State register will confirm whether the
* interrupt is ours and will flush the status block.
*/
if (unlikely(!(sblk->status & SD_STATUS_UPDATED))) {
if (tg3_flag(tp, CHIP_RESETTING) ||
(tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) {
handled = 0;
goto out;
}
}
/*
* Writing any value to intr-mbox-0 clears PCI INTA# and
* chip-internal interrupt pending events.
* Writing non-zero to intr-mbox-0 additional tells the
* NIC to stop sending us irqs, engaging "in-intr-handler"
* event coalescing.
*
* Flush the mailbox to de-assert the IRQ immediately to prevent
* spurious interrupts. The flush impacts performance but
* excessive spurious interrupts can be worse in some cases.
*/
tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000001);
if (tg3_irq_sync(tp))
goto out;
sblk->status &= ~SD_STATUS_UPDATED;
if (likely(tg3_has_work(tnapi))) {
prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]);
napi_schedule(&tnapi->napi);
} else {
/* No work, shared interrupt perhaps? re-enable
* interrupts, and flush that PCI write
*/
tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW,
0x00000000);
}
out:
return IRQ_RETVAL(handled);
}
static irqreturn_t tg3_interrupt_tagged(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
struct tg3_hw_status *sblk = tnapi->hw_status;
unsigned int handled = 1;
/* In INTx mode, it is possible for the interrupt to arrive at
* the CPU before the status block posted prior to the interrupt.
* Reading the PCI State register will confirm whether the
* interrupt is ours and will flush the status block.
*/
if (unlikely(sblk->status_tag == tnapi->last_irq_tag)) {
if (tg3_flag(tp, CHIP_RESETTING) ||
(tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) {
handled = 0;
goto out;
}
}
/*
* writing any value to intr-mbox-0 clears PCI INTA# and
* chip-internal interrupt pending events.
* writing non-zero to intr-mbox-0 additional tells the
* NIC to stop sending us irqs, engaging "in-intr-handler"
* event coalescing.
*
* Flush the mailbox to de-assert the IRQ immediately to prevent
* spurious interrupts. The flush impacts performance but
* excessive spurious interrupts can be worse in some cases.
*/
tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000001);
/*
* In a shared interrupt configuration, sometimes other devices'
* interrupts will scream. We record the current status tag here
* so that the above check can report that the screaming interrupts
* are unhandled. Eventually they will be silenced.
*/
tnapi->last_irq_tag = sblk->status_tag;
if (tg3_irq_sync(tp))
goto out;
prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]);
napi_schedule(&tnapi->napi);
out:
return IRQ_RETVAL(handled);
}
/* ISR for interrupt test */
static irqreturn_t tg3_test_isr(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
struct tg3_hw_status *sblk = tnapi->hw_status;
if ((sblk->status & SD_STATUS_UPDATED) ||
!(tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) {
tg3_disable_ints(tp);
return IRQ_RETVAL(1);
}
return IRQ_RETVAL(0);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void tg3_poll_controller(struct net_device *dev)
{
int i;
struct tg3 *tp = netdev_priv(dev);
if (tg3_irq_sync(tp))
return;
for (i = 0; i < tp->irq_cnt; i++)
tg3_interrupt(tp->napi[i].irq_vec, &tp->napi[i]);
}
#endif
static void tg3_tx_timeout(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
if (netif_msg_tx_err(tp)) {
netdev_err(dev, "transmit timed out, resetting\n");
tg3_dump_state(tp);
}
tg3_reset_task_schedule(tp);
}
/* Test for DMA buffers crossing any 4GB boundaries: 4G, 8G, etc */
static inline int tg3_4g_overflow_test(dma_addr_t mapping, int len)
{
u32 base = (u32) mapping & 0xffffffff;
return base + len + 8 < base;
}
/* Test for TSO DMA buffers that cross into regions which are within MSS bytes
* of any 4GB boundaries: 4G, 8G, etc
*/
static inline int tg3_4g_tso_overflow_test(struct tg3 *tp, dma_addr_t mapping,
u32 len, u32 mss)
{
if (tg3_asic_rev(tp) == ASIC_REV_5762 && mss) {
u32 base = (u32) mapping & 0xffffffff;
return ((base + len + (mss & 0x3fff)) < base);
}
return 0;
}
/* Test for DMA addresses > 40-bit */
static inline int tg3_40bit_overflow_test(struct tg3 *tp, dma_addr_t mapping,
int len)
{
#if defined(CONFIG_HIGHMEM) && (BITS_PER_LONG == 64)
if (tg3_flag(tp, 40BIT_DMA_BUG))
return ((u64) mapping + len) > DMA_BIT_MASK(40);
return 0;
#else
return 0;
#endif
}
static inline void tg3_tx_set_bd(struct tg3_tx_buffer_desc *txbd,
dma_addr_t mapping, u32 len, u32 flags,
u32 mss, u32 vlan)
{
txbd->addr_hi = ((u64) mapping >> 32);
txbd->addr_lo = ((u64) mapping & 0xffffffff);
txbd->len_flags = (len << TXD_LEN_SHIFT) | (flags & 0x0000ffff);
txbd->vlan_tag = (mss << TXD_MSS_SHIFT) | (vlan << TXD_VLAN_TAG_SHIFT);
}
static bool tg3_tx_frag_set(struct tg3_napi *tnapi, u32 *entry, u32 *budget,
dma_addr_t map, u32 len, u32 flags,
u32 mss, u32 vlan)
{
struct tg3 *tp = tnapi->tp;
bool hwbug = false;
if (tg3_flag(tp, SHORT_DMA_BUG) && len <= 8)
hwbug = true;
if (tg3_4g_overflow_test(map, len))
hwbug = true;
if (tg3_4g_tso_overflow_test(tp, map, len, mss))
hwbug = true;
if (tg3_40bit_overflow_test(tp, map, len))
hwbug = true;
if (tp->dma_limit) {
u32 prvidx = *entry;
u32 tmp_flag = flags & ~TXD_FLAG_END;
while (len > tp->dma_limit && *budget) {
u32 frag_len = tp->dma_limit;
len -= tp->dma_limit;
/* Avoid the 8byte DMA problem */
if (len <= 8) {
len += tp->dma_limit / 2;
frag_len = tp->dma_limit / 2;
}
tnapi->tx_buffers[*entry].fragmented = true;
tg3_tx_set_bd(&tnapi->tx_ring[*entry], map,
frag_len, tmp_flag, mss, vlan);
*budget -= 1;
prvidx = *entry;
*entry = NEXT_TX(*entry);
map += frag_len;
}
if (len) {
if (*budget) {
tg3_tx_set_bd(&tnapi->tx_ring[*entry], map,
len, flags, mss, vlan);
*budget -= 1;
*entry = NEXT_TX(*entry);
} else {
hwbug = true;
tnapi->tx_buffers[prvidx].fragmented = false;
}
}
} else {
tg3_tx_set_bd(&tnapi->tx_ring[*entry], map,
len, flags, mss, vlan);
*entry = NEXT_TX(*entry);
}
return hwbug;
}
static void tg3_tx_skb_unmap(struct tg3_napi *tnapi, u32 entry, int last)
{
int i;
struct sk_buff *skb;
struct tg3_tx_ring_info *txb = &tnapi->tx_buffers[entry];
skb = txb->skb;
txb->skb = NULL;
pci_unmap_single(tnapi->tp->pdev,
dma_unmap_addr(txb, mapping),
skb_headlen(skb),
PCI_DMA_TODEVICE);
while (txb->fragmented) {
txb->fragmented = false;
entry = NEXT_TX(entry);
txb = &tnapi->tx_buffers[entry];
}
for (i = 0; i <= last; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
entry = NEXT_TX(entry);
txb = &tnapi->tx_buffers[entry];
pci_unmap_page(tnapi->tp->pdev,
dma_unmap_addr(txb, mapping),
skb_frag_size(frag), PCI_DMA_TODEVICE);
while (txb->fragmented) {
txb->fragmented = false;
entry = NEXT_TX(entry);
txb = &tnapi->tx_buffers[entry];
}
}
}
/* Workaround 4GB and 40-bit hardware DMA bugs. */
static int tigon3_dma_hwbug_workaround(struct tg3_napi *tnapi,
struct sk_buff **pskb,
u32 *entry, u32 *budget,
u32 base_flags, u32 mss, u32 vlan)
{
struct tg3 *tp = tnapi->tp;
struct sk_buff *new_skb, *skb = *pskb;
dma_addr_t new_addr = 0;
int ret = 0;
if (tg3_asic_rev(tp) != ASIC_REV_5701)
new_skb = skb_copy(skb, GFP_ATOMIC);
else {
int more_headroom = 4 - ((unsigned long)skb->data & 3);
new_skb = skb_copy_expand(skb,
skb_headroom(skb) + more_headroom,
skb_tailroom(skb), GFP_ATOMIC);
}
if (!new_skb) {
ret = -1;
} else {
/* New SKB is guaranteed to be linear. */
new_addr = pci_map_single(tp->pdev, new_skb->data, new_skb->len,
PCI_DMA_TODEVICE);
/* Make sure the mapping succeeded */
if (pci_dma_mapping_error(tp->pdev, new_addr)) {
dev_kfree_skb_any(new_skb);
ret = -1;
} else {
u32 save_entry = *entry;
base_flags |= TXD_FLAG_END;
tnapi->tx_buffers[*entry].skb = new_skb;
dma_unmap_addr_set(&tnapi->tx_buffers[*entry],
mapping, new_addr);
if (tg3_tx_frag_set(tnapi, entry, budget, new_addr,
new_skb->len, base_flags,
mss, vlan)) {
tg3_tx_skb_unmap(tnapi, save_entry, -1);
dev_kfree_skb_any(new_skb);
ret = -1;
}
}
}
dev_kfree_skb_any(skb);
*pskb = new_skb;
return ret;
}
static netdev_tx_t tg3_start_xmit(struct sk_buff *, struct net_device *);
/* Use GSO to workaround a rare TSO bug that may be triggered when the
* TSO header is greater than 80 bytes.
*/
static int tg3_tso_bug(struct tg3 *tp, struct sk_buff *skb)
{
struct sk_buff *segs, *nskb;
u32 frag_cnt_est = skb_shinfo(skb)->gso_segs * 3;
/* Estimate the number of fragments in the worst case */
if (unlikely(tg3_tx_avail(&tp->napi[0]) <= frag_cnt_est)) {
netif_stop_queue(tp->dev);
/* netif_tx_stop_queue() must be done before checking
* checking tx index in tg3_tx_avail() below, because in
* tg3_tx(), we update tx index before checking for
* netif_tx_queue_stopped().
*/
smp_mb();
if (tg3_tx_avail(&tp->napi[0]) <= frag_cnt_est)
return NETDEV_TX_BUSY;
netif_wake_queue(tp->dev);
}
segs = skb_gso_segment(skb, tp->dev->features & ~NETIF_F_TSO);
if (IS_ERR(segs))
goto tg3_tso_bug_end;
do {
nskb = segs;
segs = segs->next;
nskb->next = NULL;
tg3_start_xmit(nskb, tp->dev);
} while (segs);
tg3_tso_bug_end:
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/* hard_start_xmit for all devices */
static netdev_tx_t tg3_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
u32 len, entry, base_flags, mss, vlan = 0;
u32 budget;
int i = -1, would_hit_hwbug;
dma_addr_t mapping;
struct tg3_napi *tnapi;
struct netdev_queue *txq;
unsigned int last;
struct iphdr *iph = NULL;
struct tcphdr *tcph = NULL;
__sum16 tcp_csum = 0, ip_csum = 0;
__be16 ip_tot_len = 0;
txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb));
tnapi = &tp->napi[skb_get_queue_mapping(skb)];
if (tg3_flag(tp, ENABLE_TSS))
tnapi++;
budget = tg3_tx_avail(tnapi);
/* We are running in BH disabled context with netif_tx_lock
* and TX reclaim runs via tp->napi.poll inside of a software
* interrupt. Furthermore, IRQ processing runs lockless so we have
* no IRQ context deadlocks to worry about either. Rejoice!
*/
if (unlikely(budget <= (skb_shinfo(skb)->nr_frags + 1))) {
if (!netif_tx_queue_stopped(txq)) {
netif_tx_stop_queue(txq);
/* This is a hard error, log it. */
netdev_err(dev,
"BUG! Tx Ring full when queue awake!\n");
}
return NETDEV_TX_BUSY;
}
entry = tnapi->tx_prod;
base_flags = 0;
if (skb->ip_summed == CHECKSUM_PARTIAL)
base_flags |= TXD_FLAG_TCPUDP_CSUM;
mss = skb_shinfo(skb)->gso_size;
if (mss) {
u32 tcp_opt_len, hdr_len;
if (skb_cow_head(skb, 0))
goto drop;
iph = ip_hdr(skb);
tcp_opt_len = tcp_optlen(skb);
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb) - ETH_HLEN;
if (!skb_is_gso_v6(skb)) {
if (unlikely((ETH_HLEN + hdr_len) > 80) &&
tg3_flag(tp, TSO_BUG))
return tg3_tso_bug(tp, skb);
ip_csum = iph->check;
ip_tot_len = iph->tot_len;
iph->check = 0;
iph->tot_len = htons(mss + hdr_len);
}
base_flags |= (TXD_FLAG_CPU_PRE_DMA |
TXD_FLAG_CPU_POST_DMA);
tcph = tcp_hdr(skb);
tcp_csum = tcph->check;
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3)) {
tcph->check = 0;
base_flags &= ~TXD_FLAG_TCPUDP_CSUM;
} else {
tcph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
0, IPPROTO_TCP, 0);
}
if (tg3_flag(tp, HW_TSO_3)) {
mss |= (hdr_len & 0xc) << 12;
if (hdr_len & 0x10)
base_flags |= 0x00000010;
base_flags |= (hdr_len & 0x3e0) << 5;
} else if (tg3_flag(tp, HW_TSO_2))
mss |= hdr_len << 9;
else if (tg3_flag(tp, HW_TSO_1) ||
tg3_asic_rev(tp) == ASIC_REV_5705) {
if (tcp_opt_len || iph->ihl > 5) {
int tsflags;
tsflags = (iph->ihl - 5) + (tcp_opt_len >> 2);
mss |= (tsflags << 11);
}
} else {
if (tcp_opt_len || iph->ihl > 5) {
int tsflags;
tsflags = (iph->ihl - 5) + (tcp_opt_len >> 2);
base_flags |= tsflags << 12;
}
}
}
if (tg3_flag(tp, USE_JUMBO_BDFLAG) &&
!mss && skb->len > VLAN_ETH_FRAME_LEN)
base_flags |= TXD_FLAG_JMB_PKT;
if (vlan_tx_tag_present(skb)) {
base_flags |= TXD_FLAG_VLAN;
vlan = vlan_tx_tag_get(skb);
}
if ((unlikely(skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP)) &&
tg3_flag(tp, TX_TSTAMP_EN)) {
skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
base_flags |= TXD_FLAG_HWTSTAMP;
}
len = skb_headlen(skb);
mapping = pci_map_single(tp->pdev, skb->data, len, PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(tp->pdev, mapping))
goto drop;
tnapi->tx_buffers[entry].skb = skb;
dma_unmap_addr_set(&tnapi->tx_buffers[entry], mapping, mapping);
would_hit_hwbug = 0;
if (tg3_flag(tp, 5701_DMA_BUG))
would_hit_hwbug = 1;
if (tg3_tx_frag_set(tnapi, &entry, &budget, mapping, len, base_flags |
((skb_shinfo(skb)->nr_frags == 0) ? TXD_FLAG_END : 0),
mss, vlan)) {
would_hit_hwbug = 1;
} else if (skb_shinfo(skb)->nr_frags > 0) {
u32 tmp_mss = mss;
if (!tg3_flag(tp, HW_TSO_1) &&
!tg3_flag(tp, HW_TSO_2) &&
!tg3_flag(tp, HW_TSO_3))
tmp_mss = 0;
/* Now loop through additional data
* fragments, and queue them.
*/
last = skb_shinfo(skb)->nr_frags - 1;
for (i = 0; i <= last; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
len = skb_frag_size(frag);
mapping = skb_frag_dma_map(&tp->pdev->dev, frag, 0,
len, DMA_TO_DEVICE);
tnapi->tx_buffers[entry].skb = NULL;
dma_unmap_addr_set(&tnapi->tx_buffers[entry], mapping,
mapping);
if (dma_mapping_error(&tp->pdev->dev, mapping))
goto dma_error;
if (!budget ||
tg3_tx_frag_set(tnapi, &entry, &budget, mapping,
len, base_flags |
((i == last) ? TXD_FLAG_END : 0),
tmp_mss, vlan)) {
would_hit_hwbug = 1;
break;
}
}
}
if (would_hit_hwbug) {
tg3_tx_skb_unmap(tnapi, tnapi->tx_prod, i);
if (mss) {
/* If it's a TSO packet, do GSO instead of
* allocating and copying to a large linear SKB
*/
if (ip_tot_len) {
iph->check = ip_csum;
iph->tot_len = ip_tot_len;
}
tcph->check = tcp_csum;
return tg3_tso_bug(tp, skb);
}
/* If the workaround fails due to memory/mapping
* failure, silently drop this packet.
*/
entry = tnapi->tx_prod;
budget = tg3_tx_avail(tnapi);
if (tigon3_dma_hwbug_workaround(tnapi, &skb, &entry, &budget,
base_flags, mss, vlan))
goto drop_nofree;
}
skb_tx_timestamp(skb);
netdev_tx_sent_queue(txq, skb->len);
/* Sync BD data before updating mailbox */
wmb();
/* Packets are ready, update Tx producer idx local and on card. */
tw32_tx_mbox(tnapi->prodmbox, entry);
tnapi->tx_prod = entry;
if (unlikely(tg3_tx_avail(tnapi) <= (MAX_SKB_FRAGS + 1))) {
netif_tx_stop_queue(txq);
/* netif_tx_stop_queue() must be done before checking
* checking tx index in tg3_tx_avail() below, because in
* tg3_tx(), we update tx index before checking for
* netif_tx_queue_stopped().
*/
smp_mb();
if (tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi))
netif_tx_wake_queue(txq);
}
mmiowb();
return NETDEV_TX_OK;
dma_error:
tg3_tx_skb_unmap(tnapi, tnapi->tx_prod, --i);
tnapi->tx_buffers[tnapi->tx_prod].skb = NULL;
drop:
dev_kfree_skb_any(skb);
drop_nofree:
tp->tx_dropped++;
return NETDEV_TX_OK;
}
static void tg3_mac_loopback(struct tg3 *tp, bool enable)
{
if (enable) {
tp->mac_mode &= ~(MAC_MODE_HALF_DUPLEX |
MAC_MODE_PORT_MODE_MASK);
tp->mac_mode |= MAC_MODE_PORT_INT_LPBACK;
if (!tg3_flag(tp, 5705_PLUS))
tp->mac_mode |= MAC_MODE_LINK_POLARITY;
if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY)
tp->mac_mode |= MAC_MODE_PORT_MODE_MII;
else
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
} else {
tp->mac_mode &= ~MAC_MODE_PORT_INT_LPBACK;
if (tg3_flag(tp, 5705_PLUS) ||
(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) ||
tg3_asic_rev(tp) == ASIC_REV_5700)
tp->mac_mode &= ~MAC_MODE_LINK_POLARITY;
}
tw32(MAC_MODE, tp->mac_mode);
udelay(40);
}
static int tg3_phy_lpbk_set(struct tg3 *tp, u32 speed, bool extlpbk)
{
u32 val, bmcr, mac_mode, ptest = 0;
tg3_phy_toggle_apd(tp, false);
tg3_phy_toggle_automdix(tp, false);
if (extlpbk && tg3_phy_set_extloopbk(tp))
return -EIO;
bmcr = BMCR_FULLDPLX;
switch (speed) {
case SPEED_10:
break;
case SPEED_100:
bmcr |= BMCR_SPEED100;
break;
case SPEED_1000:
default:
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
speed = SPEED_100;
bmcr |= BMCR_SPEED100;
} else {
speed = SPEED_1000;
bmcr |= BMCR_SPEED1000;
}
}
if (extlpbk) {
if (!(tp->phy_flags & TG3_PHYFLG_IS_FET)) {
tg3_readphy(tp, MII_CTRL1000, &val);
val |= CTL1000_AS_MASTER |
CTL1000_ENABLE_MASTER;
tg3_writephy(tp, MII_CTRL1000, val);
} else {
ptest = MII_TG3_FET_PTEST_TRIM_SEL |
MII_TG3_FET_PTEST_TRIM_2;
tg3_writephy(tp, MII_TG3_FET_PTEST, ptest);
}
} else
bmcr |= BMCR_LOOPBACK;
tg3_writephy(tp, MII_BMCR, bmcr);
/* The write needs to be flushed for the FETs */
if (tp->phy_flags & TG3_PHYFLG_IS_FET)
tg3_readphy(tp, MII_BMCR, &bmcr);
udelay(40);
if ((tp->phy_flags & TG3_PHYFLG_IS_FET) &&
tg3_asic_rev(tp) == ASIC_REV_5785) {
tg3_writephy(tp, MII_TG3_FET_PTEST, ptest |
MII_TG3_FET_PTEST_FRC_TX_LINK |
MII_TG3_FET_PTEST_FRC_TX_LOCK);
/* The write needs to be flushed for the AC131 */
tg3_readphy(tp, MII_TG3_FET_PTEST, &val);
}
/* Reset to prevent losing 1st rx packet intermittently */
if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) &&
tg3_flag(tp, 5780_CLASS)) {
tw32_f(MAC_RX_MODE, RX_MODE_RESET);
udelay(10);
tw32_f(MAC_RX_MODE, tp->rx_mode);
}
mac_mode = tp->mac_mode &
~(MAC_MODE_PORT_MODE_MASK | MAC_MODE_HALF_DUPLEX);
if (speed == SPEED_1000)
mac_mode |= MAC_MODE_PORT_MODE_GMII;
else
mac_mode |= MAC_MODE_PORT_MODE_MII;
if (tg3_asic_rev(tp) == ASIC_REV_5700) {
u32 masked_phy_id = tp->phy_id & TG3_PHY_ID_MASK;
if (masked_phy_id == TG3_PHY_ID_BCM5401)
mac_mode &= ~MAC_MODE_LINK_POLARITY;
else if (masked_phy_id == TG3_PHY_ID_BCM5411)
mac_mode |= MAC_MODE_LINK_POLARITY;
tg3_writephy(tp, MII_TG3_EXT_CTRL,
MII_TG3_EXT_CTRL_LNK3_LED_MODE);
}
tw32(MAC_MODE, mac_mode);
udelay(40);
return 0;
}
static void tg3_set_loopback(struct net_device *dev, netdev_features_t features)
{
struct tg3 *tp = netdev_priv(dev);
if (features & NETIF_F_LOOPBACK) {
if (tp->mac_mode & MAC_MODE_PORT_INT_LPBACK)
return;
spin_lock_bh(&tp->lock);
tg3_mac_loopback(tp, true);
netif_carrier_on(tp->dev);
spin_unlock_bh(&tp->lock);
netdev_info(dev, "Internal MAC loopback mode enabled.\n");
} else {
if (!(tp->mac_mode & MAC_MODE_PORT_INT_LPBACK))
return;
spin_lock_bh(&tp->lock);
tg3_mac_loopback(tp, false);
/* Force link status check */
tg3_setup_phy(tp, true);
spin_unlock_bh(&tp->lock);
netdev_info(dev, "Internal MAC loopback mode disabled.\n");
}
}
static netdev_features_t tg3_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct tg3 *tp = netdev_priv(dev);
if (dev->mtu > ETH_DATA_LEN && tg3_flag(tp, 5780_CLASS))
features &= ~NETIF_F_ALL_TSO;
return features;
}
static int tg3_set_features(struct net_device *dev, netdev_features_t features)
{
netdev_features_t changed = dev->features ^ features;
if ((changed & NETIF_F_LOOPBACK) && netif_running(dev))
tg3_set_loopback(dev, features);
return 0;
}
static void tg3_rx_prodring_free(struct tg3 *tp,
struct tg3_rx_prodring_set *tpr)
{
int i;
if (tpr != &tp->napi[0].prodring) {
for (i = tpr->rx_std_cons_idx; i != tpr->rx_std_prod_idx;
i = (i + 1) & tp->rx_std_ring_mask)
tg3_rx_data_free(tp, &tpr->rx_std_buffers[i],
tp->rx_pkt_map_sz);
if (tg3_flag(tp, JUMBO_CAPABLE)) {
for (i = tpr->rx_jmb_cons_idx;
i != tpr->rx_jmb_prod_idx;
i = (i + 1) & tp->rx_jmb_ring_mask) {
tg3_rx_data_free(tp, &tpr->rx_jmb_buffers[i],
TG3_RX_JMB_MAP_SZ);
}
}
return;
}
for (i = 0; i <= tp->rx_std_ring_mask; i++)
tg3_rx_data_free(tp, &tpr->rx_std_buffers[i],
tp->rx_pkt_map_sz);
if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) {
for (i = 0; i <= tp->rx_jmb_ring_mask; i++)
tg3_rx_data_free(tp, &tpr->rx_jmb_buffers[i],
TG3_RX_JMB_MAP_SZ);
}
}
/* Initialize rx rings for packet processing.
*
* The chip has been shut down and the driver detached from
* the networking, so no interrupts or new tx packets will
* end up in the driver. tp->{tx,}lock are held and thus
* we may not sleep.
*/
static int tg3_rx_prodring_alloc(struct tg3 *tp,
struct tg3_rx_prodring_set *tpr)
{
u32 i, rx_pkt_dma_sz;
tpr->rx_std_cons_idx = 0;
tpr->rx_std_prod_idx = 0;
tpr->rx_jmb_cons_idx = 0;
tpr->rx_jmb_prod_idx = 0;
if (tpr != &tp->napi[0].prodring) {
memset(&tpr->rx_std_buffers[0], 0,
TG3_RX_STD_BUFF_RING_SIZE(tp));
if (tpr->rx_jmb_buffers)
memset(&tpr->rx_jmb_buffers[0], 0,
TG3_RX_JMB_BUFF_RING_SIZE(tp));
goto done;
}
/* Zero out all descriptors. */
memset(tpr->rx_std, 0, TG3_RX_STD_RING_BYTES(tp));
rx_pkt_dma_sz = TG3_RX_STD_DMA_SZ;
if (tg3_flag(tp, 5780_CLASS) &&
tp->dev->mtu > ETH_DATA_LEN)
rx_pkt_dma_sz = TG3_RX_JMB_DMA_SZ;
tp->rx_pkt_map_sz = TG3_RX_DMA_TO_MAP_SZ(rx_pkt_dma_sz);
/* Initialize invariants of the rings, we only set this
* stuff once. This works because the card does not
* write into the rx buffer posting rings.
*/
for (i = 0; i <= tp->rx_std_ring_mask; i++) {
struct tg3_rx_buffer_desc *rxd;
rxd = &tpr->rx_std[i];
rxd->idx_len = rx_pkt_dma_sz << RXD_LEN_SHIFT;
rxd->type_flags = (RXD_FLAG_END << RXD_FLAGS_SHIFT);
rxd->opaque = (RXD_OPAQUE_RING_STD |
(i << RXD_OPAQUE_INDEX_SHIFT));
}
/* Now allocate fresh SKBs for each rx ring. */
for (i = 0; i < tp->rx_pending; i++) {
unsigned int frag_size;
if (tg3_alloc_rx_data(tp, tpr, RXD_OPAQUE_RING_STD, i,
&frag_size) < 0) {
netdev_warn(tp->dev,
"Using a smaller RX standard ring. Only "
"%d out of %d buffers were allocated "
"successfully\n", i, tp->rx_pending);
if (i == 0)
goto initfail;
tp->rx_pending = i;
break;
}
}
if (!tg3_flag(tp, JUMBO_CAPABLE) || tg3_flag(tp, 5780_CLASS))
goto done;
memset(tpr->rx_jmb, 0, TG3_RX_JMB_RING_BYTES(tp));
if (!tg3_flag(tp, JUMBO_RING_ENABLE))
goto done;
for (i = 0; i <= tp->rx_jmb_ring_mask; i++) {
struct tg3_rx_buffer_desc *rxd;
rxd = &tpr->rx_jmb[i].std;
rxd->idx_len = TG3_RX_JMB_DMA_SZ << RXD_LEN_SHIFT;
rxd->type_flags = (RXD_FLAG_END << RXD_FLAGS_SHIFT) |
RXD_FLAG_JUMBO;
rxd->opaque = (RXD_OPAQUE_RING_JUMBO |
(i << RXD_OPAQUE_INDEX_SHIFT));
}
for (i = 0; i < tp->rx_jumbo_pending; i++) {
unsigned int frag_size;
if (tg3_alloc_rx_data(tp, tpr, RXD_OPAQUE_RING_JUMBO, i,
&frag_size) < 0) {
netdev_warn(tp->dev,
"Using a smaller RX jumbo ring. Only %d "
"out of %d buffers were allocated "
"successfully\n", i, tp->rx_jumbo_pending);
if (i == 0)
goto initfail;
tp->rx_jumbo_pending = i;
break;
}
}
done:
return 0;
initfail:
tg3_rx_prodring_free(tp, tpr);
return -ENOMEM;
}
static void tg3_rx_prodring_fini(struct tg3 *tp,
struct tg3_rx_prodring_set *tpr)
{
kfree(tpr->rx_std_buffers);
tpr->rx_std_buffers = NULL;
kfree(tpr->rx_jmb_buffers);
tpr->rx_jmb_buffers = NULL;
if (tpr->rx_std) {
dma_free_coherent(&tp->pdev->dev, TG3_RX_STD_RING_BYTES(tp),
tpr->rx_std, tpr->rx_std_mapping);
tpr->rx_std = NULL;
}
if (tpr->rx_jmb) {
dma_free_coherent(&tp->pdev->dev, TG3_RX_JMB_RING_BYTES(tp),
tpr->rx_jmb, tpr->rx_jmb_mapping);
tpr->rx_jmb = NULL;
}
}
static int tg3_rx_prodring_init(struct tg3 *tp,
struct tg3_rx_prodring_set *tpr)
{
tpr->rx_std_buffers = kzalloc(TG3_RX_STD_BUFF_RING_SIZE(tp),
GFP_KERNEL);
if (!tpr->rx_std_buffers)
return -ENOMEM;
tpr->rx_std = dma_alloc_coherent(&tp->pdev->dev,
TG3_RX_STD_RING_BYTES(tp),
&tpr->rx_std_mapping,
GFP_KERNEL);
if (!tpr->rx_std)
goto err_out;
if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) {
tpr->rx_jmb_buffers = kzalloc(TG3_RX_JMB_BUFF_RING_SIZE(tp),
GFP_KERNEL);
if (!tpr->rx_jmb_buffers)
goto err_out;
tpr->rx_jmb = dma_alloc_coherent(&tp->pdev->dev,
TG3_RX_JMB_RING_BYTES(tp),
&tpr->rx_jmb_mapping,
GFP_KERNEL);
if (!tpr->rx_jmb)
goto err_out;
}
return 0;
err_out:
tg3_rx_prodring_fini(tp, tpr);
return -ENOMEM;
}
/* Free up pending packets in all rx/tx rings.
*
* The chip has been shut down and the driver detached from
* the networking, so no interrupts or new tx packets will
* end up in the driver. tp->{tx,}lock is not held and we are not
* in an interrupt context and thus may sleep.
*/
static void tg3_free_rings(struct tg3 *tp)
{
int i, j;
for (j = 0; j < tp->irq_cnt; j++) {
struct tg3_napi *tnapi = &tp->napi[j];
tg3_rx_prodring_free(tp, &tnapi->prodring);
if (!tnapi->tx_buffers)
continue;
for (i = 0; i < TG3_TX_RING_SIZE; i++) {
struct sk_buff *skb = tnapi->tx_buffers[i].skb;
if (!skb)
continue;
tg3_tx_skb_unmap(tnapi, i,
skb_shinfo(skb)->nr_frags - 1);
dev_kfree_skb_any(skb);
}
netdev_tx_reset_queue(netdev_get_tx_queue(tp->dev, j));
}
}
/* Initialize tx/rx rings for packet processing.
*
* The chip has been shut down and the driver detached from
* the networking, so no interrupts or new tx packets will
* end up in the driver. tp->{tx,}lock are held and thus
* we may not sleep.
*/
static int tg3_init_rings(struct tg3 *tp)
{
int i;
/* Free up all the SKBs. */
tg3_free_rings(tp);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
tnapi->last_tag = 0;
tnapi->last_irq_tag = 0;
tnapi->hw_status->status = 0;
tnapi->hw_status->status_tag = 0;
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
tnapi->tx_prod = 0;
tnapi->tx_cons = 0;
if (tnapi->tx_ring)
memset(tnapi->tx_ring, 0, TG3_TX_RING_BYTES);
tnapi->rx_rcb_ptr = 0;
if (tnapi->rx_rcb)
memset(tnapi->rx_rcb, 0, TG3_RX_RCB_RING_BYTES(tp));
if (tg3_rx_prodring_alloc(tp, &tnapi->prodring)) {
tg3_free_rings(tp);
return -ENOMEM;
}
}
return 0;
}
static void tg3_mem_tx_release(struct tg3 *tp)
{
int i;
for (i = 0; i < tp->irq_max; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tnapi->tx_ring) {
dma_free_coherent(&tp->pdev->dev, TG3_TX_RING_BYTES,
tnapi->tx_ring, tnapi->tx_desc_mapping);
tnapi->tx_ring = NULL;
}
kfree(tnapi->tx_buffers);
tnapi->tx_buffers = NULL;
}
}
static int tg3_mem_tx_acquire(struct tg3 *tp)
{
int i;
struct tg3_napi *tnapi = &tp->napi[0];
/* If multivector TSS is enabled, vector 0 does not handle
* tx interrupts. Don't allocate any resources for it.
*/
if (tg3_flag(tp, ENABLE_TSS))
tnapi++;
for (i = 0; i < tp->txq_cnt; i++, tnapi++) {
tnapi->tx_buffers = kzalloc(sizeof(struct tg3_tx_ring_info) *
TG3_TX_RING_SIZE, GFP_KERNEL);
if (!tnapi->tx_buffers)
goto err_out;
tnapi->tx_ring = dma_alloc_coherent(&tp->pdev->dev,
TG3_TX_RING_BYTES,
&tnapi->tx_desc_mapping,
GFP_KERNEL);
if (!tnapi->tx_ring)
goto err_out;
}
return 0;
err_out:
tg3_mem_tx_release(tp);
return -ENOMEM;
}
static void tg3_mem_rx_release(struct tg3 *tp)
{
int i;
for (i = 0; i < tp->irq_max; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
tg3_rx_prodring_fini(tp, &tnapi->prodring);
if (!tnapi->rx_rcb)
continue;
dma_free_coherent(&tp->pdev->dev,
TG3_RX_RCB_RING_BYTES(tp),
tnapi->rx_rcb,
tnapi->rx_rcb_mapping);
tnapi->rx_rcb = NULL;
}
}
static int tg3_mem_rx_acquire(struct tg3 *tp)
{
unsigned int i, limit;
limit = tp->rxq_cnt;
/* If RSS is enabled, we need a (dummy) producer ring
* set on vector zero. This is the true hw prodring.
*/
if (tg3_flag(tp, ENABLE_RSS))
limit++;
for (i = 0; i < limit; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tg3_rx_prodring_init(tp, &tnapi->prodring))
goto err_out;
/* If multivector RSS is enabled, vector 0
* does not handle rx or tx interrupts.
* Don't allocate any resources for it.
*/
if (!i && tg3_flag(tp, ENABLE_RSS))
continue;
tnapi->rx_rcb = dma_zalloc_coherent(&tp->pdev->dev,
TG3_RX_RCB_RING_BYTES(tp),
&tnapi->rx_rcb_mapping,
GFP_KERNEL);
if (!tnapi->rx_rcb)
goto err_out;
}
return 0;
err_out:
tg3_mem_rx_release(tp);
return -ENOMEM;
}
/*
* Must not be invoked with interrupt sources disabled and
* the hardware shutdown down.
*/
static void tg3_free_consistent(struct tg3 *tp)
{
int i;
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tnapi->hw_status) {
dma_free_coherent(&tp->pdev->dev, TG3_HW_STATUS_SIZE,
tnapi->hw_status,
tnapi->status_mapping);
tnapi->hw_status = NULL;
}
}
tg3_mem_rx_release(tp);
tg3_mem_tx_release(tp);
if (tp->hw_stats) {
dma_free_coherent(&tp->pdev->dev, sizeof(struct tg3_hw_stats),
tp->hw_stats, tp->stats_mapping);
tp->hw_stats = NULL;
}
}
/*
* Must not be invoked with interrupt sources disabled and
* the hardware shutdown down. Can sleep.
*/
static int tg3_alloc_consistent(struct tg3 *tp)
{
int i;
tp->hw_stats = dma_zalloc_coherent(&tp->pdev->dev,
sizeof(struct tg3_hw_stats),
&tp->stats_mapping, GFP_KERNEL);
if (!tp->hw_stats)
goto err_out;
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
struct tg3_hw_status *sblk;
tnapi->hw_status = dma_zalloc_coherent(&tp->pdev->dev,
TG3_HW_STATUS_SIZE,
&tnapi->status_mapping,
GFP_KERNEL);
if (!tnapi->hw_status)
goto err_out;
sblk = tnapi->hw_status;
if (tg3_flag(tp, ENABLE_RSS)) {
u16 *prodptr = NULL;
/*
* When RSS is enabled, the status block format changes
* slightly. The "rx_jumbo_consumer", "reserved",
* and "rx_mini_consumer" members get mapped to the
* other three rx return ring producer indexes.
*/
switch (i) {
case 1:
prodptr = &sblk->idx[0].rx_producer;
break;
case 2:
prodptr = &sblk->rx_jumbo_consumer;
break;
case 3:
prodptr = &sblk->reserved;
break;
case 4:
prodptr = &sblk->rx_mini_consumer;
break;
}
tnapi->rx_rcb_prod_idx = prodptr;
} else {
tnapi->rx_rcb_prod_idx = &sblk->idx[0].rx_producer;
}
}
if (tg3_mem_tx_acquire(tp) || tg3_mem_rx_acquire(tp))
goto err_out;
return 0;
err_out:
tg3_free_consistent(tp);
return -ENOMEM;
}
#define MAX_WAIT_CNT 1000
/* To stop a block, clear the enable bit and poll till it
* clears. tp->lock is held.
*/
static int tg3_stop_block(struct tg3 *tp, unsigned long ofs, u32 enable_bit, bool silent)
{
unsigned int i;
u32 val;
if (tg3_flag(tp, 5705_PLUS)) {
switch (ofs) {
case RCVLSC_MODE:
case DMAC_MODE:
case MBFREE_MODE:
case BUFMGR_MODE:
case MEMARB_MODE:
/* We can't enable/disable these bits of the
* 5705/5750, just say success.
*/
return 0;
default:
break;
}
}
val = tr32(ofs);
val &= ~enable_bit;
tw32_f(ofs, val);
for (i = 0; i < MAX_WAIT_CNT; i++) {
if (pci_channel_offline(tp->pdev)) {
dev_err(&tp->pdev->dev,
"tg3_stop_block device offline, "
"ofs=%lx enable_bit=%x\n",
ofs, enable_bit);
return -ENODEV;
}
udelay(100);
val = tr32(ofs);
if ((val & enable_bit) == 0)
break;
}
if (i == MAX_WAIT_CNT && !silent) {
dev_err(&tp->pdev->dev,
"tg3_stop_block timed out, ofs=%lx enable_bit=%x\n",
ofs, enable_bit);
return -ENODEV;
}
return 0;
}
/* tp->lock is held. */
static int tg3_abort_hw(struct tg3 *tp, bool silent)
{
int i, err;
tg3_disable_ints(tp);
if (pci_channel_offline(tp->pdev)) {
tp->rx_mode &= ~(RX_MODE_ENABLE | TX_MODE_ENABLE);
tp->mac_mode &= ~MAC_MODE_TDE_ENABLE;
err = -ENODEV;
goto err_no_dev;
}
tp->rx_mode &= ~RX_MODE_ENABLE;
tw32_f(MAC_RX_MODE, tp->rx_mode);
udelay(10);
err = tg3_stop_block(tp, RCVBDI_MODE, RCVBDI_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVLPC_MODE, RCVLPC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVLSC_MODE, RCVLSC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVDBDI_MODE, RCVDBDI_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVDCC_MODE, RCVDCC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVCC_MODE, RCVCC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDBDS_MODE, SNDBDS_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDBDI_MODE, SNDBDI_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDDATAI_MODE, SNDDATAI_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RDMAC_MODE, RDMAC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDDATAC_MODE, SNDDATAC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, DMAC_MODE, DMAC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDBDC_MODE, SNDBDC_MODE_ENABLE, silent);
tp->mac_mode &= ~MAC_MODE_TDE_ENABLE;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tp->tx_mode &= ~TX_MODE_ENABLE;
tw32_f(MAC_TX_MODE, tp->tx_mode);
for (i = 0; i < MAX_WAIT_CNT; i++) {
udelay(100);
if (!(tr32(MAC_TX_MODE) & TX_MODE_ENABLE))
break;
}
if (i >= MAX_WAIT_CNT) {
dev_err(&tp->pdev->dev,
"%s timed out, TX_MODE_ENABLE will not clear "
"MAC_TX_MODE=%08x\n", __func__, tr32(MAC_TX_MODE));
err |= -ENODEV;
}
err |= tg3_stop_block(tp, HOSTCC_MODE, HOSTCC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, WDMAC_MODE, WDMAC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, MBFREE_MODE, MBFREE_MODE_ENABLE, silent);
tw32(FTQ_RESET, 0xffffffff);
tw32(FTQ_RESET, 0x00000000);
err |= tg3_stop_block(tp, BUFMGR_MODE, BUFMGR_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, MEMARB_MODE, MEMARB_MODE_ENABLE, silent);
err_no_dev:
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tnapi->hw_status)
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
}
return err;
}
/* Save PCI command register before chip reset */
static void tg3_save_pci_state(struct tg3 *tp)
{
pci_read_config_word(tp->pdev, PCI_COMMAND, &tp->pci_cmd);
}
/* Restore PCI state after chip reset */
static void tg3_restore_pci_state(struct tg3 *tp)
{
u32 val;
/* Re-enable indirect register accesses. */
pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL,
tp->misc_host_ctrl);
/* Set MAX PCI retry to zero. */
val = (PCISTATE_ROM_ENABLE | PCISTATE_ROM_RETRY_ENABLE);
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0 &&
tg3_flag(tp, PCIX_MODE))
val |= PCISTATE_RETRY_SAME_DMA;
/* Allow reads and writes to the APE register and memory space. */
if (tg3_flag(tp, ENABLE_APE))
val |= PCISTATE_ALLOW_APE_CTLSPC_WR |
PCISTATE_ALLOW_APE_SHMEM_WR |
PCISTATE_ALLOW_APE_PSPACE_WR;
pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE, val);
pci_write_config_word(tp->pdev, PCI_COMMAND, tp->pci_cmd);
if (!tg3_flag(tp, PCI_EXPRESS)) {
pci_write_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE,
tp->pci_cacheline_sz);
pci_write_config_byte(tp->pdev, PCI_LATENCY_TIMER,
tp->pci_lat_timer);
}
/* Make sure PCI-X relaxed ordering bit is clear. */
if (tg3_flag(tp, PCIX_MODE)) {
u16 pcix_cmd;
pci_read_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD,
&pcix_cmd);
pcix_cmd &= ~PCI_X_CMD_ERO;
pci_write_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD,
pcix_cmd);
}
if (tg3_flag(tp, 5780_CLASS)) {
/* Chip reset on 5780 will reset MSI enable bit,
* so need to restore it.
*/
if (tg3_flag(tp, USING_MSI)) {
u16 ctrl;
pci_read_config_word(tp->pdev,
tp->msi_cap + PCI_MSI_FLAGS,
&ctrl);
pci_write_config_word(tp->pdev,
tp->msi_cap + PCI_MSI_FLAGS,
ctrl | PCI_MSI_FLAGS_ENABLE);
val = tr32(MSGINT_MODE);
tw32(MSGINT_MODE, val | MSGINT_MODE_ENABLE);
}
}
}
static void tg3_override_clk(struct tg3 *tp)
{
u32 val;
switch (tg3_asic_rev(tp)) {
case ASIC_REV_5717:
val = tr32(TG3_CPMU_CLCK_ORIDE_ENABLE);
tw32(TG3_CPMU_CLCK_ORIDE_ENABLE, val |
TG3_CPMU_MAC_ORIDE_ENABLE);
break;
case ASIC_REV_5719:
case ASIC_REV_5720:
tw32(TG3_CPMU_CLCK_ORIDE, CPMU_CLCK_ORIDE_MAC_ORIDE_EN);
break;
default:
return;
}
}
static void tg3_restore_clk(struct tg3 *tp)
{
u32 val;
switch (tg3_asic_rev(tp)) {
case ASIC_REV_5717:
val = tr32(TG3_CPMU_CLCK_ORIDE_ENABLE);
tw32(TG3_CPMU_CLCK_ORIDE_ENABLE,
val & ~TG3_CPMU_MAC_ORIDE_ENABLE);
break;
case ASIC_REV_5719:
case ASIC_REV_5720:
val = tr32(TG3_CPMU_CLCK_ORIDE);
tw32(TG3_CPMU_CLCK_ORIDE, val & ~CPMU_CLCK_ORIDE_MAC_ORIDE_EN);
break;
default:
return;
}
}
/* tp->lock is held. */
static int tg3_chip_reset(struct tg3 *tp)
{
u32 val;
void (*write_op)(struct tg3 *, u32, u32);
int i, err;
if (!pci_device_is_present(tp->pdev))
return -ENODEV;
tg3_nvram_lock(tp);
tg3_ape_lock(tp, TG3_APE_LOCK_GRC);
/* No matching tg3_nvram_unlock() after this because
* chip reset below will undo the nvram lock.
*/
tp->nvram_lock_cnt = 0;
/* GRC_MISC_CFG core clock reset will clear the memory
* enable bit in PCI register 4 and the MSI enable bit
* on some chips, so we save relevant registers here.
*/
tg3_save_pci_state(tp);
if (tg3_asic_rev(tp) == ASIC_REV_5752 ||
tg3_flag(tp, 5755_PLUS))
tw32(GRC_FASTBOOT_PC, 0);
/*
* We must avoid the readl() that normally takes place.
* It locks machines, causes machine checks, and other
* fun things. So, temporarily disable the 5701
* hardware workaround, while we do the reset.
*/
write_op = tp->write32;
if (write_op == tg3_write_flush_reg32)
tp->write32 = tg3_write32;
/* Prevent the irq handler from reading or writing PCI registers
* during chip reset when the memory enable bit in the PCI command
* register may be cleared. The chip does not generate interrupt
* at this time, but the irq handler may still be called due to irq
* sharing or irqpoll.
*/
tg3_flag_set(tp, CHIP_RESETTING);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tnapi->hw_status) {
tnapi->hw_status->status = 0;
tnapi->hw_status->status_tag = 0;
}
tnapi->last_tag = 0;
tnapi->last_irq_tag = 0;
}
smp_mb();
for (i = 0; i < tp->irq_cnt; i++)
synchronize_irq(tp->napi[i].irq_vec);
if (tg3_asic_rev(tp) == ASIC_REV_57780) {
val = tr32(TG3_PCIE_LNKCTL) & ~TG3_PCIE_LNKCTL_L1_PLL_PD_EN;
tw32(TG3_PCIE_LNKCTL, val | TG3_PCIE_LNKCTL_L1_PLL_PD_DIS);
}
/* do the reset */
val = GRC_MISC_CFG_CORECLK_RESET;
if (tg3_flag(tp, PCI_EXPRESS)) {
/* Force PCIe 1.0a mode */
if (tg3_asic_rev(tp) != ASIC_REV_5785 &&
!tg3_flag(tp, 57765_PLUS) &&
tr32(TG3_PCIE_PHY_TSTCTL) ==
(TG3_PCIE_PHY_TSTCTL_PCIE10 | TG3_PCIE_PHY_TSTCTL_PSCRAM))
tw32(TG3_PCIE_PHY_TSTCTL, TG3_PCIE_PHY_TSTCTL_PSCRAM);
if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0) {
tw32(GRC_MISC_CFG, (1 << 29));
val |= (1 << 29);
}
}
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
tw32(VCPU_STATUS, tr32(VCPU_STATUS) | VCPU_STATUS_DRV_RESET);
tw32(GRC_VCPU_EXT_CTRL,
tr32(GRC_VCPU_EXT_CTRL) & ~GRC_VCPU_EXT_CTRL_HALT_CPU);
}
/* Set the clock to the highest frequency to avoid timeouts. With link
* aware mode, the clock speed could be slow and bootcode does not
* complete within the expected time. Override the clock to allow the
* bootcode to finish sooner and then restore it.
*/
tg3_override_clk(tp);
/* Manage gphy power for all CPMU absent PCIe devices. */
if (tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, CPMU_PRESENT))
val |= GRC_MISC_CFG_KEEP_GPHY_POWER;
tw32(GRC_MISC_CFG, val);
/* restore 5701 hardware bug workaround write method */
tp->write32 = write_op;
/* Unfortunately, we have to delay before the PCI read back.
* Some 575X chips even will not respond to a PCI cfg access
* when the reset command is given to the chip.
*
* How do these hardware designers expect things to work
* properly if the PCI write is posted for a long period
* of time? It is always necessary to have some method by
* which a register read back can occur to push the write
* out which does the reset.
*
* For most tg3 variants the trick below was working.
* Ho hum...
*/
udelay(120);
/* Flush PCI posted writes. The normal MMIO registers
* are inaccessible at this time so this is the only
* way to make this reliably (actually, this is no longer
* the case, see above). I tried to use indirect
* register read/write but this upset some 5701 variants.
*/
pci_read_config_dword(tp->pdev, PCI_COMMAND, &val);
udelay(120);
if (tg3_flag(tp, PCI_EXPRESS) && pci_is_pcie(tp->pdev)) {
u16 val16;
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A0) {
int j;
u32 cfg_val;
/* Wait for link training to complete. */
for (j = 0; j < 5000; j++)
udelay(100);
pci_read_config_dword(tp->pdev, 0xc4, &cfg_val);
pci_write_config_dword(tp->pdev, 0xc4,
cfg_val | (1 << 15));
}
/* Clear the "no snoop" and "relaxed ordering" bits. */
val16 = PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN;
/*
* Older PCIe devices only support the 128 byte
* MPS setting. Enforce the restriction.
*/
if (!tg3_flag(tp, CPMU_PRESENT))
val16 |= PCI_EXP_DEVCTL_PAYLOAD;
pcie_capability_clear_word(tp->pdev, PCI_EXP_DEVCTL, val16);
/* Clear error status */
pcie_capability_write_word(tp->pdev, PCI_EXP_DEVSTA,
PCI_EXP_DEVSTA_CED |
PCI_EXP_DEVSTA_NFED |
PCI_EXP_DEVSTA_FED |
PCI_EXP_DEVSTA_URD);
}
tg3_restore_pci_state(tp);
tg3_flag_clear(tp, CHIP_RESETTING);
tg3_flag_clear(tp, ERROR_PROCESSED);
val = 0;
if (tg3_flag(tp, 5780_CLASS))
val = tr32(MEMARB_MODE);
tw32(MEMARB_MODE, val | MEMARB_MODE_ENABLE);
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A3) {
tg3_stop_fw(tp);
tw32(0x5000, 0x400);
}
if (tg3_flag(tp, IS_SSB_CORE)) {
/*
* BCM4785: In order to avoid repercussions from using
* potentially defective internal ROM, stop the Rx RISC CPU,
* which is not required.
*/
tg3_stop_fw(tp);
tg3_halt_cpu(tp, RX_CPU_BASE);
}
err = tg3_poll_fw(tp);
if (err)
return err;
tw32(GRC_MODE, tp->grc_mode);
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A0) {
val = tr32(0xc4);
tw32(0xc4, val | (1 << 15));
}
if ((tp->nic_sram_data_cfg & NIC_SRAM_DATA_CFG_MINI_PCI) != 0 &&
tg3_asic_rev(tp) == ASIC_REV_5705) {
tp->pci_clock_ctrl |= CLOCK_CTRL_CLKRUN_OENABLE;
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A0)
tp->pci_clock_ctrl |= CLOCK_CTRL_FORCE_CLKRUN;
tw32(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl);
}
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
tp->mac_mode = MAC_MODE_PORT_MODE_TBI;
val = tp->mac_mode;
} else if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) {
tp->mac_mode = MAC_MODE_PORT_MODE_GMII;
val = tp->mac_mode;
} else
val = 0;
tw32_f(MAC_MODE, val);
udelay(40);
tg3_ape_unlock(tp, TG3_APE_LOCK_GRC);
tg3_mdio_start(tp);
if (tg3_flag(tp, PCI_EXPRESS) &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0 &&
tg3_asic_rev(tp) != ASIC_REV_5785 &&
!tg3_flag(tp, 57765_PLUS)) {
val = tr32(0x7c00);
tw32(0x7c00, val | (1 << 25));
}
tg3_restore_clk(tp);
/* Reprobe ASF enable state. */
tg3_flag_clear(tp, ENABLE_ASF);
tp->phy_flags &= ~(TG3_PHYFLG_1G_ON_VAUX_OK |
TG3_PHYFLG_KEEP_LINK_ON_PWRDN);
tg3_flag_clear(tp, ASF_NEW_HANDSHAKE);
tg3_read_mem(tp, NIC_SRAM_DATA_SIG, &val);
if (val == NIC_SRAM_DATA_SIG_MAGIC) {
u32 nic_cfg;
tg3_read_mem(tp, NIC_SRAM_DATA_CFG, &nic_cfg);
if (nic_cfg & NIC_SRAM_DATA_CFG_ASF_ENABLE) {
tg3_flag_set(tp, ENABLE_ASF);
tp->last_event_jiffies = jiffies;
if (tg3_flag(tp, 5750_PLUS))
tg3_flag_set(tp, ASF_NEW_HANDSHAKE);
tg3_read_mem(tp, NIC_SRAM_DATA_CFG_3, &nic_cfg);
if (nic_cfg & NIC_SRAM_1G_ON_VAUX_OK)
tp->phy_flags |= TG3_PHYFLG_1G_ON_VAUX_OK;
if (nic_cfg & NIC_SRAM_LNK_FLAP_AVOID)
tp->phy_flags |= TG3_PHYFLG_KEEP_LINK_ON_PWRDN;
}
}
return 0;
}
static void tg3_get_nstats(struct tg3 *, struct rtnl_link_stats64 *);
static void tg3_get_estats(struct tg3 *, struct tg3_ethtool_stats *);
static void __tg3_set_rx_mode(struct net_device *);
/* tp->lock is held. */
static int tg3_halt(struct tg3 *tp, int kind, bool silent)
{
int err;
tg3_stop_fw(tp);
tg3_write_sig_pre_reset(tp, kind);
tg3_abort_hw(tp, silent);
err = tg3_chip_reset(tp);
__tg3_set_mac_addr(tp, false);
tg3_write_sig_legacy(tp, kind);
tg3_write_sig_post_reset(tp, kind);
if (tp->hw_stats) {
/* Save the stats across chip resets... */
tg3_get_nstats(tp, &tp->net_stats_prev);
tg3_get_estats(tp, &tp->estats_prev);
/* And make sure the next sample is new data */
memset(tp->hw_stats, 0, sizeof(struct tg3_hw_stats));
}
return err;
}
static int tg3_set_mac_addr(struct net_device *dev, void *p)
{
struct tg3 *tp = netdev_priv(dev);
struct sockaddr *addr = p;
int err = 0;
bool skip_mac_1 = false;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
if (!netif_running(dev))
return 0;
if (tg3_flag(tp, ENABLE_ASF)) {
u32 addr0_high, addr0_low, addr1_high, addr1_low;
addr0_high = tr32(MAC_ADDR_0_HIGH);
addr0_low = tr32(MAC_ADDR_0_LOW);
addr1_high = tr32(MAC_ADDR_1_HIGH);
addr1_low = tr32(MAC_ADDR_1_LOW);
/* Skip MAC addr 1 if ASF is using it. */
if ((addr0_high != addr1_high || addr0_low != addr1_low) &&
!(addr1_high == 0 && addr1_low == 0))
skip_mac_1 = true;
}
spin_lock_bh(&tp->lock);
__tg3_set_mac_addr(tp, skip_mac_1);
__tg3_set_rx_mode(dev);
spin_unlock_bh(&tp->lock);
return err;
}
/* tp->lock is held. */
static void tg3_set_bdinfo(struct tg3 *tp, u32 bdinfo_addr,
dma_addr_t mapping, u32 maxlen_flags,
u32 nic_addr)
{
tg3_write_mem(tp,
(bdinfo_addr + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH),
((u64) mapping >> 32));
tg3_write_mem(tp,
(bdinfo_addr + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW),
((u64) mapping & 0xffffffff));
tg3_write_mem(tp,
(bdinfo_addr + TG3_BDINFO_MAXLEN_FLAGS),
maxlen_flags);
if (!tg3_flag(tp, 5705_PLUS))
tg3_write_mem(tp,
(bdinfo_addr + TG3_BDINFO_NIC_ADDR),
nic_addr);
}
static void tg3_coal_tx_init(struct tg3 *tp, struct ethtool_coalesce *ec)
{
int i = 0;
if (!tg3_flag(tp, ENABLE_TSS)) {
tw32(HOSTCC_TXCOL_TICKS, ec->tx_coalesce_usecs);
tw32(HOSTCC_TXMAX_FRAMES, ec->tx_max_coalesced_frames);
tw32(HOSTCC_TXCOAL_MAXF_INT, ec->tx_max_coalesced_frames_irq);
} else {
tw32(HOSTCC_TXCOL_TICKS, 0);
tw32(HOSTCC_TXMAX_FRAMES, 0);
tw32(HOSTCC_TXCOAL_MAXF_INT, 0);
for (; i < tp->txq_cnt; i++) {
u32 reg;
reg = HOSTCC_TXCOL_TICKS_VEC1 + i * 0x18;
tw32(reg, ec->tx_coalesce_usecs);
reg = HOSTCC_TXMAX_FRAMES_VEC1 + i * 0x18;
tw32(reg, ec->tx_max_coalesced_frames);
reg = HOSTCC_TXCOAL_MAXF_INT_VEC1 + i * 0x18;
tw32(reg, ec->tx_max_coalesced_frames_irq);
}
}
for (; i < tp->irq_max - 1; i++) {
tw32(HOSTCC_TXCOL_TICKS_VEC1 + i * 0x18, 0);
tw32(HOSTCC_TXMAX_FRAMES_VEC1 + i * 0x18, 0);
tw32(HOSTCC_TXCOAL_MAXF_INT_VEC1 + i * 0x18, 0);
}
}
static void tg3_coal_rx_init(struct tg3 *tp, struct ethtool_coalesce *ec)
{
int i = 0;
u32 limit = tp->rxq_cnt;
if (!tg3_flag(tp, ENABLE_RSS)) {
tw32(HOSTCC_RXCOL_TICKS, ec->rx_coalesce_usecs);
tw32(HOSTCC_RXMAX_FRAMES, ec->rx_max_coalesced_frames);
tw32(HOSTCC_RXCOAL_MAXF_INT, ec->rx_max_coalesced_frames_irq);
limit--;
} else {
tw32(HOSTCC_RXCOL_TICKS, 0);
tw32(HOSTCC_RXMAX_FRAMES, 0);
tw32(HOSTCC_RXCOAL_MAXF_INT, 0);
}
for (; i < limit; i++) {
u32 reg;
reg = HOSTCC_RXCOL_TICKS_VEC1 + i * 0x18;
tw32(reg, ec->rx_coalesce_usecs);
reg = HOSTCC_RXMAX_FRAMES_VEC1 + i * 0x18;
tw32(reg, ec->rx_max_coalesced_frames);
reg = HOSTCC_RXCOAL_MAXF_INT_VEC1 + i * 0x18;
tw32(reg, ec->rx_max_coalesced_frames_irq);
}
for (; i < tp->irq_max - 1; i++) {
tw32(HOSTCC_RXCOL_TICKS_VEC1 + i * 0x18, 0);
tw32(HOSTCC_RXMAX_FRAMES_VEC1 + i * 0x18, 0);
tw32(HOSTCC_RXCOAL_MAXF_INT_VEC1 + i * 0x18, 0);
}
}
static void __tg3_set_coalesce(struct tg3 *tp, struct ethtool_coalesce *ec)
{
tg3_coal_tx_init(tp, ec);
tg3_coal_rx_init(tp, ec);
if (!tg3_flag(tp, 5705_PLUS)) {
u32 val = ec->stats_block_coalesce_usecs;
tw32(HOSTCC_RXCOAL_TICK_INT, ec->rx_coalesce_usecs_irq);
tw32(HOSTCC_TXCOAL_TICK_INT, ec->tx_coalesce_usecs_irq);
if (!tp->link_up)
val = 0;
tw32(HOSTCC_STAT_COAL_TICKS, val);
}
}
/* tp->lock is held. */
static void tg3_tx_rcbs_disable(struct tg3 *tp)
{
u32 txrcb, limit;
/* Disable all transmit rings but the first. */
if (!tg3_flag(tp, 5705_PLUS))
limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 16;
else if (tg3_flag(tp, 5717_PLUS))
limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 4;
else if (tg3_flag(tp, 57765_CLASS) ||
tg3_asic_rev(tp) == ASIC_REV_5762)
limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 2;
else
limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE;
for (txrcb = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE;
txrcb < limit; txrcb += TG3_BDINFO_SIZE)
tg3_write_mem(tp, txrcb + TG3_BDINFO_MAXLEN_FLAGS,
BDINFO_FLAGS_DISABLED);
}
/* tp->lock is held. */
static void tg3_tx_rcbs_init(struct tg3 *tp)
{
int i = 0;
u32 txrcb = NIC_SRAM_SEND_RCB;
if (tg3_flag(tp, ENABLE_TSS))
i++;
for (; i < tp->irq_max; i++, txrcb += TG3_BDINFO_SIZE) {
struct tg3_napi *tnapi = &tp->napi[i];
if (!tnapi->tx_ring)
continue;
tg3_set_bdinfo(tp, txrcb, tnapi->tx_desc_mapping,
(TG3_TX_RING_SIZE << BDINFO_FLAGS_MAXLEN_SHIFT),
NIC_SRAM_TX_BUFFER_DESC);
}
}
/* tp->lock is held. */
static void tg3_rx_ret_rcbs_disable(struct tg3 *tp)
{
u32 rxrcb, limit;
/* Disable all receive return rings but the first. */
if (tg3_flag(tp, 5717_PLUS))
limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 17;
else if (!tg3_flag(tp, 5705_PLUS))
limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 16;
else if (tg3_asic_rev(tp) == ASIC_REV_5755 ||
tg3_asic_rev(tp) == ASIC_REV_5762 ||
tg3_flag(tp, 57765_CLASS))
limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 4;
else
limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE;
for (rxrcb = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE;
rxrcb < limit; rxrcb += TG3_BDINFO_SIZE)
tg3_write_mem(tp, rxrcb + TG3_BDINFO_MAXLEN_FLAGS,
BDINFO_FLAGS_DISABLED);
}
/* tp->lock is held. */
static void tg3_rx_ret_rcbs_init(struct tg3 *tp)
{
int i = 0;
u32 rxrcb = NIC_SRAM_RCV_RET_RCB;
if (tg3_flag(tp, ENABLE_RSS))
i++;
for (; i < tp->irq_max; i++, rxrcb += TG3_BDINFO_SIZE) {
struct tg3_napi *tnapi = &tp->napi[i];
if (!tnapi->rx_rcb)
continue;
tg3_set_bdinfo(tp, rxrcb, tnapi->rx_rcb_mapping,
(tp->rx_ret_ring_mask + 1) <<
BDINFO_FLAGS_MAXLEN_SHIFT, 0);
}
}
/* tp->lock is held. */
static void tg3_rings_reset(struct tg3 *tp)
{
int i;
u32 stblk;
struct tg3_napi *tnapi = &tp->napi[0];
tg3_tx_rcbs_disable(tp);
tg3_rx_ret_rcbs_disable(tp);
/* Disable interrupts */
tw32_mailbox_f(tp->napi[0].int_mbox, 1);
tp->napi[0].chk_msi_cnt = 0;
tp->napi[0].last_rx_cons = 0;
tp->napi[0].last_tx_cons = 0;
/* Zero mailbox registers. */
if (tg3_flag(tp, SUPPORT_MSIX)) {
for (i = 1; i < tp->irq_max; i++) {
tp->napi[i].tx_prod = 0;
tp->napi[i].tx_cons = 0;
if (tg3_flag(tp, ENABLE_TSS))
tw32_mailbox(tp->napi[i].prodmbox, 0);
tw32_rx_mbox(tp->napi[i].consmbox, 0);
tw32_mailbox_f(tp->napi[i].int_mbox, 1);
tp->napi[i].chk_msi_cnt = 0;
tp->napi[i].last_rx_cons = 0;
tp->napi[i].last_tx_cons = 0;
}
if (!tg3_flag(tp, ENABLE_TSS))
tw32_mailbox(tp->napi[0].prodmbox, 0);
} else {
tp->napi[0].tx_prod = 0;
tp->napi[0].tx_cons = 0;
tw32_mailbox(tp->napi[0].prodmbox, 0);
tw32_rx_mbox(tp->napi[0].consmbox, 0);
}
/* Make sure the NIC-based send BD rings are disabled. */
if (!tg3_flag(tp, 5705_PLUS)) {
u32 mbox = MAILBOX_SNDNIC_PROD_IDX_0 + TG3_64BIT_REG_LOW;
for (i = 0; i < 16; i++)
tw32_tx_mbox(mbox + i * 8, 0);
}
/* Clear status block in ram. */
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
/* Set status block DMA address */
tw32(HOSTCC_STATUS_BLK_HOST_ADDR + TG3_64BIT_REG_HIGH,
((u64) tnapi->status_mapping >> 32));
tw32(HOSTCC_STATUS_BLK_HOST_ADDR + TG3_64BIT_REG_LOW,
((u64) tnapi->status_mapping & 0xffffffff));
stblk = HOSTCC_STATBLCK_RING1;
for (i = 1, tnapi++; i < tp->irq_cnt; i++, tnapi++) {
u64 mapping = (u64)tnapi->status_mapping;
tw32(stblk + TG3_64BIT_REG_HIGH, mapping >> 32);
tw32(stblk + TG3_64BIT_REG_LOW, mapping & 0xffffffff);
stblk += 8;
/* Clear status block in ram. */
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
}
tg3_tx_rcbs_init(tp);
tg3_rx_ret_rcbs_init(tp);
}
static void tg3_setup_rxbd_thresholds(struct tg3 *tp)
{
u32 val, bdcache_maxcnt, host_rep_thresh, nic_rep_thresh;
if (!tg3_flag(tp, 5750_PLUS) ||
tg3_flag(tp, 5780_CLASS) ||
tg3_asic_rev(tp) == ASIC_REV_5750 ||
tg3_asic_rev(tp) == ASIC_REV_5752 ||
tg3_flag(tp, 57765_PLUS))
bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5700;
else if (tg3_asic_rev(tp) == ASIC_REV_5755 ||
tg3_asic_rev(tp) == ASIC_REV_5787)
bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5755;
else
bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5906;
nic_rep_thresh = min(bdcache_maxcnt / 2, tp->rx_std_max_post);
host_rep_thresh = max_t(u32, tp->rx_pending / 8, 1);
val = min(nic_rep_thresh, host_rep_thresh);
tw32(RCVBDI_STD_THRESH, val);
if (tg3_flag(tp, 57765_PLUS))
tw32(STD_REPLENISH_LWM, bdcache_maxcnt);
if (!tg3_flag(tp, JUMBO_CAPABLE) || tg3_flag(tp, 5780_CLASS))
return;
bdcache_maxcnt = TG3_SRAM_RX_JMB_BDCACHE_SIZE_5700;
host_rep_thresh = max_t(u32, tp->rx_jumbo_pending / 8, 1);
val = min(bdcache_maxcnt / 2, host_rep_thresh);
tw32(RCVBDI_JUMBO_THRESH, val);
if (tg3_flag(tp, 57765_PLUS))
tw32(JMB_REPLENISH_LWM, bdcache_maxcnt);
}
static inline u32 calc_crc(unsigned char *buf, int len)
{
u32 reg;
u32 tmp;
int j, k;
reg = 0xffffffff;
for (j = 0; j < len; j++) {
reg ^= buf[j];
for (k = 0; k < 8; k++) {
tmp = reg & 0x01;
reg >>= 1;
if (tmp)
reg ^= 0xedb88320;
}
}
return ~reg;
}
static void tg3_set_multi(struct tg3 *tp, unsigned int accept_all)
{
/* accept or reject all multicast frames */
tw32(MAC_HASH_REG_0, accept_all ? 0xffffffff : 0);
tw32(MAC_HASH_REG_1, accept_all ? 0xffffffff : 0);
tw32(MAC_HASH_REG_2, accept_all ? 0xffffffff : 0);
tw32(MAC_HASH_REG_3, accept_all ? 0xffffffff : 0);
}
static void __tg3_set_rx_mode(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
u32 rx_mode;
rx_mode = tp->rx_mode & ~(RX_MODE_PROMISC |
RX_MODE_KEEP_VLAN_TAG);
#if !defined(CONFIG_VLAN_8021Q) && !defined(CONFIG_VLAN_8021Q_MODULE)
/* When ASF is in use, we always keep the RX_MODE_KEEP_VLAN_TAG
* flag clear.
*/
if (!tg3_flag(tp, ENABLE_ASF))
rx_mode |= RX_MODE_KEEP_VLAN_TAG;
#endif
if (dev->flags & IFF_PROMISC) {
/* Promiscuous mode. */
rx_mode |= RX_MODE_PROMISC;
} else if (dev->flags & IFF_ALLMULTI) {
/* Accept all multicast. */
tg3_set_multi(tp, 1);
} else if (netdev_mc_empty(dev)) {
/* Reject all multicast. */
tg3_set_multi(tp, 0);
} else {
/* Accept one or more multicast(s). */
struct netdev_hw_addr *ha;
u32 mc_filter[4] = { 0, };
u32 regidx;
u32 bit;
u32 crc;
netdev_for_each_mc_addr(ha, dev) {
crc = calc_crc(ha->addr, ETH_ALEN);
bit = ~crc & 0x7f;
regidx = (bit & 0x60) >> 5;
bit &= 0x1f;
mc_filter[regidx] |= (1 << bit);
}
tw32(MAC_HASH_REG_0, mc_filter[0]);
tw32(MAC_HASH_REG_1, mc_filter[1]);
tw32(MAC_HASH_REG_2, mc_filter[2]);
tw32(MAC_HASH_REG_3, mc_filter[3]);
}
if (netdev_uc_count(dev) > TG3_MAX_UCAST_ADDR(tp)) {
rx_mode |= RX_MODE_PROMISC;
} else if (!(dev->flags & IFF_PROMISC)) {
/* Add all entries into to the mac addr filter list */
int i = 0;
struct netdev_hw_addr *ha;
netdev_for_each_uc_addr(ha, dev) {
__tg3_set_one_mac_addr(tp, ha->addr,
i + TG3_UCAST_ADDR_IDX(tp));
i++;
}
}
if (rx_mode != tp->rx_mode) {
tp->rx_mode = rx_mode;
tw32_f(MAC_RX_MODE, rx_mode);
udelay(10);
}
}
static void tg3_rss_init_dflt_indir_tbl(struct tg3 *tp, u32 qcnt)
{
int i;
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++)
tp->rss_ind_tbl[i] = ethtool_rxfh_indir_default(i, qcnt);
}
static void tg3_rss_check_indir_tbl(struct tg3 *tp)
{
int i;
if (!tg3_flag(tp, SUPPORT_MSIX))
return;
if (tp->rxq_cnt == 1) {
memset(&tp->rss_ind_tbl[0], 0, sizeof(tp->rss_ind_tbl));
return;
}
/* Validate table against current IRQ count */
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++) {
if (tp->rss_ind_tbl[i] >= tp->rxq_cnt)
break;
}
if (i != TG3_RSS_INDIR_TBL_SIZE)
tg3_rss_init_dflt_indir_tbl(tp, tp->rxq_cnt);
}
static void tg3_rss_write_indir_tbl(struct tg3 *tp)
{
int i = 0;
u32 reg = MAC_RSS_INDIR_TBL_0;
while (i < TG3_RSS_INDIR_TBL_SIZE) {
u32 val = tp->rss_ind_tbl[i];
i++;
for (; i % 8; i++) {
val <<= 4;
val |= tp->rss_ind_tbl[i];
}
tw32(reg, val);
reg += 4;
}
}
static inline u32 tg3_lso_rd_dma_workaround_bit(struct tg3 *tp)
{
if (tg3_asic_rev(tp) == ASIC_REV_5719)
return TG3_LSO_RD_DMA_TX_LENGTH_WA_5719;
else
return TG3_LSO_RD_DMA_TX_LENGTH_WA_5720;
}
/* tp->lock is held. */
static int tg3_reset_hw(struct tg3 *tp, bool reset_phy)
{
u32 val, rdmac_mode;
int i, err, limit;
struct tg3_rx_prodring_set *tpr = &tp->napi[0].prodring;
tg3_disable_ints(tp);
tg3_stop_fw(tp);
tg3_write_sig_pre_reset(tp, RESET_KIND_INIT);
if (tg3_flag(tp, INIT_COMPLETE))
tg3_abort_hw(tp, 1);
if ((tp->phy_flags & TG3_PHYFLG_KEEP_LINK_ON_PWRDN) &&
!(tp->phy_flags & TG3_PHYFLG_USER_CONFIGURED)) {
tg3_phy_pull_config(tp);
tg3_eee_pull_config(tp, NULL);
tp->phy_flags |= TG3_PHYFLG_USER_CONFIGURED;
}
/* Enable MAC control of LPI */
if (tp->phy_flags & TG3_PHYFLG_EEE_CAP)
tg3_setup_eee(tp);
if (reset_phy)
tg3_phy_reset(tp);
err = tg3_chip_reset(tp);
if (err)
return err;
tg3_write_sig_legacy(tp, RESET_KIND_INIT);
if (tg3_chip_rev(tp) == CHIPREV_5784_AX) {
val = tr32(TG3_CPMU_CTRL);
val &= ~(CPMU_CTRL_LINK_AWARE_MODE | CPMU_CTRL_LINK_IDLE_MODE);
tw32(TG3_CPMU_CTRL, val);
val = tr32(TG3_CPMU_LSPD_10MB_CLK);
val &= ~CPMU_LSPD_10MB_MACCLK_MASK;
val |= CPMU_LSPD_10MB_MACCLK_6_25;
tw32(TG3_CPMU_LSPD_10MB_CLK, val);
val = tr32(TG3_CPMU_LNK_AWARE_PWRMD);
val &= ~CPMU_LNK_AWARE_MACCLK_MASK;
val |= CPMU_LNK_AWARE_MACCLK_6_25;
tw32(TG3_CPMU_LNK_AWARE_PWRMD, val);
val = tr32(TG3_CPMU_HST_ACC);
val &= ~CPMU_HST_ACC_MACCLK_MASK;
val |= CPMU_HST_ACC_MACCLK_6_25;
tw32(TG3_CPMU_HST_ACC, val);
}
if (tg3_asic_rev(tp) == ASIC_REV_57780) {
val = tr32(PCIE_PWR_MGMT_THRESH) & ~PCIE_PWR_MGMT_L1_THRESH_MSK;
val |= PCIE_PWR_MGMT_EXT_ASPM_TMR_EN |
PCIE_PWR_MGMT_L1_THRESH_4MS;
tw32(PCIE_PWR_MGMT_THRESH, val);
val = tr32(TG3_PCIE_EIDLE_DELAY) & ~TG3_PCIE_EIDLE_DELAY_MASK;
tw32(TG3_PCIE_EIDLE_DELAY, val | TG3_PCIE_EIDLE_DELAY_13_CLKS);
tw32(TG3_CORR_ERR_STAT, TG3_CORR_ERR_STAT_CLEAR);
val = tr32(TG3_PCIE_LNKCTL) & ~TG3_PCIE_LNKCTL_L1_PLL_PD_EN;
tw32(TG3_PCIE_LNKCTL, val | TG3_PCIE_LNKCTL_L1_PLL_PD_DIS);
}
if (tg3_flag(tp, L1PLLPD_EN)) {
u32 grc_mode = tr32(GRC_MODE);
/* Access the lower 1K of PL PCIE block registers. */
val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK;
tw32(GRC_MODE, val | GRC_MODE_PCIE_PL_SEL);
val = tr32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL1);
tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL1,
val | TG3_PCIE_PL_LO_PHYCTL1_L1PLLPD_EN);
tw32(GRC_MODE, grc_mode);
}
if (tg3_flag(tp, 57765_CLASS)) {
if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0) {
u32 grc_mode = tr32(GRC_MODE);
/* Access the lower 1K of PL PCIE block registers. */
val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK;
tw32(GRC_MODE, val | GRC_MODE_PCIE_PL_SEL);
val = tr32(TG3_PCIE_TLDLPL_PORT +
TG3_PCIE_PL_LO_PHYCTL5);
tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL5,
val | TG3_PCIE_PL_LO_PHYCTL5_DIS_L2CLKREQ);
tw32(GRC_MODE, grc_mode);
}
if (tg3_chip_rev(tp) != CHIPREV_57765_AX) {
u32 grc_mode;
/* Fix transmit hangs */
val = tr32(TG3_CPMU_PADRNG_CTL);
val |= TG3_CPMU_PADRNG_CTL_RDIV2;
tw32(TG3_CPMU_PADRNG_CTL, val);
grc_mode = tr32(GRC_MODE);
/* Access the lower 1K of DL PCIE block registers. */
val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK;
tw32(GRC_MODE, val | GRC_MODE_PCIE_DL_SEL);
val = tr32(TG3_PCIE_TLDLPL_PORT +
TG3_PCIE_DL_LO_FTSMAX);
val &= ~TG3_PCIE_DL_LO_FTSMAX_MSK;
tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_DL_LO_FTSMAX,
val | TG3_PCIE_DL_LO_FTSMAX_VAL);
tw32(GRC_MODE, grc_mode);
}
val = tr32(TG3_CPMU_LSPD_10MB_CLK);
val &= ~CPMU_LSPD_10MB_MACCLK_MASK;
val |= CPMU_LSPD_10MB_MACCLK_6_25;
tw32(TG3_CPMU_LSPD_10MB_CLK, val);
}
/* This works around an issue with Athlon chipsets on
* B3 tigon3 silicon. This bit has no effect on any
* other revision. But do not set this on PCI Express
* chips and don't even touch the clocks if the CPMU is present.
*/
if (!tg3_flag(tp, CPMU_PRESENT)) {
if (!tg3_flag(tp, PCI_EXPRESS))
tp->pci_clock_ctrl |= CLOCK_CTRL_DELAY_PCI_GRANT;
tw32_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl);
}
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0 &&
tg3_flag(tp, PCIX_MODE)) {
val = tr32(TG3PCI_PCISTATE);
val |= PCISTATE_RETRY_SAME_DMA;
tw32(TG3PCI_PCISTATE, val);
}
if (tg3_flag(tp, ENABLE_APE)) {
/* Allow reads and writes to the
* APE register and memory space.
*/
val = tr32(TG3PCI_PCISTATE);
val |= PCISTATE_ALLOW_APE_CTLSPC_WR |
PCISTATE_ALLOW_APE_SHMEM_WR |
PCISTATE_ALLOW_APE_PSPACE_WR;
tw32(TG3PCI_PCISTATE, val);
}
if (tg3_chip_rev(tp) == CHIPREV_5704_BX) {
/* Enable some hw fixes. */
val = tr32(TG3PCI_MSI_DATA);
val |= (1 << 26) | (1 << 28) | (1 << 29);
tw32(TG3PCI_MSI_DATA, val);
}
/* Descriptor ring init may make accesses to the
* NIC SRAM area to setup the TX descriptors, so we
* can only do this after the hardware has been
* successfully reset.
*/
err = tg3_init_rings(tp);
if (err)
return err;
if (tg3_flag(tp, 57765_PLUS)) {
val = tr32(TG3PCI_DMA_RW_CTRL) &
~DMA_RWCTRL_DIS_CACHE_ALIGNMENT;
if (tg3_chip_rev_id(tp) == CHIPREV_ID_57765_A0)
val &= ~DMA_RWCTRL_CRDRDR_RDMA_MRRS_MSK;
if (!tg3_flag(tp, 57765_CLASS) &&
tg3_asic_rev(tp) != ASIC_REV_5717 &&
tg3_asic_rev(tp) != ASIC_REV_5762)
val |= DMA_RWCTRL_TAGGED_STAT_WA;
tw32(TG3PCI_DMA_RW_CTRL, val | tp->dma_rwctrl);
} else if (tg3_asic_rev(tp) != ASIC_REV_5784 &&
tg3_asic_rev(tp) != ASIC_REV_5761) {
/* This value is determined during the probe time DMA
* engine test, tg3_test_dma.
*/
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
}
tp->grc_mode &= ~(GRC_MODE_HOST_SENDBDS |
GRC_MODE_4X_NIC_SEND_RINGS |
GRC_MODE_NO_TX_PHDR_CSUM |
GRC_MODE_NO_RX_PHDR_CSUM);
tp->grc_mode |= GRC_MODE_HOST_SENDBDS;
/* Pseudo-header checksum is done by hardware logic and not
* the offload processers, so make the chip do the pseudo-
* header checksums on receive. For transmit it is more
* convenient to do the pseudo-header checksum in software
* as Linux does that on transmit for us in all cases.
*/
tp->grc_mode |= GRC_MODE_NO_TX_PHDR_CSUM;
val = GRC_MODE_IRQ_ON_MAC_ATTN | GRC_MODE_HOST_STACKUP;
if (tp->rxptpctl)
tw32(TG3_RX_PTP_CTL,
tp->rxptpctl | TG3_RX_PTP_CTL_HWTS_INTERLOCK);
if (tg3_flag(tp, PTP_CAPABLE))
val |= GRC_MODE_TIME_SYNC_ENABLE;
tw32(GRC_MODE, tp->grc_mode | val);
/* Setup the timer prescalar register. Clock is always 66Mhz. */
val = tr32(GRC_MISC_CFG);
val &= ~0xff;
val |= (65 << GRC_MISC_CFG_PRESCALAR_SHIFT);
tw32(GRC_MISC_CFG, val);
/* Initialize MBUF/DESC pool. */
if (tg3_flag(tp, 5750_PLUS)) {
/* Do nothing. */
} else if (tg3_asic_rev(tp) != ASIC_REV_5705) {
tw32(BUFMGR_MB_POOL_ADDR, NIC_SRAM_MBUF_POOL_BASE);
if (tg3_asic_rev(tp) == ASIC_REV_5704)
tw32(BUFMGR_MB_POOL_SIZE, NIC_SRAM_MBUF_POOL_SIZE64);
else
tw32(BUFMGR_MB_POOL_SIZE, NIC_SRAM_MBUF_POOL_SIZE96);
tw32(BUFMGR_DMA_DESC_POOL_ADDR, NIC_SRAM_DMA_DESC_POOL_BASE);
tw32(BUFMGR_DMA_DESC_POOL_SIZE, NIC_SRAM_DMA_DESC_POOL_SIZE);
} else if (tg3_flag(tp, TSO_CAPABLE)) {
int fw_len;
fw_len = tp->fw_len;
fw_len = (fw_len + (0x80 - 1)) & ~(0x80 - 1);
tw32(BUFMGR_MB_POOL_ADDR,
NIC_SRAM_MBUF_POOL_BASE5705 + fw_len);
tw32(BUFMGR_MB_POOL_SIZE,
NIC_SRAM_MBUF_POOL_SIZE5705 - fw_len - 0xa00);
}
if (tp->dev->mtu <= ETH_DATA_LEN) {
tw32(BUFMGR_MB_RDMA_LOW_WATER,
tp->bufmgr_config.mbuf_read_dma_low_water);
tw32(BUFMGR_MB_MACRX_LOW_WATER,
tp->bufmgr_config.mbuf_mac_rx_low_water);
tw32(BUFMGR_MB_HIGH_WATER,
tp->bufmgr_config.mbuf_high_water);
} else {
tw32(BUFMGR_MB_RDMA_LOW_WATER,
tp->bufmgr_config.mbuf_read_dma_low_water_jumbo);
tw32(BUFMGR_MB_MACRX_LOW_WATER,
tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo);
tw32(BUFMGR_MB_HIGH_WATER,
tp->bufmgr_config.mbuf_high_water_jumbo);
}
tw32(BUFMGR_DMA_LOW_WATER,
tp->bufmgr_config.dma_low_water);
tw32(BUFMGR_DMA_HIGH_WATER,
tp->bufmgr_config.dma_high_water);
val = BUFMGR_MODE_ENABLE | BUFMGR_MODE_ATTN_ENABLE;
if (tg3_asic_rev(tp) == ASIC_REV_5719)
val |= BUFMGR_MODE_NO_TX_UNDERRUN;
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5762 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5720_A0)
val |= BUFMGR_MODE_MBLOW_ATTN_ENAB;
tw32(BUFMGR_MODE, val);
for (i = 0; i < 2000; i++) {
if (tr32(BUFMGR_MODE) & BUFMGR_MODE_ENABLE)
break;
udelay(10);
}
if (i >= 2000) {
netdev_err(tp->dev, "%s cannot enable BUFMGR\n", __func__);
return -ENODEV;
}
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5906_A1)
tw32(ISO_PKT_TX, (tr32(ISO_PKT_TX) & ~0x3) | 0x2);
tg3_setup_rxbd_thresholds(tp);
/* Initialize TG3_BDINFO's at:
* RCVDBDI_STD_BD: standard eth size rx ring
* RCVDBDI_JUMBO_BD: jumbo frame rx ring
* RCVDBDI_MINI_BD: small frame rx ring (??? does not work)
*
* like so:
* TG3_BDINFO_HOST_ADDR: high/low parts of DMA address of ring
* TG3_BDINFO_MAXLEN_FLAGS: (rx max buffer size << 16) |
* ring attribute flags
* TG3_BDINFO_NIC_ADDR: location of descriptors in nic SRAM
*
* Standard receive ring @ NIC_SRAM_RX_BUFFER_DESC, 512 entries.
* Jumbo receive ring @ NIC_SRAM_RX_JUMBO_BUFFER_DESC, 256 entries.
*
* The size of each ring is fixed in the firmware, but the location is
* configurable.
*/
tw32(RCVDBDI_STD_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH,
((u64) tpr->rx_std_mapping >> 32));
tw32(RCVDBDI_STD_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW,
((u64) tpr->rx_std_mapping & 0xffffffff));
if (!tg3_flag(tp, 5717_PLUS))
tw32(RCVDBDI_STD_BD + TG3_BDINFO_NIC_ADDR,
NIC_SRAM_RX_BUFFER_DESC);
/* Disable the mini ring */
if (!tg3_flag(tp, 5705_PLUS))
tw32(RCVDBDI_MINI_BD + TG3_BDINFO_MAXLEN_FLAGS,
BDINFO_FLAGS_DISABLED);
/* Program the jumbo buffer descriptor ring control
* blocks on those devices that have them.
*/
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 ||
(tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS))) {
if (tg3_flag(tp, JUMBO_RING_ENABLE)) {
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH,
((u64) tpr->rx_jmb_mapping >> 32));
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW,
((u64) tpr->rx_jmb_mapping & 0xffffffff));
val = TG3_RX_JMB_RING_SIZE(tp) <<
BDINFO_FLAGS_MAXLEN_SHIFT;
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_MAXLEN_FLAGS,
val | BDINFO_FLAGS_USE_EXT_RECV);
if (!tg3_flag(tp, USE_JUMBO_BDFLAG) ||
tg3_flag(tp, 57765_CLASS) ||
tg3_asic_rev(tp) == ASIC_REV_5762)
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_NIC_ADDR,
NIC_SRAM_RX_JUMBO_BUFFER_DESC);
} else {
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_MAXLEN_FLAGS,
BDINFO_FLAGS_DISABLED);
}
if (tg3_flag(tp, 57765_PLUS)) {
val = TG3_RX_STD_RING_SIZE(tp);
val <<= BDINFO_FLAGS_MAXLEN_SHIFT;
val |= (TG3_RX_STD_DMA_SZ << 2);
} else
val = TG3_RX_STD_DMA_SZ << BDINFO_FLAGS_MAXLEN_SHIFT;
} else
val = TG3_RX_STD_MAX_SIZE_5700 << BDINFO_FLAGS_MAXLEN_SHIFT;
tw32(RCVDBDI_STD_BD + TG3_BDINFO_MAXLEN_FLAGS, val);
tpr->rx_std_prod_idx = tp->rx_pending;
tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG, tpr->rx_std_prod_idx);
tpr->rx_jmb_prod_idx =
tg3_flag(tp, JUMBO_RING_ENABLE) ? tp->rx_jumbo_pending : 0;
tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG, tpr->rx_jmb_prod_idx);
tg3_rings_reset(tp);
/* Initialize MAC address and backoff seed. */
__tg3_set_mac_addr(tp, false);
/* MTU + ethernet header + FCS + optional VLAN tag */
tw32(MAC_RX_MTU_SIZE,
tp->dev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN);
/* The slot time is changed by tg3_setup_phy if we
* run at gigabit with half duplex.
*/
val = (2 << TX_LENGTHS_IPG_CRS_SHIFT) |
(6 << TX_LENGTHS_IPG_SHIFT) |
(32 << TX_LENGTHS_SLOT_TIME_SHIFT);
if (tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762)
val |= tr32(MAC_TX_LENGTHS) &
(TX_LENGTHS_JMB_FRM_LEN_MSK |
TX_LENGTHS_CNT_DWN_VAL_MSK);
tw32(MAC_TX_LENGTHS, val);
/* Receive rules. */
tw32(MAC_RCV_RULE_CFG, RCV_RULE_CFG_DEFAULT_CLASS);
tw32(RCVLPC_CONFIG, 0x0181);
/* Calculate RDMAC_MODE setting early, we need it to determine
* the RCVLPC_STATE_ENABLE mask.
*/
rdmac_mode = (RDMAC_MODE_ENABLE | RDMAC_MODE_TGTABORT_ENAB |
RDMAC_MODE_MSTABORT_ENAB | RDMAC_MODE_PARITYERR_ENAB |
RDMAC_MODE_ADDROFLOW_ENAB | RDMAC_MODE_FIFOOFLOW_ENAB |
RDMAC_MODE_FIFOURUN_ENAB | RDMAC_MODE_FIFOOREAD_ENAB |
RDMAC_MODE_LNGREAD_ENAB);
if (tg3_asic_rev(tp) == ASIC_REV_5717)
rdmac_mode |= RDMAC_MODE_MULT_DMA_RD_DIS;
if (tg3_asic_rev(tp) == ASIC_REV_5784 ||
tg3_asic_rev(tp) == ASIC_REV_5785 ||
tg3_asic_rev(tp) == ASIC_REV_57780)
rdmac_mode |= RDMAC_MODE_BD_SBD_CRPT_ENAB |
RDMAC_MODE_MBUF_RBD_CRPT_ENAB |
RDMAC_MODE_MBUF_SBD_CRPT_ENAB;
if (tg3_asic_rev(tp) == ASIC_REV_5705 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) {
if (tg3_flag(tp, TSO_CAPABLE) &&
tg3_asic_rev(tp) == ASIC_REV_5705) {
rdmac_mode |= RDMAC_MODE_FIFO_SIZE_128;
} else if (!(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH) &&
!tg3_flag(tp, IS_5788)) {
rdmac_mode |= RDMAC_MODE_FIFO_LONG_BURST;
}
}
if (tg3_flag(tp, PCI_EXPRESS))
rdmac_mode |= RDMAC_MODE_FIFO_LONG_BURST;
if (tg3_asic_rev(tp) == ASIC_REV_57766) {
tp->dma_limit = 0;
if (tp->dev->mtu <= ETH_DATA_LEN) {
rdmac_mode |= RDMAC_MODE_JMB_2K_MMRR;
tp->dma_limit = TG3_TX_BD_DMA_MAX_2K;
}
}
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3))
rdmac_mode |= RDMAC_MODE_IPV4_LSO_EN;
if (tg3_flag(tp, 57765_PLUS) ||
tg3_asic_rev(tp) == ASIC_REV_5785 ||
tg3_asic_rev(tp) == ASIC_REV_57780)
rdmac_mode |= RDMAC_MODE_IPV6_LSO_EN;
if (tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762)
rdmac_mode |= tr32(RDMAC_MODE) & RDMAC_MODE_H2BNC_VLAN_DET;
if (tg3_asic_rev(tp) == ASIC_REV_5761 ||
tg3_asic_rev(tp) == ASIC_REV_5784 ||
tg3_asic_rev(tp) == ASIC_REV_5785 ||
tg3_asic_rev(tp) == ASIC_REV_57780 ||
tg3_flag(tp, 57765_PLUS)) {
u32 tgtreg;
if (tg3_asic_rev(tp) == ASIC_REV_5762)
tgtreg = TG3_RDMA_RSRVCTRL_REG2;
else
tgtreg = TG3_RDMA_RSRVCTRL_REG;
val = tr32(tgtreg);
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 ||
tg3_asic_rev(tp) == ASIC_REV_5762) {
val &= ~(TG3_RDMA_RSRVCTRL_TXMRGN_MASK |
TG3_RDMA_RSRVCTRL_FIFO_LWM_MASK |
TG3_RDMA_RSRVCTRL_FIFO_HWM_MASK);
val |= TG3_RDMA_RSRVCTRL_TXMRGN_320B |
TG3_RDMA_RSRVCTRL_FIFO_LWM_1_5K |
TG3_RDMA_RSRVCTRL_FIFO_HWM_1_5K;
}
tw32(tgtreg, val | TG3_RDMA_RSRVCTRL_FIFO_OFLW_FIX);
}
if (tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762) {
u32 tgtreg;
if (tg3_asic_rev(tp) == ASIC_REV_5762)
tgtreg = TG3_LSO_RD_DMA_CRPTEN_CTRL2;
else
tgtreg = TG3_LSO_RD_DMA_CRPTEN_CTRL;
val = tr32(tgtreg);
tw32(tgtreg, val |
TG3_LSO_RD_DMA_CRPTEN_CTRL_BLEN_BD_4K |
TG3_LSO_RD_DMA_CRPTEN_CTRL_BLEN_LSO_4K);
}
/* Receive/send statistics. */
if (tg3_flag(tp, 5750_PLUS)) {
val = tr32(RCVLPC_STATS_ENABLE);
val &= ~RCVLPC_STATSENAB_DACK_FIX;
tw32(RCVLPC_STATS_ENABLE, val);
} else if ((rdmac_mode & RDMAC_MODE_FIFO_SIZE_128) &&
tg3_flag(tp, TSO_CAPABLE)) {
val = tr32(RCVLPC_STATS_ENABLE);
val &= ~RCVLPC_STATSENAB_LNGBRST_RFIX;
tw32(RCVLPC_STATS_ENABLE, val);
} else {
tw32(RCVLPC_STATS_ENABLE, 0xffffff);
}
tw32(RCVLPC_STATSCTRL, RCVLPC_STATSCTRL_ENABLE);
tw32(SNDDATAI_STATSENAB, 0xffffff);
tw32(SNDDATAI_STATSCTRL,
(SNDDATAI_SCTRL_ENABLE |
SNDDATAI_SCTRL_FASTUPD));
/* Setup host coalescing engine. */
tw32(HOSTCC_MODE, 0);
for (i = 0; i < 2000; i++) {
if (!(tr32(HOSTCC_MODE) & HOSTCC_MODE_ENABLE))
break;
udelay(10);
}
__tg3_set_coalesce(tp, &tp->coal);
if (!tg3_flag(tp, 5705_PLUS)) {
/* Status/statistics block address. See tg3_timer,
* the tg3_periodic_fetch_stats call there, and
* tg3_get_stats to see how this works for 5705/5750 chips.
*/
tw32(HOSTCC_STATS_BLK_HOST_ADDR + TG3_64BIT_REG_HIGH,
((u64) tp->stats_mapping >> 32));
tw32(HOSTCC_STATS_BLK_HOST_ADDR + TG3_64BIT_REG_LOW,
((u64) tp->stats_mapping & 0xffffffff));
tw32(HOSTCC_STATS_BLK_NIC_ADDR, NIC_SRAM_STATS_BLK);
tw32(HOSTCC_STATUS_BLK_NIC_ADDR, NIC_SRAM_STATUS_BLK);
/* Clear statistics and status block memory areas */
for (i = NIC_SRAM_STATS_BLK;
i < NIC_SRAM_STATUS_BLK + TG3_HW_STATUS_SIZE;
i += sizeof(u32)) {
tg3_write_mem(tp, i, 0);
udelay(40);
}
}
tw32(HOSTCC_MODE, HOSTCC_MODE_ENABLE | tp->coalesce_mode);
tw32(RCVCC_MODE, RCVCC_MODE_ENABLE | RCVCC_MODE_ATTN_ENABLE);
tw32(RCVLPC_MODE, RCVLPC_MODE_ENABLE);
if (!tg3_flag(tp, 5705_PLUS))
tw32(RCVLSC_MODE, RCVLSC_MODE_ENABLE | RCVLSC_MODE_ATTN_ENABLE);
if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) {
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
/* reset to prevent losing 1st rx packet intermittently */
tw32_f(MAC_RX_MODE, RX_MODE_RESET);
udelay(10);
}
tp->mac_mode |= MAC_MODE_TXSTAT_ENABLE | MAC_MODE_RXSTAT_ENABLE |
MAC_MODE_TDE_ENABLE | MAC_MODE_RDE_ENABLE |
MAC_MODE_FHDE_ENABLE;
if (tg3_flag(tp, ENABLE_APE))
tp->mac_mode |= MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN;
if (!tg3_flag(tp, 5705_PLUS) &&
!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
tg3_asic_rev(tp) != ASIC_REV_5700)
tp->mac_mode |= MAC_MODE_LINK_POLARITY;
tw32_f(MAC_MODE, tp->mac_mode | MAC_MODE_RXSTAT_CLEAR | MAC_MODE_TXSTAT_CLEAR);
udelay(40);
/* tp->grc_local_ctrl is partially set up during tg3_get_invariants().
* If TG3_FLAG_IS_NIC is zero, we should read the
* register to preserve the GPIO settings for LOMs. The GPIOs,
* whether used as inputs or outputs, are set by boot code after
* reset.
*/
if (!tg3_flag(tp, IS_NIC)) {
u32 gpio_mask;
gpio_mask = GRC_LCLCTRL_GPIO_OE0 | GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OE2 | GRC_LCLCTRL_GPIO_OUTPUT0 |
GRC_LCLCTRL_GPIO_OUTPUT1 | GRC_LCLCTRL_GPIO_OUTPUT2;
if (tg3_asic_rev(tp) == ASIC_REV_5752)
gpio_mask |= GRC_LCLCTRL_GPIO_OE3 |
GRC_LCLCTRL_GPIO_OUTPUT3;
if (tg3_asic_rev(tp) == ASIC_REV_5755)
gpio_mask |= GRC_LCLCTRL_GPIO_UART_SEL;
tp->grc_local_ctrl &= ~gpio_mask;
tp->grc_local_ctrl |= tr32(GRC_LOCAL_CTRL) & gpio_mask;
/* GPIO1 must be driven high for eeprom write protect */
if (tg3_flag(tp, EEPROM_WRITE_PROT))
tp->grc_local_ctrl |= (GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OUTPUT1);
}
tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl);
udelay(100);
if (tg3_flag(tp, USING_MSIX)) {
val = tr32(MSGINT_MODE);
val |= MSGINT_MODE_ENABLE;
if (tp->irq_cnt > 1)
val |= MSGINT_MODE_MULTIVEC_EN;
if (!tg3_flag(tp, 1SHOT_MSI))
val |= MSGINT_MODE_ONE_SHOT_DISABLE;
tw32(MSGINT_MODE, val);
}
if (!tg3_flag(tp, 5705_PLUS)) {
tw32_f(DMAC_MODE, DMAC_MODE_ENABLE);
udelay(40);
}
val = (WDMAC_MODE_ENABLE | WDMAC_MODE_TGTABORT_ENAB |
WDMAC_MODE_MSTABORT_ENAB | WDMAC_MODE_PARITYERR_ENAB |
WDMAC_MODE_ADDROFLOW_ENAB | WDMAC_MODE_FIFOOFLOW_ENAB |
WDMAC_MODE_FIFOURUN_ENAB | WDMAC_MODE_FIFOOREAD_ENAB |
WDMAC_MODE_LNGREAD_ENAB);
if (tg3_asic_rev(tp) == ASIC_REV_5705 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) {
if (tg3_flag(tp, TSO_CAPABLE) &&
(tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A1 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A2)) {
/* nothing */
} else if (!(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH) &&
!tg3_flag(tp, IS_5788)) {
val |= WDMAC_MODE_RX_ACCEL;
}
}
/* Enable host coalescing bug fix */
if (tg3_flag(tp, 5755_PLUS))
val |= WDMAC_MODE_STATUS_TAG_FIX;
if (tg3_asic_rev(tp) == ASIC_REV_5785)
val |= WDMAC_MODE_BURST_ALL_DATA;
tw32_f(WDMAC_MODE, val);
udelay(40);
if (tg3_flag(tp, PCIX_MODE)) {
u16 pcix_cmd;
pci_read_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD,
&pcix_cmd);
if (tg3_asic_rev(tp) == ASIC_REV_5703) {
pcix_cmd &= ~PCI_X_CMD_MAX_READ;
pcix_cmd |= PCI_X_CMD_READ_2K;
} else if (tg3_asic_rev(tp) == ASIC_REV_5704) {
pcix_cmd &= ~(PCI_X_CMD_MAX_SPLIT | PCI_X_CMD_MAX_READ);
pcix_cmd |= PCI_X_CMD_READ_2K;
}
pci_write_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD,
pcix_cmd);
}
tw32_f(RDMAC_MODE, rdmac_mode);
udelay(40);
if (tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720) {
for (i = 0; i < TG3_NUM_RDMA_CHANNELS; i++) {
if (tr32(TG3_RDMA_LENGTH + (i << 2)) > TG3_MAX_MTU(tp))
break;
}
if (i < TG3_NUM_RDMA_CHANNELS) {
val = tr32(TG3_LSO_RD_DMA_CRPTEN_CTRL);
val |= tg3_lso_rd_dma_workaround_bit(tp);
tw32(TG3_LSO_RD_DMA_CRPTEN_CTRL, val);
tg3_flag_set(tp, 5719_5720_RDMA_BUG);
}
}
tw32(RCVDCC_MODE, RCVDCC_MODE_ENABLE | RCVDCC_MODE_ATTN_ENABLE);
if (!tg3_flag(tp, 5705_PLUS))
tw32(MBFREE_MODE, MBFREE_MODE_ENABLE);
if (tg3_asic_rev(tp) == ASIC_REV_5761)
tw32(SNDDATAC_MODE,
SNDDATAC_MODE_ENABLE | SNDDATAC_MODE_CDELAY);
else
tw32(SNDDATAC_MODE, SNDDATAC_MODE_ENABLE);
tw32(SNDBDC_MODE, SNDBDC_MODE_ENABLE | SNDBDC_MODE_ATTN_ENABLE);
tw32(RCVBDI_MODE, RCVBDI_MODE_ENABLE | RCVBDI_MODE_RCB_ATTN_ENAB);
val = RCVDBDI_MODE_ENABLE | RCVDBDI_MODE_INV_RING_SZ;
if (tg3_flag(tp, LRG_PROD_RING_CAP))
val |= RCVDBDI_MODE_LRG_RING_SZ;
tw32(RCVDBDI_MODE, val);
tw32(SNDDATAI_MODE, SNDDATAI_MODE_ENABLE);
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3))
tw32(SNDDATAI_MODE, SNDDATAI_MODE_ENABLE | 0x8);
val = SNDBDI_MODE_ENABLE | SNDBDI_MODE_ATTN_ENABLE;
if (tg3_flag(tp, ENABLE_TSS))
val |= SNDBDI_MODE_MULTI_TXQ_EN;
tw32(SNDBDI_MODE, val);
tw32(SNDBDS_MODE, SNDBDS_MODE_ENABLE | SNDBDS_MODE_ATTN_ENABLE);
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0) {
err = tg3_load_5701_a0_firmware_fix(tp);
if (err)
return err;
}
if (tg3_asic_rev(tp) == ASIC_REV_57766) {
/* Ignore any errors for the firmware download. If download
* fails, the device will operate with EEE disabled
*/
tg3_load_57766_firmware(tp);
}
if (tg3_flag(tp, TSO_CAPABLE)) {
err = tg3_load_tso_firmware(tp);
if (err)
return err;
}
tp->tx_mode = TX_MODE_ENABLE;
if (tg3_flag(tp, 5755_PLUS) ||
tg3_asic_rev(tp) == ASIC_REV_5906)
tp->tx_mode |= TX_MODE_MBUF_LOCKUP_FIX;
if (tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762) {
val = TX_MODE_JMB_FRM_LEN | TX_MODE_CNT_DN_MODE;
tp->tx_mode &= ~val;
tp->tx_mode |= tr32(MAC_TX_MODE) & val;
}
tw32_f(MAC_TX_MODE, tp->tx_mode);
udelay(100);
if (tg3_flag(tp, ENABLE_RSS)) {
tg3_rss_write_indir_tbl(tp);
/* Setup the "secret" hash key. */
tw32(MAC_RSS_HASH_KEY_0, 0x5f865437);
tw32(MAC_RSS_HASH_KEY_1, 0xe4ac62cc);
tw32(MAC_RSS_HASH_KEY_2, 0x50103a45);
tw32(MAC_RSS_HASH_KEY_3, 0x36621985);
tw32(MAC_RSS_HASH_KEY_4, 0xbf14c0e8);
tw32(MAC_RSS_HASH_KEY_5, 0x1bc27a1e);
tw32(MAC_RSS_HASH_KEY_6, 0x84f4b556);
tw32(MAC_RSS_HASH_KEY_7, 0x094ea6fe);
tw32(MAC_RSS_HASH_KEY_8, 0x7dda01e7);
tw32(MAC_RSS_HASH_KEY_9, 0xc04d7481);
}
tp->rx_mode = RX_MODE_ENABLE;
if (tg3_flag(tp, 5755_PLUS))
tp->rx_mode |= RX_MODE_IPV6_CSUM_ENABLE;
if (tg3_asic_rev(tp) == ASIC_REV_5762)
tp->rx_mode |= RX_MODE_IPV4_FRAG_FIX;
if (tg3_flag(tp, ENABLE_RSS))
tp->rx_mode |= RX_MODE_RSS_ENABLE |
RX_MODE_RSS_ITBL_HASH_BITS_7 |
RX_MODE_RSS_IPV6_HASH_EN |
RX_MODE_RSS_TCP_IPV6_HASH_EN |
RX_MODE_RSS_IPV4_HASH_EN |
RX_MODE_RSS_TCP_IPV4_HASH_EN;
tw32_f(MAC_RX_MODE, tp->rx_mode);
udelay(10);
tw32(MAC_LED_CTRL, tp->led_ctrl);
tw32(MAC_MI_STAT, MAC_MI_STAT_LNKSTAT_ATTN_ENAB);
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
tw32_f(MAC_RX_MODE, RX_MODE_RESET);
udelay(10);
}
tw32_f(MAC_RX_MODE, tp->rx_mode);
udelay(10);
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
if ((tg3_asic_rev(tp) == ASIC_REV_5704) &&
!(tp->phy_flags & TG3_PHYFLG_SERDES_PREEMPHASIS)) {
/* Set drive transmission level to 1.2V */
/* only if the signal pre-emphasis bit is not set */
val = tr32(MAC_SERDES_CFG);
val &= 0xfffff000;
val |= 0x880;
tw32(MAC_SERDES_CFG, val);
}
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A1)
tw32(MAC_SERDES_CFG, 0x616000);
}
/* Prevent chip from dropping frames when flow control
* is enabled.
*/
if (tg3_flag(tp, 57765_CLASS))
val = 1;
else
val = 2;
tw32_f(MAC_LOW_WMARK_MAX_RX_FRAME, val);
if (tg3_asic_rev(tp) == ASIC_REV_5704 &&
(tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) {
/* Use hardware link auto-negotiation */
tg3_flag_set(tp, HW_AUTONEG);
}
if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) &&
tg3_asic_rev(tp) == ASIC_REV_5714) {
u32 tmp;
tmp = tr32(SERDES_RX_CTRL);
tw32(SERDES_RX_CTRL, tmp | SERDES_RX_SIG_DETECT);
tp->grc_local_ctrl &= ~GRC_LCLCTRL_USE_EXT_SIG_DETECT;
tp->grc_local_ctrl |= GRC_LCLCTRL_USE_SIG_DETECT;
tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl);
}
if (!tg3_flag(tp, USE_PHYLIB)) {
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)
tp->phy_flags &= ~TG3_PHYFLG_IS_LOW_POWER;
err = tg3_setup_phy(tp, false);
if (err)
return err;
if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
!(tp->phy_flags & TG3_PHYFLG_IS_FET)) {
u32 tmp;
/* Clear CRC stats. */
if (!tg3_readphy(tp, MII_TG3_TEST1, &tmp)) {
tg3_writephy(tp, MII_TG3_TEST1,
tmp | MII_TG3_TEST1_CRC_EN);
tg3_readphy(tp, MII_TG3_RXR_COUNTERS, &tmp);
}
}
}
__tg3_set_rx_mode(tp->dev);
/* Initialize receive rules. */
tw32(MAC_RCV_RULE_0, 0xc2000000 & RCV_RULE_DISABLE_MASK);
tw32(MAC_RCV_VALUE_0, 0xffffffff & RCV_RULE_DISABLE_MASK);
tw32(MAC_RCV_RULE_1, 0x86000004 & RCV_RULE_DISABLE_MASK);
tw32(MAC_RCV_VALUE_1, 0xffffffff & RCV_RULE_DISABLE_MASK);
if (tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, 5780_CLASS))
limit = 8;
else
limit = 16;
if (tg3_flag(tp, ENABLE_ASF))
limit -= 4;
switch (limit) {
case 16:
tw32(MAC_RCV_RULE_15, 0); tw32(MAC_RCV_VALUE_15, 0);
case 15:
tw32(MAC_RCV_RULE_14, 0); tw32(MAC_RCV_VALUE_14, 0);
case 14:
tw32(MAC_RCV_RULE_13, 0); tw32(MAC_RCV_VALUE_13, 0);
case 13:
tw32(MAC_RCV_RULE_12, 0); tw32(MAC_RCV_VALUE_12, 0);
case 12:
tw32(MAC_RCV_RULE_11, 0); tw32(MAC_RCV_VALUE_11, 0);
case 11:
tw32(MAC_RCV_RULE_10, 0); tw32(MAC_RCV_VALUE_10, 0);
case 10:
tw32(MAC_RCV_RULE_9, 0); tw32(MAC_RCV_VALUE_9, 0);
case 9:
tw32(MAC_RCV_RULE_8, 0); tw32(MAC_RCV_VALUE_8, 0);
case 8:
tw32(MAC_RCV_RULE_7, 0); tw32(MAC_RCV_VALUE_7, 0);
case 7:
tw32(MAC_RCV_RULE_6, 0); tw32(MAC_RCV_VALUE_6, 0);
case 6:
tw32(MAC_RCV_RULE_5, 0); tw32(MAC_RCV_VALUE_5, 0);
case 5:
tw32(MAC_RCV_RULE_4, 0); tw32(MAC_RCV_VALUE_4, 0);
case 4:
/* tw32(MAC_RCV_RULE_3, 0); tw32(MAC_RCV_VALUE_3, 0); */
case 3:
/* tw32(MAC_RCV_RULE_2, 0); tw32(MAC_RCV_VALUE_2, 0); */
case 2:
case 1:
default:
break;
}
if (tg3_flag(tp, ENABLE_APE))
/* Write our heartbeat update interval to APE. */
tg3_ape_write32(tp, TG3_APE_HOST_HEARTBEAT_INT_MS,
APE_HOST_HEARTBEAT_INT_DISABLE);
tg3_write_sig_post_reset(tp, RESET_KIND_INIT);
return 0;
}
/* Called at device open time to get the chip ready for
* packet processing. Invoked with tp->lock held.
*/
static int tg3_init_hw(struct tg3 *tp, bool reset_phy)
{
/* Chip may have been just powered on. If so, the boot code may still
* be running initialization. Wait for it to finish to avoid races in
* accessing the hardware.
*/
tg3_enable_register_access(tp);
tg3_poll_fw(tp);
tg3_switch_clocks(tp);
tw32(TG3PCI_MEM_WIN_BASE_ADDR, 0);
return tg3_reset_hw(tp, reset_phy);
}
static void tg3_sd_scan_scratchpad(struct tg3 *tp, struct tg3_ocir *ocir)
{
int i;
for (i = 0; i < TG3_SD_NUM_RECS; i++, ocir++) {
u32 off = i * TG3_OCIR_LEN, len = TG3_OCIR_LEN;
tg3_ape_scratchpad_read(tp, (u32 *) ocir, off, len);
off += len;
if (ocir->signature != TG3_OCIR_SIG_MAGIC ||
!(ocir->version_flags & TG3_OCIR_FLAG_ACTIVE))
memset(ocir, 0, TG3_OCIR_LEN);
}
}
/* sysfs attributes for hwmon */
static ssize_t tg3_show_temp(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct tg3 *tp = dev_get_drvdata(dev);
u32 temperature;
spin_lock_bh(&tp->lock);
tg3_ape_scratchpad_read(tp, &temperature, attr->index,
sizeof(temperature));
spin_unlock_bh(&tp->lock);
return sprintf(buf, "%u\n", temperature);
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, tg3_show_temp, NULL,
TG3_TEMP_SENSOR_OFFSET);
static SENSOR_DEVICE_ATTR(temp1_crit, S_IRUGO, tg3_show_temp, NULL,
TG3_TEMP_CAUTION_OFFSET);
static SENSOR_DEVICE_ATTR(temp1_max, S_IRUGO, tg3_show_temp, NULL,
TG3_TEMP_MAX_OFFSET);
static struct attribute *tg3_attrs[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_crit.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
NULL
};
ATTRIBUTE_GROUPS(tg3);
static void tg3_hwmon_close(struct tg3 *tp)
{
if (tp->hwmon_dev) {
hwmon_device_unregister(tp->hwmon_dev);
tp->hwmon_dev = NULL;
}
}
static void tg3_hwmon_open(struct tg3 *tp)
{
int i;
u32 size = 0;
struct pci_dev *pdev = tp->pdev;
struct tg3_ocir ocirs[TG3_SD_NUM_RECS];
tg3_sd_scan_scratchpad(tp, ocirs);
for (i = 0; i < TG3_SD_NUM_RECS; i++) {
if (!ocirs[i].src_data_length)
continue;
size += ocirs[i].src_hdr_length;
size += ocirs[i].src_data_length;
}
if (!size)
return;
tp->hwmon_dev = hwmon_device_register_with_groups(&pdev->dev, "tg3",
tp, tg3_groups);
if (IS_ERR(tp->hwmon_dev)) {
tp->hwmon_dev = NULL;
dev_err(&pdev->dev, "Cannot register hwmon device, aborting\n");
}
}
#define TG3_STAT_ADD32(PSTAT, REG) \
do { u32 __val = tr32(REG); \
(PSTAT)->low += __val; \
if ((PSTAT)->low < __val) \
(PSTAT)->high += 1; \
} while (0)
static void tg3_periodic_fetch_stats(struct tg3 *tp)
{
struct tg3_hw_stats *sp = tp->hw_stats;
if (!tp->link_up)
return;
TG3_STAT_ADD32(&sp->tx_octets, MAC_TX_STATS_OCTETS);
TG3_STAT_ADD32(&sp->tx_collisions, MAC_TX_STATS_COLLISIONS);
TG3_STAT_ADD32(&sp->tx_xon_sent, MAC_TX_STATS_XON_SENT);
TG3_STAT_ADD32(&sp->tx_xoff_sent, MAC_TX_STATS_XOFF_SENT);
TG3_STAT_ADD32(&sp->tx_mac_errors, MAC_TX_STATS_MAC_ERRORS);
TG3_STAT_ADD32(&sp->tx_single_collisions, MAC_TX_STATS_SINGLE_COLLISIONS);
TG3_STAT_ADD32(&sp->tx_mult_collisions, MAC_TX_STATS_MULT_COLLISIONS);
TG3_STAT_ADD32(&sp->tx_deferred, MAC_TX_STATS_DEFERRED);
TG3_STAT_ADD32(&sp->tx_excessive_collisions, MAC_TX_STATS_EXCESSIVE_COL);
TG3_STAT_ADD32(&sp->tx_late_collisions, MAC_TX_STATS_LATE_COL);
TG3_STAT_ADD32(&sp->tx_ucast_packets, MAC_TX_STATS_UCAST);
TG3_STAT_ADD32(&sp->tx_mcast_packets, MAC_TX_STATS_MCAST);
TG3_STAT_ADD32(&sp->tx_bcast_packets, MAC_TX_STATS_BCAST);
if (unlikely(tg3_flag(tp, 5719_5720_RDMA_BUG) &&
(sp->tx_ucast_packets.low + sp->tx_mcast_packets.low +
sp->tx_bcast_packets.low) > TG3_NUM_RDMA_CHANNELS)) {
u32 val;
val = tr32(TG3_LSO_RD_DMA_CRPTEN_CTRL);
val &= ~tg3_lso_rd_dma_workaround_bit(tp);
tw32(TG3_LSO_RD_DMA_CRPTEN_CTRL, val);
tg3_flag_clear(tp, 5719_5720_RDMA_BUG);
}
TG3_STAT_ADD32(&sp->rx_octets, MAC_RX_STATS_OCTETS);
TG3_STAT_ADD32(&sp->rx_fragments, MAC_RX_STATS_FRAGMENTS);
TG3_STAT_ADD32(&sp->rx_ucast_packets, MAC_RX_STATS_UCAST);
TG3_STAT_ADD32(&sp->rx_mcast_packets, MAC_RX_STATS_MCAST);
TG3_STAT_ADD32(&sp->rx_bcast_packets, MAC_RX_STATS_BCAST);
TG3_STAT_ADD32(&sp->rx_fcs_errors, MAC_RX_STATS_FCS_ERRORS);
TG3_STAT_ADD32(&sp->rx_align_errors, MAC_RX_STATS_ALIGN_ERRORS);
TG3_STAT_ADD32(&sp->rx_xon_pause_rcvd, MAC_RX_STATS_XON_PAUSE_RECVD);
TG3_STAT_ADD32(&sp->rx_xoff_pause_rcvd, MAC_RX_STATS_XOFF_PAUSE_RECVD);
TG3_STAT_ADD32(&sp->rx_mac_ctrl_rcvd, MAC_RX_STATS_MAC_CTRL_RECVD);
TG3_STAT_ADD32(&sp->rx_xoff_entered, MAC_RX_STATS_XOFF_ENTERED);
TG3_STAT_ADD32(&sp->rx_frame_too_long_errors, MAC_RX_STATS_FRAME_TOO_LONG);
TG3_STAT_ADD32(&sp->rx_jabbers, MAC_RX_STATS_JABBERS);
TG3_STAT_ADD32(&sp->rx_undersize_packets, MAC_RX_STATS_UNDERSIZE);
TG3_STAT_ADD32(&sp->rxbds_empty, RCVLPC_NO_RCV_BD_CNT);
if (tg3_asic_rev(tp) != ASIC_REV_5717 &&
tg3_asic_rev(tp) != ASIC_REV_5762 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5719_A0 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5720_A0) {
TG3_STAT_ADD32(&sp->rx_discards, RCVLPC_IN_DISCARDS_CNT);
} else {
u32 val = tr32(HOSTCC_FLOW_ATTN);
val = (val & HOSTCC_FLOW_ATTN_MBUF_LWM) ? 1 : 0;
if (val) {
tw32(HOSTCC_FLOW_ATTN, HOSTCC_FLOW_ATTN_MBUF_LWM);
sp->rx_discards.low += val;
if (sp->rx_discards.low < val)
sp->rx_discards.high += 1;
}
sp->mbuf_lwm_thresh_hit = sp->rx_discards;
}
TG3_STAT_ADD32(&sp->rx_errors, RCVLPC_IN_ERRORS_CNT);
}
static void tg3_chk_missed_msi(struct tg3 *tp)
{
u32 i;
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tg3_has_work(tnapi)) {
if (tnapi->last_rx_cons == tnapi->rx_rcb_ptr &&
tnapi->last_tx_cons == tnapi->tx_cons) {
if (tnapi->chk_msi_cnt < 1) {
tnapi->chk_msi_cnt++;
return;
}
tg3_msi(0, tnapi);
}
}
tnapi->chk_msi_cnt = 0;
tnapi->last_rx_cons = tnapi->rx_rcb_ptr;
tnapi->last_tx_cons = tnapi->tx_cons;
}
}
static void tg3_timer(unsigned long __opaque)
{
struct tg3 *tp = (struct tg3 *) __opaque;
if (tp->irq_sync || tg3_flag(tp, RESET_TASK_PENDING))
goto restart_timer;
spin_lock(&tp->lock);
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_flag(tp, 57765_CLASS))
tg3_chk_missed_msi(tp);
if (tg3_flag(tp, FLUSH_POSTED_WRITES)) {
/* BCM4785: Flush posted writes from GbE to host memory. */
tr32(HOSTCC_MODE);
}
if (!tg3_flag(tp, TAGGED_STATUS)) {
/* All of this garbage is because when using non-tagged
* IRQ status the mailbox/status_block protocol the chip
* uses with the cpu is race prone.
*/
if (tp->napi[0].hw_status->status & SD_STATUS_UPDATED) {
tw32(GRC_LOCAL_CTRL,
tp->grc_local_ctrl | GRC_LCLCTRL_SETINT);
} else {
tw32(HOSTCC_MODE, tp->coalesce_mode |
HOSTCC_MODE_ENABLE | HOSTCC_MODE_NOW);
}
if (!(tr32(WDMAC_MODE) & WDMAC_MODE_ENABLE)) {
spin_unlock(&tp->lock);
tg3_reset_task_schedule(tp);
goto restart_timer;
}
}
/* This part only runs once per second. */
if (!--tp->timer_counter) {
if (tg3_flag(tp, 5705_PLUS))
tg3_periodic_fetch_stats(tp);
if (tp->setlpicnt && !--tp->setlpicnt)
tg3_phy_eee_enable(tp);
if (tg3_flag(tp, USE_LINKCHG_REG)) {
u32 mac_stat;
int phy_event;
mac_stat = tr32(MAC_STATUS);
phy_event = 0;
if (tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT) {
if (mac_stat & MAC_STATUS_MI_INTERRUPT)
phy_event = 1;
} else if (mac_stat & MAC_STATUS_LNKSTATE_CHANGED)
phy_event = 1;
if (phy_event)
tg3_setup_phy(tp, false);
} else if (tg3_flag(tp, POLL_SERDES)) {
u32 mac_stat = tr32(MAC_STATUS);
int need_setup = 0;
if (tp->link_up &&
(mac_stat & MAC_STATUS_LNKSTATE_CHANGED)) {
need_setup = 1;
}
if (!tp->link_up &&
(mac_stat & (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_SIGNAL_DET))) {
need_setup = 1;
}
if (need_setup) {
if (!tp->serdes_counter) {
tw32_f(MAC_MODE,
(tp->mac_mode &
~MAC_MODE_PORT_MODE_MASK));
udelay(40);
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
}
tg3_setup_phy(tp, false);
}
} else if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) &&
tg3_flag(tp, 5780_CLASS)) {
tg3_serdes_parallel_detect(tp);
} else if (tg3_flag(tp, POLL_CPMU_LINK)) {
u32 cpmu = tr32(TG3_CPMU_STATUS);
bool link_up = !((cpmu & TG3_CPMU_STATUS_LINK_MASK) ==
TG3_CPMU_STATUS_LINK_MASK);
if (link_up != tp->link_up)
tg3_setup_phy(tp, false);
}
tp->timer_counter = tp->timer_multiplier;
}
/* Heartbeat is only sent once every 2 seconds.
*
* The heartbeat is to tell the ASF firmware that the host
* driver is still alive. In the event that the OS crashes,
* ASF needs to reset the hardware to free up the FIFO space
* that may be filled with rx packets destined for the host.
* If the FIFO is full, ASF will no longer function properly.
*
* Unintended resets have been reported on real time kernels
* where the timer doesn't run on time. Netpoll will also have
* same problem.
*
* The new FWCMD_NICDRV_ALIVE3 command tells the ASF firmware
* to check the ring condition when the heartbeat is expiring
* before doing the reset. This will prevent most unintended
* resets.
*/
if (!--tp->asf_counter) {
if (tg3_flag(tp, ENABLE_ASF) && !tg3_flag(tp, ENABLE_APE)) {
tg3_wait_for_event_ack(tp);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX,
FWCMD_NICDRV_ALIVE3);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_LEN_MBOX, 4);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX,
TG3_FW_UPDATE_TIMEOUT_SEC);
tg3_generate_fw_event(tp);
}
tp->asf_counter = tp->asf_multiplier;
}
spin_unlock(&tp->lock);
restart_timer:
tp->timer.expires = jiffies + tp->timer_offset;
add_timer(&tp->timer);
}
static void tg3_timer_init(struct tg3 *tp)
{
if (tg3_flag(tp, TAGGED_STATUS) &&
tg3_asic_rev(tp) != ASIC_REV_5717 &&
!tg3_flag(tp, 57765_CLASS))
tp->timer_offset = HZ;
else
tp->timer_offset = HZ / 10;
BUG_ON(tp->timer_offset > HZ);
tp->timer_multiplier = (HZ / tp->timer_offset);
tp->asf_multiplier = (HZ / tp->timer_offset) *
TG3_FW_UPDATE_FREQ_SEC;
init_timer(&tp->timer);
tp->timer.data = (unsigned long) tp;
tp->timer.function = tg3_timer;
}
static void tg3_timer_start(struct tg3 *tp)
{
tp->asf_counter = tp->asf_multiplier;
tp->timer_counter = tp->timer_multiplier;
tp->timer.expires = jiffies + tp->timer_offset;
add_timer(&tp->timer);
}
static void tg3_timer_stop(struct tg3 *tp)
{
del_timer_sync(&tp->timer);
}
/* Restart hardware after configuration changes, self-test, etc.
* Invoked with tp->lock held.
*/
static int tg3_restart_hw(struct tg3 *tp, bool reset_phy)
__releases(tp->lock)
__acquires(tp->lock)
{
int err;
err = tg3_init_hw(tp, reset_phy);
if (err) {
netdev_err(tp->dev,
"Failed to re-initialize device, aborting\n");
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_full_unlock(tp);
tg3_timer_stop(tp);
tp->irq_sync = 0;
tg3_napi_enable(tp);
dev_close(tp->dev);
tg3_full_lock(tp, 0);
}
return err;
}
static void tg3_reset_task(struct work_struct *work)
{
struct tg3 *tp = container_of(work, struct tg3, reset_task);
int err;
tg3_full_lock(tp, 0);
if (!netif_running(tp->dev)) {
tg3_flag_clear(tp, RESET_TASK_PENDING);
tg3_full_unlock(tp);
return;
}
tg3_full_unlock(tp);
tg3_phy_stop(tp);
tg3_netif_stop(tp);
tg3_full_lock(tp, 1);
if (tg3_flag(tp, TX_RECOVERY_PENDING)) {
tp->write32_tx_mbox = tg3_write32_tx_mbox;
tp->write32_rx_mbox = tg3_write_flush_reg32;
tg3_flag_set(tp, MBOX_WRITE_REORDER);
tg3_flag_clear(tp, TX_RECOVERY_PENDING);
}
tg3_halt(tp, RESET_KIND_SHUTDOWN, 0);
err = tg3_init_hw(tp, true);
if (err)
goto out;
tg3_netif_start(tp);
out:
tg3_full_unlock(tp);
if (!err)
tg3_phy_start(tp);
tg3_flag_clear(tp, RESET_TASK_PENDING);
}
static int tg3_request_irq(struct tg3 *tp, int irq_num)
{
irq_handler_t fn;
unsigned long flags;
char *name;
struct tg3_napi *tnapi = &tp->napi[irq_num];
if (tp->irq_cnt == 1)
name = tp->dev->name;
else {
name = &tnapi->irq_lbl[0];
if (tnapi->tx_buffers && tnapi->rx_rcb)
snprintf(name, IFNAMSIZ,
"%s-txrx-%d", tp->dev->name, irq_num);
else if (tnapi->tx_buffers)
snprintf(name, IFNAMSIZ,
"%s-tx-%d", tp->dev->name, irq_num);
else if (tnapi->rx_rcb)
snprintf(name, IFNAMSIZ,
"%s-rx-%d", tp->dev->name, irq_num);
else
snprintf(name, IFNAMSIZ,
"%s-%d", tp->dev->name, irq_num);
name[IFNAMSIZ-1] = 0;
}
if (tg3_flag(tp, USING_MSI) || tg3_flag(tp, USING_MSIX)) {
fn = tg3_msi;
if (tg3_flag(tp, 1SHOT_MSI))
fn = tg3_msi_1shot;
flags = 0;
} else {
fn = tg3_interrupt;
if (tg3_flag(tp, TAGGED_STATUS))
fn = tg3_interrupt_tagged;
flags = IRQF_SHARED;
}
return request_irq(tnapi->irq_vec, fn, flags, name, tnapi);
}
static int tg3_test_interrupt(struct tg3 *tp)
{
struct tg3_napi *tnapi = &tp->napi[0];
struct net_device *dev = tp->dev;
int err, i, intr_ok = 0;
u32 val;
if (!netif_running(dev))
return -ENODEV;
tg3_disable_ints(tp);
free_irq(tnapi->irq_vec, tnapi);
/*
* Turn off MSI one shot mode. Otherwise this test has no
* observable way to know whether the interrupt was delivered.
*/
if (tg3_flag(tp, 57765_PLUS)) {
val = tr32(MSGINT_MODE) | MSGINT_MODE_ONE_SHOT_DISABLE;
tw32(MSGINT_MODE, val);
}
err = request_irq(tnapi->irq_vec, tg3_test_isr,
IRQF_SHARED, dev->name, tnapi);
if (err)
return err;
tnapi->hw_status->status &= ~SD_STATUS_UPDATED;
tg3_enable_ints(tp);
tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE |
tnapi->coal_now);
for (i = 0; i < 5; i++) {
u32 int_mbox, misc_host_ctrl;
int_mbox = tr32_mailbox(tnapi->int_mbox);
misc_host_ctrl = tr32(TG3PCI_MISC_HOST_CTRL);
if ((int_mbox != 0) ||
(misc_host_ctrl & MISC_HOST_CTRL_MASK_PCI_INT)) {
intr_ok = 1;
break;
}
if (tg3_flag(tp, 57765_PLUS) &&
tnapi->hw_status->status_tag != tnapi->last_tag)
tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24);
msleep(10);
}
tg3_disable_ints(tp);
free_irq(tnapi->irq_vec, tnapi);
err = tg3_request_irq(tp, 0);
if (err)
return err;
if (intr_ok) {
/* Reenable MSI one shot mode. */
if (tg3_flag(tp, 57765_PLUS) && tg3_flag(tp, 1SHOT_MSI)) {
val = tr32(MSGINT_MODE) & ~MSGINT_MODE_ONE_SHOT_DISABLE;
tw32(MSGINT_MODE, val);
}
return 0;
}
return -EIO;
}
/* Returns 0 if MSI test succeeds or MSI test fails and INTx mode is
* successfully restored
*/
static int tg3_test_msi(struct tg3 *tp)
{
int err;
u16 pci_cmd;
if (!tg3_flag(tp, USING_MSI))
return 0;
/* Turn off SERR reporting in case MSI terminates with Master
* Abort.
*/
pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd);
pci_write_config_word(tp->pdev, PCI_COMMAND,
pci_cmd & ~PCI_COMMAND_SERR);
err = tg3_test_interrupt(tp);
pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd);
if (!err)
return 0;
/* other failures */
if (err != -EIO)
return err;
/* MSI test failed, go back to INTx mode */
netdev_warn(tp->dev, "No interrupt was generated using MSI. Switching "
"to INTx mode. Please report this failure to the PCI "
"maintainer and include system chipset information\n");
free_irq(tp->napi[0].irq_vec, &tp->napi[0]);
pci_disable_msi(tp->pdev);
tg3_flag_clear(tp, USING_MSI);
tp->napi[0].irq_vec = tp->pdev->irq;
err = tg3_request_irq(tp, 0);
if (err)
return err;
/* Need to reset the chip because the MSI cycle may have terminated
* with Master Abort.
*/
tg3_full_lock(tp, 1);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
err = tg3_init_hw(tp, true);
tg3_full_unlock(tp);
if (err)
free_irq(tp->napi[0].irq_vec, &tp->napi[0]);
return err;
}
static int tg3_request_firmware(struct tg3 *tp)
{
const struct tg3_firmware_hdr *fw_hdr;
if (request_firmware(&tp->fw, tp->fw_needed, &tp->pdev->dev)) {
netdev_err(tp->dev, "Failed to load firmware \"%s\"\n",
tp->fw_needed);
return -ENOENT;
}
fw_hdr = (struct tg3_firmware_hdr *)tp->fw->data;
/* Firmware blob starts with version numbers, followed by
* start address and _full_ length including BSS sections
* (which must be longer than the actual data, of course
*/
tp->fw_len = be32_to_cpu(fw_hdr->len); /* includes bss */
if (tp->fw_len < (tp->fw->size - TG3_FW_HDR_LEN)) {
netdev_err(tp->dev, "bogus length %d in \"%s\"\n",
tp->fw_len, tp->fw_needed);
release_firmware(tp->fw);
tp->fw = NULL;
return -EINVAL;
}
/* We no longer need firmware; we have it. */
tp->fw_needed = NULL;
return 0;
}
static u32 tg3_irq_count(struct tg3 *tp)
{
u32 irq_cnt = max(tp->rxq_cnt, tp->txq_cnt);
if (irq_cnt > 1) {
/* We want as many rx rings enabled as there are cpus.
* In multiqueue MSI-X mode, the first MSI-X vector
* only deals with link interrupts, etc, so we add
* one to the number of vectors we are requesting.
*/
irq_cnt = min_t(unsigned, irq_cnt + 1, tp->irq_max);
}
return irq_cnt;
}
static bool tg3_enable_msix(struct tg3 *tp)
{
int i, rc;
struct msix_entry msix_ent[TG3_IRQ_MAX_VECS];
tp->txq_cnt = tp->txq_req;
tp->rxq_cnt = tp->rxq_req;
if (!tp->rxq_cnt)
tp->rxq_cnt = netif_get_num_default_rss_queues();
if (tp->rxq_cnt > tp->rxq_max)
tp->rxq_cnt = tp->rxq_max;
/* Disable multiple TX rings by default. Simple round-robin hardware
* scheduling of the TX rings can cause starvation of rings with
* small packets when other rings have TSO or jumbo packets.
*/
if (!tp->txq_req)
tp->txq_cnt = 1;
tp->irq_cnt = tg3_irq_count(tp);
for (i = 0; i < tp->irq_max; i++) {
msix_ent[i].entry = i;
msix_ent[i].vector = 0;
}
rc = pci_enable_msix_range(tp->pdev, msix_ent, 1, tp->irq_cnt);
if (rc < 0) {
return false;
} else if (rc < tp->irq_cnt) {
netdev_notice(tp->dev, "Requested %d MSI-X vectors, received %d\n",
tp->irq_cnt, rc);
tp->irq_cnt = rc;
tp->rxq_cnt = max(rc - 1, 1);
if (tp->txq_cnt)
tp->txq_cnt = min(tp->rxq_cnt, tp->txq_max);
}
for (i = 0; i < tp->irq_max; i++)
tp->napi[i].irq_vec = msix_ent[i].vector;
if (netif_set_real_num_rx_queues(tp->dev, tp->rxq_cnt)) {
pci_disable_msix(tp->pdev);
return false;
}
if (tp->irq_cnt == 1)
return true;
tg3_flag_set(tp, ENABLE_RSS);
if (tp->txq_cnt > 1)
tg3_flag_set(tp, ENABLE_TSS);
netif_set_real_num_tx_queues(tp->dev, tp->txq_cnt);
return true;
}
static void tg3_ints_init(struct tg3 *tp)
{
if ((tg3_flag(tp, SUPPORT_MSI) || tg3_flag(tp, SUPPORT_MSIX)) &&
!tg3_flag(tp, TAGGED_STATUS)) {
/* All MSI supporting chips should support tagged
* status. Assert that this is the case.
*/
netdev_warn(tp->dev,
"MSI without TAGGED_STATUS? Not using MSI\n");
goto defcfg;
}
if (tg3_flag(tp, SUPPORT_MSIX) && tg3_enable_msix(tp))
tg3_flag_set(tp, USING_MSIX);
else if (tg3_flag(tp, SUPPORT_MSI) && pci_enable_msi(tp->pdev) == 0)
tg3_flag_set(tp, USING_MSI);
if (tg3_flag(tp, USING_MSI) || tg3_flag(tp, USING_MSIX)) {
u32 msi_mode = tr32(MSGINT_MODE);
if (tg3_flag(tp, USING_MSIX) && tp->irq_cnt > 1)
msi_mode |= MSGINT_MODE_MULTIVEC_EN;
if (!tg3_flag(tp, 1SHOT_MSI))
msi_mode |= MSGINT_MODE_ONE_SHOT_DISABLE;
tw32(MSGINT_MODE, msi_mode | MSGINT_MODE_ENABLE);
}
defcfg:
if (!tg3_flag(tp, USING_MSIX)) {
tp->irq_cnt = 1;
tp->napi[0].irq_vec = tp->pdev->irq;
}
if (tp->irq_cnt == 1) {
tp->txq_cnt = 1;
tp->rxq_cnt = 1;
netif_set_real_num_tx_queues(tp->dev, 1);
netif_set_real_num_rx_queues(tp->dev, 1);
}
}
static void tg3_ints_fini(struct tg3 *tp)
{
if (tg3_flag(tp, USING_MSIX))
pci_disable_msix(tp->pdev);
else if (tg3_flag(tp, USING_MSI))
pci_disable_msi(tp->pdev);
tg3_flag_clear(tp, USING_MSI);
tg3_flag_clear(tp, USING_MSIX);
tg3_flag_clear(tp, ENABLE_RSS);
tg3_flag_clear(tp, ENABLE_TSS);
}
static int tg3_start(struct tg3 *tp, bool reset_phy, bool test_irq,
bool init)
{
struct net_device *dev = tp->dev;
int i, err;
/*
* Setup interrupts first so we know how
* many NAPI resources to allocate
*/
tg3_ints_init(tp);
tg3_rss_check_indir_tbl(tp);
/* The placement of this call is tied
* to the setup and use of Host TX descriptors.
*/
err = tg3_alloc_consistent(tp);
if (err)
goto out_ints_fini;
tg3_napi_init(tp);
tg3_napi_enable(tp);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
err = tg3_request_irq(tp, i);
if (err) {
for (i--; i >= 0; i--) {
tnapi = &tp->napi[i];
free_irq(tnapi->irq_vec, tnapi);
}
goto out_napi_fini;
}
}
tg3_full_lock(tp, 0);
if (init)
tg3_ape_driver_state_change(tp, RESET_KIND_INIT);
err = tg3_init_hw(tp, reset_phy);
if (err) {
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_free_rings(tp);
}
tg3_full_unlock(tp);
if (err)
goto out_free_irq;
if (test_irq && tg3_flag(tp, USING_MSI)) {
err = tg3_test_msi(tp);
if (err) {
tg3_full_lock(tp, 0);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_free_rings(tp);
tg3_full_unlock(tp);
goto out_napi_fini;
}
if (!tg3_flag(tp, 57765_PLUS) && tg3_flag(tp, USING_MSI)) {
u32 val = tr32(PCIE_TRANSACTION_CFG);
tw32(PCIE_TRANSACTION_CFG,
val | PCIE_TRANS_CFG_1SHOT_MSI);
}
}
tg3_phy_start(tp);
tg3_hwmon_open(tp);
tg3_full_lock(tp, 0);
tg3_timer_start(tp);
tg3_flag_set(tp, INIT_COMPLETE);
tg3_enable_ints(tp);
if (init)
tg3_ptp_init(tp);
else
tg3_ptp_resume(tp);
tg3_full_unlock(tp);
netif_tx_start_all_queues(dev);
/*
* Reset loopback feature if it was turned on while the device was down
* make sure that it's installed properly now.
*/
if (dev->features & NETIF_F_LOOPBACK)
tg3_set_loopback(dev, dev->features);
return 0;
out_free_irq:
for (i = tp->irq_cnt - 1; i >= 0; i--) {
struct tg3_napi *tnapi = &tp->napi[i];
free_irq(tnapi->irq_vec, tnapi);
}
out_napi_fini:
tg3_napi_disable(tp);
tg3_napi_fini(tp);
tg3_free_consistent(tp);
out_ints_fini:
tg3_ints_fini(tp);
return err;
}
static void tg3_stop(struct tg3 *tp)
{
int i;
tg3_reset_task_cancel(tp);
tg3_netif_stop(tp);
tg3_timer_stop(tp);
tg3_hwmon_close(tp);
tg3_phy_stop(tp);
tg3_full_lock(tp, 1);
tg3_disable_ints(tp);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_free_rings(tp);
tg3_flag_clear(tp, INIT_COMPLETE);
tg3_full_unlock(tp);
for (i = tp->irq_cnt - 1; i >= 0; i--) {
struct tg3_napi *tnapi = &tp->napi[i];
free_irq(tnapi->irq_vec, tnapi);
}
tg3_ints_fini(tp);
tg3_napi_fini(tp);
tg3_free_consistent(tp);
}
static int tg3_open(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
int err;
if (tp->fw_needed) {
err = tg3_request_firmware(tp);
if (tg3_asic_rev(tp) == ASIC_REV_57766) {
if (err) {
netdev_warn(tp->dev, "EEE capability disabled\n");
tp->phy_flags &= ~TG3_PHYFLG_EEE_CAP;
} else if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) {
netdev_warn(tp->dev, "EEE capability restored\n");
tp->phy_flags |= TG3_PHYFLG_EEE_CAP;
}
} else if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0) {
if (err)
return err;
} else if (err) {
netdev_warn(tp->dev, "TSO capability disabled\n");
tg3_flag_clear(tp, TSO_CAPABLE);
} else if (!tg3_flag(tp, TSO_CAPABLE)) {
netdev_notice(tp->dev, "TSO capability restored\n");
tg3_flag_set(tp, TSO_CAPABLE);
}
}
tg3_carrier_off(tp);
err = tg3_power_up(tp);
if (err)
return err;
tg3_full_lock(tp, 0);
tg3_disable_ints(tp);
tg3_flag_clear(tp, INIT_COMPLETE);
tg3_full_unlock(tp);
err = tg3_start(tp,
!(tp->phy_flags & TG3_PHYFLG_KEEP_LINK_ON_PWRDN),
true, true);
if (err) {
tg3_frob_aux_power(tp, false);
pci_set_power_state(tp->pdev, PCI_D3hot);
}
if (tg3_flag(tp, PTP_CAPABLE)) {
tp->ptp_clock = ptp_clock_register(&tp->ptp_info,
&tp->pdev->dev);
if (IS_ERR(tp->ptp_clock))
tp->ptp_clock = NULL;
}
return err;
}
static int tg3_close(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
tg3_ptp_fini(tp);
tg3_stop(tp);
/* Clear stats across close / open calls */
memset(&tp->net_stats_prev, 0, sizeof(tp->net_stats_prev));
memset(&tp->estats_prev, 0, sizeof(tp->estats_prev));
if (pci_device_is_present(tp->pdev)) {
tg3_power_down_prepare(tp);
tg3_carrier_off(tp);
}
return 0;
}
static inline u64 get_stat64(tg3_stat64_t *val)
{
return ((u64)val->high << 32) | ((u64)val->low);
}
static u64 tg3_calc_crc_errors(struct tg3 *tp)
{
struct tg3_hw_stats *hw_stats = tp->hw_stats;
if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
(tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701)) {
u32 val;
if (!tg3_readphy(tp, MII_TG3_TEST1, &val)) {
tg3_writephy(tp, MII_TG3_TEST1,
val | MII_TG3_TEST1_CRC_EN);
tg3_readphy(tp, MII_TG3_RXR_COUNTERS, &val);
} else
val = 0;
tp->phy_crc_errors += val;
return tp->phy_crc_errors;
}
return get_stat64(&hw_stats->rx_fcs_errors);
}
#define ESTAT_ADD(member) \
estats->member = old_estats->member + \
get_stat64(&hw_stats->member)
static void tg3_get_estats(struct tg3 *tp, struct tg3_ethtool_stats *estats)
{
struct tg3_ethtool_stats *old_estats = &tp->estats_prev;
struct tg3_hw_stats *hw_stats = tp->hw_stats;
ESTAT_ADD(rx_octets);
ESTAT_ADD(rx_fragments);
ESTAT_ADD(rx_ucast_packets);
ESTAT_ADD(rx_mcast_packets);
ESTAT_ADD(rx_bcast_packets);
ESTAT_ADD(rx_fcs_errors);
ESTAT_ADD(rx_align_errors);
ESTAT_ADD(rx_xon_pause_rcvd);
ESTAT_ADD(rx_xoff_pause_rcvd);
ESTAT_ADD(rx_mac_ctrl_rcvd);
ESTAT_ADD(rx_xoff_entered);
ESTAT_ADD(rx_frame_too_long_errors);
ESTAT_ADD(rx_jabbers);
ESTAT_ADD(rx_undersize_packets);
ESTAT_ADD(rx_in_length_errors);
ESTAT_ADD(rx_out_length_errors);
ESTAT_ADD(rx_64_or_less_octet_packets);
ESTAT_ADD(rx_65_to_127_octet_packets);
ESTAT_ADD(rx_128_to_255_octet_packets);
ESTAT_ADD(rx_256_to_511_octet_packets);
ESTAT_ADD(rx_512_to_1023_octet_packets);
ESTAT_ADD(rx_1024_to_1522_octet_packets);
ESTAT_ADD(rx_1523_to_2047_octet_packets);
ESTAT_ADD(rx_2048_to_4095_octet_packets);
ESTAT_ADD(rx_4096_to_8191_octet_packets);
ESTAT_ADD(rx_8192_to_9022_octet_packets);
ESTAT_ADD(tx_octets);
ESTAT_ADD(tx_collisions);
ESTAT_ADD(tx_xon_sent);
ESTAT_ADD(tx_xoff_sent);
ESTAT_ADD(tx_flow_control);
ESTAT_ADD(tx_mac_errors);
ESTAT_ADD(tx_single_collisions);
ESTAT_ADD(tx_mult_collisions);
ESTAT_ADD(tx_deferred);
ESTAT_ADD(tx_excessive_collisions);
ESTAT_ADD(tx_late_collisions);
ESTAT_ADD(tx_collide_2times);
ESTAT_ADD(tx_collide_3times);
ESTAT_ADD(tx_collide_4times);
ESTAT_ADD(tx_collide_5times);
ESTAT_ADD(tx_collide_6times);
ESTAT_ADD(tx_collide_7times);
ESTAT_ADD(tx_collide_8times);
ESTAT_ADD(tx_collide_9times);
ESTAT_ADD(tx_collide_10times);
ESTAT_ADD(tx_collide_11times);
ESTAT_ADD(tx_collide_12times);
ESTAT_ADD(tx_collide_13times);
ESTAT_ADD(tx_collide_14times);
ESTAT_ADD(tx_collide_15times);
ESTAT_ADD(tx_ucast_packets);
ESTAT_ADD(tx_mcast_packets);
ESTAT_ADD(tx_bcast_packets);
ESTAT_ADD(tx_carrier_sense_errors);
ESTAT_ADD(tx_discards);
ESTAT_ADD(tx_errors);
ESTAT_ADD(dma_writeq_full);
ESTAT_ADD(dma_write_prioq_full);
ESTAT_ADD(rxbds_empty);
ESTAT_ADD(rx_discards);
ESTAT_ADD(rx_errors);
ESTAT_ADD(rx_threshold_hit);
ESTAT_ADD(dma_readq_full);
ESTAT_ADD(dma_read_prioq_full);
ESTAT_ADD(tx_comp_queue_full);
ESTAT_ADD(ring_set_send_prod_index);
ESTAT_ADD(ring_status_update);
ESTAT_ADD(nic_irqs);
ESTAT_ADD(nic_avoided_irqs);
ESTAT_ADD(nic_tx_threshold_hit);
ESTAT_ADD(mbuf_lwm_thresh_hit);
}
static void tg3_get_nstats(struct tg3 *tp, struct rtnl_link_stats64 *stats)
{
struct rtnl_link_stats64 *old_stats = &tp->net_stats_prev;
struct tg3_hw_stats *hw_stats = tp->hw_stats;
stats->rx_packets = old_stats->rx_packets +
get_stat64(&hw_stats->rx_ucast_packets) +
get_stat64(&hw_stats->rx_mcast_packets) +
get_stat64(&hw_stats->rx_bcast_packets);
stats->tx_packets = old_stats->tx_packets +
get_stat64(&hw_stats->tx_ucast_packets) +
get_stat64(&hw_stats->tx_mcast_packets) +
get_stat64(&hw_stats->tx_bcast_packets);
stats->rx_bytes = old_stats->rx_bytes +
get_stat64(&hw_stats->rx_octets);
stats->tx_bytes = old_stats->tx_bytes +
get_stat64(&hw_stats->tx_octets);
stats->rx_errors = old_stats->rx_errors +
get_stat64(&hw_stats->rx_errors);
stats->tx_errors = old_stats->tx_errors +
get_stat64(&hw_stats->tx_errors) +
get_stat64(&hw_stats->tx_mac_errors) +
get_stat64(&hw_stats->tx_carrier_sense_errors) +
get_stat64(&hw_stats->tx_discards);
stats->multicast = old_stats->multicast +
get_stat64(&hw_stats->rx_mcast_packets);
stats->collisions = old_stats->collisions +
get_stat64(&hw_stats->tx_collisions);
stats->rx_length_errors = old_stats->rx_length_errors +
get_stat64(&hw_stats->rx_frame_too_long_errors) +
get_stat64(&hw_stats->rx_undersize_packets);
stats->rx_frame_errors = old_stats->rx_frame_errors +
get_stat64(&hw_stats->rx_align_errors);
stats->tx_aborted_errors = old_stats->tx_aborted_errors +
get_stat64(&hw_stats->tx_discards);
stats->tx_carrier_errors = old_stats->tx_carrier_errors +
get_stat64(&hw_stats->tx_carrier_sense_errors);
stats->rx_crc_errors = old_stats->rx_crc_errors +
tg3_calc_crc_errors(tp);
stats->rx_missed_errors = old_stats->rx_missed_errors +
get_stat64(&hw_stats->rx_discards);
stats->rx_dropped = tp->rx_dropped;
stats->tx_dropped = tp->tx_dropped;
}
static int tg3_get_regs_len(struct net_device *dev)
{
return TG3_REG_BLK_SIZE;
}
static void tg3_get_regs(struct net_device *dev,
struct ethtool_regs *regs, void *_p)
{
struct tg3 *tp = netdev_priv(dev);
regs->version = 0;
memset(_p, 0, TG3_REG_BLK_SIZE);
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)
return;
tg3_full_lock(tp, 0);
tg3_dump_legacy_regs(tp, (u32 *)_p);
tg3_full_unlock(tp);
}
static int tg3_get_eeprom_len(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
return tp->nvram_size;
}
static int tg3_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data)
{
struct tg3 *tp = netdev_priv(dev);
int ret, cpmu_restore = 0;
u8 *pd;
u32 i, offset, len, b_offset, b_count, cpmu_val = 0;
__be32 val;
if (tg3_flag(tp, NO_NVRAM))
return -EINVAL;
offset = eeprom->offset;
len = eeprom->len;
eeprom->len = 0;
eeprom->magic = TG3_EEPROM_MAGIC;
/* Override clock, link aware and link idle modes */
if (tg3_flag(tp, CPMU_PRESENT)) {
cpmu_val = tr32(TG3_CPMU_CTRL);
if (cpmu_val & (CPMU_CTRL_LINK_AWARE_MODE |
CPMU_CTRL_LINK_IDLE_MODE)) {
tw32(TG3_CPMU_CTRL, cpmu_val &
~(CPMU_CTRL_LINK_AWARE_MODE |
CPMU_CTRL_LINK_IDLE_MODE));
cpmu_restore = 1;
}
}
tg3_override_clk(tp);
if (offset & 3) {
/* adjustments to start on required 4 byte boundary */
b_offset = offset & 3;
b_count = 4 - b_offset;
if (b_count > len) {
/* i.e. offset=1 len=2 */
b_count = len;
}
ret = tg3_nvram_read_be32(tp, offset-b_offset, &val);
if (ret)
goto eeprom_done;
memcpy(data, ((char *)&val) + b_offset, b_count);
len -= b_count;
offset += b_count;
eeprom->len += b_count;
}
/* read bytes up to the last 4 byte boundary */
pd = &data[eeprom->len];
for (i = 0; i < (len - (len & 3)); i += 4) {
ret = tg3_nvram_read_be32(tp, offset + i, &val);
if (ret) {
if (i)
i -= 4;
eeprom->len += i;
goto eeprom_done;
}
memcpy(pd + i, &val, 4);
if (need_resched()) {
if (signal_pending(current)) {
eeprom->len += i;
ret = -EINTR;
goto eeprom_done;
}
cond_resched();
}
}
eeprom->len += i;
if (len & 3) {
/* read last bytes not ending on 4 byte boundary */
pd = &data[eeprom->len];
b_count = len & 3;
b_offset = offset + len - b_count;
ret = tg3_nvram_read_be32(tp, b_offset, &val);
if (ret)
goto eeprom_done;
memcpy(pd, &val, b_count);
eeprom->len += b_count;
}
ret = 0;
eeprom_done:
/* Restore clock, link aware and link idle modes */
tg3_restore_clk(tp);
if (cpmu_restore)
tw32(TG3_CPMU_CTRL, cpmu_val);
return ret;
}
static int tg3_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data)
{
struct tg3 *tp = netdev_priv(dev);
int ret;
u32 offset, len, b_offset, odd_len;
u8 *buf;
__be32 start, end;
if (tg3_flag(tp, NO_NVRAM) ||
eeprom->magic != TG3_EEPROM_MAGIC)
return -EINVAL;
offset = eeprom->offset;
len = eeprom->len;
if ((b_offset = (offset & 3))) {
/* adjustments to start on required 4 byte boundary */
ret = tg3_nvram_read_be32(tp, offset-b_offset, &start);
if (ret)
return ret;
len += b_offset;
offset &= ~3;
if (len < 4)
len = 4;
}
odd_len = 0;
if (len & 3) {
/* adjustments to end on required 4 byte boundary */
odd_len = 1;
len = (len + 3) & ~3;
ret = tg3_nvram_read_be32(tp, offset+len-4, &end);
if (ret)
return ret;
}
buf = data;
if (b_offset || odd_len) {
buf = kmalloc(len, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (b_offset)
memcpy(buf, &start, 4);
if (odd_len)
memcpy(buf+len-4, &end, 4);
memcpy(buf + b_offset, data, eeprom->len);
}
ret = tg3_nvram_write_block(tp, offset, len, buf);
if (buf != data)
kfree(buf);
return ret;
}
static int tg3_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct tg3 *tp = netdev_priv(dev);
if (tg3_flag(tp, USE_PHYLIB)) {
struct phy_device *phydev;
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return -EAGAIN;
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
return phy_ethtool_gset(phydev, cmd);
}
cmd->supported = (SUPPORTED_Autoneg);
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY))
cmd->supported |= (SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full);
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) {
cmd->supported |= (SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_TP);
cmd->port = PORT_TP;
} else {
cmd->supported |= SUPPORTED_FIBRE;
cmd->port = PORT_FIBRE;
}
cmd->advertising = tp->link_config.advertising;
if (tg3_flag(tp, PAUSE_AUTONEG)) {
if (tp->link_config.flowctrl & FLOW_CTRL_RX) {
if (tp->link_config.flowctrl & FLOW_CTRL_TX) {
cmd->advertising |= ADVERTISED_Pause;
} else {
cmd->advertising |= ADVERTISED_Pause |
ADVERTISED_Asym_Pause;
}
} else if (tp->link_config.flowctrl & FLOW_CTRL_TX) {
cmd->advertising |= ADVERTISED_Asym_Pause;
}
}
if (netif_running(dev) && tp->link_up) {
ethtool_cmd_speed_set(cmd, tp->link_config.active_speed);
cmd->duplex = tp->link_config.active_duplex;
cmd->lp_advertising = tp->link_config.rmt_adv;
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) {
if (tp->phy_flags & TG3_PHYFLG_MDIX_STATE)
cmd->eth_tp_mdix = ETH_TP_MDI_X;
else
cmd->eth_tp_mdix = ETH_TP_MDI;
}
} else {
ethtool_cmd_speed_set(cmd, SPEED_UNKNOWN);
cmd->duplex = DUPLEX_UNKNOWN;
cmd->eth_tp_mdix = ETH_TP_MDI_INVALID;
}
cmd->phy_address = tp->phy_addr;
cmd->transceiver = XCVR_INTERNAL;
cmd->autoneg = tp->link_config.autoneg;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static int tg3_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct tg3 *tp = netdev_priv(dev);
u32 speed = ethtool_cmd_speed(cmd);
if (tg3_flag(tp, USE_PHYLIB)) {
struct phy_device *phydev;
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return -EAGAIN;
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
return phy_ethtool_sset(phydev, cmd);
}
if (cmd->autoneg != AUTONEG_ENABLE &&
cmd->autoneg != AUTONEG_DISABLE)
return -EINVAL;
if (cmd->autoneg == AUTONEG_DISABLE &&
cmd->duplex != DUPLEX_FULL &&
cmd->duplex != DUPLEX_HALF)
return -EINVAL;
if (cmd->autoneg == AUTONEG_ENABLE) {
u32 mask = ADVERTISED_Autoneg |
ADVERTISED_Pause |
ADVERTISED_Asym_Pause;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY))
mask |= ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full;
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
mask |= ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full |
ADVERTISED_TP;
else
mask |= ADVERTISED_FIBRE;
if (cmd->advertising & ~mask)
return -EINVAL;
mask &= (ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full |
ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full);
cmd->advertising &= mask;
} else {
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES) {
if (speed != SPEED_1000)
return -EINVAL;
if (cmd->duplex != DUPLEX_FULL)
return -EINVAL;
} else {
if (speed != SPEED_100 &&
speed != SPEED_10)
return -EINVAL;
}
}
tg3_full_lock(tp, 0);
tp->link_config.autoneg = cmd->autoneg;
if (cmd->autoneg == AUTONEG_ENABLE) {
tp->link_config.advertising = (cmd->advertising |
ADVERTISED_Autoneg);
tp->link_config.speed = SPEED_UNKNOWN;
tp->link_config.duplex = DUPLEX_UNKNOWN;
} else {
tp->link_config.advertising = 0;
tp->link_config.speed = speed;
tp->link_config.duplex = cmd->duplex;
}
tp->phy_flags |= TG3_PHYFLG_USER_CONFIGURED;
tg3_warn_mgmt_link_flap(tp);
if (netif_running(dev))
tg3_setup_phy(tp, true);
tg3_full_unlock(tp);
return 0;
}
static void tg3_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct tg3 *tp = netdev_priv(dev);
strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version));
strlcpy(info->fw_version, tp->fw_ver, sizeof(info->fw_version));
strlcpy(info->bus_info, pci_name(tp->pdev), sizeof(info->bus_info));
}
static void tg3_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct tg3 *tp = netdev_priv(dev);
if (tg3_flag(tp, WOL_CAP) && device_can_wakeup(&tp->pdev->dev))
wol->supported = WAKE_MAGIC;
else
wol->supported = 0;
wol->wolopts = 0;
if (tg3_flag(tp, WOL_ENABLE) && device_can_wakeup(&tp->pdev->dev))
wol->wolopts = WAKE_MAGIC;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int tg3_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct tg3 *tp = netdev_priv(dev);
struct device *dp = &tp->pdev->dev;
if (wol->wolopts & ~WAKE_MAGIC)
return -EINVAL;
if ((wol->wolopts & WAKE_MAGIC) &&
!(tg3_flag(tp, WOL_CAP) && device_can_wakeup(dp)))
return -EINVAL;
device_set_wakeup_enable(dp, wol->wolopts & WAKE_MAGIC);
if (device_may_wakeup(dp))
tg3_flag_set(tp, WOL_ENABLE);
else
tg3_flag_clear(tp, WOL_ENABLE);
return 0;
}
static u32 tg3_get_msglevel(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
return tp->msg_enable;
}
static void tg3_set_msglevel(struct net_device *dev, u32 value)
{
struct tg3 *tp = netdev_priv(dev);
tp->msg_enable = value;
}
static int tg3_nway_reset(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
int r;
if (!netif_running(dev))
return -EAGAIN;
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
return -EINVAL;
tg3_warn_mgmt_link_flap(tp);
if (tg3_flag(tp, USE_PHYLIB)) {
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return -EAGAIN;
r = phy_start_aneg(tp->mdio_bus->phy_map[tp->phy_addr]);
} else {
u32 bmcr;
spin_lock_bh(&tp->lock);
r = -EINVAL;
tg3_readphy(tp, MII_BMCR, &bmcr);
if (!tg3_readphy(tp, MII_BMCR, &bmcr) &&
((bmcr & BMCR_ANENABLE) ||
(tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT))) {
tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANRESTART |
BMCR_ANENABLE);
r = 0;
}
spin_unlock_bh(&tp->lock);
}
return r;
}
static void tg3_get_ringparam(struct net_device *dev, struct ethtool_ringparam *ering)
{
struct tg3 *tp = netdev_priv(dev);
ering->rx_max_pending = tp->rx_std_ring_mask;
if (tg3_flag(tp, JUMBO_RING_ENABLE))
ering->rx_jumbo_max_pending = tp->rx_jmb_ring_mask;
else
ering->rx_jumbo_max_pending = 0;
ering->tx_max_pending = TG3_TX_RING_SIZE - 1;
ering->rx_pending = tp->rx_pending;
if (tg3_flag(tp, JUMBO_RING_ENABLE))
ering->rx_jumbo_pending = tp->rx_jumbo_pending;
else
ering->rx_jumbo_pending = 0;
ering->tx_pending = tp->napi[0].tx_pending;
}
static int tg3_set_ringparam(struct net_device *dev, struct ethtool_ringparam *ering)
{
struct tg3 *tp = netdev_priv(dev);
int i, irq_sync = 0, err = 0;
if ((ering->rx_pending > tp->rx_std_ring_mask) ||
(ering->rx_jumbo_pending > tp->rx_jmb_ring_mask) ||
(ering->tx_pending > TG3_TX_RING_SIZE - 1) ||
(ering->tx_pending <= MAX_SKB_FRAGS) ||
(tg3_flag(tp, TSO_BUG) &&
(ering->tx_pending <= (MAX_SKB_FRAGS * 3))))
return -EINVAL;
if (netif_running(dev)) {
tg3_phy_stop(tp);
tg3_netif_stop(tp);
irq_sync = 1;
}
tg3_full_lock(tp, irq_sync);
tp->rx_pending = ering->rx_pending;
if (tg3_flag(tp, MAX_RXPEND_64) &&
tp->rx_pending > 63)
tp->rx_pending = 63;
if (tg3_flag(tp, JUMBO_RING_ENABLE))
tp->rx_jumbo_pending = ering->rx_jumbo_pending;
for (i = 0; i < tp->irq_max; i++)
tp->napi[i].tx_pending = ering->tx_pending;
if (netif_running(dev)) {
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
err = tg3_restart_hw(tp, false);
if (!err)
tg3_netif_start(tp);
}
tg3_full_unlock(tp);
if (irq_sync && !err)
tg3_phy_start(tp);
return err;
}
static void tg3_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause)
{
struct tg3 *tp = netdev_priv(dev);
epause->autoneg = !!tg3_flag(tp, PAUSE_AUTONEG);
if (tp->link_config.flowctrl & FLOW_CTRL_RX)
epause->rx_pause = 1;
else
epause->rx_pause = 0;
if (tp->link_config.flowctrl & FLOW_CTRL_TX)
epause->tx_pause = 1;
else
epause->tx_pause = 0;
}
static int tg3_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause)
{
struct tg3 *tp = netdev_priv(dev);
int err = 0;
if (tp->link_config.autoneg == AUTONEG_ENABLE)
tg3_warn_mgmt_link_flap(tp);
if (tg3_flag(tp, USE_PHYLIB)) {
u32 newadv;
struct phy_device *phydev;
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
if (!(phydev->supported & SUPPORTED_Pause) ||
(!(phydev->supported & SUPPORTED_Asym_Pause) &&
(epause->rx_pause != epause->tx_pause)))
return -EINVAL;
tp->link_config.flowctrl = 0;
if (epause->rx_pause) {
tp->link_config.flowctrl |= FLOW_CTRL_RX;
if (epause->tx_pause) {
tp->link_config.flowctrl |= FLOW_CTRL_TX;
newadv = ADVERTISED_Pause;
} else
newadv = ADVERTISED_Pause |
ADVERTISED_Asym_Pause;
} else if (epause->tx_pause) {
tp->link_config.flowctrl |= FLOW_CTRL_TX;
newadv = ADVERTISED_Asym_Pause;
} else
newadv = 0;
if (epause->autoneg)
tg3_flag_set(tp, PAUSE_AUTONEG);
else
tg3_flag_clear(tp, PAUSE_AUTONEG);
if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) {
u32 oldadv = phydev->advertising &
(ADVERTISED_Pause | ADVERTISED_Asym_Pause);
if (oldadv != newadv) {
phydev->advertising &=
~(ADVERTISED_Pause |
ADVERTISED_Asym_Pause);
phydev->advertising |= newadv;
if (phydev->autoneg) {
/*
* Always renegotiate the link to
* inform our link partner of our
* flow control settings, even if the
* flow control is forced. Let
* tg3_adjust_link() do the final
* flow control setup.
*/
return phy_start_aneg(phydev);
}
}
if (!epause->autoneg)
tg3_setup_flow_control(tp, 0, 0);
} else {
tp->link_config.advertising &=
~(ADVERTISED_Pause |
ADVERTISED_Asym_Pause);
tp->link_config.advertising |= newadv;
}
} else {
int irq_sync = 0;
if (netif_running(dev)) {
tg3_netif_stop(tp);
irq_sync = 1;
}
tg3_full_lock(tp, irq_sync);
if (epause->autoneg)
tg3_flag_set(tp, PAUSE_AUTONEG);
else
tg3_flag_clear(tp, PAUSE_AUTONEG);
if (epause->rx_pause)
tp->link_config.flowctrl |= FLOW_CTRL_RX;
else
tp->link_config.flowctrl &= ~FLOW_CTRL_RX;
if (epause->tx_pause)
tp->link_config.flowctrl |= FLOW_CTRL_TX;
else
tp->link_config.flowctrl &= ~FLOW_CTRL_TX;
if (netif_running(dev)) {
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
err = tg3_restart_hw(tp, false);
if (!err)
tg3_netif_start(tp);
}
tg3_full_unlock(tp);
}
tp->phy_flags |= TG3_PHYFLG_USER_CONFIGURED;
return err;
}
static int tg3_get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_TEST:
return TG3_NUM_TEST;
case ETH_SS_STATS:
return TG3_NUM_STATS;
default:
return -EOPNOTSUPP;
}
}
static int tg3_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info,
u32 *rules __always_unused)
{
struct tg3 *tp = netdev_priv(dev);
if (!tg3_flag(tp, SUPPORT_MSIX))
return -EOPNOTSUPP;
switch (info->cmd) {
case ETHTOOL_GRXRINGS:
if (netif_running(tp->dev))
info->data = tp->rxq_cnt;
else {
info->data = num_online_cpus();
if (info->data > TG3_RSS_MAX_NUM_QS)
info->data = TG3_RSS_MAX_NUM_QS;
}
/* The first interrupt vector only
* handles link interrupts.
*/
info->data -= 1;
return 0;
default:
return -EOPNOTSUPP;
}
}
static u32 tg3_get_rxfh_indir_size(struct net_device *dev)
{
u32 size = 0;
struct tg3 *tp = netdev_priv(dev);
if (tg3_flag(tp, SUPPORT_MSIX))
size = TG3_RSS_INDIR_TBL_SIZE;
return size;
}
static int tg3_get_rxfh(struct net_device *dev, u32 *indir, u8 *key)
{
struct tg3 *tp = netdev_priv(dev);
int i;
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++)
indir[i] = tp->rss_ind_tbl[i];
return 0;
}
static int tg3_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key)
{
struct tg3 *tp = netdev_priv(dev);
size_t i;
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++)
tp->rss_ind_tbl[i] = indir[i];
if (!netif_running(dev) || !tg3_flag(tp, ENABLE_RSS))
return 0;
/* It is legal to write the indirection
* table while the device is running.
*/
tg3_full_lock(tp, 0);
tg3_rss_write_indir_tbl(tp);
tg3_full_unlock(tp);
return 0;
}
static void tg3_get_channels(struct net_device *dev,
struct ethtool_channels *channel)
{
struct tg3 *tp = netdev_priv(dev);
u32 deflt_qs = netif_get_num_default_rss_queues();
channel->max_rx = tp->rxq_max;
channel->max_tx = tp->txq_max;
if (netif_running(dev)) {
channel->rx_count = tp->rxq_cnt;
channel->tx_count = tp->txq_cnt;
} else {
if (tp->rxq_req)
channel->rx_count = tp->rxq_req;
else
channel->rx_count = min(deflt_qs, tp->rxq_max);
if (tp->txq_req)
channel->tx_count = tp->txq_req;
else
channel->tx_count = min(deflt_qs, tp->txq_max);
}
}
static int tg3_set_channels(struct net_device *dev,
struct ethtool_channels *channel)
{
struct tg3 *tp = netdev_priv(dev);
if (!tg3_flag(tp, SUPPORT_MSIX))
return -EOPNOTSUPP;
if (channel->rx_count > tp->rxq_max ||
channel->tx_count > tp->txq_max)
return -EINVAL;
tp->rxq_req = channel->rx_count;
tp->txq_req = channel->tx_count;
if (!netif_running(dev))
return 0;
tg3_stop(tp);
tg3_carrier_off(tp);
tg3_start(tp, true, false, false);
return 0;
}
static void tg3_get_strings(struct net_device *dev, u32 stringset, u8 *buf)
{
switch (stringset) {
case ETH_SS_STATS:
memcpy(buf, ðtool_stats_keys, sizeof(ethtool_stats_keys));
break;
case ETH_SS_TEST:
memcpy(buf, ðtool_test_keys, sizeof(ethtool_test_keys));
break;
default:
WARN_ON(1); /* we need a WARN() */
break;
}
}
static int tg3_set_phys_id(struct net_device *dev,
enum ethtool_phys_id_state state)
{
struct tg3 *tp = netdev_priv(dev);
if (!netif_running(tp->dev))
return -EAGAIN;
switch (state) {
case ETHTOOL_ID_ACTIVE:
return 1; /* cycle on/off once per second */
case ETHTOOL_ID_ON:
tw32(MAC_LED_CTRL, LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_1000MBPS_ON |
LED_CTRL_100MBPS_ON |
LED_CTRL_10MBPS_ON |
LED_CTRL_TRAFFIC_OVERRIDE |
LED_CTRL_TRAFFIC_BLINK |
LED_CTRL_TRAFFIC_LED);
break;
case ETHTOOL_ID_OFF:
tw32(MAC_LED_CTRL, LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_TRAFFIC_OVERRIDE);
break;
case ETHTOOL_ID_INACTIVE:
tw32(MAC_LED_CTRL, tp->led_ctrl);
break;
}
return 0;
}
static void tg3_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *estats, u64 *tmp_stats)
{
struct tg3 *tp = netdev_priv(dev);
if (tp->hw_stats)
tg3_get_estats(tp, (struct tg3_ethtool_stats *)tmp_stats);
else
memset(tmp_stats, 0, sizeof(struct tg3_ethtool_stats));
}
static __be32 *tg3_vpd_readblock(struct tg3 *tp, u32 *vpdlen)
{
int i;
__be32 *buf;
u32 offset = 0, len = 0;
u32 magic, val;
if (tg3_flag(tp, NO_NVRAM) || tg3_nvram_read(tp, 0, &magic))
return NULL;
if (magic == TG3_EEPROM_MAGIC) {
for (offset = TG3_NVM_DIR_START;
offset < TG3_NVM_DIR_END;
offset += TG3_NVM_DIRENT_SIZE) {
if (tg3_nvram_read(tp, offset, &val))
return NULL;
if ((val >> TG3_NVM_DIRTYPE_SHIFT) ==
TG3_NVM_DIRTYPE_EXTVPD)
break;
}
if (offset != TG3_NVM_DIR_END) {
len = (val & TG3_NVM_DIRTYPE_LENMSK) * 4;
if (tg3_nvram_read(tp, offset + 4, &offset))
return NULL;
offset = tg3_nvram_logical_addr(tp, offset);
}
}
if (!offset || !len) {
offset = TG3_NVM_VPD_OFF;
len = TG3_NVM_VPD_LEN;
}
buf = kmalloc(len, GFP_KERNEL);
if (buf == NULL)
return NULL;
if (magic == TG3_EEPROM_MAGIC) {
for (i = 0; i < len; i += 4) {
/* The data is in little-endian format in NVRAM.
* Use the big-endian read routines to preserve
* the byte order as it exists in NVRAM.
*/
if (tg3_nvram_read_be32(tp, offset + i, &buf[i/4]))
goto error;
}
} else {
u8 *ptr;
ssize_t cnt;
unsigned int pos = 0;
ptr = (u8 *)&buf[0];
for (i = 0; pos < len && i < 3; i++, pos += cnt, ptr += cnt) {
cnt = pci_read_vpd(tp->pdev, pos,
len - pos, ptr);
if (cnt == -ETIMEDOUT || cnt == -EINTR)
cnt = 0;
else if (cnt < 0)
goto error;
}
if (pos != len)
goto error;
}
*vpdlen = len;
return buf;
error:
kfree(buf);
return NULL;
}
#define NVRAM_TEST_SIZE 0x100
#define NVRAM_SELFBOOT_FORMAT1_0_SIZE 0x14
#define NVRAM_SELFBOOT_FORMAT1_2_SIZE 0x18
#define NVRAM_SELFBOOT_FORMAT1_3_SIZE 0x1c
#define NVRAM_SELFBOOT_FORMAT1_4_SIZE 0x20
#define NVRAM_SELFBOOT_FORMAT1_5_SIZE 0x24
#define NVRAM_SELFBOOT_FORMAT1_6_SIZE 0x50
#define NVRAM_SELFBOOT_HW_SIZE 0x20
#define NVRAM_SELFBOOT_DATA_SIZE 0x1c
static int tg3_test_nvram(struct tg3 *tp)
{
u32 csum, magic, len;
__be32 *buf;
int i, j, k, err = 0, size;
if (tg3_flag(tp, NO_NVRAM))
return 0;
if (tg3_nvram_read(tp, 0, &magic) != 0)
return -EIO;
if (magic == TG3_EEPROM_MAGIC)
size = NVRAM_TEST_SIZE;
else if ((magic & TG3_EEPROM_MAGIC_FW_MSK) == TG3_EEPROM_MAGIC_FW) {
if ((magic & TG3_EEPROM_SB_FORMAT_MASK) ==
TG3_EEPROM_SB_FORMAT_1) {
switch (magic & TG3_EEPROM_SB_REVISION_MASK) {
case TG3_EEPROM_SB_REVISION_0:
size = NVRAM_SELFBOOT_FORMAT1_0_SIZE;
break;
case TG3_EEPROM_SB_REVISION_2:
size = NVRAM_SELFBOOT_FORMAT1_2_SIZE;
break;
case TG3_EEPROM_SB_REVISION_3:
size = NVRAM_SELFBOOT_FORMAT1_3_SIZE;
break;
case TG3_EEPROM_SB_REVISION_4:
size = NVRAM_SELFBOOT_FORMAT1_4_SIZE;
break;
case TG3_EEPROM_SB_REVISION_5:
size = NVRAM_SELFBOOT_FORMAT1_5_SIZE;
break;
case TG3_EEPROM_SB_REVISION_6:
size = NVRAM_SELFBOOT_FORMAT1_6_SIZE;
break;
default:
return -EIO;
}
} else
return 0;
} else if ((magic & TG3_EEPROM_MAGIC_HW_MSK) == TG3_EEPROM_MAGIC_HW)
size = NVRAM_SELFBOOT_HW_SIZE;
else
return -EIO;
buf = kmalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
err = -EIO;
for (i = 0, j = 0; i < size; i += 4, j++) {
err = tg3_nvram_read_be32(tp, i, &buf[j]);
if (err)
break;
}
if (i < size)
goto out;
/* Selfboot format */
magic = be32_to_cpu(buf[0]);
if ((magic & TG3_EEPROM_MAGIC_FW_MSK) ==
TG3_EEPROM_MAGIC_FW) {
u8 *buf8 = (u8 *) buf, csum8 = 0;
if ((magic & TG3_EEPROM_SB_REVISION_MASK) ==
TG3_EEPROM_SB_REVISION_2) {
/* For rev 2, the csum doesn't include the MBA. */
for (i = 0; i < TG3_EEPROM_SB_F1R2_MBA_OFF; i++)
csum8 += buf8[i];
for (i = TG3_EEPROM_SB_F1R2_MBA_OFF + 4; i < size; i++)
csum8 += buf8[i];
} else {
for (i = 0; i < size; i++)
csum8 += buf8[i];
}
if (csum8 == 0) {
err = 0;
goto out;
}
err = -EIO;
goto out;
}
if ((magic & TG3_EEPROM_MAGIC_HW_MSK) ==
TG3_EEPROM_MAGIC_HW) {
u8 data[NVRAM_SELFBOOT_DATA_SIZE];
u8 parity[NVRAM_SELFBOOT_DATA_SIZE];
u8 *buf8 = (u8 *) buf;
/* Separate the parity bits and the data bytes. */
for (i = 0, j = 0, k = 0; i < NVRAM_SELFBOOT_HW_SIZE; i++) {
if ((i == 0) || (i == 8)) {
int l;
u8 msk;
for (l = 0, msk = 0x80; l < 7; l++, msk >>= 1)
parity[k++] = buf8[i] & msk;
i++;
} else if (i == 16) {
int l;
u8 msk;
for (l = 0, msk = 0x20; l < 6; l++, msk >>= 1)
parity[k++] = buf8[i] & msk;
i++;
for (l = 0, msk = 0x80; l < 8; l++, msk >>= 1)
parity[k++] = buf8[i] & msk;
i++;
}
data[j++] = buf8[i];
}
err = -EIO;
for (i = 0; i < NVRAM_SELFBOOT_DATA_SIZE; i++) {
u8 hw8 = hweight8(data[i]);
if ((hw8 & 0x1) && parity[i])
goto out;
else if (!(hw8 & 0x1) && !parity[i])
goto out;
}
err = 0;
goto out;
}
err = -EIO;
/* Bootstrap checksum at offset 0x10 */
csum = calc_crc((unsigned char *) buf, 0x10);
if (csum != le32_to_cpu(buf[0x10/4]))
goto out;
/* Manufacturing block starts at offset 0x74, checksum at 0xfc */
csum = calc_crc((unsigned char *) &buf[0x74/4], 0x88);
if (csum != le32_to_cpu(buf[0xfc/4]))
goto out;
kfree(buf);
buf = tg3_vpd_readblock(tp, &len);
if (!buf)
return -ENOMEM;
i = pci_vpd_find_tag((u8 *)buf, 0, len, PCI_VPD_LRDT_RO_DATA);
if (i > 0) {
j = pci_vpd_lrdt_size(&((u8 *)buf)[i]);
if (j < 0)
goto out;
if (i + PCI_VPD_LRDT_TAG_SIZE + j > len)
goto out;
i += PCI_VPD_LRDT_TAG_SIZE;
j = pci_vpd_find_info_keyword((u8 *)buf, i, j,
PCI_VPD_RO_KEYWORD_CHKSUM);
if (j > 0) {
u8 csum8 = 0;
j += PCI_VPD_INFO_FLD_HDR_SIZE;
for (i = 0; i <= j; i++)
csum8 += ((u8 *)buf)[i];
if (csum8)
goto out;
}
}
err = 0;
out:
kfree(buf);
return err;
}
#define TG3_SERDES_TIMEOUT_SEC 2
#define TG3_COPPER_TIMEOUT_SEC 6
static int tg3_test_link(struct tg3 *tp)
{
int i, max;
if (!netif_running(tp->dev))
return -ENODEV;
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)
max = TG3_SERDES_TIMEOUT_SEC;
else
max = TG3_COPPER_TIMEOUT_SEC;
for (i = 0; i < max; i++) {
if (tp->link_up)
return 0;
if (msleep_interruptible(1000))
break;
}
return -EIO;
}
/* Only test the commonly used registers */
static int tg3_test_registers(struct tg3 *tp)
{
int i, is_5705, is_5750;
u32 offset, read_mask, write_mask, val, save_val, read_val;
static struct {
u16 offset;
u16 flags;
#define TG3_FL_5705 0x1
#define TG3_FL_NOT_5705 0x2
#define TG3_FL_NOT_5788 0x4
#define TG3_FL_NOT_5750 0x8
u32 read_mask;
u32 write_mask;
} reg_tbl[] = {
/* MAC Control Registers */
{ MAC_MODE, TG3_FL_NOT_5705,
0x00000000, 0x00ef6f8c },
{ MAC_MODE, TG3_FL_5705,
0x00000000, 0x01ef6b8c },
{ MAC_STATUS, TG3_FL_NOT_5705,
0x03800107, 0x00000000 },
{ MAC_STATUS, TG3_FL_5705,
0x03800100, 0x00000000 },
{ MAC_ADDR_0_HIGH, 0x0000,
0x00000000, 0x0000ffff },
{ MAC_ADDR_0_LOW, 0x0000,
0x00000000, 0xffffffff },
{ MAC_RX_MTU_SIZE, 0x0000,
0x00000000, 0x0000ffff },
{ MAC_TX_MODE, 0x0000,
0x00000000, 0x00000070 },
{ MAC_TX_LENGTHS, 0x0000,
0x00000000, 0x00003fff },
{ MAC_RX_MODE, TG3_FL_NOT_5705,
0x00000000, 0x000007fc },
{ MAC_RX_MODE, TG3_FL_5705,
0x00000000, 0x000007dc },
{ MAC_HASH_REG_0, 0x0000,
0x00000000, 0xffffffff },
{ MAC_HASH_REG_1, 0x0000,
0x00000000, 0xffffffff },
{ MAC_HASH_REG_2, 0x0000,
0x00000000, 0xffffffff },
{ MAC_HASH_REG_3, 0x0000,
0x00000000, 0xffffffff },
/* Receive Data and Receive BD Initiator Control Registers. */
{ RCVDBDI_JUMBO_BD+0, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ RCVDBDI_JUMBO_BD+4, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ RCVDBDI_JUMBO_BD+8, TG3_FL_NOT_5705,
0x00000000, 0x00000003 },
{ RCVDBDI_JUMBO_BD+0xc, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ RCVDBDI_STD_BD+0, 0x0000,
0x00000000, 0xffffffff },
{ RCVDBDI_STD_BD+4, 0x0000,
0x00000000, 0xffffffff },
{ RCVDBDI_STD_BD+8, 0x0000,
0x00000000, 0xffff0002 },
{ RCVDBDI_STD_BD+0xc, 0x0000,
0x00000000, 0xffffffff },
/* Receive BD Initiator Control Registers. */
{ RCVBDI_STD_THRESH, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ RCVBDI_STD_THRESH, TG3_FL_5705,
0x00000000, 0x000003ff },
{ RCVBDI_JUMBO_THRESH, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
/* Host Coalescing Control Registers. */
{ HOSTCC_MODE, TG3_FL_NOT_5705,
0x00000000, 0x00000004 },
{ HOSTCC_MODE, TG3_FL_5705,
0x00000000, 0x000000f6 },
{ HOSTCC_RXCOL_TICKS, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_RXCOL_TICKS, TG3_FL_5705,
0x00000000, 0x000003ff },
{ HOSTCC_TXCOL_TICKS, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_TXCOL_TICKS, TG3_FL_5705,
0x00000000, 0x000003ff },
{ HOSTCC_RXMAX_FRAMES, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_RXMAX_FRAMES, TG3_FL_5705 | TG3_FL_NOT_5788,
0x00000000, 0x000000ff },
{ HOSTCC_TXMAX_FRAMES, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_TXMAX_FRAMES, TG3_FL_5705 | TG3_FL_NOT_5788,
0x00000000, 0x000000ff },
{ HOSTCC_RXCOAL_TICK_INT, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_TXCOAL_TICK_INT, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_RXCOAL_MAXF_INT, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_RXCOAL_MAXF_INT, TG3_FL_5705 | TG3_FL_NOT_5788,
0x00000000, 0x000000ff },
{ HOSTCC_TXCOAL_MAXF_INT, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_TXCOAL_MAXF_INT, TG3_FL_5705 | TG3_FL_NOT_5788,
0x00000000, 0x000000ff },
{ HOSTCC_STAT_COAL_TICKS, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_STATS_BLK_HOST_ADDR, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_STATS_BLK_HOST_ADDR+4, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_STATUS_BLK_HOST_ADDR, 0x0000,
0x00000000, 0xffffffff },
{ HOSTCC_STATUS_BLK_HOST_ADDR+4, 0x0000,
0x00000000, 0xffffffff },
{ HOSTCC_STATS_BLK_NIC_ADDR, 0x0000,
0xffffffff, 0x00000000 },
{ HOSTCC_STATUS_BLK_NIC_ADDR, 0x0000,
0xffffffff, 0x00000000 },
/* Buffer Manager Control Registers. */
{ BUFMGR_MB_POOL_ADDR, TG3_FL_NOT_5750,
0x00000000, 0x007fff80 },
{ BUFMGR_MB_POOL_SIZE, TG3_FL_NOT_5750,
0x00000000, 0x007fffff },
{ BUFMGR_MB_RDMA_LOW_WATER, 0x0000,
0x00000000, 0x0000003f },
{ BUFMGR_MB_MACRX_LOW_WATER, 0x0000,
0x00000000, 0x000001ff },
{ BUFMGR_MB_HIGH_WATER, 0x0000,
0x00000000, 0x000001ff },
{ BUFMGR_DMA_DESC_POOL_ADDR, TG3_FL_NOT_5705,
0xffffffff, 0x00000000 },
{ BUFMGR_DMA_DESC_POOL_SIZE, TG3_FL_NOT_5705,
0xffffffff, 0x00000000 },
/* Mailbox Registers */
{ GRCMBOX_RCVSTD_PROD_IDX+4, 0x0000,
0x00000000, 0x000001ff },
{ GRCMBOX_RCVJUMBO_PROD_IDX+4, TG3_FL_NOT_5705,
0x00000000, 0x000001ff },
{ GRCMBOX_RCVRET_CON_IDX_0+4, 0x0000,
0x00000000, 0x000007ff },
{ GRCMBOX_SNDHOST_PROD_IDX_0+4, 0x0000,
0x00000000, 0x000001ff },
{ 0xffff, 0x0000, 0x00000000, 0x00000000 },
};
is_5705 = is_5750 = 0;
if (tg3_flag(tp, 5705_PLUS)) {
is_5705 = 1;
if (tg3_flag(tp, 5750_PLUS))
is_5750 = 1;
}
for (i = 0; reg_tbl[i].offset != 0xffff; i++) {
if (is_5705 && (reg_tbl[i].flags & TG3_FL_NOT_5705))
continue;
if (!is_5705 && (reg_tbl[i].flags & TG3_FL_5705))
continue;
if (tg3_flag(tp, IS_5788) &&
(reg_tbl[i].flags & TG3_FL_NOT_5788))
continue;
if (is_5750 && (reg_tbl[i].flags & TG3_FL_NOT_5750))
continue;
offset = (u32) reg_tbl[i].offset;
read_mask = reg_tbl[i].read_mask;
write_mask = reg_tbl[i].write_mask;
/* Save the original register content */
save_val = tr32(offset);
/* Determine the read-only value. */
read_val = save_val & read_mask;
/* Write zero to the register, then make sure the read-only bits
* are not changed and the read/write bits are all zeros.
*/
tw32(offset, 0);
val = tr32(offset);
/* Test the read-only and read/write bits. */
if (((val & read_mask) != read_val) || (val & write_mask))
goto out;
/* Write ones to all the bits defined by RdMask and WrMask, then
* make sure the read-only bits are not changed and the
* read/write bits are all ones.
*/
tw32(offset, read_mask | write_mask);
val = tr32(offset);
/* Test the read-only bits. */
if ((val & read_mask) != read_val)
goto out;
/* Test the read/write bits. */
if ((val & write_mask) != write_mask)
goto out;
tw32(offset, save_val);
}
return 0;
out:
if (netif_msg_hw(tp))
netdev_err(tp->dev,
"Register test failed at offset %x\n", offset);
tw32(offset, save_val);
return -EIO;
}
static int tg3_do_mem_test(struct tg3 *tp, u32 offset, u32 len)
{
static const u32 test_pattern[] = { 0x00000000, 0xffffffff, 0xaa55a55a };
int i;
u32 j;
for (i = 0; i < ARRAY_SIZE(test_pattern); i++) {
for (j = 0; j < len; j += 4) {
u32 val;
tg3_write_mem(tp, offset + j, test_pattern[i]);
tg3_read_mem(tp, offset + j, &val);
if (val != test_pattern[i])
return -EIO;
}
}
return 0;
}
static int tg3_test_memory(struct tg3 *tp)
{
static struct mem_entry {
u32 offset;
u32 len;
} mem_tbl_570x[] = {
{ 0x00000000, 0x00b50},
{ 0x00002000, 0x1c000},
{ 0xffffffff, 0x00000}
}, mem_tbl_5705[] = {
{ 0x00000100, 0x0000c},
{ 0x00000200, 0x00008},
{ 0x00004000, 0x00800},
{ 0x00006000, 0x01000},
{ 0x00008000, 0x02000},
{ 0x00010000, 0x0e000},
{ 0xffffffff, 0x00000}
}, mem_tbl_5755[] = {
{ 0x00000200, 0x00008},
{ 0x00004000, 0x00800},
{ 0x00006000, 0x00800},
{ 0x00008000, 0x02000},
{ 0x00010000, 0x0c000},
{ 0xffffffff, 0x00000}
}, mem_tbl_5906[] = {
{ 0x00000200, 0x00008},
{ 0x00004000, 0x00400},
{ 0x00006000, 0x00400},
{ 0x00008000, 0x01000},
{ 0x00010000, 0x01000},
{ 0xffffffff, 0x00000}
}, mem_tbl_5717[] = {
{ 0x00000200, 0x00008},
{ 0x00010000, 0x0a000},
{ 0x00020000, 0x13c00},
{ 0xffffffff, 0x00000}
}, mem_tbl_57765[] = {
{ 0x00000200, 0x00008},
{ 0x00004000, 0x00800},
{ 0x00006000, 0x09800},
{ 0x00010000, 0x0a000},
{ 0xffffffff, 0x00000}
};
struct mem_entry *mem_tbl;
int err = 0;
int i;
if (tg3_flag(tp, 5717_PLUS))
mem_tbl = mem_tbl_5717;
else if (tg3_flag(tp, 57765_CLASS) ||
tg3_asic_rev(tp) == ASIC_REV_5762)
mem_tbl = mem_tbl_57765;
else if (tg3_flag(tp, 5755_PLUS))
mem_tbl = mem_tbl_5755;
else if (tg3_asic_rev(tp) == ASIC_REV_5906)
mem_tbl = mem_tbl_5906;
else if (tg3_flag(tp, 5705_PLUS))
mem_tbl = mem_tbl_5705;
else
mem_tbl = mem_tbl_570x;
for (i = 0; mem_tbl[i].offset != 0xffffffff; i++) {
err = tg3_do_mem_test(tp, mem_tbl[i].offset, mem_tbl[i].len);
if (err)
break;
}
return err;
}
#define TG3_TSO_MSS 500
#define TG3_TSO_IP_HDR_LEN 20
#define TG3_TSO_TCP_HDR_LEN 20
#define TG3_TSO_TCP_OPT_LEN 12
static const u8 tg3_tso_header[] = {
0x08, 0x00,
0x45, 0x00, 0x00, 0x00,
0x00, 0x00, 0x40, 0x00,
0x40, 0x06, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x01,
0x0a, 0x00, 0x00, 0x02,
0x0d, 0x00, 0xe0, 0x00,
0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x02, 0x00,
0x80, 0x10, 0x10, 0x00,
0x14, 0x09, 0x00, 0x00,
0x01, 0x01, 0x08, 0x0a,
0x11, 0x11, 0x11, 0x11,
0x11, 0x11, 0x11, 0x11,
};
static int tg3_run_loopback(struct tg3 *tp, u32 pktsz, bool tso_loopback)
{
u32 rx_start_idx, rx_idx, tx_idx, opaque_key;
u32 base_flags = 0, mss = 0, desc_idx, coal_now, data_off, val;
u32 budget;
struct sk_buff *skb;
u8 *tx_data, *rx_data;
dma_addr_t map;
int num_pkts, tx_len, rx_len, i, err;
struct tg3_rx_buffer_desc *desc;
struct tg3_napi *tnapi, *rnapi;
struct tg3_rx_prodring_set *tpr = &tp->napi[0].prodring;
tnapi = &tp->napi[0];
rnapi = &tp->napi[0];
if (tp->irq_cnt > 1) {
if (tg3_flag(tp, ENABLE_RSS))
rnapi = &tp->napi[1];
if (tg3_flag(tp, ENABLE_TSS))
tnapi = &tp->napi[1];
}
coal_now = tnapi->coal_now | rnapi->coal_now;
err = -EIO;
tx_len = pktsz;
skb = netdev_alloc_skb(tp->dev, tx_len);
if (!skb)
return -ENOMEM;
tx_data = skb_put(skb, tx_len);
memcpy(tx_data, tp->dev->dev_addr, ETH_ALEN);
memset(tx_data + ETH_ALEN, 0x0, 8);
tw32(MAC_RX_MTU_SIZE, tx_len + ETH_FCS_LEN);
if (tso_loopback) {
struct iphdr *iph = (struct iphdr *)&tx_data[ETH_HLEN];
u32 hdr_len = TG3_TSO_IP_HDR_LEN + TG3_TSO_TCP_HDR_LEN +
TG3_TSO_TCP_OPT_LEN;
memcpy(tx_data + ETH_ALEN * 2, tg3_tso_header,
sizeof(tg3_tso_header));
mss = TG3_TSO_MSS;
val = tx_len - ETH_ALEN * 2 - sizeof(tg3_tso_header);
num_pkts = DIV_ROUND_UP(val, TG3_TSO_MSS);
/* Set the total length field in the IP header */
iph->tot_len = htons((u16)(mss + hdr_len));
base_flags = (TXD_FLAG_CPU_PRE_DMA |
TXD_FLAG_CPU_POST_DMA);
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3)) {
struct tcphdr *th;
val = ETH_HLEN + TG3_TSO_IP_HDR_LEN;
th = (struct tcphdr *)&tx_data[val];
th->check = 0;
} else
base_flags |= TXD_FLAG_TCPUDP_CSUM;
if (tg3_flag(tp, HW_TSO_3)) {
mss |= (hdr_len & 0xc) << 12;
if (hdr_len & 0x10)
base_flags |= 0x00000010;
base_flags |= (hdr_len & 0x3e0) << 5;
} else if (tg3_flag(tp, HW_TSO_2))
mss |= hdr_len << 9;
else if (tg3_flag(tp, HW_TSO_1) ||
tg3_asic_rev(tp) == ASIC_REV_5705) {
mss |= (TG3_TSO_TCP_OPT_LEN << 9);
} else {
base_flags |= (TG3_TSO_TCP_OPT_LEN << 10);
}
data_off = ETH_ALEN * 2 + sizeof(tg3_tso_header);
} else {
num_pkts = 1;
data_off = ETH_HLEN;
if (tg3_flag(tp, USE_JUMBO_BDFLAG) &&
tx_len > VLAN_ETH_FRAME_LEN)
base_flags |= TXD_FLAG_JMB_PKT;
}
for (i = data_off; i < tx_len; i++)
tx_data[i] = (u8) (i & 0xff);
map = pci_map_single(tp->pdev, skb->data, tx_len, PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(tp->pdev, map)) {
dev_kfree_skb(skb);
return -EIO;
}
val = tnapi->tx_prod;
tnapi->tx_buffers[val].skb = skb;
dma_unmap_addr_set(&tnapi->tx_buffers[val], mapping, map);
tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE |
rnapi->coal_now);
udelay(10);
rx_start_idx = rnapi->hw_status->idx[0].rx_producer;
budget = tg3_tx_avail(tnapi);
if (tg3_tx_frag_set(tnapi, &val, &budget, map, tx_len,
base_flags | TXD_FLAG_END, mss, 0)) {
tnapi->tx_buffers[val].skb = NULL;
dev_kfree_skb(skb);
return -EIO;
}
tnapi->tx_prod++;
/* Sync BD data before updating mailbox */
wmb();
tw32_tx_mbox(tnapi->prodmbox, tnapi->tx_prod);
tr32_mailbox(tnapi->prodmbox);
udelay(10);
/* 350 usec to allow enough time on some 10/100 Mbps devices. */
for (i = 0; i < 35; i++) {
tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE |
coal_now);
udelay(10);
tx_idx = tnapi->hw_status->idx[0].tx_consumer;
rx_idx = rnapi->hw_status->idx[0].rx_producer;
if ((tx_idx == tnapi->tx_prod) &&
(rx_idx == (rx_start_idx + num_pkts)))
break;
}
tg3_tx_skb_unmap(tnapi, tnapi->tx_prod - 1, -1);
dev_kfree_skb(skb);
if (tx_idx != tnapi->tx_prod)
goto out;
if (rx_idx != rx_start_idx + num_pkts)
goto out;
val = data_off;
while (rx_idx != rx_start_idx) {
desc = &rnapi->rx_rcb[rx_start_idx++];
desc_idx = desc->opaque & RXD_OPAQUE_INDEX_MASK;
opaque_key = desc->opaque & RXD_OPAQUE_RING_MASK;
if ((desc->err_vlan & RXD_ERR_MASK) != 0 &&
(desc->err_vlan != RXD_ERR_ODD_NIBBLE_RCVD_MII))
goto out;
rx_len = ((desc->idx_len & RXD_LEN_MASK) >> RXD_LEN_SHIFT)
- ETH_FCS_LEN;
if (!tso_loopback) {
if (rx_len != tx_len)
goto out;
if (pktsz <= TG3_RX_STD_DMA_SZ - ETH_FCS_LEN) {
if (opaque_key != RXD_OPAQUE_RING_STD)
goto out;
} else {
if (opaque_key != RXD_OPAQUE_RING_JUMBO)
goto out;
}
} else if ((desc->type_flags & RXD_FLAG_TCPUDP_CSUM) &&
(desc->ip_tcp_csum & RXD_TCPCSUM_MASK)
>> RXD_TCPCSUM_SHIFT != 0xffff) {
goto out;
}
if (opaque_key == RXD_OPAQUE_RING_STD) {
rx_data = tpr->rx_std_buffers[desc_idx].data;
map = dma_unmap_addr(&tpr->rx_std_buffers[desc_idx],
mapping);
} else if (opaque_key == RXD_OPAQUE_RING_JUMBO) {
rx_data = tpr->rx_jmb_buffers[desc_idx].data;
map = dma_unmap_addr(&tpr->rx_jmb_buffers[desc_idx],
mapping);
} else
goto out;
pci_dma_sync_single_for_cpu(tp->pdev, map, rx_len,
PCI_DMA_FROMDEVICE);
rx_data += TG3_RX_OFFSET(tp);
for (i = data_off; i < rx_len; i++, val++) {
if (*(rx_data + i) != (u8) (val & 0xff))
goto out;
}
}
err = 0;
/* tg3_free_rings will unmap and free the rx_data */
out:
return err;
}
#define TG3_STD_LOOPBACK_FAILED 1
#define TG3_JMB_LOOPBACK_FAILED 2
#define TG3_TSO_LOOPBACK_FAILED 4
#define TG3_LOOPBACK_FAILED \
(TG3_STD_LOOPBACK_FAILED | \
TG3_JMB_LOOPBACK_FAILED | \
TG3_TSO_LOOPBACK_FAILED)
static int tg3_test_loopback(struct tg3 *tp, u64 *data, bool do_extlpbk)
{
int err = -EIO;
u32 eee_cap;
u32 jmb_pkt_sz = 9000;
if (tp->dma_limit)
jmb_pkt_sz = tp->dma_limit - ETH_HLEN;
eee_cap = tp->phy_flags & TG3_PHYFLG_EEE_CAP;
tp->phy_flags &= ~TG3_PHYFLG_EEE_CAP;
if (!netif_running(tp->dev)) {
data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED;
data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED;
if (do_extlpbk)
data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED;
goto done;
}
err = tg3_reset_hw(tp, true);
if (err) {
data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED;
data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED;
if (do_extlpbk)
data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED;
goto done;
}
if (tg3_flag(tp, ENABLE_RSS)) {
int i;
/* Reroute all rx packets to the 1st queue */
for (i = MAC_RSS_INDIR_TBL_0;
i < MAC_RSS_INDIR_TBL_0 + TG3_RSS_INDIR_TBL_SIZE; i += 4)
tw32(i, 0x0);
}
/* HW errata - mac loopback fails in some cases on 5780.
* Normal traffic and PHY loopback are not affected by
* errata. Also, the MAC loopback test is deprecated for
* all newer ASIC revisions.
*/
if (tg3_asic_rev(tp) != ASIC_REV_5780 &&
!tg3_flag(tp, CPMU_PRESENT)) {
tg3_mac_loopback(tp, true);
if (tg3_run_loopback(tp, ETH_FRAME_LEN, false))
data[TG3_MAC_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED;
if (tg3_flag(tp, JUMBO_RING_ENABLE) &&
tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false))
data[TG3_MAC_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED;
tg3_mac_loopback(tp, false);
}
if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
!tg3_flag(tp, USE_PHYLIB)) {
int i;
tg3_phy_lpbk_set(tp, 0, false);
/* Wait for link */
for (i = 0; i < 100; i++) {
if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP)
break;
mdelay(1);
}
if (tg3_run_loopback(tp, ETH_FRAME_LEN, false))
data[TG3_PHY_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED;
if (tg3_flag(tp, TSO_CAPABLE) &&
tg3_run_loopback(tp, ETH_FRAME_LEN, true))
data[TG3_PHY_LOOPB_TEST] |= TG3_TSO_LOOPBACK_FAILED;
if (tg3_flag(tp, JUMBO_RING_ENABLE) &&
tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false))
data[TG3_PHY_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED;
if (do_extlpbk) {
tg3_phy_lpbk_set(tp, 0, true);
/* All link indications report up, but the hardware
* isn't really ready for about 20 msec. Double it
* to be sure.
*/
mdelay(40);
if (tg3_run_loopback(tp, ETH_FRAME_LEN, false))
data[TG3_EXT_LOOPB_TEST] |=
TG3_STD_LOOPBACK_FAILED;
if (tg3_flag(tp, TSO_CAPABLE) &&
tg3_run_loopback(tp, ETH_FRAME_LEN, true))
data[TG3_EXT_LOOPB_TEST] |=
TG3_TSO_LOOPBACK_FAILED;
if (tg3_flag(tp, JUMBO_RING_ENABLE) &&
tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false))
data[TG3_EXT_LOOPB_TEST] |=
TG3_JMB_LOOPBACK_FAILED;
}
/* Re-enable gphy autopowerdown. */
if (tp->phy_flags & TG3_PHYFLG_ENABLE_APD)
tg3_phy_toggle_apd(tp, true);
}
err = (data[TG3_MAC_LOOPB_TEST] | data[TG3_PHY_LOOPB_TEST] |
data[TG3_EXT_LOOPB_TEST]) ? -EIO : 0;
done:
tp->phy_flags |= eee_cap;
return err;
}
static void tg3_self_test(struct net_device *dev, struct ethtool_test *etest,
u64 *data)
{
struct tg3 *tp = netdev_priv(dev);
bool doextlpbk = etest->flags & ETH_TEST_FL_EXTERNAL_LB;
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) {
if (tg3_power_up(tp)) {
etest->flags |= ETH_TEST_FL_FAILED;
memset(data, 1, sizeof(u64) * TG3_NUM_TEST);
return;
}
tg3_ape_driver_state_change(tp, RESET_KIND_INIT);
}
memset(data, 0, sizeof(u64) * TG3_NUM_TEST);
if (tg3_test_nvram(tp) != 0) {
etest->flags |= ETH_TEST_FL_FAILED;
data[TG3_NVRAM_TEST] = 1;
}
if (!doextlpbk && tg3_test_link(tp)) {
etest->flags |= ETH_TEST_FL_FAILED;
data[TG3_LINK_TEST] = 1;
}
if (etest->flags & ETH_TEST_FL_OFFLINE) {
int err, err2 = 0, irq_sync = 0;
if (netif_running(dev)) {
tg3_phy_stop(tp);
tg3_netif_stop(tp);
irq_sync = 1;
}
tg3_full_lock(tp, irq_sync);
tg3_halt(tp, RESET_KIND_SUSPEND, 1);
err = tg3_nvram_lock(tp);
tg3_halt_cpu(tp, RX_CPU_BASE);
if (!tg3_flag(tp, 5705_PLUS))
tg3_halt_cpu(tp, TX_CPU_BASE);
if (!err)
tg3_nvram_unlock(tp);
if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
tg3_phy_reset(tp);
if (tg3_test_registers(tp) != 0) {
etest->flags |= ETH_TEST_FL_FAILED;
data[TG3_REGISTER_TEST] = 1;
}
if (tg3_test_memory(tp) != 0) {
etest->flags |= ETH_TEST_FL_FAILED;
data[TG3_MEMORY_TEST] = 1;
}
if (doextlpbk)
etest->flags |= ETH_TEST_FL_EXTERNAL_LB_DONE;
if (tg3_test_loopback(tp, data, doextlpbk))
etest->flags |= ETH_TEST_FL_FAILED;
tg3_full_unlock(tp);
if (tg3_test_interrupt(tp) != 0) {
etest->flags |= ETH_TEST_FL_FAILED;
data[TG3_INTERRUPT_TEST] = 1;
}
tg3_full_lock(tp, 0);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
if (netif_running(dev)) {
tg3_flag_set(tp, INIT_COMPLETE);
err2 = tg3_restart_hw(tp, true);
if (!err2)
tg3_netif_start(tp);
}
tg3_full_unlock(tp);
if (irq_sync && !err2)
tg3_phy_start(tp);
}
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)
tg3_power_down_prepare(tp);
}
static int tg3_hwtstamp_set(struct net_device *dev, struct ifreq *ifr)
{
struct tg3 *tp = netdev_priv(dev);
struct hwtstamp_config stmpconf;
if (!tg3_flag(tp, PTP_CAPABLE))
return -EOPNOTSUPP;
if (copy_from_user(&stmpconf, ifr->ifr_data, sizeof(stmpconf)))
return -EFAULT;
if (stmpconf.flags)
return -EINVAL;
if (stmpconf.tx_type != HWTSTAMP_TX_ON &&
stmpconf.tx_type != HWTSTAMP_TX_OFF)
return -ERANGE;
switch (stmpconf.rx_filter) {
case HWTSTAMP_FILTER_NONE:
tp->rxptpctl = 0;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V1_EN |
TG3_RX_PTP_CTL_ALL_V1_EVENTS;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V1_EN |
TG3_RX_PTP_CTL_SYNC_EVNT;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V1_EN |
TG3_RX_PTP_CTL_DELAY_REQ;
break;
case HWTSTAMP_FILTER_PTP_V2_EVENT:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_EN |
TG3_RX_PTP_CTL_ALL_V2_EVENTS;
break;
case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN |
TG3_RX_PTP_CTL_ALL_V2_EVENTS;
break;
case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN |
TG3_RX_PTP_CTL_ALL_V2_EVENTS;
break;
case HWTSTAMP_FILTER_PTP_V2_SYNC:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_EN |
TG3_RX_PTP_CTL_SYNC_EVNT;
break;
case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN |
TG3_RX_PTP_CTL_SYNC_EVNT;
break;
case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN |
TG3_RX_PTP_CTL_SYNC_EVNT;
break;
case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_EN |
TG3_RX_PTP_CTL_DELAY_REQ;
break;
case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN |
TG3_RX_PTP_CTL_DELAY_REQ;
break;
case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
tp->rxptpctl = TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN |
TG3_RX_PTP_CTL_DELAY_REQ;
break;
default:
return -ERANGE;
}
if (netif_running(dev) && tp->rxptpctl)
tw32(TG3_RX_PTP_CTL,
tp->rxptpctl | TG3_RX_PTP_CTL_HWTS_INTERLOCK);
if (stmpconf.tx_type == HWTSTAMP_TX_ON)
tg3_flag_set(tp, TX_TSTAMP_EN);
else
tg3_flag_clear(tp, TX_TSTAMP_EN);
return copy_to_user(ifr->ifr_data, &stmpconf, sizeof(stmpconf)) ?
-EFAULT : 0;
}
static int tg3_hwtstamp_get(struct net_device *dev, struct ifreq *ifr)
{
struct tg3 *tp = netdev_priv(dev);
struct hwtstamp_config stmpconf;
if (!tg3_flag(tp, PTP_CAPABLE))
return -EOPNOTSUPP;
stmpconf.flags = 0;
stmpconf.tx_type = (tg3_flag(tp, TX_TSTAMP_EN) ?
HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF);
switch (tp->rxptpctl) {
case 0:
stmpconf.rx_filter = HWTSTAMP_FILTER_NONE;
break;
case TG3_RX_PTP_CTL_RX_PTP_V1_EN | TG3_RX_PTP_CTL_ALL_V1_EVENTS:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_EVENT;
break;
case TG3_RX_PTP_CTL_RX_PTP_V1_EN | TG3_RX_PTP_CTL_SYNC_EVNT:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_SYNC;
break;
case TG3_RX_PTP_CTL_RX_PTP_V1_EN | TG3_RX_PTP_CTL_DELAY_REQ:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_EN | TG3_RX_PTP_CTL_ALL_V2_EVENTS:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_EVENT;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN | TG3_RX_PTP_CTL_ALL_V2_EVENTS:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_L2_EVENT;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN | TG3_RX_PTP_CTL_ALL_V2_EVENTS:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_EVENT;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_EN | TG3_RX_PTP_CTL_SYNC_EVNT:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_SYNC;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN | TG3_RX_PTP_CTL_SYNC_EVNT:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_L2_SYNC;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN | TG3_RX_PTP_CTL_SYNC_EVNT:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_SYNC;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_EN | TG3_RX_PTP_CTL_DELAY_REQ:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_DELAY_REQ;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_L2_EN | TG3_RX_PTP_CTL_DELAY_REQ:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ;
break;
case TG3_RX_PTP_CTL_RX_PTP_V2_L4_EN | TG3_RX_PTP_CTL_DELAY_REQ:
stmpconf.rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ;
break;
default:
WARN_ON_ONCE(1);
return -ERANGE;
}
return copy_to_user(ifr->ifr_data, &stmpconf, sizeof(stmpconf)) ?
-EFAULT : 0;
}
static int tg3_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct mii_ioctl_data *data = if_mii(ifr);
struct tg3 *tp = netdev_priv(dev);
int err;
if (tg3_flag(tp, USE_PHYLIB)) {
struct phy_device *phydev;
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return -EAGAIN;
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
return phy_mii_ioctl(phydev, ifr, cmd);
}
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = tp->phy_addr;
/* fallthru */
case SIOCGMIIREG: {
u32 mii_regval;
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
break; /* We have no PHY */
if (!netif_running(dev))
return -EAGAIN;
spin_lock_bh(&tp->lock);
err = __tg3_readphy(tp, data->phy_id & 0x1f,
data->reg_num & 0x1f, &mii_regval);
spin_unlock_bh(&tp->lock);
data->val_out = mii_regval;
return err;
}
case SIOCSMIIREG:
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
break; /* We have no PHY */
if (!netif_running(dev))
return -EAGAIN;
spin_lock_bh(&tp->lock);
err = __tg3_writephy(tp, data->phy_id & 0x1f,
data->reg_num & 0x1f, data->val_in);
spin_unlock_bh(&tp->lock);
return err;
case SIOCSHWTSTAMP:
return tg3_hwtstamp_set(dev, ifr);
case SIOCGHWTSTAMP:
return tg3_hwtstamp_get(dev, ifr);
default:
/* do nothing */
break;
}
return -EOPNOTSUPP;
}
static int tg3_get_coalesce(struct net_device *dev, struct ethtool_coalesce *ec)
{
struct tg3 *tp = netdev_priv(dev);
memcpy(ec, &tp->coal, sizeof(*ec));
return 0;
}
static int tg3_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec)
{
struct tg3 *tp = netdev_priv(dev);
u32 max_rxcoal_tick_int = 0, max_txcoal_tick_int = 0;
u32 max_stat_coal_ticks = 0, min_stat_coal_ticks = 0;
if (!tg3_flag(tp, 5705_PLUS)) {
max_rxcoal_tick_int = MAX_RXCOAL_TICK_INT;
max_txcoal_tick_int = MAX_TXCOAL_TICK_INT;
max_stat_coal_ticks = MAX_STAT_COAL_TICKS;
min_stat_coal_ticks = MIN_STAT_COAL_TICKS;
}
if ((ec->rx_coalesce_usecs > MAX_RXCOL_TICKS) ||
(ec->tx_coalesce_usecs > MAX_TXCOL_TICKS) ||
(ec->rx_max_coalesced_frames > MAX_RXMAX_FRAMES) ||
(ec->tx_max_coalesced_frames > MAX_TXMAX_FRAMES) ||
(ec->rx_coalesce_usecs_irq > max_rxcoal_tick_int) ||
(ec->tx_coalesce_usecs_irq > max_txcoal_tick_int) ||
(ec->rx_max_coalesced_frames_irq > MAX_RXCOAL_MAXF_INT) ||
(ec->tx_max_coalesced_frames_irq > MAX_TXCOAL_MAXF_INT) ||
(ec->stats_block_coalesce_usecs > max_stat_coal_ticks) ||
(ec->stats_block_coalesce_usecs < min_stat_coal_ticks))
return -EINVAL;
/* No rx interrupts will be generated if both are zero */
if ((ec->rx_coalesce_usecs == 0) &&
(ec->rx_max_coalesced_frames == 0))
return -EINVAL;
/* No tx interrupts will be generated if both are zero */
if ((ec->tx_coalesce_usecs == 0) &&
(ec->tx_max_coalesced_frames == 0))
return -EINVAL;
/* Only copy relevant parameters, ignore all others. */
tp->coal.rx_coalesce_usecs = ec->rx_coalesce_usecs;
tp->coal.tx_coalesce_usecs = ec->tx_coalesce_usecs;
tp->coal.rx_max_coalesced_frames = ec->rx_max_coalesced_frames;
tp->coal.tx_max_coalesced_frames = ec->tx_max_coalesced_frames;
tp->coal.rx_coalesce_usecs_irq = ec->rx_coalesce_usecs_irq;
tp->coal.tx_coalesce_usecs_irq = ec->tx_coalesce_usecs_irq;
tp->coal.rx_max_coalesced_frames_irq = ec->rx_max_coalesced_frames_irq;
tp->coal.tx_max_coalesced_frames_irq = ec->tx_max_coalesced_frames_irq;
tp->coal.stats_block_coalesce_usecs = ec->stats_block_coalesce_usecs;
if (netif_running(dev)) {
tg3_full_lock(tp, 0);
__tg3_set_coalesce(tp, &tp->coal);
tg3_full_unlock(tp);
}
return 0;
}
static int tg3_set_eee(struct net_device *dev, struct ethtool_eee *edata)
{
struct tg3 *tp = netdev_priv(dev);
if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) {
netdev_warn(tp->dev, "Board does not support EEE!\n");
return -EOPNOTSUPP;
}
if (edata->advertised != tp->eee.advertised) {
netdev_warn(tp->dev,
"Direct manipulation of EEE advertisement is not supported\n");
return -EINVAL;
}
if (edata->tx_lpi_timer > TG3_CPMU_DBTMR1_LNKIDLE_MAX) {
netdev_warn(tp->dev,
"Maximal Tx Lpi timer supported is %#x(u)\n",
TG3_CPMU_DBTMR1_LNKIDLE_MAX);
return -EINVAL;
}
tp->eee = *edata;
tp->phy_flags |= TG3_PHYFLG_USER_CONFIGURED;
tg3_warn_mgmt_link_flap(tp);
if (netif_running(tp->dev)) {
tg3_full_lock(tp, 0);
tg3_setup_eee(tp);
tg3_phy_reset(tp);
tg3_full_unlock(tp);
}
return 0;
}
static int tg3_get_eee(struct net_device *dev, struct ethtool_eee *edata)
{
struct tg3 *tp = netdev_priv(dev);
if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP)) {
netdev_warn(tp->dev,
"Board does not support EEE!\n");
return -EOPNOTSUPP;
}
*edata = tp->eee;
return 0;
}
static const struct ethtool_ops tg3_ethtool_ops = {
.get_settings = tg3_get_settings,
.set_settings = tg3_set_settings,
.get_drvinfo = tg3_get_drvinfo,
.get_regs_len = tg3_get_regs_len,
.get_regs = tg3_get_regs,
.get_wol = tg3_get_wol,
.set_wol = tg3_set_wol,
.get_msglevel = tg3_get_msglevel,
.set_msglevel = tg3_set_msglevel,
.nway_reset = tg3_nway_reset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = tg3_get_eeprom_len,
.get_eeprom = tg3_get_eeprom,
.set_eeprom = tg3_set_eeprom,
.get_ringparam = tg3_get_ringparam,
.set_ringparam = tg3_set_ringparam,
.get_pauseparam = tg3_get_pauseparam,
.set_pauseparam = tg3_set_pauseparam,
.self_test = tg3_self_test,
.get_strings = tg3_get_strings,
.set_phys_id = tg3_set_phys_id,
.get_ethtool_stats = tg3_get_ethtool_stats,
.get_coalesce = tg3_get_coalesce,
.set_coalesce = tg3_set_coalesce,
.get_sset_count = tg3_get_sset_count,
.get_rxnfc = tg3_get_rxnfc,
.get_rxfh_indir_size = tg3_get_rxfh_indir_size,
.get_rxfh = tg3_get_rxfh,
.set_rxfh = tg3_set_rxfh,
.get_channels = tg3_get_channels,
.set_channels = tg3_set_channels,
.get_ts_info = tg3_get_ts_info,
.get_eee = tg3_get_eee,
.set_eee = tg3_set_eee,
};
static struct rtnl_link_stats64 *tg3_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
struct tg3 *tp = netdev_priv(dev);
spin_lock_bh(&tp->lock);
if (!tp->hw_stats) {
spin_unlock_bh(&tp->lock);
return &tp->net_stats_prev;
}
tg3_get_nstats(tp, stats);
spin_unlock_bh(&tp->lock);
return stats;
}
static void tg3_set_rx_mode(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
if (!netif_running(dev))
return;
tg3_full_lock(tp, 0);
__tg3_set_rx_mode(dev);
tg3_full_unlock(tp);
}
static inline void tg3_set_mtu(struct net_device *dev, struct tg3 *tp,
int new_mtu)
{
dev->mtu = new_mtu;
if (new_mtu > ETH_DATA_LEN) {
if (tg3_flag(tp, 5780_CLASS)) {
netdev_update_features(dev);
tg3_flag_clear(tp, TSO_CAPABLE);
} else {
tg3_flag_set(tp, JUMBO_RING_ENABLE);
}
} else {
if (tg3_flag(tp, 5780_CLASS)) {
tg3_flag_set(tp, TSO_CAPABLE);
netdev_update_features(dev);
}
tg3_flag_clear(tp, JUMBO_RING_ENABLE);
}
}
static int tg3_change_mtu(struct net_device *dev, int new_mtu)
{
struct tg3 *tp = netdev_priv(dev);
int err;
bool reset_phy = false;
if (new_mtu < TG3_MIN_MTU || new_mtu > TG3_MAX_MTU(tp))
return -EINVAL;
if (!netif_running(dev)) {
/* We'll just catch it later when the
* device is up'd.
*/
tg3_set_mtu(dev, tp, new_mtu);
return 0;
}
tg3_phy_stop(tp);
tg3_netif_stop(tp);
tg3_set_mtu(dev, tp, new_mtu);
tg3_full_lock(tp, 1);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
/* Reset PHY, otherwise the read DMA engine will be in a mode that
* breaks all requests to 256 bytes.
*/
if (tg3_asic_rev(tp) == ASIC_REV_57766)
reset_phy = true;
err = tg3_restart_hw(tp, reset_phy);
if (!err)
tg3_netif_start(tp);
tg3_full_unlock(tp);
if (!err)
tg3_phy_start(tp);
return err;
}
static const struct net_device_ops tg3_netdev_ops = {
.ndo_open = tg3_open,
.ndo_stop = tg3_close,
.ndo_start_xmit = tg3_start_xmit,
.ndo_get_stats64 = tg3_get_stats64,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = tg3_set_rx_mode,
.ndo_set_mac_address = tg3_set_mac_addr,
.ndo_do_ioctl = tg3_ioctl,
.ndo_tx_timeout = tg3_tx_timeout,
.ndo_change_mtu = tg3_change_mtu,
.ndo_fix_features = tg3_fix_features,
.ndo_set_features = tg3_set_features,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = tg3_poll_controller,
#endif
};
static void tg3_get_eeprom_size(struct tg3 *tp)
{
u32 cursize, val, magic;
tp->nvram_size = EEPROM_CHIP_SIZE;
if (tg3_nvram_read(tp, 0, &magic) != 0)
return;
if ((magic != TG3_EEPROM_MAGIC) &&
((magic & TG3_EEPROM_MAGIC_FW_MSK) != TG3_EEPROM_MAGIC_FW) &&
((magic & TG3_EEPROM_MAGIC_HW_MSK) != TG3_EEPROM_MAGIC_HW))
return;
/*
* Size the chip by reading offsets at increasing powers of two.
* When we encounter our validation signature, we know the addressing
* has wrapped around, and thus have our chip size.
*/
cursize = 0x10;
while (cursize < tp->nvram_size) {
if (tg3_nvram_read(tp, cursize, &val) != 0)
return;
if (val == magic)
break;
cursize <<= 1;
}
tp->nvram_size = cursize;
}
static void tg3_get_nvram_size(struct tg3 *tp)
{
u32 val;
if (tg3_flag(tp, NO_NVRAM) || tg3_nvram_read(tp, 0, &val) != 0)
return;
/* Selfboot format */
if (val != TG3_EEPROM_MAGIC) {
tg3_get_eeprom_size(tp);
return;
}
if (tg3_nvram_read(tp, 0xf0, &val) == 0) {
if (val != 0) {
/* This is confusing. We want to operate on the
* 16-bit value at offset 0xf2. The tg3_nvram_read()
* call will read from NVRAM and byteswap the data
* according to the byteswapping settings for all
* other register accesses. This ensures the data we
* want will always reside in the lower 16-bits.
* However, the data in NVRAM is in LE format, which
* means the data from the NVRAM read will always be
* opposite the endianness of the CPU. The 16-bit
* byteswap then brings the data to CPU endianness.
*/
tp->nvram_size = swab16((u16)(val & 0x0000ffff)) * 1024;
return;
}
}
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
}
static void tg3_get_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
if (nvcfg1 & NVRAM_CFG1_FLASHIF_ENAB) {
tg3_flag_set(tp, FLASH);
} else {
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
}
if (tg3_asic_rev(tp) == ASIC_REV_5750 ||
tg3_flag(tp, 5780_CLASS)) {
switch (nvcfg1 & NVRAM_CFG1_VENDOR_MASK) {
case FLASH_VENDOR_ATMEL_FLASH_BUFFERED:
tp->nvram_jedecnum = JEDEC_ATMEL;
tp->nvram_pagesize = ATMEL_AT45DB0X1B_PAGE_SIZE;
tg3_flag_set(tp, NVRAM_BUFFERED);
break;
case FLASH_VENDOR_ATMEL_FLASH_UNBUFFERED:
tp->nvram_jedecnum = JEDEC_ATMEL;
tp->nvram_pagesize = ATMEL_AT25F512_PAGE_SIZE;
break;
case FLASH_VENDOR_ATMEL_EEPROM:
tp->nvram_jedecnum = JEDEC_ATMEL;
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
tg3_flag_set(tp, NVRAM_BUFFERED);
break;
case FLASH_VENDOR_ST:
tp->nvram_jedecnum = JEDEC_ST;
tp->nvram_pagesize = ST_M45PEX0_PAGE_SIZE;
tg3_flag_set(tp, NVRAM_BUFFERED);
break;
case FLASH_VENDOR_SAIFUN:
tp->nvram_jedecnum = JEDEC_SAIFUN;
tp->nvram_pagesize = SAIFUN_SA25F0XX_PAGE_SIZE;
break;
case FLASH_VENDOR_SST_SMALL:
case FLASH_VENDOR_SST_LARGE:
tp->nvram_jedecnum = JEDEC_SST;
tp->nvram_pagesize = SST_25VF0X0_PAGE_SIZE;
break;
}
} else {
tp->nvram_jedecnum = JEDEC_ATMEL;
tp->nvram_pagesize = ATMEL_AT45DB0X1B_PAGE_SIZE;
tg3_flag_set(tp, NVRAM_BUFFERED);
}
}
static void tg3_nvram_get_pagesize(struct tg3 *tp, u32 nvmcfg1)
{
switch (nvmcfg1 & NVRAM_CFG1_5752PAGE_SIZE_MASK) {
case FLASH_5752PAGE_SIZE_256:
tp->nvram_pagesize = 256;
break;
case FLASH_5752PAGE_SIZE_512:
tp->nvram_pagesize = 512;
break;
case FLASH_5752PAGE_SIZE_1K:
tp->nvram_pagesize = 1024;
break;
case FLASH_5752PAGE_SIZE_2K:
tp->nvram_pagesize = 2048;
break;
case FLASH_5752PAGE_SIZE_4K:
tp->nvram_pagesize = 4096;
break;
case FLASH_5752PAGE_SIZE_264:
tp->nvram_pagesize = 264;
break;
case FLASH_5752PAGE_SIZE_528:
tp->nvram_pagesize = 528;
break;
}
}
static void tg3_get_5752_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
/* NVRAM protection for TPM */
if (nvcfg1 & (1 << 27))
tg3_flag_set(tp, PROTECTED_NVRAM);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5752VENDOR_ATMEL_EEPROM_64KHZ:
case FLASH_5752VENDOR_ATMEL_EEPROM_376KHZ:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
break;
case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
break;
case FLASH_5752VENDOR_ST_M45PE10:
case FLASH_5752VENDOR_ST_M45PE20:
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
break;
}
if (tg3_flag(tp, FLASH)) {
tg3_nvram_get_pagesize(tp, nvcfg1);
} else {
/* For eeprom, set pagesize to maximum eeprom size */
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
}
}
static void tg3_get_5755_nvram_info(struct tg3 *tp)
{
u32 nvcfg1, protect = 0;
nvcfg1 = tr32(NVRAM_CFG1);
/* NVRAM protection for TPM */
if (nvcfg1 & (1 << 27)) {
tg3_flag_set(tp, PROTECTED_NVRAM);
protect = 1;
}
nvcfg1 &= NVRAM_CFG1_5752VENDOR_MASK;
switch (nvcfg1) {
case FLASH_5755VENDOR_ATMEL_FLASH_1:
case FLASH_5755VENDOR_ATMEL_FLASH_2:
case FLASH_5755VENDOR_ATMEL_FLASH_3:
case FLASH_5755VENDOR_ATMEL_FLASH_5:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 264;
if (nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_1 ||
nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_5)
tp->nvram_size = (protect ? 0x3e200 :
TG3_NVRAM_SIZE_512KB);
else if (nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_2)
tp->nvram_size = (protect ? 0x1f200 :
TG3_NVRAM_SIZE_256KB);
else
tp->nvram_size = (protect ? 0x1f200 :
TG3_NVRAM_SIZE_128KB);
break;
case FLASH_5752VENDOR_ST_M45PE10:
case FLASH_5752VENDOR_ST_M45PE20:
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 256;
if (nvcfg1 == FLASH_5752VENDOR_ST_M45PE10)
tp->nvram_size = (protect ?
TG3_NVRAM_SIZE_64KB :
TG3_NVRAM_SIZE_128KB);
else if (nvcfg1 == FLASH_5752VENDOR_ST_M45PE20)
tp->nvram_size = (protect ?
TG3_NVRAM_SIZE_64KB :
TG3_NVRAM_SIZE_256KB);
else
tp->nvram_size = (protect ?
TG3_NVRAM_SIZE_128KB :
TG3_NVRAM_SIZE_512KB);
break;
}
}
static void tg3_get_5787_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5787VENDOR_ATMEL_EEPROM_64KHZ:
case FLASH_5787VENDOR_ATMEL_EEPROM_376KHZ:
case FLASH_5787VENDOR_MICRO_EEPROM_64KHZ:
case FLASH_5787VENDOR_MICRO_EEPROM_376KHZ:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
break;
case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED:
case FLASH_5755VENDOR_ATMEL_FLASH_1:
case FLASH_5755VENDOR_ATMEL_FLASH_2:
case FLASH_5755VENDOR_ATMEL_FLASH_3:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 264;
break;
case FLASH_5752VENDOR_ST_M45PE10:
case FLASH_5752VENDOR_ST_M45PE20:
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 256;
break;
}
}
static void tg3_get_5761_nvram_info(struct tg3 *tp)
{
u32 nvcfg1, protect = 0;
nvcfg1 = tr32(NVRAM_CFG1);
/* NVRAM protection for TPM */
if (nvcfg1 & (1 << 27)) {
tg3_flag_set(tp, PROTECTED_NVRAM);
protect = 1;
}
nvcfg1 &= NVRAM_CFG1_5752VENDOR_MASK;
switch (nvcfg1) {
case FLASH_5761VENDOR_ATMEL_ADB021D:
case FLASH_5761VENDOR_ATMEL_ADB041D:
case FLASH_5761VENDOR_ATMEL_ADB081D:
case FLASH_5761VENDOR_ATMEL_ADB161D:
case FLASH_5761VENDOR_ATMEL_MDB021D:
case FLASH_5761VENDOR_ATMEL_MDB041D:
case FLASH_5761VENDOR_ATMEL_MDB081D:
case FLASH_5761VENDOR_ATMEL_MDB161D:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS);
tp->nvram_pagesize = 256;
break;
case FLASH_5761VENDOR_ST_A_M45PE20:
case FLASH_5761VENDOR_ST_A_M45PE40:
case FLASH_5761VENDOR_ST_A_M45PE80:
case FLASH_5761VENDOR_ST_A_M45PE16:
case FLASH_5761VENDOR_ST_M_M45PE20:
case FLASH_5761VENDOR_ST_M_M45PE40:
case FLASH_5761VENDOR_ST_M_M45PE80:
case FLASH_5761VENDOR_ST_M_M45PE16:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 256;
break;
}
if (protect) {
tp->nvram_size = tr32(NVRAM_ADDR_LOCKOUT);
} else {
switch (nvcfg1) {
case FLASH_5761VENDOR_ATMEL_ADB161D:
case FLASH_5761VENDOR_ATMEL_MDB161D:
case FLASH_5761VENDOR_ST_A_M45PE16:
case FLASH_5761VENDOR_ST_M_M45PE16:
tp->nvram_size = TG3_NVRAM_SIZE_2MB;
break;
case FLASH_5761VENDOR_ATMEL_ADB081D:
case FLASH_5761VENDOR_ATMEL_MDB081D:
case FLASH_5761VENDOR_ST_A_M45PE80:
case FLASH_5761VENDOR_ST_M_M45PE80:
tp->nvram_size = TG3_NVRAM_SIZE_1MB;
break;
case FLASH_5761VENDOR_ATMEL_ADB041D:
case FLASH_5761VENDOR_ATMEL_MDB041D:
case FLASH_5761VENDOR_ST_A_M45PE40:
case FLASH_5761VENDOR_ST_M_M45PE40:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
case FLASH_5761VENDOR_ATMEL_ADB021D:
case FLASH_5761VENDOR_ATMEL_MDB021D:
case FLASH_5761VENDOR_ST_A_M45PE20:
case FLASH_5761VENDOR_ST_M_M45PE20:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
}
}
}
static void tg3_get_5906_nvram_info(struct tg3 *tp)
{
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
}
static void tg3_get_57780_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5787VENDOR_ATMEL_EEPROM_376KHZ:
case FLASH_5787VENDOR_MICRO_EEPROM_376KHZ:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
return;
case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED:
case FLASH_57780VENDOR_ATMEL_AT45DB011D:
case FLASH_57780VENDOR_ATMEL_AT45DB011B:
case FLASH_57780VENDOR_ATMEL_AT45DB021D:
case FLASH_57780VENDOR_ATMEL_AT45DB021B:
case FLASH_57780VENDOR_ATMEL_AT45DB041D:
case FLASH_57780VENDOR_ATMEL_AT45DB041B:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED:
case FLASH_57780VENDOR_ATMEL_AT45DB011D:
case FLASH_57780VENDOR_ATMEL_AT45DB011B:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
case FLASH_57780VENDOR_ATMEL_AT45DB021D:
case FLASH_57780VENDOR_ATMEL_AT45DB021B:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
case FLASH_57780VENDOR_ATMEL_AT45DB041D:
case FLASH_57780VENDOR_ATMEL_AT45DB041B:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
}
break;
case FLASH_5752VENDOR_ST_M45PE10:
case FLASH_5752VENDOR_ST_M45PE20:
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5752VENDOR_ST_M45PE10:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
case FLASH_5752VENDOR_ST_M45PE20:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
}
break;
default:
tg3_flag_set(tp, NO_NVRAM);
return;
}
tg3_nvram_get_pagesize(tp, nvcfg1);
if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528)
tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS);
}
static void tg3_get_5717_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5717VENDOR_ATMEL_EEPROM:
case FLASH_5717VENDOR_MICRO_EEPROM:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
return;
case FLASH_5717VENDOR_ATMEL_MDB011D:
case FLASH_5717VENDOR_ATMEL_ADB011B:
case FLASH_5717VENDOR_ATMEL_ADB011D:
case FLASH_5717VENDOR_ATMEL_MDB021D:
case FLASH_5717VENDOR_ATMEL_ADB021B:
case FLASH_5717VENDOR_ATMEL_ADB021D:
case FLASH_5717VENDOR_ATMEL_45USPT:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5717VENDOR_ATMEL_MDB021D:
/* Detect size with tg3_nvram_get_size() */
break;
case FLASH_5717VENDOR_ATMEL_ADB021B:
case FLASH_5717VENDOR_ATMEL_ADB021D:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
default:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
}
break;
case FLASH_5717VENDOR_ST_M_M25PE10:
case FLASH_5717VENDOR_ST_A_M25PE10:
case FLASH_5717VENDOR_ST_M_M45PE10:
case FLASH_5717VENDOR_ST_A_M45PE10:
case FLASH_5717VENDOR_ST_M_M25PE20:
case FLASH_5717VENDOR_ST_A_M25PE20:
case FLASH_5717VENDOR_ST_M_M45PE20:
case FLASH_5717VENDOR_ST_A_M45PE20:
case FLASH_5717VENDOR_ST_25USPT:
case FLASH_5717VENDOR_ST_45USPT:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5717VENDOR_ST_M_M25PE20:
case FLASH_5717VENDOR_ST_M_M45PE20:
/* Detect size with tg3_nvram_get_size() */
break;
case FLASH_5717VENDOR_ST_A_M25PE20:
case FLASH_5717VENDOR_ST_A_M45PE20:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
default:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
}
break;
default:
tg3_flag_set(tp, NO_NVRAM);
return;
}
tg3_nvram_get_pagesize(tp, nvcfg1);
if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528)
tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS);
}
static void tg3_get_5720_nvram_info(struct tg3 *tp)
{
u32 nvcfg1, nvmpinstrp;
nvcfg1 = tr32(NVRAM_CFG1);
nvmpinstrp = nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK;
if (tg3_asic_rev(tp) == ASIC_REV_5762) {
if (!(nvcfg1 & NVRAM_CFG1_5762VENDOR_MASK)) {
tg3_flag_set(tp, NO_NVRAM);
return;
}
switch (nvmpinstrp) {
case FLASH_5762_EEPROM_HD:
nvmpinstrp = FLASH_5720_EEPROM_HD;
break;
case FLASH_5762_EEPROM_LD:
nvmpinstrp = FLASH_5720_EEPROM_LD;
break;
case FLASH_5720VENDOR_M_ST_M45PE20:
/* This pinstrap supports multiple sizes, so force it
* to read the actual size from location 0xf0.
*/
nvmpinstrp = FLASH_5720VENDOR_ST_45USPT;
break;
}
}
switch (nvmpinstrp) {
case FLASH_5720_EEPROM_HD:
case FLASH_5720_EEPROM_LD:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
if (nvmpinstrp == FLASH_5720_EEPROM_HD)
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
else
tp->nvram_pagesize = ATMEL_AT24C02_CHIP_SIZE;
return;
case FLASH_5720VENDOR_M_ATMEL_DB011D:
case FLASH_5720VENDOR_A_ATMEL_DB011B:
case FLASH_5720VENDOR_A_ATMEL_DB011D:
case FLASH_5720VENDOR_M_ATMEL_DB021D:
case FLASH_5720VENDOR_A_ATMEL_DB021B:
case FLASH_5720VENDOR_A_ATMEL_DB021D:
case FLASH_5720VENDOR_M_ATMEL_DB041D:
case FLASH_5720VENDOR_A_ATMEL_DB041B:
case FLASH_5720VENDOR_A_ATMEL_DB041D:
case FLASH_5720VENDOR_M_ATMEL_DB081D:
case FLASH_5720VENDOR_A_ATMEL_DB081D:
case FLASH_5720VENDOR_ATMEL_45USPT:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvmpinstrp) {
case FLASH_5720VENDOR_M_ATMEL_DB021D:
case FLASH_5720VENDOR_A_ATMEL_DB021B:
case FLASH_5720VENDOR_A_ATMEL_DB021D:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
case FLASH_5720VENDOR_M_ATMEL_DB041D:
case FLASH_5720VENDOR_A_ATMEL_DB041B:
case FLASH_5720VENDOR_A_ATMEL_DB041D:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
case FLASH_5720VENDOR_M_ATMEL_DB081D:
case FLASH_5720VENDOR_A_ATMEL_DB081D:
tp->nvram_size = TG3_NVRAM_SIZE_1MB;
break;
default:
if (tg3_asic_rev(tp) != ASIC_REV_5762)
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
}
break;
case FLASH_5720VENDOR_M_ST_M25PE10:
case FLASH_5720VENDOR_M_ST_M45PE10:
case FLASH_5720VENDOR_A_ST_M25PE10:
case FLASH_5720VENDOR_A_ST_M45PE10:
case FLASH_5720VENDOR_M_ST_M25PE20:
case FLASH_5720VENDOR_M_ST_M45PE20:
case FLASH_5720VENDOR_A_ST_M25PE20:
case FLASH_5720VENDOR_A_ST_M45PE20:
case FLASH_5720VENDOR_M_ST_M25PE40:
case FLASH_5720VENDOR_M_ST_M45PE40:
case FLASH_5720VENDOR_A_ST_M25PE40:
case FLASH_5720VENDOR_A_ST_M45PE40:
case FLASH_5720VENDOR_M_ST_M25PE80:
case FLASH_5720VENDOR_M_ST_M45PE80:
case FLASH_5720VENDOR_A_ST_M25PE80:
case FLASH_5720VENDOR_A_ST_M45PE80:
case FLASH_5720VENDOR_ST_25USPT:
case FLASH_5720VENDOR_ST_45USPT:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvmpinstrp) {
case FLASH_5720VENDOR_M_ST_M25PE20:
case FLASH_5720VENDOR_M_ST_M45PE20:
case FLASH_5720VENDOR_A_ST_M25PE20:
case FLASH_5720VENDOR_A_ST_M45PE20:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
case FLASH_5720VENDOR_M_ST_M25PE40:
case FLASH_5720VENDOR_M_ST_M45PE40:
case FLASH_5720VENDOR_A_ST_M25PE40:
case FLASH_5720VENDOR_A_ST_M45PE40:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
case FLASH_5720VENDOR_M_ST_M25PE80:
case FLASH_5720VENDOR_M_ST_M45PE80:
case FLASH_5720VENDOR_A_ST_M25PE80:
case FLASH_5720VENDOR_A_ST_M45PE80:
tp->nvram_size = TG3_NVRAM_SIZE_1MB;
break;
default:
if (tg3_asic_rev(tp) != ASIC_REV_5762)
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
}
break;
default:
tg3_flag_set(tp, NO_NVRAM);
return;
}
tg3_nvram_get_pagesize(tp, nvcfg1);
if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528)
tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS);
if (tg3_asic_rev(tp) == ASIC_REV_5762) {
u32 val;
if (tg3_nvram_read(tp, 0, &val))
return;
if (val != TG3_EEPROM_MAGIC &&
(val & TG3_EEPROM_MAGIC_FW_MSK) != TG3_EEPROM_MAGIC_FW)
tg3_flag_set(tp, NO_NVRAM);
}
}
/* Chips other than 5700/5701 use the NVRAM for fetching info. */
static void tg3_nvram_init(struct tg3 *tp)
{
if (tg3_flag(tp, IS_SSB_CORE)) {
/* No NVRAM and EEPROM on the SSB Broadcom GigE core. */
tg3_flag_clear(tp, NVRAM);
tg3_flag_clear(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, NO_NVRAM);
return;
}
tw32_f(GRC_EEPROM_ADDR,
(EEPROM_ADDR_FSM_RESET |
(EEPROM_DEFAULT_CLOCK_PERIOD <<
EEPROM_ADDR_CLKPERD_SHIFT)));
msleep(1);
/* Enable seeprom accesses. */
tw32_f(GRC_LOCAL_CTRL,
tr32(GRC_LOCAL_CTRL) | GRC_LCLCTRL_AUTO_SEEPROM);
udelay(100);
if (tg3_asic_rev(tp) != ASIC_REV_5700 &&
tg3_asic_rev(tp) != ASIC_REV_5701) {
tg3_flag_set(tp, NVRAM);
if (tg3_nvram_lock(tp)) {
netdev_warn(tp->dev,
"Cannot get nvram lock, %s failed\n",
__func__);
return;
}
tg3_enable_nvram_access(tp);
tp->nvram_size = 0;
if (tg3_asic_rev(tp) == ASIC_REV_5752)
tg3_get_5752_nvram_info(tp);
else if (tg3_asic_rev(tp) == ASIC_REV_5755)
tg3_get_5755_nvram_info(tp);
else if (tg3_asic_rev(tp) == ASIC_REV_5787 ||
tg3_asic_rev(tp) == ASIC_REV_5784 ||
tg3_asic_rev(tp) == ASIC_REV_5785)
tg3_get_5787_nvram_info(tp);
else if (tg3_asic_rev(tp) == ASIC_REV_5761)
tg3_get_5761_nvram_info(tp);
else if (tg3_asic_rev(tp) == ASIC_REV_5906)
tg3_get_5906_nvram_info(tp);
else if (tg3_asic_rev(tp) == ASIC_REV_57780 ||
tg3_flag(tp, 57765_CLASS))
tg3_get_57780_nvram_info(tp);
else if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719)
tg3_get_5717_nvram_info(tp);
else if (tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762)
tg3_get_5720_nvram_info(tp);
else
tg3_get_nvram_info(tp);
if (tp->nvram_size == 0)
tg3_get_nvram_size(tp);
tg3_disable_nvram_access(tp);
tg3_nvram_unlock(tp);
} else {
tg3_flag_clear(tp, NVRAM);
tg3_flag_clear(tp, NVRAM_BUFFERED);
tg3_get_eeprom_size(tp);
}
}
struct subsys_tbl_ent {
u16 subsys_vendor, subsys_devid;
u32 phy_id;
};
static struct subsys_tbl_ent subsys_id_to_phy_id[] = {
/* Broadcom boards. */
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95700A6, TG3_PHY_ID_BCM5401 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701A5, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95700T6, TG3_PHY_ID_BCM8002 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95700A9, 0 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701T1, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701T8, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701A7, 0 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701A10, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701A12, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95703AX1, TG3_PHY_ID_BCM5703 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95703AX2, TG3_PHY_ID_BCM5703 },
/* 3com boards. */
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C996T, TG3_PHY_ID_BCM5401 },
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C996BT, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C996SX, 0 },
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C1000T, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C940BR01, TG3_PHY_ID_BCM5701 },
/* DELL boards. */
{ TG3PCI_SUBVENDOR_ID_DELL,
TG3PCI_SUBDEVICE_ID_DELL_VIPER, TG3_PHY_ID_BCM5401 },
{ TG3PCI_SUBVENDOR_ID_DELL,
TG3PCI_SUBDEVICE_ID_DELL_JAGUAR, TG3_PHY_ID_BCM5401 },
{ TG3PCI_SUBVENDOR_ID_DELL,
TG3PCI_SUBDEVICE_ID_DELL_MERLOT, TG3_PHY_ID_BCM5411 },
{ TG3PCI_SUBVENDOR_ID_DELL,
TG3PCI_SUBDEVICE_ID_DELL_SLIM_MERLOT, TG3_PHY_ID_BCM5411 },
/* Compaq boards. */
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_BANSHEE, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_BANSHEE_2, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_CHANGELING, 0 },
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_NC7780, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_NC7780_2, TG3_PHY_ID_BCM5701 },
/* IBM boards. */
{ TG3PCI_SUBVENDOR_ID_IBM,
TG3PCI_SUBDEVICE_ID_IBM_5703SAX2, 0 }
};
static struct subsys_tbl_ent *tg3_lookup_by_subsys(struct tg3 *tp)
{
int i;
for (i = 0; i < ARRAY_SIZE(subsys_id_to_phy_id); i++) {
if ((subsys_id_to_phy_id[i].subsys_vendor ==
tp->pdev->subsystem_vendor) &&
(subsys_id_to_phy_id[i].subsys_devid ==
tp->pdev->subsystem_device))
return &subsys_id_to_phy_id[i];
}
return NULL;
}
static void tg3_get_eeprom_hw_cfg(struct tg3 *tp)
{
u32 val;
tp->phy_id = TG3_PHY_ID_INVALID;
tp->led_ctrl = LED_CTRL_MODE_PHY_1;
/* Assume an onboard device and WOL capable by default. */
tg3_flag_set(tp, EEPROM_WRITE_PROT);
tg3_flag_set(tp, WOL_CAP);
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
if (!(tr32(PCIE_TRANSACTION_CFG) & PCIE_TRANS_CFG_LOM)) {
tg3_flag_clear(tp, EEPROM_WRITE_PROT);
tg3_flag_set(tp, IS_NIC);
}
val = tr32(VCPU_CFGSHDW);
if (val & VCPU_CFGSHDW_ASPM_DBNC)
tg3_flag_set(tp, ASPM_WORKAROUND);
if ((val & VCPU_CFGSHDW_WOL_ENABLE) &&
(val & VCPU_CFGSHDW_WOL_MAGPKT)) {
tg3_flag_set(tp, WOL_ENABLE);
device_set_wakeup_enable(&tp->pdev->dev, true);
}
goto done;
}
tg3_read_mem(tp, NIC_SRAM_DATA_SIG, &val);
if (val == NIC_SRAM_DATA_SIG_MAGIC) {
u32 nic_cfg, led_cfg;
u32 cfg2 = 0, cfg4 = 0, cfg5 = 0;
u32 nic_phy_id, ver, eeprom_phy_id;
int eeprom_phy_serdes = 0;
tg3_read_mem(tp, NIC_SRAM_DATA_CFG, &nic_cfg);
tp->nic_sram_data_cfg = nic_cfg;
tg3_read_mem(tp, NIC_SRAM_DATA_VER, &ver);
ver >>= NIC_SRAM_DATA_VER_SHIFT;
if (tg3_asic_rev(tp) != ASIC_REV_5700 &&
tg3_asic_rev(tp) != ASIC_REV_5701 &&
tg3_asic_rev(tp) != ASIC_REV_5703 &&
(ver > 0) && (ver < 0x100))
tg3_read_mem(tp, NIC_SRAM_DATA_CFG_2, &cfg2);
if (tg3_asic_rev(tp) == ASIC_REV_5785)
tg3_read_mem(tp, NIC_SRAM_DATA_CFG_4, &cfg4);
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720)
tg3_read_mem(tp, NIC_SRAM_DATA_CFG_5, &cfg5);
if ((nic_cfg & NIC_SRAM_DATA_CFG_PHY_TYPE_MASK) ==
NIC_SRAM_DATA_CFG_PHY_TYPE_FIBER)
eeprom_phy_serdes = 1;
tg3_read_mem(tp, NIC_SRAM_DATA_PHY_ID, &nic_phy_id);
if (nic_phy_id != 0) {
u32 id1 = nic_phy_id & NIC_SRAM_DATA_PHY_ID1_MASK;
u32 id2 = nic_phy_id & NIC_SRAM_DATA_PHY_ID2_MASK;
eeprom_phy_id = (id1 >> 16) << 10;
eeprom_phy_id |= (id2 & 0xfc00) << 16;
eeprom_phy_id |= (id2 & 0x03ff) << 0;
} else
eeprom_phy_id = 0;
tp->phy_id = eeprom_phy_id;
if (eeprom_phy_serdes) {
if (!tg3_flag(tp, 5705_PLUS))
tp->phy_flags |= TG3_PHYFLG_PHY_SERDES;
else
tp->phy_flags |= TG3_PHYFLG_MII_SERDES;
}
if (tg3_flag(tp, 5750_PLUS))
led_cfg = cfg2 & (NIC_SRAM_DATA_CFG_LED_MODE_MASK |
SHASTA_EXT_LED_MODE_MASK);
else
led_cfg = nic_cfg & NIC_SRAM_DATA_CFG_LED_MODE_MASK;
switch (led_cfg) {
default:
case NIC_SRAM_DATA_CFG_LED_MODE_PHY_1:
tp->led_ctrl = LED_CTRL_MODE_PHY_1;
break;
case NIC_SRAM_DATA_CFG_LED_MODE_PHY_2:
tp->led_ctrl = LED_CTRL_MODE_PHY_2;
break;
case NIC_SRAM_DATA_CFG_LED_MODE_MAC:
tp->led_ctrl = LED_CTRL_MODE_MAC;
/* Default to PHY_1_MODE if 0 (MAC_MODE) is
* read on some older 5700/5701 bootcode.
*/
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701)
tp->led_ctrl = LED_CTRL_MODE_PHY_1;
break;
case SHASTA_EXT_LED_SHARED:
tp->led_ctrl = LED_CTRL_MODE_SHARED;
if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A1)
tp->led_ctrl |= (LED_CTRL_MODE_PHY_1 |
LED_CTRL_MODE_PHY_2);
if (tg3_flag(tp, 5717_PLUS) ||
tg3_asic_rev(tp) == ASIC_REV_5762)
tp->led_ctrl |= LED_CTRL_BLINK_RATE_OVERRIDE |
LED_CTRL_BLINK_RATE_MASK;
break;
case SHASTA_EXT_LED_MAC:
tp->led_ctrl = LED_CTRL_MODE_SHASTA_MAC;
break;
case SHASTA_EXT_LED_COMBO:
tp->led_ctrl = LED_CTRL_MODE_COMBO;
if (tg3_chip_rev_id(tp) != CHIPREV_ID_5750_A0)
tp->led_ctrl |= (LED_CTRL_MODE_PHY_1 |
LED_CTRL_MODE_PHY_2);
break;
}
if ((tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701) &&
tp->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL)
tp->led_ctrl = LED_CTRL_MODE_PHY_2;
if (tg3_chip_rev(tp) == CHIPREV_5784_AX)
tp->led_ctrl = LED_CTRL_MODE_PHY_1;
if (nic_cfg & NIC_SRAM_DATA_CFG_EEPROM_WP) {
tg3_flag_set(tp, EEPROM_WRITE_PROT);
if ((tp->pdev->subsystem_vendor ==
PCI_VENDOR_ID_ARIMA) &&
(tp->pdev->subsystem_device == 0x205a ||
tp->pdev->subsystem_device == 0x2063))
tg3_flag_clear(tp, EEPROM_WRITE_PROT);
} else {
tg3_flag_clear(tp, EEPROM_WRITE_PROT);
tg3_flag_set(tp, IS_NIC);
}
if (nic_cfg & NIC_SRAM_DATA_CFG_ASF_ENABLE) {
tg3_flag_set(tp, ENABLE_ASF);
if (tg3_flag(tp, 5750_PLUS))
tg3_flag_set(tp, ASF_NEW_HANDSHAKE);
}
if ((nic_cfg & NIC_SRAM_DATA_CFG_APE_ENABLE) &&
tg3_flag(tp, 5750_PLUS))
tg3_flag_set(tp, ENABLE_APE);
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES &&
!(nic_cfg & NIC_SRAM_DATA_CFG_FIBER_WOL))
tg3_flag_clear(tp, WOL_CAP);
if (tg3_flag(tp, WOL_CAP) &&
(nic_cfg & NIC_SRAM_DATA_CFG_WOL_ENABLE)) {
tg3_flag_set(tp, WOL_ENABLE);
device_set_wakeup_enable(&tp->pdev->dev, true);
}
if (cfg2 & (1 << 17))
tp->phy_flags |= TG3_PHYFLG_CAPACITIVE_COUPLING;
/* serdes signal pre-emphasis in register 0x590 set by */
/* bootcode if bit 18 is set */
if (cfg2 & (1 << 18))
tp->phy_flags |= TG3_PHYFLG_SERDES_PREEMPHASIS;
if ((tg3_flag(tp, 57765_PLUS) ||
(tg3_asic_rev(tp) == ASIC_REV_5784 &&
tg3_chip_rev(tp) != CHIPREV_5784_AX)) &&
(cfg2 & NIC_SRAM_DATA_CFG_2_APD_EN))
tp->phy_flags |= TG3_PHYFLG_ENABLE_APD;
if (tg3_flag(tp, PCI_EXPRESS)) {
u32 cfg3;
tg3_read_mem(tp, NIC_SRAM_DATA_CFG_3, &cfg3);
if (tg3_asic_rev(tp) != ASIC_REV_5785 &&
!tg3_flag(tp, 57765_PLUS) &&
(cfg3 & NIC_SRAM_ASPM_DEBOUNCE))
tg3_flag_set(tp, ASPM_WORKAROUND);
if (cfg3 & NIC_SRAM_LNK_FLAP_AVOID)
tp->phy_flags |= TG3_PHYFLG_KEEP_LINK_ON_PWRDN;
if (cfg3 & NIC_SRAM_1G_ON_VAUX_OK)
tp->phy_flags |= TG3_PHYFLG_1G_ON_VAUX_OK;
}
if (cfg4 & NIC_SRAM_RGMII_INBAND_DISABLE)
tg3_flag_set(tp, RGMII_INBAND_DISABLE);
if (cfg4 & NIC_SRAM_RGMII_EXT_IBND_RX_EN)
tg3_flag_set(tp, RGMII_EXT_IBND_RX_EN);
if (cfg4 & NIC_SRAM_RGMII_EXT_IBND_TX_EN)
tg3_flag_set(tp, RGMII_EXT_IBND_TX_EN);
if (cfg5 & NIC_SRAM_DISABLE_1G_HALF_ADV)
tp->phy_flags |= TG3_PHYFLG_DISABLE_1G_HD_ADV;
}
done:
if (tg3_flag(tp, WOL_CAP))
device_set_wakeup_enable(&tp->pdev->dev,
tg3_flag(tp, WOL_ENABLE));
else
device_set_wakeup_capable(&tp->pdev->dev, false);
}
static int tg3_ape_otp_read(struct tg3 *tp, u32 offset, u32 *val)
{
int i, err;
u32 val2, off = offset * 8;
err = tg3_nvram_lock(tp);
if (err)
return err;
tg3_ape_write32(tp, TG3_APE_OTP_ADDR, off | APE_OTP_ADDR_CPU_ENABLE);
tg3_ape_write32(tp, TG3_APE_OTP_CTRL, APE_OTP_CTRL_PROG_EN |
APE_OTP_CTRL_CMD_RD | APE_OTP_CTRL_START);
tg3_ape_read32(tp, TG3_APE_OTP_CTRL);
udelay(10);
for (i = 0; i < 100; i++) {
val2 = tg3_ape_read32(tp, TG3_APE_OTP_STATUS);
if (val2 & APE_OTP_STATUS_CMD_DONE) {
*val = tg3_ape_read32(tp, TG3_APE_OTP_RD_DATA);
break;
}
udelay(10);
}
tg3_ape_write32(tp, TG3_APE_OTP_CTRL, 0);
tg3_nvram_unlock(tp);
if (val2 & APE_OTP_STATUS_CMD_DONE)
return 0;
return -EBUSY;
}
static int tg3_issue_otp_command(struct tg3 *tp, u32 cmd)
{
int i;
u32 val;
tw32(OTP_CTRL, cmd | OTP_CTRL_OTP_CMD_START);
tw32(OTP_CTRL, cmd);
/* Wait for up to 1 ms for command to execute. */
for (i = 0; i < 100; i++) {
val = tr32(OTP_STATUS);
if (val & OTP_STATUS_CMD_DONE)
break;
udelay(10);
}
return (val & OTP_STATUS_CMD_DONE) ? 0 : -EBUSY;
}
/* Read the gphy configuration from the OTP region of the chip. The gphy
* configuration is a 32-bit value that straddles the alignment boundary.
* We do two 32-bit reads and then shift and merge the results.
*/
static u32 tg3_read_otp_phycfg(struct tg3 *tp)
{
u32 bhalf_otp, thalf_otp;
tw32(OTP_MODE, OTP_MODE_OTP_THRU_GRC);
if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_INIT))
return 0;
tw32(OTP_ADDRESS, OTP_ADDRESS_MAGIC1);
if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_READ))
return 0;
thalf_otp = tr32(OTP_READ_DATA);
tw32(OTP_ADDRESS, OTP_ADDRESS_MAGIC2);
if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_READ))
return 0;
bhalf_otp = tr32(OTP_READ_DATA);
return ((thalf_otp & 0x0000ffff) << 16) | (bhalf_otp >> 16);
}
static void tg3_phy_init_link_config(struct tg3 *tp)
{
u32 adv = ADVERTISED_Autoneg;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
if (!(tp->phy_flags & TG3_PHYFLG_DISABLE_1G_HD_ADV))
adv |= ADVERTISED_1000baseT_Half;
adv |= ADVERTISED_1000baseT_Full;
}
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
adv |= ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full |
ADVERTISED_TP;
else
adv |= ADVERTISED_FIBRE;
tp->link_config.advertising = adv;
tp->link_config.speed = SPEED_UNKNOWN;
tp->link_config.duplex = DUPLEX_UNKNOWN;
tp->link_config.autoneg = AUTONEG_ENABLE;
tp->link_config.active_speed = SPEED_UNKNOWN;
tp->link_config.active_duplex = DUPLEX_UNKNOWN;
tp->old_link = -1;
}
static int tg3_phy_probe(struct tg3 *tp)
{
u32 hw_phy_id_1, hw_phy_id_2;
u32 hw_phy_id, hw_phy_id_masked;
int err;
/* flow control autonegotiation is default behavior */
tg3_flag_set(tp, PAUSE_AUTONEG);
tp->link_config.flowctrl = FLOW_CTRL_TX | FLOW_CTRL_RX;
if (tg3_flag(tp, ENABLE_APE)) {
switch (tp->pci_fn) {
case 0:
tp->phy_ape_lock = TG3_APE_LOCK_PHY0;
break;
case 1:
tp->phy_ape_lock = TG3_APE_LOCK_PHY1;
break;
case 2:
tp->phy_ape_lock = TG3_APE_LOCK_PHY2;
break;
case 3:
tp->phy_ape_lock = TG3_APE_LOCK_PHY3;
break;
}
}
if (!tg3_flag(tp, ENABLE_ASF) &&
!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES) &&
!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY))
tp->phy_flags &= ~(TG3_PHYFLG_1G_ON_VAUX_OK |
TG3_PHYFLG_KEEP_LINK_ON_PWRDN);
if (tg3_flag(tp, USE_PHYLIB))
return tg3_phy_init(tp);
/* Reading the PHY ID register can conflict with ASF
* firmware access to the PHY hardware.
*/
err = 0;
if (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE)) {
hw_phy_id = hw_phy_id_masked = TG3_PHY_ID_INVALID;
} else {
/* Now read the physical PHY_ID from the chip and verify
* that it is sane. If it doesn't look good, we fall back
* to either the hard-coded table based PHY_ID and failing
* that the value found in the eeprom area.
*/
err |= tg3_readphy(tp, MII_PHYSID1, &hw_phy_id_1);
err |= tg3_readphy(tp, MII_PHYSID2, &hw_phy_id_2);
hw_phy_id = (hw_phy_id_1 & 0xffff) << 10;
hw_phy_id |= (hw_phy_id_2 & 0xfc00) << 16;
hw_phy_id |= (hw_phy_id_2 & 0x03ff) << 0;
hw_phy_id_masked = hw_phy_id & TG3_PHY_ID_MASK;
}
if (!err && TG3_KNOWN_PHY_ID(hw_phy_id_masked)) {
tp->phy_id = hw_phy_id;
if (hw_phy_id_masked == TG3_PHY_ID_BCM8002)
tp->phy_flags |= TG3_PHYFLG_PHY_SERDES;
else
tp->phy_flags &= ~TG3_PHYFLG_PHY_SERDES;
} else {
if (tp->phy_id != TG3_PHY_ID_INVALID) {
/* Do nothing, phy ID already set up in
* tg3_get_eeprom_hw_cfg().
*/
} else {
struct subsys_tbl_ent *p;
/* No eeprom signature? Try the hardcoded
* subsys device table.
*/
p = tg3_lookup_by_subsys(tp);
if (p) {
tp->phy_id = p->phy_id;
} else if (!tg3_flag(tp, IS_SSB_CORE)) {
/* For now we saw the IDs 0xbc050cd0,
* 0xbc050f80 and 0xbc050c30 on devices
* connected to an BCM4785 and there are
* probably more. Just assume that the phy is
* supported when it is connected to a SSB core
* for now.
*/
return -ENODEV;
}
if (!tp->phy_id ||
tp->phy_id == TG3_PHY_ID_BCM8002)
tp->phy_flags |= TG3_PHYFLG_PHY_SERDES;
}
}
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES) &&
(tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_57766 ||
tg3_asic_rev(tp) == ASIC_REV_5762 ||
(tg3_asic_rev(tp) == ASIC_REV_5717 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5717_A0) ||
(tg3_asic_rev(tp) == ASIC_REV_57765 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_57765_A0))) {
tp->phy_flags |= TG3_PHYFLG_EEE_CAP;
tp->eee.supported = SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Full;
tp->eee.advertised = ADVERTISED_100baseT_Full |
ADVERTISED_1000baseT_Full;
tp->eee.eee_enabled = 1;
tp->eee.tx_lpi_enabled = 1;
tp->eee.tx_lpi_timer = TG3_CPMU_DBTMR1_LNKIDLE_2047US;
}
tg3_phy_init_link_config(tp);
if (!(tp->phy_flags & TG3_PHYFLG_KEEP_LINK_ON_PWRDN) &&
!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES) &&
!tg3_flag(tp, ENABLE_APE) &&
!tg3_flag(tp, ENABLE_ASF)) {
u32 bmsr, dummy;
tg3_readphy(tp, MII_BMSR, &bmsr);
if (!tg3_readphy(tp, MII_BMSR, &bmsr) &&
(bmsr & BMSR_LSTATUS))
goto skip_phy_reset;
err = tg3_phy_reset(tp);
if (err)
return err;
tg3_phy_set_wirespeed(tp);
if (!tg3_phy_copper_an_config_ok(tp, &dummy)) {
tg3_phy_autoneg_cfg(tp, tp->link_config.advertising,
tp->link_config.flowctrl);
tg3_writephy(tp, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART);
}
}
skip_phy_reset:
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) {
err = tg3_init_5401phy_dsp(tp);
if (err)
return err;
err = tg3_init_5401phy_dsp(tp);
}
return err;
}
static void tg3_read_vpd(struct tg3 *tp)
{
u8 *vpd_data;
unsigned int block_end, rosize, len;
u32 vpdlen;
int j, i = 0;
vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen);
if (!vpd_data)
goto out_no_vpd;
i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA);
if (i < 0)
goto out_not_found;
rosize = pci_vpd_lrdt_size(&vpd_data[i]);
block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize;
i += PCI_VPD_LRDT_TAG_SIZE;
if (block_end > vpdlen)
goto out_not_found;
j = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_MFR_ID);
if (j > 0) {
len = pci_vpd_info_field_size(&vpd_data[j]);
j += PCI_VPD_INFO_FLD_HDR_SIZE;
if (j + len > block_end || len != 4 ||
memcmp(&vpd_data[j], "1028", 4))
goto partno;
j = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_VENDOR0);
if (j < 0)
goto partno;
len = pci_vpd_info_field_size(&vpd_data[j]);
j += PCI_VPD_INFO_FLD_HDR_SIZE;
if (j + len > block_end)
goto partno;
if (len >= sizeof(tp->fw_ver))
len = sizeof(tp->fw_ver) - 1;
memset(tp->fw_ver, 0, sizeof(tp->fw_ver));
snprintf(tp->fw_ver, sizeof(tp->fw_ver), "%.*s bc ", len,
&vpd_data[j]);
}
partno:
i = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_PARTNO);
if (i < 0)
goto out_not_found;
len = pci_vpd_info_field_size(&vpd_data[i]);
i += PCI_VPD_INFO_FLD_HDR_SIZE;
if (len > TG3_BPN_SIZE ||
(len + i) > vpdlen)
goto out_not_found;
memcpy(tp->board_part_number, &vpd_data[i], len);
out_not_found:
kfree(vpd_data);
if (tp->board_part_number[0])
return;
out_no_vpd:
if (tg3_asic_rev(tp) == ASIC_REV_5717) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C)
strcpy(tp->board_part_number, "BCM5717");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718)
strcpy(tp->board_part_number, "BCM5718");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57780) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780)
strcpy(tp->board_part_number, "BCM57780");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760)
strcpy(tp->board_part_number, "BCM57760");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790)
strcpy(tp->board_part_number, "BCM57790");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788)
strcpy(tp->board_part_number, "BCM57788");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57765) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761)
strcpy(tp->board_part_number, "BCM57761");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765)
strcpy(tp->board_part_number, "BCM57765");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781)
strcpy(tp->board_part_number, "BCM57781");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785)
strcpy(tp->board_part_number, "BCM57785");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791)
strcpy(tp->board_part_number, "BCM57791");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795)
strcpy(tp->board_part_number, "BCM57795");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_57766) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762)
strcpy(tp->board_part_number, "BCM57762");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766)
strcpy(tp->board_part_number, "BCM57766");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782)
strcpy(tp->board_part_number, "BCM57782");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786)
strcpy(tp->board_part_number, "BCM57786");
else
goto nomatch;
} else if (tg3_asic_rev(tp) == ASIC_REV_5906) {
strcpy(tp->board_part_number, "BCM95906");
} else {
nomatch:
strcpy(tp->board_part_number, "none");
}
}
static int tg3_fw_img_is_valid(struct tg3 *tp, u32 offset)
{
u32 val;
if (tg3_nvram_read(tp, offset, &val) ||
(val & 0xfc000000) != 0x0c000000 ||
tg3_nvram_read(tp, offset + 4, &val) ||
val != 0)
return 0;
return 1;
}
static void tg3_read_bc_ver(struct tg3 *tp)
{
u32 val, offset, start, ver_offset;
int i, dst_off;
bool newver = false;
if (tg3_nvram_read(tp, 0xc, &offset) ||
tg3_nvram_read(tp, 0x4, &start))
return;
offset = tg3_nvram_logical_addr(tp, offset);
if (tg3_nvram_read(tp, offset, &val))
return;
if ((val & 0xfc000000) == 0x0c000000) {
if (tg3_nvram_read(tp, offset + 4, &val))
return;
if (val == 0)
newver = true;
}
dst_off = strlen(tp->fw_ver);
if (newver) {
if (TG3_VER_SIZE - dst_off < 16 ||
tg3_nvram_read(tp, offset + 8, &ver_offset))
return;
offset = offset + ver_offset - start;
for (i = 0; i < 16; i += 4) {
__be32 v;
if (tg3_nvram_read_be32(tp, offset + i, &v))
return;
memcpy(tp->fw_ver + dst_off + i, &v, sizeof(v));
}
} else {
u32 major, minor;
if (tg3_nvram_read(tp, TG3_NVM_PTREV_BCVER, &ver_offset))
return;
major = (ver_offset & TG3_NVM_BCVER_MAJMSK) >>
TG3_NVM_BCVER_MAJSFT;
minor = ver_offset & TG3_NVM_BCVER_MINMSK;
snprintf(&tp->fw_ver[dst_off], TG3_VER_SIZE - dst_off,
"v%d.%02d", major, minor);
}
}
static void tg3_read_hwsb_ver(struct tg3 *tp)
{
u32 val, major, minor;
/* Use native endian representation */
if (tg3_nvram_read(tp, TG3_NVM_HWSB_CFG1, &val))
return;
major = (val & TG3_NVM_HWSB_CFG1_MAJMSK) >>
TG3_NVM_HWSB_CFG1_MAJSFT;
minor = (val & TG3_NVM_HWSB_CFG1_MINMSK) >>
TG3_NVM_HWSB_CFG1_MINSFT;
snprintf(&tp->fw_ver[0], 32, "sb v%d.%02d", major, minor);
}
static void tg3_read_sb_ver(struct tg3 *tp, u32 val)
{
u32 offset, major, minor, build;
strncat(tp->fw_ver, "sb", TG3_VER_SIZE - strlen(tp->fw_ver) - 1);
if ((val & TG3_EEPROM_SB_FORMAT_MASK) != TG3_EEPROM_SB_FORMAT_1)
return;
switch (val & TG3_EEPROM_SB_REVISION_MASK) {
case TG3_EEPROM_SB_REVISION_0:
offset = TG3_EEPROM_SB_F1R0_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_2:
offset = TG3_EEPROM_SB_F1R2_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_3:
offset = TG3_EEPROM_SB_F1R3_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_4:
offset = TG3_EEPROM_SB_F1R4_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_5:
offset = TG3_EEPROM_SB_F1R5_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_6:
offset = TG3_EEPROM_SB_F1R6_EDH_OFF;
break;
default:
return;
}
if (tg3_nvram_read(tp, offset, &val))
return;
build = (val & TG3_EEPROM_SB_EDH_BLD_MASK) >>
TG3_EEPROM_SB_EDH_BLD_SHFT;
major = (val & TG3_EEPROM_SB_EDH_MAJ_MASK) >>
TG3_EEPROM_SB_EDH_MAJ_SHFT;
minor = val & TG3_EEPROM_SB_EDH_MIN_MASK;
if (minor > 99 || build > 26)
return;
offset = strlen(tp->fw_ver);
snprintf(&tp->fw_ver[offset], TG3_VER_SIZE - offset,
" v%d.%02d", major, minor);
if (build > 0) {
offset = strlen(tp->fw_ver);
if (offset < TG3_VER_SIZE - 1)
tp->fw_ver[offset] = 'a' + build - 1;
}
}
static void tg3_read_mgmtfw_ver(struct tg3 *tp)
{
u32 val, offset, start;
int i, vlen;
for (offset = TG3_NVM_DIR_START;
offset < TG3_NVM_DIR_END;
offset += TG3_NVM_DIRENT_SIZE) {
if (tg3_nvram_read(tp, offset, &val))
return;
if ((val >> TG3_NVM_DIRTYPE_SHIFT) == TG3_NVM_DIRTYPE_ASFINI)
break;
}
if (offset == TG3_NVM_DIR_END)
return;
if (!tg3_flag(tp, 5705_PLUS))
start = 0x08000000;
else if (tg3_nvram_read(tp, offset - 4, &start))
return;
if (tg3_nvram_read(tp, offset + 4, &offset) ||
!tg3_fw_img_is_valid(tp, offset) ||
tg3_nvram_read(tp, offset + 8, &val))
return;
offset += val - start;
vlen = strlen(tp->fw_ver);
tp->fw_ver[vlen++] = ',';
tp->fw_ver[vlen++] = ' ';
for (i = 0; i < 4; i++) {
__be32 v;
if (tg3_nvram_read_be32(tp, offset, &v))
return;
offset += sizeof(v);
if (vlen > TG3_VER_SIZE - sizeof(v)) {
memcpy(&tp->fw_ver[vlen], &v, TG3_VER_SIZE - vlen);
break;
}
memcpy(&tp->fw_ver[vlen], &v, sizeof(v));
vlen += sizeof(v);
}
}
static void tg3_probe_ncsi(struct tg3 *tp)
{
u32 apedata;
apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG);
if (apedata != APE_SEG_SIG_MAGIC)
return;
apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS);
if (!(apedata & APE_FW_STATUS_READY))
return;
if (tg3_ape_read32(tp, TG3_APE_FW_FEATURES) & TG3_APE_FW_FEATURE_NCSI)
tg3_flag_set(tp, APE_HAS_NCSI);
}
static void tg3_read_dash_ver(struct tg3 *tp)
{
int vlen;
u32 apedata;
char *fwtype;
apedata = tg3_ape_read32(tp, TG3_APE_FW_VERSION);
if (tg3_flag(tp, APE_HAS_NCSI))
fwtype = "NCSI";
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5725)
fwtype = "SMASH";
else
fwtype = "DASH";
vlen = strlen(tp->fw_ver);
snprintf(&tp->fw_ver[vlen], TG3_VER_SIZE - vlen, " %s v%d.%d.%d.%d",
fwtype,
(apedata & APE_FW_VERSION_MAJMSK) >> APE_FW_VERSION_MAJSFT,
(apedata & APE_FW_VERSION_MINMSK) >> APE_FW_VERSION_MINSFT,
(apedata & APE_FW_VERSION_REVMSK) >> APE_FW_VERSION_REVSFT,
(apedata & APE_FW_VERSION_BLDMSK));
}
static void tg3_read_otp_ver(struct tg3 *tp)
{
u32 val, val2;
if (tg3_asic_rev(tp) != ASIC_REV_5762)
return;
if (!tg3_ape_otp_read(tp, OTP_ADDRESS_MAGIC0, &val) &&
!tg3_ape_otp_read(tp, OTP_ADDRESS_MAGIC0 + 4, &val2) &&
TG3_OTP_MAGIC0_VALID(val)) {
u64 val64 = (u64) val << 32 | val2;
u32 ver = 0;
int i, vlen;
for (i = 0; i < 7; i++) {
if ((val64 & 0xff) == 0)
break;
ver = val64 & 0xff;
val64 >>= 8;
}
vlen = strlen(tp->fw_ver);
snprintf(&tp->fw_ver[vlen], TG3_VER_SIZE - vlen, " .%02d", ver);
}
}
static void tg3_read_fw_ver(struct tg3 *tp)
{
u32 val;
bool vpd_vers = false;
if (tp->fw_ver[0] != 0)
vpd_vers = true;
if (tg3_flag(tp, NO_NVRAM)) {
strcat(tp->fw_ver, "sb");
tg3_read_otp_ver(tp);
return;
}
if (tg3_nvram_read(tp, 0, &val))
return;
if (val == TG3_EEPROM_MAGIC)
tg3_read_bc_ver(tp);
else if ((val & TG3_EEPROM_MAGIC_FW_MSK) == TG3_EEPROM_MAGIC_FW)
tg3_read_sb_ver(tp, val);
else if ((val & TG3_EEPROM_MAGIC_HW_MSK) == TG3_EEPROM_MAGIC_HW)
tg3_read_hwsb_ver(tp);
if (tg3_flag(tp, ENABLE_ASF)) {
if (tg3_flag(tp, ENABLE_APE)) {
tg3_probe_ncsi(tp);
if (!vpd_vers)
tg3_read_dash_ver(tp);
} else if (!vpd_vers) {
tg3_read_mgmtfw_ver(tp);
}
}
tp->fw_ver[TG3_VER_SIZE - 1] = 0;
}
static inline u32 tg3_rx_ret_ring_size(struct tg3 *tp)
{
if (tg3_flag(tp, LRG_PROD_RING_CAP))
return TG3_RX_RET_MAX_SIZE_5717;
else if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS))
return TG3_RX_RET_MAX_SIZE_5700;
else
return TG3_RX_RET_MAX_SIZE_5705;
}
static DEFINE_PCI_DEVICE_TABLE(tg3_write_reorder_chipsets) = {
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_FE_GATE_700C) },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE) },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8385_0) },
{ },
};
static struct pci_dev *tg3_find_peer(struct tg3 *tp)
{
struct pci_dev *peer;
unsigned int func, devnr = tp->pdev->devfn & ~7;
for (func = 0; func < 8; func++) {
peer = pci_get_slot(tp->pdev->bus, devnr | func);
if (peer && peer != tp->pdev)
break;
pci_dev_put(peer);
}
/* 5704 can be configured in single-port mode, set peer to
* tp->pdev in that case.
*/
if (!peer) {
peer = tp->pdev;
return peer;
}
/*
* We don't need to keep the refcount elevated; there's no way
* to remove one half of this device without removing the other
*/
pci_dev_put(peer);
return peer;
}
static void tg3_detect_asic_rev(struct tg3 *tp, u32 misc_ctrl_reg)
{
tp->pci_chip_rev_id = misc_ctrl_reg >> MISC_HOST_CTRL_CHIPREV_SHIFT;
if (tg3_asic_rev(tp) == ASIC_REV_USE_PROD_ID_REG) {
u32 reg;
/* All devices that use the alternate
* ASIC REV location have a CPMU.
*/
tg3_flag_set(tp, CPMU_PRESENT);
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5719 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5720 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57767 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57764 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5762 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5725 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5727 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57787)
reg = TG3PCI_GEN2_PRODID_ASICREV;
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786)
reg = TG3PCI_GEN15_PRODID_ASICREV;
else
reg = TG3PCI_PRODID_ASICREV;
pci_read_config_dword(tp->pdev, reg, &tp->pci_chip_rev_id);
}
/* Wrong chip ID in 5752 A0. This code can be removed later
* as A0 is not in production.
*/
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5752_A0_HW)
tp->pci_chip_rev_id = CHIPREV_ID_5752_A0;
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5717_C0)
tp->pci_chip_rev_id = CHIPREV_ID_5720_A0;
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720)
tg3_flag_set(tp, 5717_PLUS);
if (tg3_asic_rev(tp) == ASIC_REV_57765 ||
tg3_asic_rev(tp) == ASIC_REV_57766)
tg3_flag_set(tp, 57765_CLASS);
if (tg3_flag(tp, 57765_CLASS) || tg3_flag(tp, 5717_PLUS) ||
tg3_asic_rev(tp) == ASIC_REV_5762)
tg3_flag_set(tp, 57765_PLUS);
/* Intentionally exclude ASIC_REV_5906 */
if (tg3_asic_rev(tp) == ASIC_REV_5755 ||
tg3_asic_rev(tp) == ASIC_REV_5787 ||
tg3_asic_rev(tp) == ASIC_REV_5784 ||
tg3_asic_rev(tp) == ASIC_REV_5761 ||
tg3_asic_rev(tp) == ASIC_REV_5785 ||
tg3_asic_rev(tp) == ASIC_REV_57780 ||
tg3_flag(tp, 57765_PLUS))
tg3_flag_set(tp, 5755_PLUS);
if (tg3_asic_rev(tp) == ASIC_REV_5780 ||
tg3_asic_rev(tp) == ASIC_REV_5714)
tg3_flag_set(tp, 5780_CLASS);
if (tg3_asic_rev(tp) == ASIC_REV_5750 ||
tg3_asic_rev(tp) == ASIC_REV_5752 ||
tg3_asic_rev(tp) == ASIC_REV_5906 ||
tg3_flag(tp, 5755_PLUS) ||
tg3_flag(tp, 5780_CLASS))
tg3_flag_set(tp, 5750_PLUS);
if (tg3_asic_rev(tp) == ASIC_REV_5705 ||
tg3_flag(tp, 5750_PLUS))
tg3_flag_set(tp, 5705_PLUS);
}
static bool tg3_10_100_only_device(struct tg3 *tp,
const struct pci_device_id *ent)
{
u32 grc_misc_cfg = tr32(GRC_MISC_CFG) & GRC_MISC_CFG_BOARD_ID_MASK;
if ((tg3_asic_rev(tp) == ASIC_REV_5703 &&
(grc_misc_cfg == 0x8000 || grc_misc_cfg == 0x4000)) ||
(tp->phy_flags & TG3_PHYFLG_IS_FET))
return true;
if (ent->driver_data & TG3_DRV_DATA_FLAG_10_100_ONLY) {
if (tg3_asic_rev(tp) == ASIC_REV_5705) {
if (ent->driver_data & TG3_DRV_DATA_FLAG_5705_10_100)
return true;
} else {
return true;
}
}
return false;
}
static int tg3_get_invariants(struct tg3 *tp, const struct pci_device_id *ent)
{
u32 misc_ctrl_reg;
u32 pci_state_reg, grc_misc_cfg;
u32 val;
u16 pci_cmd;
int err;
/* Force memory write invalidate off. If we leave it on,
* then on 5700_BX chips we have to enable a workaround.
* The workaround is to set the TG3PCI_DMA_RW_CTRL boundary
* to match the cacheline size. The Broadcom driver have this
* workaround but turns MWI off all the times so never uses
* it. This seems to suggest that the workaround is insufficient.
*/
pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd);
pci_cmd &= ~PCI_COMMAND_INVALIDATE;
pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd);
/* Important! -- Make sure register accesses are byteswapped
* correctly. Also, for those chips that require it, make
* sure that indirect register accesses are enabled before
* the first operation.
*/
pci_read_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL,
&misc_ctrl_reg);
tp->misc_host_ctrl |= (misc_ctrl_reg &
MISC_HOST_CTRL_CHIPREV);
pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL,
tp->misc_host_ctrl);
tg3_detect_asic_rev(tp, misc_ctrl_reg);
/* If we have 5702/03 A1 or A2 on certain ICH chipsets,
* we need to disable memory and use config. cycles
* only to access all registers. The 5702/03 chips
* can mistakenly decode the special cycles from the
* ICH chipsets as memory write cycles, causing corruption
* of register and memory space. Only certain ICH bridges
* will drive special cycles with non-zero data during the
* address phase which can fall within the 5703's address
* range. This is not an ICH bug as the PCI spec allows
* non-zero address during special cycles. However, only
* these ICH bridges are known to drive non-zero addresses
* during special cycles.
*
* Since special cycles do not cross PCI bridges, we only
* enable this workaround if the 5703 is on the secondary
* bus of these ICH bridges.
*/
if ((tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A1) ||
(tg3_chip_rev_id(tp) == CHIPREV_ID_5703_A2)) {
static struct tg3_dev_id {
u32 vendor;
u32 device;
u32 rev;
} ich_chipsets[] = {
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_8,
PCI_ANY_ID },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AB_8,
PCI_ANY_ID },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_11,
0xa },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_6,
PCI_ANY_ID },
{ },
};
struct tg3_dev_id *pci_id = &ich_chipsets[0];
struct pci_dev *bridge = NULL;
while (pci_id->vendor != 0) {
bridge = pci_get_device(pci_id->vendor, pci_id->device,
bridge);
if (!bridge) {
pci_id++;
continue;
}
if (pci_id->rev != PCI_ANY_ID) {
if (bridge->revision > pci_id->rev)
continue;
}
if (bridge->subordinate &&
(bridge->subordinate->number ==
tp->pdev->bus->number)) {
tg3_flag_set(tp, ICH_WORKAROUND);
pci_dev_put(bridge);
break;
}
}
}
if (tg3_asic_rev(tp) == ASIC_REV_5701) {
static struct tg3_dev_id {
u32 vendor;
u32 device;
} bridge_chipsets[] = {
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0 },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1 },
{ },
};
struct tg3_dev_id *pci_id = &bridge_chipsets[0];
struct pci_dev *bridge = NULL;
while (pci_id->vendor != 0) {
bridge = pci_get_device(pci_id->vendor,
pci_id->device,
bridge);
if (!bridge) {
pci_id++;
continue;
}
if (bridge->subordinate &&
(bridge->subordinate->number <=
tp->pdev->bus->number) &&
(bridge->subordinate->busn_res.end >=
tp->pdev->bus->number)) {
tg3_flag_set(tp, 5701_DMA_BUG);
pci_dev_put(bridge);
break;
}
}
}
/* The EPB bridge inside 5714, 5715, and 5780 cannot support
* DMA addresses > 40-bit. This bridge may have other additional
* 57xx devices behind it in some 4-port NIC designs for example.
* Any tg3 device found behind the bridge will also need the 40-bit
* DMA workaround.
*/
if (tg3_flag(tp, 5780_CLASS)) {
tg3_flag_set(tp, 40BIT_DMA_BUG);
tp->msi_cap = tp->pdev->msi_cap;
} else {
struct pci_dev *bridge = NULL;
do {
bridge = pci_get_device(PCI_VENDOR_ID_SERVERWORKS,
PCI_DEVICE_ID_SERVERWORKS_EPB,
bridge);
if (bridge && bridge->subordinate &&
(bridge->subordinate->number <=
tp->pdev->bus->number) &&
(bridge->subordinate->busn_res.end >=
tp->pdev->bus->number)) {
tg3_flag_set(tp, 40BIT_DMA_BUG);
pci_dev_put(bridge);
break;
}
} while (bridge);
}
if (tg3_asic_rev(tp) == ASIC_REV_5704 ||
tg3_asic_rev(tp) == ASIC_REV_5714)
tp->pdev_peer = tg3_find_peer(tp);
/* Determine TSO capabilities */
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0)
; /* Do nothing. HW bug. */
else if (tg3_flag(tp, 57765_PLUS))
tg3_flag_set(tp, HW_TSO_3);
else if (tg3_flag(tp, 5755_PLUS) ||
tg3_asic_rev(tp) == ASIC_REV_5906)
tg3_flag_set(tp, HW_TSO_2);
else if (tg3_flag(tp, 5750_PLUS)) {
tg3_flag_set(tp, HW_TSO_1);
tg3_flag_set(tp, TSO_BUG);
if (tg3_asic_rev(tp) == ASIC_REV_5750 &&
tg3_chip_rev_id(tp) >= CHIPREV_ID_5750_C2)
tg3_flag_clear(tp, TSO_BUG);
} else if (tg3_asic_rev(tp) != ASIC_REV_5700 &&
tg3_asic_rev(tp) != ASIC_REV_5701 &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) {
tg3_flag_set(tp, FW_TSO);
tg3_flag_set(tp, TSO_BUG);
if (tg3_asic_rev(tp) == ASIC_REV_5705)
tp->fw_needed = FIRMWARE_TG3TSO5;
else
tp->fw_needed = FIRMWARE_TG3TSO;
}
/* Selectively allow TSO based on operating conditions */
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3) ||
tg3_flag(tp, FW_TSO)) {
/* For firmware TSO, assume ASF is disabled.
* We'll disable TSO later if we discover ASF
* is enabled in tg3_get_eeprom_hw_cfg().
*/
tg3_flag_set(tp, TSO_CAPABLE);
} else {
tg3_flag_clear(tp, TSO_CAPABLE);
tg3_flag_clear(tp, TSO_BUG);
tp->fw_needed = NULL;
}
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0)
tp->fw_needed = FIRMWARE_TG3;
if (tg3_asic_rev(tp) == ASIC_REV_57766)
tp->fw_needed = FIRMWARE_TG357766;
tp->irq_max = 1;
if (tg3_flag(tp, 5750_PLUS)) {
tg3_flag_set(tp, SUPPORT_MSI);
if (tg3_chip_rev(tp) == CHIPREV_5750_AX ||
tg3_chip_rev(tp) == CHIPREV_5750_BX ||
(tg3_asic_rev(tp) == ASIC_REV_5714 &&
tg3_chip_rev_id(tp) <= CHIPREV_ID_5714_A2 &&
tp->pdev_peer == tp->pdev))
tg3_flag_clear(tp, SUPPORT_MSI);
if (tg3_flag(tp, 5755_PLUS) ||
tg3_asic_rev(tp) == ASIC_REV_5906) {
tg3_flag_set(tp, 1SHOT_MSI);
}
if (tg3_flag(tp, 57765_PLUS)) {
tg3_flag_set(tp, SUPPORT_MSIX);
tp->irq_max = TG3_IRQ_MAX_VECS;
}
}
tp->txq_max = 1;
tp->rxq_max = 1;
if (tp->irq_max > 1) {
tp->rxq_max = TG3_RSS_MAX_NUM_QS;
tg3_rss_init_dflt_indir_tbl(tp, TG3_RSS_MAX_NUM_QS);
if (tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720)
tp->txq_max = tp->irq_max - 1;
}
if (tg3_flag(tp, 5755_PLUS) ||
tg3_asic_rev(tp) == ASIC_REV_5906)
tg3_flag_set(tp, SHORT_DMA_BUG);
if (tg3_asic_rev(tp) == ASIC_REV_5719)
tp->dma_limit = TG3_TX_BD_DMA_MAX_4K;
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762)
tg3_flag_set(tp, LRG_PROD_RING_CAP);
if (tg3_flag(tp, 57765_PLUS) &&
tg3_chip_rev_id(tp) != CHIPREV_ID_5719_A0)
tg3_flag_set(tp, USE_JUMBO_BDFLAG);
if (!tg3_flag(tp, 5705_PLUS) ||
tg3_flag(tp, 5780_CLASS) ||
tg3_flag(tp, USE_JUMBO_BDFLAG))
tg3_flag_set(tp, JUMBO_CAPABLE);
pci_read_config_dword(tp->pdev, TG3PCI_PCISTATE,
&pci_state_reg);
if (pci_is_pcie(tp->pdev)) {
u16 lnkctl;
tg3_flag_set(tp, PCI_EXPRESS);
pcie_capability_read_word(tp->pdev, PCI_EXP_LNKCTL, &lnkctl);
if (lnkctl & PCI_EXP_LNKCTL_CLKREQ_EN) {
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
tg3_flag_clear(tp, HW_TSO_2);
tg3_flag_clear(tp, TSO_CAPABLE);
}
if (tg3_asic_rev(tp) == ASIC_REV_5784 ||
tg3_asic_rev(tp) == ASIC_REV_5761 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_57780_A0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_57780_A1)
tg3_flag_set(tp, CLKREQ_BUG);
} else if (tg3_chip_rev_id(tp) == CHIPREV_ID_5717_A0) {
tg3_flag_set(tp, L1PLLPD_EN);
}
} else if (tg3_asic_rev(tp) == ASIC_REV_5785) {
/* BCM5785 devices are effectively PCIe devices, and should
* follow PCIe codepaths, but do not have a PCIe capabilities
* section.
*/
tg3_flag_set(tp, PCI_EXPRESS);
} else if (!tg3_flag(tp, 5705_PLUS) ||
tg3_flag(tp, 5780_CLASS)) {
tp->pcix_cap = pci_find_capability(tp->pdev, PCI_CAP_ID_PCIX);
if (!tp->pcix_cap) {
dev_err(&tp->pdev->dev,
"Cannot find PCI-X capability, aborting\n");
return -EIO;
}
if (!(pci_state_reg & PCISTATE_CONV_PCI_MODE))
tg3_flag_set(tp, PCIX_MODE);
}
/* If we have an AMD 762 or VIA K8T800 chipset, write
* reordering to the mailbox registers done by the host
* controller can cause major troubles. We read back from
* every mailbox register write to force the writes to be
* posted to the chip in order.
*/
if (pci_dev_present(tg3_write_reorder_chipsets) &&
!tg3_flag(tp, PCI_EXPRESS))
tg3_flag_set(tp, MBOX_WRITE_REORDER);
pci_read_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE,
&tp->pci_cacheline_sz);
pci_read_config_byte(tp->pdev, PCI_LATENCY_TIMER,
&tp->pci_lat_timer);
if (tg3_asic_rev(tp) == ASIC_REV_5703 &&
tp->pci_lat_timer < 64) {
tp->pci_lat_timer = 64;
pci_write_config_byte(tp->pdev, PCI_LATENCY_TIMER,
tp->pci_lat_timer);
}
/* Important! -- It is critical that the PCI-X hw workaround
* situation is decided before the first MMIO register access.
*/
if (tg3_chip_rev(tp) == CHIPREV_5700_BX) {
/* 5700 BX chips need to have their TX producer index
* mailboxes written twice to workaround a bug.
*/
tg3_flag_set(tp, TXD_MBOX_HWBUG);
/* If we are in PCI-X mode, enable register write workaround.
*
* The workaround is to use indirect register accesses
* for all chip writes not to mailbox registers.
*/
if (tg3_flag(tp, PCIX_MODE)) {
u32 pm_reg;
tg3_flag_set(tp, PCIX_TARGET_HWBUG);
/* The chip can have it's power management PCI config
* space registers clobbered due to this bug.
* So explicitly force the chip into D0 here.
*/
pci_read_config_dword(tp->pdev,
tp->pdev->pm_cap + PCI_PM_CTRL,
&pm_reg);
pm_reg &= ~PCI_PM_CTRL_STATE_MASK;
pm_reg |= PCI_PM_CTRL_PME_ENABLE | 0 /* D0 */;
pci_write_config_dword(tp->pdev,
tp->pdev->pm_cap + PCI_PM_CTRL,
pm_reg);
/* Also, force SERR#/PERR# in PCI command. */
pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd);
pci_cmd |= PCI_COMMAND_PARITY | PCI_COMMAND_SERR;
pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd);
}
}
if ((pci_state_reg & PCISTATE_BUS_SPEED_HIGH) != 0)
tg3_flag_set(tp, PCI_HIGH_SPEED);
if ((pci_state_reg & PCISTATE_BUS_32BIT) != 0)
tg3_flag_set(tp, PCI_32BIT);
/* Chip-specific fixup from Broadcom driver */
if ((tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0) &&
(!(pci_state_reg & PCISTATE_RETRY_SAME_DMA))) {
pci_state_reg |= PCISTATE_RETRY_SAME_DMA;
pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE, pci_state_reg);
}
/* Default fast path register access methods */
tp->read32 = tg3_read32;
tp->write32 = tg3_write32;
tp->read32_mbox = tg3_read32;
tp->write32_mbox = tg3_write32;
tp->write32_tx_mbox = tg3_write32;
tp->write32_rx_mbox = tg3_write32;
/* Various workaround register access methods */
if (tg3_flag(tp, PCIX_TARGET_HWBUG))
tp->write32 = tg3_write_indirect_reg32;
else if (tg3_asic_rev(tp) == ASIC_REV_5701 ||
(tg3_flag(tp, PCI_EXPRESS) &&
tg3_chip_rev_id(tp) == CHIPREV_ID_5750_A0)) {
/*
* Back to back register writes can cause problems on these
* chips, the workaround is to read back all reg writes
* except those to mailbox regs.
*
* See tg3_write_indirect_reg32().
*/
tp->write32 = tg3_write_flush_reg32;
}
if (tg3_flag(tp, TXD_MBOX_HWBUG) || tg3_flag(tp, MBOX_WRITE_REORDER)) {
tp->write32_tx_mbox = tg3_write32_tx_mbox;
if (tg3_flag(tp, MBOX_WRITE_REORDER))
tp->write32_rx_mbox = tg3_write_flush_reg32;
}
if (tg3_flag(tp, ICH_WORKAROUND)) {
tp->read32 = tg3_read_indirect_reg32;
tp->write32 = tg3_write_indirect_reg32;
tp->read32_mbox = tg3_read_indirect_mbox;
tp->write32_mbox = tg3_write_indirect_mbox;
tp->write32_tx_mbox = tg3_write_indirect_mbox;
tp->write32_rx_mbox = tg3_write_indirect_mbox;
iounmap(tp->regs);
tp->regs = NULL;
pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd);
pci_cmd &= ~PCI_COMMAND_MEMORY;
pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd);
}
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
tp->read32_mbox = tg3_read32_mbox_5906;
tp->write32_mbox = tg3_write32_mbox_5906;
tp->write32_tx_mbox = tg3_write32_mbox_5906;
tp->write32_rx_mbox = tg3_write32_mbox_5906;
}
if (tp->write32 == tg3_write_indirect_reg32 ||
(tg3_flag(tp, PCIX_MODE) &&
(tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701)))
tg3_flag_set(tp, SRAM_USE_CONFIG);
/* The memory arbiter has to be enabled in order for SRAM accesses
* to succeed. Normally on powerup the tg3 chip firmware will make
* sure it is enabled, but other entities such as system netboot
* code might disable it.
*/
val = tr32(MEMARB_MODE);
tw32(MEMARB_MODE, val | MEMARB_MODE_ENABLE);
tp->pci_fn = PCI_FUNC(tp->pdev->devfn) & 3;
if (tg3_asic_rev(tp) == ASIC_REV_5704 ||
tg3_flag(tp, 5780_CLASS)) {
if (tg3_flag(tp, PCIX_MODE)) {
pci_read_config_dword(tp->pdev,
tp->pcix_cap + PCI_X_STATUS,
&val);
tp->pci_fn = val & 0x7;
}
} else if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720) {
tg3_read_mem(tp, NIC_SRAM_CPMU_STATUS, &val);
if ((val & NIC_SRAM_CPMUSTAT_SIG_MSK) != NIC_SRAM_CPMUSTAT_SIG)
val = tr32(TG3_CPMU_STATUS);
if (tg3_asic_rev(tp) == ASIC_REV_5717)
tp->pci_fn = (val & TG3_CPMU_STATUS_FMSK_5717) ? 1 : 0;
else
tp->pci_fn = (val & TG3_CPMU_STATUS_FMSK_5719) >>
TG3_CPMU_STATUS_FSHFT_5719;
}
if (tg3_flag(tp, FLUSH_POSTED_WRITES)) {
tp->write32_tx_mbox = tg3_write_flush_reg32;
tp->write32_rx_mbox = tg3_write_flush_reg32;
}
/* Get eeprom hw config before calling tg3_set_power_state().
* In particular, the TG3_FLAG_IS_NIC flag must be
* determined before calling tg3_set_power_state() so that
* we know whether or not to switch out of Vaux power.
* When the flag is set, it means that GPIO1 is used for eeprom
* write protect and also implies that it is a LOM where GPIOs
* are not used to switch power.
*/
tg3_get_eeprom_hw_cfg(tp);
if (tg3_flag(tp, FW_TSO) && tg3_flag(tp, ENABLE_ASF)) {
tg3_flag_clear(tp, TSO_CAPABLE);
tg3_flag_clear(tp, TSO_BUG);
tp->fw_needed = NULL;
}
if (tg3_flag(tp, ENABLE_APE)) {
/* Allow reads and writes to the
* APE register and memory space.
*/
pci_state_reg |= PCISTATE_ALLOW_APE_CTLSPC_WR |
PCISTATE_ALLOW_APE_SHMEM_WR |
PCISTATE_ALLOW_APE_PSPACE_WR;
pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE,
pci_state_reg);
tg3_ape_lock_init(tp);
}
/* Set up tp->grc_local_ctrl before calling
* tg3_pwrsrc_switch_to_vmain(). GPIO1 driven high
* will bring 5700's external PHY out of reset.
* It is also used as eeprom write protect on LOMs.
*/
tp->grc_local_ctrl = GRC_LCLCTRL_INT_ON_ATTN | GRC_LCLCTRL_AUTO_SEEPROM;
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_flag(tp, EEPROM_WRITE_PROT))
tp->grc_local_ctrl |= (GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OUTPUT1);
/* Unused GPIO3 must be driven as output on 5752 because there
* are no pull-up resistors on unused GPIO pins.
*/
else if (tg3_asic_rev(tp) == ASIC_REV_5752)
tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE3;
if (tg3_asic_rev(tp) == ASIC_REV_5755 ||
tg3_asic_rev(tp) == ASIC_REV_57780 ||
tg3_flag(tp, 57765_CLASS))
tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_UART_SEL;
if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S) {
/* Turn off the debug UART. */
tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_UART_SEL;
if (tg3_flag(tp, IS_NIC))
/* Keep VMain power. */
tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE0 |
GRC_LCLCTRL_GPIO_OUTPUT0;
}
if (tg3_asic_rev(tp) == ASIC_REV_5762)
tp->grc_local_ctrl |=
tr32(GRC_LOCAL_CTRL) & GRC_LCLCTRL_GPIO_UART_SEL;
/* Switch out of Vaux if it is a NIC */
tg3_pwrsrc_switch_to_vmain(tp);
/* Derive initial jumbo mode from MTU assigned in
* ether_setup() via the alloc_etherdev() call
*/
if (tp->dev->mtu > ETH_DATA_LEN && !tg3_flag(tp, 5780_CLASS))
tg3_flag_set(tp, JUMBO_RING_ENABLE);
/* Determine WakeOnLan speed to use. */
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B2) {
tg3_flag_clear(tp, WOL_SPEED_100MB);
} else {
tg3_flag_set(tp, WOL_SPEED_100MB);
}
if (tg3_asic_rev(tp) == ASIC_REV_5906)
tp->phy_flags |= TG3_PHYFLG_IS_FET;
/* A few boards don't want Ethernet@WireSpeed phy feature */
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
(tg3_asic_rev(tp) == ASIC_REV_5705 &&
(tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A0) &&
(tg3_chip_rev_id(tp) != CHIPREV_ID_5705_A1)) ||
(tp->phy_flags & TG3_PHYFLG_IS_FET) ||
(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
tp->phy_flags |= TG3_PHYFLG_NO_ETH_WIRE_SPEED;
if (tg3_chip_rev(tp) == CHIPREV_5703_AX ||
tg3_chip_rev(tp) == CHIPREV_5704_AX)
tp->phy_flags |= TG3_PHYFLG_ADC_BUG;
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5704_A0)
tp->phy_flags |= TG3_PHYFLG_5704_A0_BUG;
if (tg3_flag(tp, 5705_PLUS) &&
!(tp->phy_flags & TG3_PHYFLG_IS_FET) &&
tg3_asic_rev(tp) != ASIC_REV_5785 &&
tg3_asic_rev(tp) != ASIC_REV_57780 &&
!tg3_flag(tp, 57765_PLUS)) {
if (tg3_asic_rev(tp) == ASIC_REV_5755 ||
tg3_asic_rev(tp) == ASIC_REV_5787 ||
tg3_asic_rev(tp) == ASIC_REV_5784 ||
tg3_asic_rev(tp) == ASIC_REV_5761) {
if (tp->pdev->device != PCI_DEVICE_ID_TIGON3_5756 &&
tp->pdev->device != PCI_DEVICE_ID_TIGON3_5722)
tp->phy_flags |= TG3_PHYFLG_JITTER_BUG;
if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5755M)
tp->phy_flags |= TG3_PHYFLG_ADJUST_TRIM;
} else
tp->phy_flags |= TG3_PHYFLG_BER_BUG;
}
if (tg3_asic_rev(tp) == ASIC_REV_5784 &&
tg3_chip_rev(tp) != CHIPREV_5784_AX) {
tp->phy_otp = tg3_read_otp_phycfg(tp);
if (tp->phy_otp == 0)
tp->phy_otp = TG3_OTP_DEFAULT;
}
if (tg3_flag(tp, CPMU_PRESENT))
tp->mi_mode = MAC_MI_MODE_500KHZ_CONST;
else
tp->mi_mode = MAC_MI_MODE_BASE;
tp->coalesce_mode = 0;
if (tg3_chip_rev(tp) != CHIPREV_5700_AX &&
tg3_chip_rev(tp) != CHIPREV_5700_BX)
tp->coalesce_mode |= HOSTCC_MODE_32BYTE;
/* Set these bits to enable statistics workaround. */
if (tg3_asic_rev(tp) == ASIC_REV_5717 ||
tg3_asic_rev(tp) == ASIC_REV_5762 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5719_A0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5720_A0) {
tp->coalesce_mode |= HOSTCC_MODE_ATTN;
tp->grc_mode |= GRC_MODE_IRQ_ON_FLOW_ATTN;
}
if (tg3_asic_rev(tp) == ASIC_REV_5785 ||
tg3_asic_rev(tp) == ASIC_REV_57780)
tg3_flag_set(tp, USE_PHYLIB);
err = tg3_mdio_init(tp);
if (err)
return err;
/* Initialize data/descriptor byte/word swapping. */
val = tr32(GRC_MODE);
if (tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762)
val &= (GRC_MODE_BYTE_SWAP_B2HRX_DATA |
GRC_MODE_WORD_SWAP_B2HRX_DATA |
GRC_MODE_B2HRX_ENABLE |
GRC_MODE_HTX2B_ENABLE |
GRC_MODE_HOST_STACKUP);
else
val &= GRC_MODE_HOST_STACKUP;
tw32(GRC_MODE, val | tp->grc_mode);
tg3_switch_clocks(tp);
/* Clear this out for sanity. */
tw32(TG3PCI_MEM_WIN_BASE_ADDR, 0);
/* Clear TG3PCI_REG_BASE_ADDR to prevent hangs. */
tw32(TG3PCI_REG_BASE_ADDR, 0);
pci_read_config_dword(tp->pdev, TG3PCI_PCISTATE,
&pci_state_reg);
if ((pci_state_reg & PCISTATE_CONV_PCI_MODE) == 0 &&
!tg3_flag(tp, PCIX_TARGET_HWBUG)) {
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5701_A0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B0 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B2 ||
tg3_chip_rev_id(tp) == CHIPREV_ID_5701_B5) {
void __iomem *sram_base;
/* Write some dummy words into the SRAM status block
* area, see if it reads back correctly. If the return
* value is bad, force enable the PCIX workaround.
*/
sram_base = tp->regs + NIC_SRAM_WIN_BASE + NIC_SRAM_STATS_BLK;
writel(0x00000000, sram_base);
writel(0x00000000, sram_base + 4);
writel(0xffffffff, sram_base + 4);
if (readl(sram_base) != 0x00000000)
tg3_flag_set(tp, PCIX_TARGET_HWBUG);
}
}
udelay(50);
tg3_nvram_init(tp);
/* If the device has an NVRAM, no need to load patch firmware */
if (tg3_asic_rev(tp) == ASIC_REV_57766 &&
!tg3_flag(tp, NO_NVRAM))
tp->fw_needed = NULL;
grc_misc_cfg = tr32(GRC_MISC_CFG);
grc_misc_cfg &= GRC_MISC_CFG_BOARD_ID_MASK;
if (tg3_asic_rev(tp) == ASIC_REV_5705 &&
(grc_misc_cfg == GRC_MISC_CFG_BOARD_ID_5788 ||
grc_misc_cfg == GRC_MISC_CFG_BOARD_ID_5788M))
tg3_flag_set(tp, IS_5788);
if (!tg3_flag(tp, IS_5788) &&
tg3_asic_rev(tp) != ASIC_REV_5700)
tg3_flag_set(tp, TAGGED_STATUS);
if (tg3_flag(tp, TAGGED_STATUS)) {
tp->coalesce_mode |= (HOSTCC_MODE_CLRTICK_RXBD |
HOSTCC_MODE_CLRTICK_TXBD);
tp->misc_host_ctrl |= MISC_HOST_CTRL_TAGGED_STATUS;
pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL,
tp->misc_host_ctrl);
}
/* Preserve the APE MAC_MODE bits */
if (tg3_flag(tp, ENABLE_APE))
tp->mac_mode = MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN;
else
tp->mac_mode = 0;
if (tg3_10_100_only_device(tp, ent))
tp->phy_flags |= TG3_PHYFLG_10_100_ONLY;
err = tg3_phy_probe(tp);
if (err) {
dev_err(&tp->pdev->dev, "phy probe failed, err %d\n", err);
/* ... but do not return immediately ... */
tg3_mdio_fini(tp);
}
tg3_read_vpd(tp);
tg3_read_fw_ver(tp);
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
tp->phy_flags &= ~TG3_PHYFLG_USE_MI_INTERRUPT;
} else {
if (tg3_asic_rev(tp) == ASIC_REV_5700)
tp->phy_flags |= TG3_PHYFLG_USE_MI_INTERRUPT;
else
tp->phy_flags &= ~TG3_PHYFLG_USE_MI_INTERRUPT;
}
/* 5700 {AX,BX} chips have a broken status block link
* change bit implementation, so we must use the
* status register in those cases.
*/
if (tg3_asic_rev(tp) == ASIC_REV_5700)
tg3_flag_set(tp, USE_LINKCHG_REG);
else
tg3_flag_clear(tp, USE_LINKCHG_REG);
/* The led_ctrl is set during tg3_phy_probe, here we might
* have to force the link status polling mechanism based
* upon subsystem IDs.
*/
if (tp->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL &&
tg3_asic_rev(tp) == ASIC_REV_5701 &&
!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) {
tp->phy_flags |= TG3_PHYFLG_USE_MI_INTERRUPT;
tg3_flag_set(tp, USE_LINKCHG_REG);
}
/* For all SERDES we poll the MAC status register. */
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
tg3_flag_set(tp, POLL_SERDES);
else
tg3_flag_clear(tp, POLL_SERDES);
if (tg3_flag(tp, ENABLE_APE) && tg3_flag(tp, ENABLE_ASF))
tg3_flag_set(tp, POLL_CPMU_LINK);
tp->rx_offset = NET_SKB_PAD + NET_IP_ALIGN;
tp->rx_copy_thresh = TG3_RX_COPY_THRESHOLD;
if (tg3_asic_rev(tp) == ASIC_REV_5701 &&
tg3_flag(tp, PCIX_MODE)) {
tp->rx_offset = NET_SKB_PAD;
#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
tp->rx_copy_thresh = ~(u16)0;
#endif
}
tp->rx_std_ring_mask = TG3_RX_STD_RING_SIZE(tp) - 1;
tp->rx_jmb_ring_mask = TG3_RX_JMB_RING_SIZE(tp) - 1;
tp->rx_ret_ring_mask = tg3_rx_ret_ring_size(tp) - 1;
tp->rx_std_max_post = tp->rx_std_ring_mask + 1;
/* Increment the rx prod index on the rx std ring by at most
* 8 for these chips to workaround hw errata.
*/
if (tg3_asic_rev(tp) == ASIC_REV_5750 ||
tg3_asic_rev(tp) == ASIC_REV_5752 ||
tg3_asic_rev(tp) == ASIC_REV_5755)
tp->rx_std_max_post = 8;
if (tg3_flag(tp, ASPM_WORKAROUND))
tp->pwrmgmt_thresh = tr32(PCIE_PWR_MGMT_THRESH) &
PCIE_PWR_MGMT_L1_THRESH_MSK;
return err;
}
#ifdef CONFIG_SPARC
static int tg3_get_macaddr_sparc(struct tg3 *tp)
{
struct net_device *dev = tp->dev;
struct pci_dev *pdev = tp->pdev;
struct device_node *dp = pci_device_to_OF_node(pdev);
const unsigned char *addr;
int len;
addr = of_get_property(dp, "local-mac-address", &len);
if (addr && len == ETH_ALEN) {
memcpy(dev->dev_addr, addr, ETH_ALEN);
return 0;
}
return -ENODEV;
}
static int tg3_get_default_macaddr_sparc(struct tg3 *tp)
{
struct net_device *dev = tp->dev;
memcpy(dev->dev_addr, idprom->id_ethaddr, ETH_ALEN);
return 0;
}
#endif
static int tg3_get_device_address(struct tg3 *tp)
{
struct net_device *dev = tp->dev;
u32 hi, lo, mac_offset;
int addr_ok = 0;
int err;
#ifdef CONFIG_SPARC
if (!tg3_get_macaddr_sparc(tp))
return 0;
#endif
if (tg3_flag(tp, IS_SSB_CORE)) {
err = ssb_gige_get_macaddr(tp->pdev, &dev->dev_addr[0]);
if (!err && is_valid_ether_addr(&dev->dev_addr[0]))
return 0;
}
mac_offset = 0x7c;
if (tg3_asic_rev(tp) == ASIC_REV_5704 ||
tg3_flag(tp, 5780_CLASS)) {
if (tr32(TG3PCI_DUAL_MAC_CTRL) & DUAL_MAC_CTRL_ID)
mac_offset = 0xcc;
if (tg3_nvram_lock(tp))
tw32_f(NVRAM_CMD, NVRAM_CMD_RESET);
else
tg3_nvram_unlock(tp);
} else if (tg3_flag(tp, 5717_PLUS)) {
if (tp->pci_fn & 1)
mac_offset = 0xcc;
if (tp->pci_fn > 1)
mac_offset += 0x18c;
} else if (tg3_asic_rev(tp) == ASIC_REV_5906)
mac_offset = 0x10;
/* First try to get it from MAC address mailbox. */
tg3_read_mem(tp, NIC_SRAM_MAC_ADDR_HIGH_MBOX, &hi);
if ((hi >> 16) == 0x484b) {
dev->dev_addr[0] = (hi >> 8) & 0xff;
dev->dev_addr[1] = (hi >> 0) & 0xff;
tg3_read_mem(tp, NIC_SRAM_MAC_ADDR_LOW_MBOX, &lo);
dev->dev_addr[2] = (lo >> 24) & 0xff;
dev->dev_addr[3] = (lo >> 16) & 0xff;
dev->dev_addr[4] = (lo >> 8) & 0xff;
dev->dev_addr[5] = (lo >> 0) & 0xff;
/* Some old bootcode may report a 0 MAC address in SRAM */
addr_ok = is_valid_ether_addr(&dev->dev_addr[0]);
}
if (!addr_ok) {
/* Next, try NVRAM. */
if (!tg3_flag(tp, NO_NVRAM) &&
!tg3_nvram_read_be32(tp, mac_offset + 0, &hi) &&
!tg3_nvram_read_be32(tp, mac_offset + 4, &lo)) {
memcpy(&dev->dev_addr[0], ((char *)&hi) + 2, 2);
memcpy(&dev->dev_addr[2], (char *)&lo, sizeof(lo));
}
/* Finally just fetch it out of the MAC control regs. */
else {
hi = tr32(MAC_ADDR_0_HIGH);
lo = tr32(MAC_ADDR_0_LOW);
dev->dev_addr[5] = lo & 0xff;
dev->dev_addr[4] = (lo >> 8) & 0xff;
dev->dev_addr[3] = (lo >> 16) & 0xff;
dev->dev_addr[2] = (lo >> 24) & 0xff;
dev->dev_addr[1] = hi & 0xff;
dev->dev_addr[0] = (hi >> 8) & 0xff;
}
}
if (!is_valid_ether_addr(&dev->dev_addr[0])) {
#ifdef CONFIG_SPARC
if (!tg3_get_default_macaddr_sparc(tp))
return 0;
#endif
return -EINVAL;
}
return 0;
}
#define BOUNDARY_SINGLE_CACHELINE 1
#define BOUNDARY_MULTI_CACHELINE 2
static u32 tg3_calc_dma_bndry(struct tg3 *tp, u32 val)
{
int cacheline_size;
u8 byte;
int goal;
pci_read_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE, &byte);
if (byte == 0)
cacheline_size = 1024;
else
cacheline_size = (int) byte * 4;
/* On 5703 and later chips, the boundary bits have no
* effect.
*/
if (tg3_asic_rev(tp) != ASIC_REV_5700 &&
tg3_asic_rev(tp) != ASIC_REV_5701 &&
!tg3_flag(tp, PCI_EXPRESS))
goto out;
#if defined(CONFIG_PPC64) || defined(CONFIG_IA64) || defined(CONFIG_PARISC)
goal = BOUNDARY_MULTI_CACHELINE;
#else
#if defined(CONFIG_SPARC64) || defined(CONFIG_ALPHA)
goal = BOUNDARY_SINGLE_CACHELINE;
#else
goal = 0;
#endif
#endif
if (tg3_flag(tp, 57765_PLUS)) {
val = goal ? 0 : DMA_RWCTRL_DIS_CACHE_ALIGNMENT;
goto out;
}
if (!goal)
goto out;
/* PCI controllers on most RISC systems tend to disconnect
* when a device tries to burst across a cache-line boundary.
* Therefore, letting tg3 do so just wastes PCI bandwidth.
*
* Unfortunately, for PCI-E there are only limited
* write-side controls for this, and thus for reads
* we will still get the disconnects. We'll also waste
* these PCI cycles for both read and write for chips
* other than 5700 and 5701 which do not implement the
* boundary bits.
*/
if (tg3_flag(tp, PCIX_MODE) && !tg3_flag(tp, PCI_EXPRESS)) {
switch (cacheline_size) {
case 16:
case 32:
case 64:
case 128:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_128_PCIX |
DMA_RWCTRL_WRITE_BNDRY_128_PCIX);
} else {
val |= (DMA_RWCTRL_READ_BNDRY_384_PCIX |
DMA_RWCTRL_WRITE_BNDRY_384_PCIX);
}
break;
case 256:
val |= (DMA_RWCTRL_READ_BNDRY_256_PCIX |
DMA_RWCTRL_WRITE_BNDRY_256_PCIX);
break;
default:
val |= (DMA_RWCTRL_READ_BNDRY_384_PCIX |
DMA_RWCTRL_WRITE_BNDRY_384_PCIX);
break;
}
} else if (tg3_flag(tp, PCI_EXPRESS)) {
switch (cacheline_size) {
case 16:
case 32:
case 64:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val &= ~DMA_RWCTRL_WRITE_BNDRY_DISAB_PCIE;
val |= DMA_RWCTRL_WRITE_BNDRY_64_PCIE;
break;
}
/* fallthrough */
case 128:
default:
val &= ~DMA_RWCTRL_WRITE_BNDRY_DISAB_PCIE;
val |= DMA_RWCTRL_WRITE_BNDRY_128_PCIE;
break;
}
} else {
switch (cacheline_size) {
case 16:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_16 |
DMA_RWCTRL_WRITE_BNDRY_16);
break;
}
/* fallthrough */
case 32:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_32 |
DMA_RWCTRL_WRITE_BNDRY_32);
break;
}
/* fallthrough */
case 64:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_64 |
DMA_RWCTRL_WRITE_BNDRY_64);
break;
}
/* fallthrough */
case 128:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_128 |
DMA_RWCTRL_WRITE_BNDRY_128);
break;
}
/* fallthrough */
case 256:
val |= (DMA_RWCTRL_READ_BNDRY_256 |
DMA_RWCTRL_WRITE_BNDRY_256);
break;
case 512:
val |= (DMA_RWCTRL_READ_BNDRY_512 |
DMA_RWCTRL_WRITE_BNDRY_512);
break;
case 1024:
default:
val |= (DMA_RWCTRL_READ_BNDRY_1024 |
DMA_RWCTRL_WRITE_BNDRY_1024);
break;
}
}
out:
return val;
}
static int tg3_do_test_dma(struct tg3 *tp, u32 *buf, dma_addr_t buf_dma,
int size, bool to_device)
{
struct tg3_internal_buffer_desc test_desc;
u32 sram_dma_descs;
int i, ret;
sram_dma_descs = NIC_SRAM_DMA_DESC_POOL_BASE;
tw32(FTQ_RCVBD_COMP_FIFO_ENQDEQ, 0);
tw32(FTQ_RCVDATA_COMP_FIFO_ENQDEQ, 0);
tw32(RDMAC_STATUS, 0);
tw32(WDMAC_STATUS, 0);
tw32(BUFMGR_MODE, 0);
tw32(FTQ_RESET, 0);
test_desc.addr_hi = ((u64) buf_dma) >> 32;
test_desc.addr_lo = buf_dma & 0xffffffff;
test_desc.nic_mbuf = 0x00002100;
test_desc.len = size;
/*
* HP ZX1 was seeing test failures for 5701 cards running at 33Mhz
* the *second* time the tg3 driver was getting loaded after an
* initial scan.
*
* Broadcom tells me:
* ...the DMA engine is connected to the GRC block and a DMA
* reset may affect the GRC block in some unpredictable way...
* The behavior of resets to individual blocks has not been tested.
*
* Broadcom noted the GRC reset will also reset all sub-components.
*/
if (to_device) {
test_desc.cqid_sqid = (13 << 8) | 2;
tw32_f(RDMAC_MODE, RDMAC_MODE_ENABLE);
udelay(40);
} else {
test_desc.cqid_sqid = (16 << 8) | 7;
tw32_f(WDMAC_MODE, WDMAC_MODE_ENABLE);
udelay(40);
}
test_desc.flags = 0x00000005;
for (i = 0; i < (sizeof(test_desc) / sizeof(u32)); i++) {
u32 val;
val = *(((u32 *)&test_desc) + i);
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR,
sram_dma_descs + (i * sizeof(u32)));
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val);
}
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0);
if (to_device)
tw32(FTQ_DMA_HIGH_READ_FIFO_ENQDEQ, sram_dma_descs);
else
tw32(FTQ_DMA_HIGH_WRITE_FIFO_ENQDEQ, sram_dma_descs);
ret = -ENODEV;
for (i = 0; i < 40; i++) {
u32 val;
if (to_device)
val = tr32(FTQ_RCVBD_COMP_FIFO_ENQDEQ);
else
val = tr32(FTQ_RCVDATA_COMP_FIFO_ENQDEQ);
if ((val & 0xffff) == sram_dma_descs) {
ret = 0;
break;
}
udelay(100);
}
return ret;
}
#define TEST_BUFFER_SIZE 0x2000
static DEFINE_PCI_DEVICE_TABLE(tg3_dma_wait_state_chipsets) = {
{ PCI_DEVICE(PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_UNI_N_PCI15) },
{ },
};
static int tg3_test_dma(struct tg3 *tp)
{
dma_addr_t buf_dma;
u32 *buf, saved_dma_rwctrl;
int ret = 0;
buf = dma_alloc_coherent(&tp->pdev->dev, TEST_BUFFER_SIZE,
&buf_dma, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto out_nofree;
}
tp->dma_rwctrl = ((0x7 << DMA_RWCTRL_PCI_WRITE_CMD_SHIFT) |
(0x6 << DMA_RWCTRL_PCI_READ_CMD_SHIFT));
tp->dma_rwctrl = tg3_calc_dma_bndry(tp, tp->dma_rwctrl);
if (tg3_flag(tp, 57765_PLUS))
goto out;
if (tg3_flag(tp, PCI_EXPRESS)) {
/* DMA read watermark not used on PCIE */
tp->dma_rwctrl |= 0x00180000;
} else if (!tg3_flag(tp, PCIX_MODE)) {
if (tg3_asic_rev(tp) == ASIC_REV_5705 ||
tg3_asic_rev(tp) == ASIC_REV_5750)
tp->dma_rwctrl |= 0x003f0000;
else
tp->dma_rwctrl |= 0x003f000f;
} else {
if (tg3_asic_rev(tp) == ASIC_REV_5703 ||
tg3_asic_rev(tp) == ASIC_REV_5704) {
u32 ccval = (tr32(TG3PCI_CLOCK_CTRL) & 0x1f);
u32 read_water = 0x7;
/* If the 5704 is behind the EPB bridge, we can
* do the less restrictive ONE_DMA workaround for
* better performance.
*/
if (tg3_flag(tp, 40BIT_DMA_BUG) &&
tg3_asic_rev(tp) == ASIC_REV_5704)
tp->dma_rwctrl |= 0x8000;
else if (ccval == 0x6 || ccval == 0x7)
tp->dma_rwctrl |= DMA_RWCTRL_ONE_DMA;
if (tg3_asic_rev(tp) == ASIC_REV_5703)
read_water = 4;
/* Set bit 23 to enable PCIX hw bug fix */
tp->dma_rwctrl |=
(read_water << DMA_RWCTRL_READ_WATER_SHIFT) |
(0x3 << DMA_RWCTRL_WRITE_WATER_SHIFT) |
(1 << 23);
} else if (tg3_asic_rev(tp) == ASIC_REV_5780) {
/* 5780 always in PCIX mode */
tp->dma_rwctrl |= 0x00144000;
} else if (tg3_asic_rev(tp) == ASIC_REV_5714) {
/* 5714 always in PCIX mode */
tp->dma_rwctrl |= 0x00148000;
} else {
tp->dma_rwctrl |= 0x001b000f;
}
}
if (tg3_flag(tp, ONE_DMA_AT_ONCE))
tp->dma_rwctrl |= DMA_RWCTRL_ONE_DMA;
if (tg3_asic_rev(tp) == ASIC_REV_5703 ||
tg3_asic_rev(tp) == ASIC_REV_5704)
tp->dma_rwctrl &= 0xfffffff0;
if (tg3_asic_rev(tp) == ASIC_REV_5700 ||
tg3_asic_rev(tp) == ASIC_REV_5701) {
/* Remove this if it causes problems for some boards. */
tp->dma_rwctrl |= DMA_RWCTRL_USE_MEM_READ_MULT;
/* On 5700/5701 chips, we need to set this bit.
* Otherwise the chip will issue cacheline transactions
* to streamable DMA memory with not all the byte
* enables turned on. This is an error on several
* RISC PCI controllers, in particular sparc64.
*
* On 5703/5704 chips, this bit has been reassigned
* a different meaning. In particular, it is used
* on those chips to enable a PCI-X workaround.
*/
tp->dma_rwctrl |= DMA_RWCTRL_ASSERT_ALL_BE;
}
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
if (tg3_asic_rev(tp) != ASIC_REV_5700 &&
tg3_asic_rev(tp) != ASIC_REV_5701)
goto out;
/* It is best to perform DMA test with maximum write burst size
* to expose the 5700/5701 write DMA bug.
*/
saved_dma_rwctrl = tp->dma_rwctrl;
tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK;
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
while (1) {
u32 *p = buf, i;
for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++)
p[i] = i;
/* Send the buffer to the chip. */
ret = tg3_do_test_dma(tp, buf, buf_dma, TEST_BUFFER_SIZE, true);
if (ret) {
dev_err(&tp->pdev->dev,
"%s: Buffer write failed. err = %d\n",
__func__, ret);
break;
}
/* Now read it back. */
ret = tg3_do_test_dma(tp, buf, buf_dma, TEST_BUFFER_SIZE, false);
if (ret) {
dev_err(&tp->pdev->dev, "%s: Buffer read failed. "
"err = %d\n", __func__, ret);
break;
}
/* Verify it. */
for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++) {
if (p[i] == i)
continue;
if ((tp->dma_rwctrl & DMA_RWCTRL_WRITE_BNDRY_MASK) !=
DMA_RWCTRL_WRITE_BNDRY_16) {
tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK;
tp->dma_rwctrl |= DMA_RWCTRL_WRITE_BNDRY_16;
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
break;
} else {
dev_err(&tp->pdev->dev,
"%s: Buffer corrupted on read back! "
"(%d != %d)\n", __func__, p[i], i);
ret = -ENODEV;
goto out;
}
}
if (i == (TEST_BUFFER_SIZE / sizeof(u32))) {
/* Success. */
ret = 0;
break;
}
}
if ((tp->dma_rwctrl & DMA_RWCTRL_WRITE_BNDRY_MASK) !=
DMA_RWCTRL_WRITE_BNDRY_16) {
/* DMA test passed without adjusting DMA boundary,
* now look for chipsets that are known to expose the
* DMA bug without failing the test.
*/
if (pci_dev_present(tg3_dma_wait_state_chipsets)) {
tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK;
tp->dma_rwctrl |= DMA_RWCTRL_WRITE_BNDRY_16;
} else {
/* Safe to use the calculated DMA boundary. */
tp->dma_rwctrl = saved_dma_rwctrl;
}
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
}
out:
dma_free_coherent(&tp->pdev->dev, TEST_BUFFER_SIZE, buf, buf_dma);
out_nofree:
return ret;
}
static void tg3_init_bufmgr_config(struct tg3 *tp)
{
if (tg3_flag(tp, 57765_PLUS)) {
tp->bufmgr_config.mbuf_read_dma_low_water =
DEFAULT_MB_RDMA_LOW_WATER_5705;
tp->bufmgr_config.mbuf_mac_rx_low_water =
DEFAULT_MB_MACRX_LOW_WATER_57765;
tp->bufmgr_config.mbuf_high_water =
DEFAULT_MB_HIGH_WATER_57765;
tp->bufmgr_config.mbuf_read_dma_low_water_jumbo =
DEFAULT_MB_RDMA_LOW_WATER_5705;
tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo =
DEFAULT_MB_MACRX_LOW_WATER_JUMBO_57765;
tp->bufmgr_config.mbuf_high_water_jumbo =
DEFAULT_MB_HIGH_WATER_JUMBO_57765;
} else if (tg3_flag(tp, 5705_PLUS)) {
tp->bufmgr_config.mbuf_read_dma_low_water =
DEFAULT_MB_RDMA_LOW_WATER_5705;
tp->bufmgr_config.mbuf_mac_rx_low_water =
DEFAULT_MB_MACRX_LOW_WATER_5705;
tp->bufmgr_config.mbuf_high_water =
DEFAULT_MB_HIGH_WATER_5705;
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
tp->bufmgr_config.mbuf_mac_rx_low_water =
DEFAULT_MB_MACRX_LOW_WATER_5906;
tp->bufmgr_config.mbuf_high_water =
DEFAULT_MB_HIGH_WATER_5906;
}
tp->bufmgr_config.mbuf_read_dma_low_water_jumbo =
DEFAULT_MB_RDMA_LOW_WATER_JUMBO_5780;
tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo =
DEFAULT_MB_MACRX_LOW_WATER_JUMBO_5780;
tp->bufmgr_config.mbuf_high_water_jumbo =
DEFAULT_MB_HIGH_WATER_JUMBO_5780;
} else {
tp->bufmgr_config.mbuf_read_dma_low_water =
DEFAULT_MB_RDMA_LOW_WATER;
tp->bufmgr_config.mbuf_mac_rx_low_water =
DEFAULT_MB_MACRX_LOW_WATER;
tp->bufmgr_config.mbuf_high_water =
DEFAULT_MB_HIGH_WATER;
tp->bufmgr_config.mbuf_read_dma_low_water_jumbo =
DEFAULT_MB_RDMA_LOW_WATER_JUMBO;
tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo =
DEFAULT_MB_MACRX_LOW_WATER_JUMBO;
tp->bufmgr_config.mbuf_high_water_jumbo =
DEFAULT_MB_HIGH_WATER_JUMBO;
}
tp->bufmgr_config.dma_low_water = DEFAULT_DMA_LOW_WATER;
tp->bufmgr_config.dma_high_water = DEFAULT_DMA_HIGH_WATER;
}
static char *tg3_phy_string(struct tg3 *tp)
{
switch (tp->phy_id & TG3_PHY_ID_MASK) {
case TG3_PHY_ID_BCM5400: return "5400";
case TG3_PHY_ID_BCM5401: return "5401";
case TG3_PHY_ID_BCM5411: return "5411";
case TG3_PHY_ID_BCM5701: return "5701";
case TG3_PHY_ID_BCM5703: return "5703";
case TG3_PHY_ID_BCM5704: return "5704";
case TG3_PHY_ID_BCM5705: return "5705";
case TG3_PHY_ID_BCM5750: return "5750";
case TG3_PHY_ID_BCM5752: return "5752";
case TG3_PHY_ID_BCM5714: return "5714";
case TG3_PHY_ID_BCM5780: return "5780";
case TG3_PHY_ID_BCM5755: return "5755";
case TG3_PHY_ID_BCM5787: return "5787";
case TG3_PHY_ID_BCM5784: return "5784";
case TG3_PHY_ID_BCM5756: return "5722/5756";
case TG3_PHY_ID_BCM5906: return "5906";
case TG3_PHY_ID_BCM5761: return "5761";
case TG3_PHY_ID_BCM5718C: return "5718C";
case TG3_PHY_ID_BCM5718S: return "5718S";
case TG3_PHY_ID_BCM57765: return "57765";
case TG3_PHY_ID_BCM5719C: return "5719C";
case TG3_PHY_ID_BCM5720C: return "5720C";
case TG3_PHY_ID_BCM5762: return "5762C";
case TG3_PHY_ID_BCM8002: return "8002/serdes";
case 0: return "serdes";
default: return "unknown";
}
}
static char *tg3_bus_string(struct tg3 *tp, char *str)
{
if (tg3_flag(tp, PCI_EXPRESS)) {
strcpy(str, "PCI Express");
return str;
} else if (tg3_flag(tp, PCIX_MODE)) {
u32 clock_ctrl = tr32(TG3PCI_CLOCK_CTRL) & 0x1f;
strcpy(str, "PCIX:");
if ((clock_ctrl == 7) ||
((tr32(GRC_MISC_CFG) & GRC_MISC_CFG_BOARD_ID_MASK) ==
GRC_MISC_CFG_BOARD_ID_5704CIOBE))
strcat(str, "133MHz");
else if (clock_ctrl == 0)
strcat(str, "33MHz");
else if (clock_ctrl == 2)
strcat(str, "50MHz");
else if (clock_ctrl == 4)
strcat(str, "66MHz");
else if (clock_ctrl == 6)
strcat(str, "100MHz");
} else {
strcpy(str, "PCI:");
if (tg3_flag(tp, PCI_HIGH_SPEED))
strcat(str, "66MHz");
else
strcat(str, "33MHz");
}
if (tg3_flag(tp, PCI_32BIT))
strcat(str, ":32-bit");
else
strcat(str, ":64-bit");
return str;
}
static void tg3_init_coal(struct tg3 *tp)
{
struct ethtool_coalesce *ec = &tp->coal;
memset(ec, 0, sizeof(*ec));
ec->cmd = ETHTOOL_GCOALESCE;
ec->rx_coalesce_usecs = LOW_RXCOL_TICKS;
ec->tx_coalesce_usecs = LOW_TXCOL_TICKS;
ec->rx_max_coalesced_frames = LOW_RXMAX_FRAMES;
ec->tx_max_coalesced_frames = LOW_TXMAX_FRAMES;
ec->rx_coalesce_usecs_irq = DEFAULT_RXCOAL_TICK_INT;
ec->tx_coalesce_usecs_irq = DEFAULT_TXCOAL_TICK_INT;
ec->rx_max_coalesced_frames_irq = DEFAULT_RXCOAL_MAXF_INT;
ec->tx_max_coalesced_frames_irq = DEFAULT_TXCOAL_MAXF_INT;
ec->stats_block_coalesce_usecs = DEFAULT_STAT_COAL_TICKS;
if (tp->coalesce_mode & (HOSTCC_MODE_CLRTICK_RXBD |
HOSTCC_MODE_CLRTICK_TXBD)) {
ec->rx_coalesce_usecs = LOW_RXCOL_TICKS_CLRTCKS;
ec->rx_coalesce_usecs_irq = DEFAULT_RXCOAL_TICK_INT_CLRTCKS;
ec->tx_coalesce_usecs = LOW_TXCOL_TICKS_CLRTCKS;
ec->tx_coalesce_usecs_irq = DEFAULT_TXCOAL_TICK_INT_CLRTCKS;
}
if (tg3_flag(tp, 5705_PLUS)) {
ec->rx_coalesce_usecs_irq = 0;
ec->tx_coalesce_usecs_irq = 0;
ec->stats_block_coalesce_usecs = 0;
}
}
static int tg3_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev;
struct tg3 *tp;
int i, err;
u32 sndmbx, rcvmbx, intmbx;
char str[40];
u64 dma_mask, persist_dma_mask;
netdev_features_t features = 0;
printk_once(KERN_INFO "%s\n", version);
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "Cannot enable PCI device, aborting\n");
return err;
}
err = pci_request_regions(pdev, DRV_MODULE_NAME);
if (err) {
dev_err(&pdev->dev, "Cannot obtain PCI resources, aborting\n");
goto err_out_disable_pdev;
}
pci_set_master(pdev);
dev = alloc_etherdev_mq(sizeof(*tp), TG3_IRQ_MAX_VECS);
if (!dev) {
err = -ENOMEM;
goto err_out_free_res;
}
SET_NETDEV_DEV(dev, &pdev->dev);
tp = netdev_priv(dev);
tp->pdev = pdev;
tp->dev = dev;
tp->rx_mode = TG3_DEF_RX_MODE;
tp->tx_mode = TG3_DEF_TX_MODE;
tp->irq_sync = 1;
if (tg3_debug > 0)
tp->msg_enable = tg3_debug;
else
tp->msg_enable = TG3_DEF_MSG_ENABLE;
if (pdev_is_ssb_gige_core(pdev)) {
tg3_flag_set(tp, IS_SSB_CORE);
if (ssb_gige_must_flush_posted_writes(pdev))
tg3_flag_set(tp, FLUSH_POSTED_WRITES);
if (ssb_gige_one_dma_at_once(pdev))
tg3_flag_set(tp, ONE_DMA_AT_ONCE);
if (ssb_gige_have_roboswitch(pdev)) {
tg3_flag_set(tp, USE_PHYLIB);
tg3_flag_set(tp, ROBOSWITCH);
}
if (ssb_gige_is_rgmii(pdev))
tg3_flag_set(tp, RGMII_MODE);
}
/* The word/byte swap controls here control register access byte
* swapping. DMA data byte swapping is controlled in the GRC_MODE
* setting below.
*/
tp->misc_host_ctrl =
MISC_HOST_CTRL_MASK_PCI_INT |
MISC_HOST_CTRL_WORD_SWAP |
MISC_HOST_CTRL_INDIR_ACCESS |
MISC_HOST_CTRL_PCISTATE_RW;
/* The NONFRM (non-frame) byte/word swap controls take effect
* on descriptor entries, anything which isn't packet data.
*
* The StrongARM chips on the board (one for tx, one for rx)
* are running in big-endian mode.
*/
tp->grc_mode = (GRC_MODE_WSWAP_DATA | GRC_MODE_BSWAP_DATA |
GRC_MODE_WSWAP_NONFRM_DATA);
#ifdef __BIG_ENDIAN
tp->grc_mode |= GRC_MODE_BSWAP_NONFRM_DATA;
#endif
spin_lock_init(&tp->lock);
spin_lock_init(&tp->indirect_lock);
INIT_WORK(&tp->reset_task, tg3_reset_task);
tp->regs = pci_ioremap_bar(pdev, BAR_0);
if (!tp->regs) {
dev_err(&pdev->dev, "Cannot map device registers, aborting\n");
err = -ENOMEM;
goto err_out_free_dev;
}
if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 ||
tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761E ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761SE ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5719 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5720 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57767 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57764 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5762 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5725 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5727 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57787) {
tg3_flag_set(tp, ENABLE_APE);
tp->aperegs = pci_ioremap_bar(pdev, BAR_2);
if (!tp->aperegs) {
dev_err(&pdev->dev,
"Cannot map APE registers, aborting\n");
err = -ENOMEM;
goto err_out_iounmap;
}
}
tp->rx_pending = TG3_DEF_RX_RING_PENDING;
tp->rx_jumbo_pending = TG3_DEF_RX_JUMBO_RING_PENDING;
dev->ethtool_ops = &tg3_ethtool_ops;
dev->watchdog_timeo = TG3_TX_TIMEOUT;
dev->netdev_ops = &tg3_netdev_ops;
dev->irq = pdev->irq;
err = tg3_get_invariants(tp, ent);
if (err) {
dev_err(&pdev->dev,
"Problem fetching invariants of chip, aborting\n");
goto err_out_apeunmap;
}
/* The EPB bridge inside 5714, 5715, and 5780 and any
* device behind the EPB cannot support DMA addresses > 40-bit.
* On 64-bit systems with IOMMU, use 40-bit dma_mask.
* On 64-bit systems without IOMMU, use 64-bit dma_mask and
* do DMA address check in tg3_start_xmit().
*/
if (tg3_flag(tp, IS_5788))
persist_dma_mask = dma_mask = DMA_BIT_MASK(32);
else if (tg3_flag(tp, 40BIT_DMA_BUG)) {
persist_dma_mask = dma_mask = DMA_BIT_MASK(40);
#ifdef CONFIG_HIGHMEM
dma_mask = DMA_BIT_MASK(64);
#endif
} else
persist_dma_mask = dma_mask = DMA_BIT_MASK(64);
/* Configure DMA attributes. */
if (dma_mask > DMA_BIT_MASK(32)) {
err = pci_set_dma_mask(pdev, dma_mask);
if (!err) {
features |= NETIF_F_HIGHDMA;
err = pci_set_consistent_dma_mask(pdev,
persist_dma_mask);
if (err < 0) {
dev_err(&pdev->dev, "Unable to obtain 64 bit "
"DMA for consistent allocations\n");
goto err_out_apeunmap;
}
}
}
if (err || dma_mask == DMA_BIT_MASK(32)) {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev,
"No usable DMA configuration, aborting\n");
goto err_out_apeunmap;
}
}
tg3_init_bufmgr_config(tp);
/* 5700 B0 chips do not support checksumming correctly due
* to hardware bugs.
*/
if (tg3_chip_rev_id(tp) != CHIPREV_ID_5700_B0) {
features |= NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_RXCSUM;
if (tg3_flag(tp, 5755_PLUS))
features |= NETIF_F_IPV6_CSUM;
}
/* TSO is on by default on chips that support hardware TSO.
* Firmware TSO on older chips gives lower performance, so it
* is off by default, but can be enabled using ethtool.
*/
if ((tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3)) &&
(features & NETIF_F_IP_CSUM))
features |= NETIF_F_TSO;
if (tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) {
if (features & NETIF_F_IPV6_CSUM)
features |= NETIF_F_TSO6;
if (tg3_flag(tp, HW_TSO_3) ||
tg3_asic_rev(tp) == ASIC_REV_5761 ||
(tg3_asic_rev(tp) == ASIC_REV_5784 &&
tg3_chip_rev(tp) != CHIPREV_5784_AX) ||
tg3_asic_rev(tp) == ASIC_REV_5785 ||
tg3_asic_rev(tp) == ASIC_REV_57780)
features |= NETIF_F_TSO_ECN;
}
dev->features |= features | NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_CTAG_RX;
dev->vlan_features |= features;
/*
* Add loopback capability only for a subset of devices that support
* MAC-LOOPBACK. Eventually this need to be enhanced to allow INT-PHY
* loopback for the remaining devices.
*/
if (tg3_asic_rev(tp) != ASIC_REV_5780 &&
!tg3_flag(tp, CPMU_PRESENT))
/* Add the loopback capability */
features |= NETIF_F_LOOPBACK;
dev->hw_features |= features;
dev->priv_flags |= IFF_UNICAST_FLT;
if (tg3_chip_rev_id(tp) == CHIPREV_ID_5705_A1 &&
!tg3_flag(tp, TSO_CAPABLE) &&
!(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH)) {
tg3_flag_set(tp, MAX_RXPEND_64);
tp->rx_pending = 63;
}
err = tg3_get_device_address(tp);
if (err) {
dev_err(&pdev->dev,
"Could not obtain valid ethernet address, aborting\n");
goto err_out_apeunmap;
}
/*
* Reset chip in case UNDI or EFI driver did not shutdown
* DMA self test will enable WDMAC and we'll see (spurious)
* pending DMA on the PCI bus at that point.
*/
if ((tr32(HOSTCC_MODE) & HOSTCC_MODE_ENABLE) ||
(tr32(WDMAC_MODE) & WDMAC_MODE_ENABLE)) {
tw32(MEMARB_MODE, MEMARB_MODE_ENABLE);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
}
err = tg3_test_dma(tp);
if (err) {
dev_err(&pdev->dev, "DMA engine test failed, aborting\n");
goto err_out_apeunmap;
}
intmbx = MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW;
rcvmbx = MAILBOX_RCVRET_CON_IDX_0 + TG3_64BIT_REG_LOW;
sndmbx = MAILBOX_SNDHOST_PROD_IDX_0 + TG3_64BIT_REG_LOW;
for (i = 0; i < tp->irq_max; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
tnapi->tp = tp;
tnapi->tx_pending = TG3_DEF_TX_RING_PENDING;
tnapi->int_mbox = intmbx;
if (i <= 4)
intmbx += 0x8;
else
intmbx += 0x4;
tnapi->consmbox = rcvmbx;
tnapi->prodmbox = sndmbx;
if (i)
tnapi->coal_now = HOSTCC_MODE_COAL_VEC1_NOW << (i - 1);
else
tnapi->coal_now = HOSTCC_MODE_NOW;
if (!tg3_flag(tp, SUPPORT_MSIX))
break;
/*
* If we support MSIX, we'll be using RSS. If we're using
* RSS, the first vector only handles link interrupts and the
* remaining vectors handle rx and tx interrupts. Reuse the
* mailbox values for the next iteration. The values we setup
* above are still useful for the single vectored mode.
*/
if (!i)
continue;
rcvmbx += 0x8;
if (sndmbx & 0x4)
sndmbx -= 0x4;
else
sndmbx += 0xc;
}
tg3_init_coal(tp);
pci_set_drvdata(pdev, dev);
if (tg3_asic_rev(tp) == ASIC_REV_5719 ||
tg3_asic_rev(tp) == ASIC_REV_5720 ||
tg3_asic_rev(tp) == ASIC_REV_5762)
tg3_flag_set(tp, PTP_CAPABLE);
tg3_timer_init(tp);
tg3_carrier_off(tp);
err = register_netdev(dev);
if (err) {
dev_err(&pdev->dev, "Cannot register net device, aborting\n");
goto err_out_apeunmap;
}
netdev_info(dev, "Tigon3 [partno(%s) rev %04x] (%s) MAC address %pM\n",
tp->board_part_number,
tg3_chip_rev_id(tp),
tg3_bus_string(tp, str),
dev->dev_addr);
if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) {
struct phy_device *phydev;
phydev = tp->mdio_bus->phy_map[tp->phy_addr];
netdev_info(dev,
"attached PHY driver [%s] (mii_bus:phy_addr=%s)\n",
phydev->drv->name, dev_name(&phydev->dev));
} else {
char *ethtype;
if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY)
ethtype = "10/100Base-TX";
else if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)
ethtype = "1000Base-SX";
else
ethtype = "10/100/1000Base-T";
netdev_info(dev, "attached PHY is %s (%s Ethernet) "
"(WireSpeed[%d], EEE[%d])\n",
tg3_phy_string(tp), ethtype,
(tp->phy_flags & TG3_PHYFLG_NO_ETH_WIRE_SPEED) == 0,
(tp->phy_flags & TG3_PHYFLG_EEE_CAP) != 0);
}
netdev_info(dev, "RXcsums[%d] LinkChgREG[%d] MIirq[%d] ASF[%d] TSOcap[%d]\n",
(dev->features & NETIF_F_RXCSUM) != 0,
tg3_flag(tp, USE_LINKCHG_REG) != 0,
(tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT) != 0,
tg3_flag(tp, ENABLE_ASF) != 0,
tg3_flag(tp, TSO_CAPABLE) != 0);
netdev_info(dev, "dma_rwctrl[%08x] dma_mask[%d-bit]\n",
tp->dma_rwctrl,
pdev->dma_mask == DMA_BIT_MASK(32) ? 32 :
((u64)pdev->dma_mask) == DMA_BIT_MASK(40) ? 40 : 64);
pci_save_state(pdev);
return 0;
err_out_apeunmap:
if (tp->aperegs) {
iounmap(tp->aperegs);
tp->aperegs = NULL;
}
err_out_iounmap:
if (tp->regs) {
iounmap(tp->regs);
tp->regs = NULL;
}
err_out_free_dev:
free_netdev(dev);
err_out_free_res:
pci_release_regions(pdev);
err_out_disable_pdev:
if (pci_is_enabled(pdev))
pci_disable_device(pdev);
return err;
}
static void tg3_remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
if (dev) {
struct tg3 *tp = netdev_priv(dev);
release_firmware(tp->fw);
tg3_reset_task_cancel(tp);
if (tg3_flag(tp, USE_PHYLIB)) {
tg3_phy_fini(tp);
tg3_mdio_fini(tp);
}
unregister_netdev(dev);
if (tp->aperegs) {
iounmap(tp->aperegs);
tp->aperegs = NULL;
}
if (tp->regs) {
iounmap(tp->regs);
tp->regs = NULL;
}
free_netdev(dev);
pci_release_regions(pdev);
pci_disable_device(pdev);
}
}
#ifdef CONFIG_PM_SLEEP
static int tg3_suspend(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct net_device *dev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(dev);
int err = 0;
rtnl_lock();
if (!netif_running(dev))
goto unlock;
tg3_reset_task_cancel(tp);
tg3_phy_stop(tp);
tg3_netif_stop(tp);
tg3_timer_stop(tp);
tg3_full_lock(tp, 1);
tg3_disable_ints(tp);
tg3_full_unlock(tp);
netif_device_detach(dev);
tg3_full_lock(tp, 0);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_flag_clear(tp, INIT_COMPLETE);
tg3_full_unlock(tp);
err = tg3_power_down_prepare(tp);
if (err) {
int err2;
tg3_full_lock(tp, 0);
tg3_flag_set(tp, INIT_COMPLETE);
err2 = tg3_restart_hw(tp, true);
if (err2)
goto out;
tg3_timer_start(tp);
netif_device_attach(dev);
tg3_netif_start(tp);
out:
tg3_full_unlock(tp);
if (!err2)
tg3_phy_start(tp);
}
unlock:
rtnl_unlock();
return err;
}
static int tg3_resume(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct net_device *dev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(dev);
int err = 0;
rtnl_lock();
if (!netif_running(dev))
goto unlock;
netif_device_attach(dev);
tg3_full_lock(tp, 0);
tg3_ape_driver_state_change(tp, RESET_KIND_INIT);
tg3_flag_set(tp, INIT_COMPLETE);
err = tg3_restart_hw(tp,
!(tp->phy_flags & TG3_PHYFLG_KEEP_LINK_ON_PWRDN));
if (err)
goto out;
tg3_timer_start(tp);
tg3_netif_start(tp);
out:
tg3_full_unlock(tp);
if (!err)
tg3_phy_start(tp);
unlock:
rtnl_unlock();
return err;
}
#endif /* CONFIG_PM_SLEEP */
static SIMPLE_DEV_PM_OPS(tg3_pm_ops, tg3_suspend, tg3_resume);
static void tg3_shutdown(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(dev);
rtnl_lock();
netif_device_detach(dev);
if (netif_running(dev))
dev_close(dev);
if (system_state == SYSTEM_POWER_OFF)
tg3_power_down(tp);
rtnl_unlock();
}
/**
* tg3_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t tg3_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(netdev);
pci_ers_result_t err = PCI_ERS_RESULT_NEED_RESET;
netdev_info(netdev, "PCI I/O error detected\n");
rtnl_lock();
/* We probably don't have netdev yet */
if (!netdev || !netif_running(netdev))
goto done;
tg3_phy_stop(tp);
tg3_netif_stop(tp);
tg3_timer_stop(tp);
/* Want to make sure that the reset task doesn't run */
tg3_reset_task_cancel(tp);
netif_device_detach(netdev);
/* Clean up software state, even if MMIO is blocked */
tg3_full_lock(tp, 0);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 0);
tg3_full_unlock(tp);
done:
if (state == pci_channel_io_perm_failure) {
if (netdev) {
tg3_napi_enable(tp);
dev_close(netdev);
}
err = PCI_ERS_RESULT_DISCONNECT;
} else {
pci_disable_device(pdev);
}
rtnl_unlock();
return err;
}
/**
* tg3_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot.
* At this point, the card has exprienced a hard reset,
* followed by fixups by BIOS, and has its config space
* set up identically to what it was at cold boot.
*/
static pci_ers_result_t tg3_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(netdev);
pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
int err;
rtnl_lock();
if (pci_enable_device(pdev)) {
dev_err(&pdev->dev,
"Cannot re-enable PCI device after reset.\n");
goto done;
}
pci_set_master(pdev);
pci_restore_state(pdev);
pci_save_state(pdev);
if (!netdev || !netif_running(netdev)) {
rc = PCI_ERS_RESULT_RECOVERED;
goto done;
}
err = tg3_power_up(tp);
if (err)
goto done;
rc = PCI_ERS_RESULT_RECOVERED;
done:
if (rc != PCI_ERS_RESULT_RECOVERED && netdev && netif_running(netdev)) {
tg3_napi_enable(tp);
dev_close(netdev);
}
rtnl_unlock();
return rc;
}
/**
* tg3_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells
* us that its OK to resume normal operation.
*/
static void tg3_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(netdev);
int err;
rtnl_lock();
if (!netif_running(netdev))
goto done;
tg3_full_lock(tp, 0);
tg3_ape_driver_state_change(tp, RESET_KIND_INIT);
tg3_flag_set(tp, INIT_COMPLETE);
err = tg3_restart_hw(tp, true);
if (err) {
tg3_full_unlock(tp);
netdev_err(netdev, "Cannot restart hardware after reset.\n");
goto done;
}
netif_device_attach(netdev);
tg3_timer_start(tp);
tg3_netif_start(tp);
tg3_full_unlock(tp);
tg3_phy_start(tp);
done:
rtnl_unlock();
}
static const struct pci_error_handlers tg3_err_handler = {
.error_detected = tg3_io_error_detected,
.slot_reset = tg3_io_slot_reset,
.resume = tg3_io_resume
};
static struct pci_driver tg3_driver = {
.name = DRV_MODULE_NAME,
.id_table = tg3_pci_tbl,
.probe = tg3_init_one,
.remove = tg3_remove_one,
.err_handler = &tg3_err_handler,
.driver.pm = &tg3_pm_ops,
.shutdown = tg3_shutdown,
};
module_pci_driver(tg3_driver);
| tusharbehera/linux | drivers/net/ethernet/broadcom/tg3.c | C | gpl-2.0 | 475,167 |
//=============================================================================
/**
* @file config-win32-msvc.h
*
* $Id: config-win32-msvc.h 82643 2008-08-19 14:02:12Z johnnyw $
*
* @brief Microsoft Visual C++ configuration file.
*
* This file is the ACE configuration file for Microsoft Visual C++ versions
* 5.0, 6.0, and 7.0 (.NET)
*
* @author Darrell Brunsch <brunsch@cs.wustl.edu>
*/
//=============================================================================
#ifndef ACE_CONFIG_WIN32_MSVC_H
#define ACE_CONFIG_WIN32_MSVC_H
#include /**/ "ace/pre.h"
#ifndef ACE_CONFIG_WIN32_H
#error Use config-win32.h in config.h instead of this header
#endif /* ACE_CONFIG_WIN32_H */
#define ACE_CC_NAME ACE_TEXT ("Visual C++")
#ifndef ACE_USING_MCPP_PREPROCESSOR
# define ACE_CC_PREPROCESSOR "CL.EXE"
# define ACE_CC_PREPROCESSOR_ARGS "-nologo -E"
#endif
#define ACE_CC_MAJOR_VERSION (_MSC_VER / 100 - 6)
#define ACE_CC_MINOR_VERSION (_MSC_VER % 100)
#define ACE_CC_BETA_VERSION (0)
#if !defined (ACE_LD_DECORATOR_STR)
# if defined (_DEBUG)
# define ACE_LD_DECORATOR_STR ACE_TEXT ("d")
# endif /* _DEBUG */
#endif /* ACE_LD_DECORATOR_STR */
#if !defined(_NATIVE_WCHAR_T_DEFINED)
#define ACE_LACKS_NATIVE_WCHAR_T
#endif
// Win Mobile still does thread exits differently than PC Windows.
#if defined (_WIN32_WCE)
# define ACE_ENDTHREADEX(STATUS) ExitThread ((DWORD) STATUS)
#else
# define ACE_ENDTHREADEX(STATUS) ::_endthreadex ((DWORD) STATUS)
#endif /* _WIN32_WCE */
#if (_MSC_VER >= 1500)
# include "ace/config-win32-msvc-9.h"
#elif (_MSC_VER >= 1400)
# include "ace/config-win32-msvc-8.h"
#elif (_MSC_VER >= 1310)
# include "ace/config-win32-msvc-7.h"
#else
# error This version of Microsoft Visual C++ is not supported.
#endif
// MFC changes the behavior of operator new at all MSVC versions from 6 up
// by throwing a static CMemoryException* instead of std::bad_alloc
// (see ace/OS_Memory.h). This MFC exception object needs to be cleaned up
// by calling its Delete() method.
#if defined (ACE_HAS_MFC) && (ACE_HAS_MFC == 1)
# if !defined (ACE_NEW_THROWS_EXCEPTIONS)
# define ACE_NEW_THROWS_EXCEPTIONS
# endif
# if defined (ACE_bad_alloc)
# undef ACE_bad_alloc
# endif
# define ACE_bad_alloc CMemoryException *e
# if defined (ACE_del_bad_alloc)
# undef ACE_del_bad_alloc
# endif
# define ACE_del_bad_alloc e->Delete();
#endif /* ACE_HAS_MFC && ACE_HAS_MFC==1 */
#if defined(ACE_MT_SAFE) && (ACE_MT_SAFE != 0)
// must have _MT defined to include multithreading
// features from win32 headers
# if !defined(_MT) && !defined (ACE_HAS_WINCE)
// *** DO NOT *** defeat this error message by defining _MT yourself.
// On MSVC, this is changed by selecting the Multithreaded
// DLL or Debug Multithreaded DLL in the Project Settings
// under C++ Code Generation.
# error You must link against multi-threaded libraries when using ACE (check your project settings)
# endif /* !_MT && !ACE_HAS_WINCE */
#endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */
#include <malloc.h>
// Although ACE does have alloca() on this compiler/platform combination, it is
// disabled by default since it can be dangerous. Uncomment the following line
// if you ACE to use it.
//#define ACE_HAS_ALLOCA 1
#define ACE_LACKS_DIRENT_H
#define ACE_LACKS_DLFCN_H
#define ACE_LACKS_INTTYPES_H
#define ACE_LACKS_NETDB_H
#define ACE_LACKS_NET_IF_H
#define ACE_LACKS_NETINET_IN_H
#define ACE_LACKS_STDINT_H
#define ACE_LACKS_STROPTS_H
#define ACE_LACKS_SYS_IOCTL_H
#define ACE_LACKS_SYS_IPC_H
#define ACE_LACKS_SYS_MMAN_H
#define ACE_LACKS_SYS_RESOURCE_H
#define ACE_LACKS_SYS_SELECT_H
#define ACE_LACKS_SYS_SEM_H
#define ACE_LACKS_SYS_SOCKET_H
#define ACE_LACKS_SYS_TIME_H
#define ACE_LACKS_SYS_UIO_H
#define ACE_LACKS_SYS_WAIT_H
#define ACE_LACKS_UCONTEXT_H
#define ACE_LACKS_SEMAPHORE_H
#define ACE_LACKS_STRINGS_H
#define ACE_LACKS_PWD_H
#define ACE_LACKS_POLL_H
#define ACE_LACKS_SYS_SHM_H
#define ACE_LACKS_SYS_MSG_H
#define ACE_LACKS_NETINET_TCP_H
#define ACE_LACKS_TERMIOS_H
#define ACE_LACKS_REGEX_H
#define ACE_INT64_FORMAT_SPECIFIER ACE_TEXT ("%I64d")
#define ACE_UINT64_FORMAT_SPECIFIER ACE_TEXT ("%I64u")
#define ACE_STRTOULL_EQUIVALENT ::_strtoui64
#define ACE_WCSTOOULL_EQUIVALENT ::_wcstoui64
// Turn off warnings for /W4
// To resume any of these warning: #pragma warning(default: 4xxx)
// which should be placed after these defines
#if !defined (ALL_WARNINGS) && defined(_MSC_VER) && !defined(ghs) && !defined(__MINGW32__)
# pragma warning(disable: 4127) /* constant expression for TRACE/ASSERT */
# pragma warning(disable: 4134) /* message map member fxn casts */
# pragma warning(disable: 4511) /* private copy constructors are good to have */
# pragma warning(disable: 4512) /* private operator= are good to have */
# pragma warning(disable: 4514) /* unreferenced inlines are common */
# pragma warning(disable: 4710) /* private constructors are disallowed */
# pragma warning(disable: 4705) /* statement has no effect in optimized code */
# pragma warning(disable: 4791) /* loss of debugging info in retail version */
# pragma warning(disable: 4275) /* deriving exported class from non-exported */
# pragma warning(disable: 4251) /* using non-exported as public in exported */
# pragma warning(disable: 4786) /* identifier was truncated to '255' characters in the browser information */
# pragma warning(disable: 4097) /* typedef-name used as synonym for class-name */
# pragma warning(disable: 4800) /* converting int to boolean */
# if defined (__INTEL_COMPILER)
# pragma warning(disable: 1744) /* field of class type without a DLL interface used in a class with a DLL interface */
# pragma warning(disable: 1738)
# endif
#endif /* !ALL_WARNINGS && _MSV_VER && !ghs && !__MINGW32__ */
// STRICT type checking in WINDOWS.H enhances type safety for Windows
// programs by using distinct types to represent all the different
// HANDLES in Windows. So for example, STRICT prevents you from
// mistakenly passing an HPEN to a routine expecting an HBITMAP.
// Note that we only use this if we
# if defined (ACE_HAS_STRICT) && (ACE_HAS_STRICT != 0)
# if !defined (STRICT) /* may already be defined */
# define STRICT
# endif /* !STRICT */
# endif /* ACE_HAS_STRICT */
#include /**/ "ace/post.h"
#endif /* ACE_CONFIG_WIN32_MSVC_H */
| skyne/NeoCore | dep/ACE_wrappers/ace/config-win32-msvc.h | C | gpl-2.0 | 6,365 |
<html>
<head>
<title>Flare Dendrogram</title>
<script type="text/javascript" src="../../protovis.js"></script>
<script type="text/javascript" src="../flare.js"></script>
</head>
<body>
<script type="text/javascript+protovis">
var vis = new pv.Panel()
.height(100)
.width(1200);
vis.add(pv.Layout.Cluster.Fill)
.nodes(pv.dom(flare).root("flare").nodes())
.group(true)
.orient("top")
.node.add(pv.Bar);
vis.render();
</script>
</body>
</html>
| songjio/j_asset_glpi_kr | plugins/mreporting/lib/protovis/tests/layout/cluster-fill-group.html | HTML | gpl-2.0 | 495 |
/*
PM8921 Charge IC include file
*/
#ifndef __AXC_PM8921CHARGER_H__
#define __AXC_PM8921CHARGER_H__
#include <linux/types.h>
#include "axi_charger.h"
#include <linux/workqueue.h>
#include <linux/param.h>
//#define STAND_ALONE_WITHOUT_USB_DRIVER
#if 0
#define HIGH (1)
#define LOW (0)
#define CHARGE_PIN1_GPIO (MFP_PIN_GPIO57)
#define CHARGE_PIN2_GPIO (MFP_PIN_GPIO58)
#define CHARGE_DISABLE_GPIO (MFP_PIN_GPIO99)
#define CHARGE_PLUG_IN_GPIO (MFP_PIN_GPIO13)
#define CHARGE_FAULT_GPIO (MFP_PIN_GPIO20)
#define CHARGE_DONE_GPIO (MFP_PIN_GPIO36)
#define CHARGE_STATUS_GPIO (MFP_PIN_GPIO19)
#define BATTERY_LOW (MFP_PIN_GPIO8)
#endif
#define TIME_FOR_NOTIFY_AFTER_PLUGIN_CABLE (60*HZ) //5s
typedef struct AXC_PM8921Charger {
bool mbInited;
int mnType;
AXE_Charger_Type type;
int mnPin1;
int mnPin2;
int mnChargerDisablePin;
int mnChargePlugInPin;
int mnChargeFaultPin;
int mnChargeDonePin;
int mnChargeStatusPin;
//int mnBatteryLowPin;
bool m_is_bat_valid;
AXI_ChargerStateChangeNotifier *mpNotifier;
AXI_Charger msParentCharger;
//struct delayed_work msNotifierWorker;
#ifdef CHARGER_SELF_TEST_ENABLE
AXI_SelfTest msParentSelfTest;
#endif //CHARGER_SELF_TEST_ENABLE
}AXC_PM8921Charger;
extern void AXC_PM8921Charger_Binding(AXI_Charger *apCharger,int anType);
#endif //__AXC_PM8921CHARGER_H__
| shakalaca/ASUS_PadFone_PF500KL | kernel/drivers/power/charger/axc_PM8921Charger.h | C | gpl-2.0 | 1,649 |
/**
* @file
*
* AMD Family_10 Hydra Logical ID Table
*
* @xrefitem bom "File Content Label" "Release Content"
* @e project: AGESA
* @e sub-project: CPU/FAMILY/0x10
* @e \$Revision: 6261 $ @e \$Date: 2008-06-04 17:38:17 -0500 (Wed, 04 Jun 2008) $
*
*/
/*
******************************************************************************
*
* Copyright (c) 2011, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Advanced Micro Devices, Inc. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. 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.
*
******************************************************************************
*/
/*----------------------------------------------------------------------------------------
* M O D U L E S U S E D
*----------------------------------------------------------------------------------------
*/
#include "AGESA.h"
#include "cpuRegisters.h"
#include "Filecode.h"
#define FILECODE PROC_CPU_FAMILY_0X10_REVD_HY_F10HYLOGICALIDTABLES_FILECODE
/*----------------------------------------------------------------------------------------
* D E F I N I T I O N S A N D M A C R O S
*----------------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------------------
* T Y P E D E F S A N D S T R U C T U R E S
*----------------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------------------
* P R O T O T Y P E S O F L O C A L F U N C T I O N S
*----------------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------------------
* E X P O R T E D F U N C T I O N S
*----------------------------------------------------------------------------------------
*/
VOID
GetF10HyLogicalIdAndRev (
OUT CONST CPU_LOGICAL_ID_XLAT **HyIdPtr,
OUT UINT8 *NumberOfElements,
OUT UINT64 *LogicalFamily,
IN OUT AMD_CONFIG_PARAMS *StdHeader
);
STATIC CONST CPU_LOGICAL_ID_XLAT ROMDATA CpuF10HyLogicalIdAndRevArray[] =
{
{
0x1080,
AMD_F10_HY_SCM_D0
},
{
0x1090,
AMD_F10_HY_MCM_D0
},
{
0x1081,
AMD_F10_HY_SCM_D1
},
{
0x1091,
AMD_F10_HY_MCM_D1
}
};
VOID
GetF10HyLogicalIdAndRev (
OUT CONST CPU_LOGICAL_ID_XLAT **HyIdPtr,
OUT UINT8 *NumberOfElements,
OUT UINT64 *LogicalFamily,
IN OUT AMD_CONFIG_PARAMS *StdHeader
)
{
*NumberOfElements = (sizeof (CpuF10HyLogicalIdAndRevArray) / sizeof (CPU_LOGICAL_ID_XLAT));
*HyIdPtr = CpuF10HyLogicalIdAndRevArray;
*LogicalFamily = AMD_FAMILY_10_HY;
}
| hustcalm/coreboot-hacking | src/vendorcode/amd/agesa/f10/Proc/CPU/Family/0x10/RevD/HY/F10HyLogicalIdTables.c | C | gpl-2.0 | 4,284 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "bladerunner/script/scene_script.h"
namespace BladeRunner {
enum kCT04Loops {
kCT04LoopInshot = 0,
kCT04LoopMainLoop = 1
};
void SceneScriptCT04::InitializeScene() {
if (Game_Flag_Query(kFlagCT03toCT04)) {
Scene_Loop_Start_Special(kSceneLoopModeLoseControl, kCT04LoopInshot, false);
Scene_Loop_Set_Default(kCT04LoopMainLoop);
Setup_Scene_Information(-150.0f, -621.3f, 357.0f, 533);
} else {
Scene_Loop_Set_Default(kCT04LoopMainLoop);
Setup_Scene_Information(-82.86f, -621.3f, 769.03f, 1020);
}
Scene_Exit_Add_2D_Exit(0, 590, 0, 639, 479, 1);
Scene_Exit_Add_2D_Exit(1, 194, 84, 320, 274, 0);
if (_vm->_cutContent) {
Scene_Exit_Add_2D_Exit(2, 0, 440, 590, 479, 2);
}
Ambient_Sounds_Add_Looping_Sound(kSfxCTRAIN1, 50, 1, 1);
Ambient_Sounds_Add_Looping_Sound(kSfxCTAMBR1, 15, -100, 1);
Ambient_Sounds_Add_Looping_Sound(kSfxCTRUNOFF, 34, 100, 1);
Ambient_Sounds_Add_Sound(kSfxSPIN2B, 10, 40, 33, 50, 0, 0, -101, -101, 0, 0);
Ambient_Sounds_Add_Sound(kSfxSPIN3A, 10, 40, 33, 50, 0, 0, -101, -101, 0, 0);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 0, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 20, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 40, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 50, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Sound(kSfxTHNDER3, 10, 60, 33, 50, -100, 100, -101, -101, 0, 0);
Ambient_Sounds_Add_Sound(kSfxTHNDER4, 10, 60, 33, 50, -100, 100, -101, -101, 0, 0);
}
void SceneScriptCT04::SceneLoaded() {
Obstacle_Object("DUMPSTER", true);
Obstacle_Object("RIGHTWALL01", true);
Obstacle_Object("BACK-BLDNG", true);
Clickable_Object("DUMPSTER");
Footstep_Sounds_Set(0, 1);
if (Game_Flag_Query(kFlagCT03toCT04)) {
Game_Flag_Reset(kFlagCT03toCT04);
}
if (Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault) {
Actor_Change_Animation_Mode(kActorTransient, 38);
}
}
bool SceneScriptCT04::MouseClick(int x, int y) {
return false;
}
bool SceneScriptCT04::ClickedOn3DObject(const char *objectName, bool a2) {
if (objectName) { // this can be only "DUMPSTER"
if (!Game_Flag_Query(kFlagCT04HomelessTalk)
&& !Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)
&& Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault
) {
Game_Flag_Set(kFlagCT04HomelessTalk);
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
if ( Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)
&& !Game_Flag_Query(kFlagCT04HomelessBodyInDumpster)
&& !Game_Flag_Query(kFlagCT04HomelessBodyFound)
&& !Game_Flag_Query(kFlagCT04HomelessBodyThrownAway)
&& Global_Variable_Query(kVariableChapter) == 1
) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -147.41f, -621.3f, 724.57f, 0, true, false, false)) {
Player_Loses_Control();
Actor_Face_Heading(kActorMcCoy, 792, false);
Actor_Put_In_Set(kActorTransient, kSetFreeSlotI);
Actor_Set_At_XYZ(kActorTransient, 0, 0, 0, 0);
Actor_Change_Animation_Mode(kActorMcCoy, 40);
Actor_Voice_Over(320, kActorVoiceOver);
Actor_Voice_Over(330, kActorVoiceOver);
Actor_Voice_Over(340, kActorVoiceOver);
Game_Flag_Set(kFlagCT04HomelessBodyInDumpster);
Game_Flag_Set(kFlagCT04HomelessBodyInDumpsterNotChecked);
}
return false;
}
if (Game_Flag_Query(kFlagCT04HomelessBodyInDumpster)) {
if (Game_Flag_Query(kFlagCT04HomelessBodyThrownAway)) {
Actor_Voice_Over(270, kActorVoiceOver);
Actor_Voice_Over(280, kActorVoiceOver);
} else if (Game_Flag_Query(kFlagCT04HomelessBodyFound)) {
Actor_Voice_Over(250, kActorVoiceOver);
Actor_Voice_Over(260, kActorVoiceOver);
} else {
Actor_Voice_Over(230, kActorVoiceOver);
Actor_Voice_Over(240, kActorVoiceOver);
Game_Flag_Reset(kFlagCT04HomelessBodyInDumpsterNotChecked);
}
return true;
}
if (!Game_Flag_Query(kFlagCT04LicensePlaceFound)) {
if (!Loop_Actor_Walk_To_Waypoint(kActorMcCoy, 75, 0, true, false)) {
Actor_Face_Heading(kActorMcCoy, 707, false);
Actor_Change_Animation_Mode(kActorMcCoy, 38);
Actor_Clue_Acquire(kActorMcCoy, kClueLicensePlate, true, -1);
Item_Pickup_Spin_Effect(kModelAnimationLicensePlate, 392, 225);
Game_Flag_Set(kFlagCT04LicensePlaceFound);
return true;
}
}
if (!Loop_Actor_Walk_To_Waypoint(kActorMcCoy, 75, 0, true, false)) {
Actor_Face_Heading(kActorMcCoy, 707, false);
Actor_Change_Animation_Mode(kActorMcCoy, 38);
Ambient_Sounds_Play_Sound(kSfxGARBAGE, 45, 30, 30, 0);
Actor_Voice_Over(1810, kActorVoiceOver);
Actor_Voice_Over(1820, kActorVoiceOver);
return true;
}
}
return false;
}
void SceneScriptCT04::dialogueWithHomeless() {
Dialogue_Menu_Clear_List();
if (Global_Variable_Query(kVariableChinyen) > 10
|| Query_Difficulty_Level() == kGameDifficultyEasy
) {
DM_Add_To_List_Never_Repeat_Once_Selected(410, 8, 4, -1); // YES
}
DM_Add_To_List_Never_Repeat_Once_Selected(420, 2, 6, 8); // NO
Dialogue_Menu_Appear(320, 240);
int answer = Dialogue_Menu_Query_Input();
Dialogue_Menu_Disappear();
switch (answer) {
case 410: // YES
Actor_Says(kActorTransient, 10, 14); // Thanks. The big man. He kind of limping.
Actor_Says(kActorTransient, 20, 14); // That way.
Actor_Modify_Friendliness_To_Other(kActorTransient, kActorMcCoy, 5);
if (Query_Difficulty_Level() != kGameDifficultyEasy) {
Global_Variable_Decrement(kVariableChinyen, 10);
}
break;
case 420: // NO
Actor_Says(kActorMcCoy, 430, 3);
Actor_Says(kActorTransient, 30, 14); // Hey, that'd work.
Actor_Modify_Friendliness_To_Other(kActorTransient, kActorMcCoy, -5);
break;
}
}
bool SceneScriptCT04::ClickedOnActor(int actorId) {
if (actorId == kActorTransient) {
if (Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)) {
if (!Loop_Actor_Walk_To_Actor(kActorMcCoy, kActorTransient, 36, true, false)) {
Actor_Voice_Over(290, kActorVoiceOver);
Actor_Voice_Over(300, kActorVoiceOver);
Actor_Voice_Over(310, kActorVoiceOver);
}
} else {
Actor_Set_Targetable(kActorTransient, false);
if (!Loop_Actor_Walk_To_Actor(kActorMcCoy, kActorTransient, 36, true, false)) {
Actor_Face_Actor(kActorMcCoy, kActorTransient, true);
if (!Game_Flag_Query(kFlagCT04HomelessTalk)) {
if (Game_Flag_Query(kFlagZubenRetired)) {
Actor_Says(kActorMcCoy, 435, kAnimationModeTalk);
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
} else {
Music_Stop(3);
Actor_Says(kActorMcCoy, 425, kAnimationModeTalk);
Actor_Says(kActorTransient, 0, 13); // Hey, maybe spare some chinyen?
dialogueWithHomeless();
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
Game_Flag_Set(kFlagCT04HomelessTalk);
} else {
Actor_Face_Actor(kActorMcCoy, kActorTransient, true);
Actor_Says(kActorMcCoy, 435, kAnimationModeTalk);
}
}
}
return true;
}
return false;
}
bool SceneScriptCT04::ClickedOnItem(int itemId, bool a2) {
return false;
}
bool SceneScriptCT04::ClickedOnExit(int exitId) {
if (exitId == 1) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -82.86f, -621.3f, 769.03f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
if (Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault) {
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
Game_Flag_Set(kFlagCT04toCT05);
Set_Enter(kSetCT05, kSceneCT05);
}
return true;
}
if (exitId == 0) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -187.0f, -621.3f, 437.0f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
Game_Flag_Set(kFlagCT04toCT03);
Set_Enter(kSetCT03_CT04, kSceneCT03);
}
return true;
}
if (_vm->_cutContent) {
if (exitId == 2) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -106.94f, -619.08f, 429.20f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
Game_Flag_Set(kFlagCT04toCT03);
Set_Enter(kSetCT03_CT04, kSceneCT03);
}
return true;
}
}
return false;
}
bool SceneScriptCT04::ClickedOn2DRegion(int region) {
return false;
}
void SceneScriptCT04::SceneFrameAdvanced(int frame) {
if (Game_Flag_Query(kFlagCT04BodyDumped)) {
Game_Flag_Reset(kFlagCT04BodyDumped);
Sound_Play(kSfxGARBAGE4, 100, 80, 80, 50);
}
}
void SceneScriptCT04::ActorChangedGoal(int actorId, int newGoal, int oldGoal, bool currentSet) {
}
void SceneScriptCT04::PlayerWalkedIn() {
}
void SceneScriptCT04::PlayerWalkedOut() {
}
void SceneScriptCT04::DialogueQueueFlushed(int a1) {
}
} // End of namespace BladeRunner
| alexbevi/scummvm | engines/bladerunner/script/scene/ct04.cpp | C++ | gpl-2.0 | 9,795 |
/*
* 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.
*/
package p2;
public class c2 {
int i;
public void method2() { i = 5; System.out.println("c2 method2 called"); }
}
| JetBrains/jdk8u_hotspot | test/runtime/ClassUnload/p2/c2.java | Java | gpl-2.0 | 1,173 |
/* -*- Mode:C; c-basic-offset:4; tab-width:4; indent-tabs-mode:nil -*- */
/*
* vmx_fault.c: handling VMX architecture-related VM exits
* Copyright (c) 2005, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
*
* Xiaoyan Feng (Fleming Feng) <fleming.feng@intel.com>
* Xuefei Xu (Anthony Xu) (Anthony.xu@intel.com)
*/
#include <xen/config.h>
#include <xen/lib.h>
#include <xen/errno.h>
#include <xen/sched.h>
#include <xen/smp.h>
#include <asm/ptrace.h>
#include <xen/delay.h>
#include <linux/efi.h> /* FOR EFI_UNIMPLEMENTED */
#include <asm/sal.h> /* FOR struct ia64_sal_retval */
#include <asm/system.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/desc.h>
#include <asm/vlsapic.h>
#include <xen/irq.h>
#include <xen/event.h>
#include <asm/regionreg.h>
#include <asm/privop.h>
#include <asm/ia64_int.h>
#include <asm/debugger.h>
#include <asm/dom_fw.h>
#include <asm/vmx_vcpu.h>
#include <asm/kregs.h>
#include <asm/vmx.h>
#include <asm/vmmu.h>
#include <asm/vmx_mm_def.h>
#include <asm/vmx_phy_mode.h>
#include <xen/mm.h>
#include <asm/vmx_pal.h>
#include <asm/shadow.h>
#include <asm/sioemu.h>
#include <public/arch-ia64/sioemu.h>
#include <xen/hvm/irq.h>
/* reset all PSR field to 0, except up,mfl,mfh,pk,dt,rt,mc,it */
#define INITIAL_PSR_VALUE_AT_INTERRUPTION 0x0000001808028034
extern unsigned long handle_fpu_swa (int fp_fault, struct pt_regs *regs, unsigned long isr);
#define DOMN_PAL_REQUEST 0x110000
#define DOMN_SAL_REQUEST 0x110001
static const u16 vec2off[68] = {0x0,0x400,0x800,0xc00,0x1000,0x1400,0x1800,
0x1c00,0x2000,0x2400,0x2800,0x2c00,0x3000,0x3400,0x3800,0x3c00,0x4000,
0x4400,0x4800,0x4c00,0x5000,0x5100,0x5200,0x5300,0x5400,0x5500,0x5600,
0x5700,0x5800,0x5900,0x5a00,0x5b00,0x5c00,0x5d00,0x5e00,0x5f00,0x6000,
0x6100,0x6200,0x6300,0x6400,0x6500,0x6600,0x6700,0x6800,0x6900,0x6a00,
0x6b00,0x6c00,0x6d00,0x6e00,0x6f00,0x7000,0x7100,0x7200,0x7300,0x7400,
0x7500,0x7600,0x7700,0x7800,0x7900,0x7a00,0x7b00,0x7c00,0x7d00,0x7e00,
0x7f00
};
void vmx_lazy_load_fpu(struct vcpu *vcpu)
{
if (FP_PSR(vcpu) & IA64_PSR_DFH) {
FP_PSR(vcpu) = IA64_PSR_MFH;
if (__ia64_per_cpu_var(fp_owner) != vcpu)
__ia64_load_fpu(vcpu->arch._thread.fph);
}
}
void vmx_reflect_interruption(u64 ifa, u64 isr, u64 iim,
u64 vec, REGS *regs)
{
u64 status, vector;
VCPU *vcpu = current;
u64 vpsr = VCPU(vcpu, vpsr);
vector = vec2off[vec];
switch (vec) {
case 5: // IA64_DATA_NESTED_TLB_VECTOR
break;
case 22: // IA64_INST_ACCESS_RIGHTS_VECTOR
if (!(vpsr & IA64_PSR_IC))
goto nested_fault;
if (vhpt_access_rights_fixup(vcpu, ifa, 0))
return;
break;
case 25: // IA64_DISABLED_FPREG_VECTOR
if (!(vpsr & IA64_PSR_IC))
goto nested_fault;
vmx_lazy_load_fpu(vcpu);
if (!(VCPU(vcpu, vpsr) & IA64_PSR_DFH)) {
regs->cr_ipsr &= ~IA64_PSR_DFH;
return;
}
break;
case 32: // IA64_FP_FAULT_VECTOR
if (!(vpsr & IA64_PSR_IC))
goto nested_fault;
// handle fpswa emulation
// fp fault
status = handle_fpu_swa(1, regs, isr);
if (!status) {
vcpu_increment_iip(vcpu);
return;
}
break;
case 33: // IA64_FP_TRAP_VECTOR
if (!(vpsr & IA64_PSR_IC))
goto nested_fault;
//fp trap
status = handle_fpu_swa(0, regs, isr);
if (!status)
return;
break;
case 29: // IA64_DEBUG_VECTOR
case 35: // IA64_TAKEN_BRANCH_TRAP_VECTOR
case 36: // IA64_SINGLE_STEP_TRAP_VECTOR
if (vmx_guest_kernel_mode(regs)
&& current->domain->debugger_attached) {
domain_pause_for_debugger();
return;
}
if (!(vpsr & IA64_PSR_IC))
goto nested_fault;
break;
default:
if (!(vpsr & IA64_PSR_IC))
goto nested_fault;
break;
}
VCPU(vcpu,isr) = isr;
VCPU(vcpu,iipa) = regs->cr_iip;
if (vector == IA64_BREAK_VECTOR || vector == IA64_SPECULATION_VECTOR)
VCPU(vcpu,iim) = iim;
else
set_ifa_itir_iha(vcpu, ifa, 1, 1, 1);
inject_guest_interruption(vcpu, vector);
return;
nested_fault:
panic_domain(regs, "Guest nested fault vector=%lx!\n", vector);
}
IA64FAULT
vmx_ia64_handle_break (unsigned long ifa, struct pt_regs *regs, unsigned long isr, unsigned long iim)
{
struct domain *d = current->domain;
struct vcpu *v = current;
perfc_incr(vmx_ia64_handle_break);
#ifdef CRASH_DEBUG
if ((iim == 0 || iim == CDB_BREAK_NUM) && !vmx_user_mode(regs) &&
IS_VMM_ADDRESS(regs->cr_iip)) {
if (iim == 0)
show_registers(regs);
debugger_trap_fatal(0 /* don't care */, regs);
regs_increment_iip(regs);
return IA64_NO_FAULT;
}
#endif
if (!vmx_user_mode(regs)) {
show_registers(regs);
gdprintk(XENLOG_DEBUG, "%s:%d imm %lx\n", __func__, __LINE__, iim);
ia64_fault(11 /* break fault */, isr, ifa, iim,
0 /* cr.itir */, 0, 0, 0, (unsigned long)regs);
}
if (ia64_psr(regs)->cpl == 0) {
/* Allow hypercalls only when cpl = 0. */
/* Only common hypercalls are handled by vmx_break_fault. */
if (iim == d->arch.breakimm) {
ia64_hypercall(regs);
vcpu_increment_iip(v);
return IA64_NO_FAULT;
}
/* normal hypercalls are handled by vmx_break_fault */
BUG_ON(iim == d->arch.breakimm);
if (iim == DOMN_PAL_REQUEST) {
pal_emul(v);
vcpu_increment_iip(v);
return IA64_NO_FAULT;
} else if (iim == DOMN_SAL_REQUEST) {
if (d->arch.is_sioemu)
sioemu_sal_assist(v);
else {
sal_emul(v);
vcpu_increment_iip(v);
}
return IA64_NO_FAULT;
}
}
vmx_reflect_interruption(ifa, isr, iim, 11, regs);
return IA64_NO_FAULT;
}
void save_banked_regs_to_vpd(VCPU *v, REGS *regs)
{
unsigned long i=0UL, * src,* dst, *sunat, *dunat;
IA64_PSR vpsr;
src = ®s->r16;
sunat = ®s->eml_unat;
vpsr.val = VCPU(v, vpsr);
if (vpsr.bn) {
dst = &VCPU(v, vgr[0]);
dunat =&VCPU(v, vnat);
__asm__ __volatile__ (";;extr.u %0 = %1,%4,16;; \
dep %2 = %0, %2, 0, 16;; \
st8 [%3] = %2;;"
::"r"(i),"r"(*sunat),"r"(*dunat),"r"(dunat),"i"(IA64_PT_REGS_R16_SLOT):"memory");
} else {
dst = &VCPU(v, vbgr[0]);
// dunat =&VCPU(v, vbnat);
// __asm__ __volatile__ (";;extr.u %0 = %1,%4,16;;
// dep %2 = %0, %2, 16, 16;;
// st8 [%3] = %2;;"
// ::"r"(i),"r"(*sunat),"r"(*dunat),"r"(dunat),"i"(IA64_PT_REGS_R16_SLOT):"memory");
}
for (i = 0; i < 16; i++)
*dst++ = *src++;
}
// ONLY gets called from ia64_leave_kernel
// ONLY call with interrupts disabled?? (else might miss one?)
// NEVER successful if already reflecting a trap/fault because psr.i==0
void leave_hypervisor_tail(void)
{
struct domain *d = current->domain;
struct vcpu *v = current;
/* FIXME: can this happen ? */
if (is_idle_domain(current->domain))
return;
// A softirq may generate an interrupt. So call softirq early.
local_irq_enable();
do_softirq();
local_irq_disable();
// FIXME: Will this work properly if doing an RFI???
if (d->arch.is_sioemu) {
if (local_events_need_delivery()) {
sioemu_deliver_event();
}
} else if (v->vcpu_id == 0) {
unsigned long callback_irq =
d->arch.hvm_domain.params[HVM_PARAM_CALLBACK_IRQ];
if (v->arch.arch_vmx.pal_init_pending) {
/* inject INIT interruption to guest pal */
v->arch.arch_vmx.pal_init_pending = 0;
deliver_pal_init(v);
return;
}
/*
* val[63:56] == 1: val[55:0] is a delivery PCI INTx line:
* Domain = val[47:32], Bus = val[31:16],
* DevFn = val[15: 8], IntX = val[ 1: 0]
* val[63:56] == 0: val[55:0] is a delivery as GSI
*/
if (callback_irq != 0 && local_events_need_delivery()) {
/* change level for para-device callback irq */
/* use level irq to send discrete event */
if ((uint8_t)(callback_irq >> 56) == 1) {
/* case of using PCI INTx line as callback irq */
int pdev = (callback_irq >> 11) & 0x1f;
int pintx = callback_irq & 3;
viosapic_set_pci_irq(d, pdev, pintx, 1);
viosapic_set_pci_irq(d, pdev, pintx, 0);
} else {
/* case of using GSI as callback irq */
viosapic_set_irq(d, callback_irq, 1);
viosapic_set_irq(d, callback_irq, 0);
}
}
}
rmb();
if (xchg(&v->arch.irq_new_pending, 0)) {
v->arch.irq_new_condition = 0;
vmx_check_pending_irq(v);
} else if (v->arch.irq_new_condition) {
v->arch.irq_new_condition = 0;
vhpi_detection(v);
}
}
static int vmx_handle_lds(REGS* regs)
{
regs->cr_ipsr |= IA64_PSR_ED;
return IA64_FAULT;
}
static inline int unimpl_phys_addr (u64 paddr)
{
return (pa_clear_uc(paddr) >> MAX_PHYS_ADDR_BITS) != 0;
}
/* We came here because the H/W VHPT walker failed to find an entry */
IA64FAULT
vmx_hpw_miss(u64 vadr, u64 vec, REGS* regs)
{
IA64_PSR vpsr;
int type;
u64 vhpt_adr, gppa, pteval, rr, itir;
ISR misr;
PTA vpta;
thash_data_t *data;
VCPU *v = current;
vpsr.val = VCPU(v, vpsr);
misr.val = VMX(v,cr_isr);
if (vec == 1 || vec == 3)
type = ISIDE_TLB;
else if (vec == 2 || vec == 4)
type = DSIDE_TLB;
else
panic_domain(regs, "wrong vec:%lx\n", vec);
/* Physical mode. */
if (type == ISIDE_TLB) {
if (!vpsr.it) {
if (unlikely(unimpl_phys_addr(vadr))) {
unimpl_iaddr_trap(v, vadr);
return IA64_FAULT;
}
physical_tlb_miss(v, vadr, type);
return IA64_FAULT;
}
} else { /* DTLB miss. */
if (!misr.rs) {
if (!vpsr.dt) {
u64 pte;
if (misr.sp) /* Refer to SDM Vol2 Table 4-11,4-12 */
return vmx_handle_lds(regs);
if (unlikely(unimpl_phys_addr(vadr))) {
unimpl_daddr(v);
return IA64_FAULT;
}
pte = lookup_domain_mpa(v->domain, pa_clear_uc(vadr), NULL);
if (v->domain != dom0 && (pte & _PAGE_IO)) {
emulate_io_inst(v, pa_clear_uc(vadr), 4,
pte_pfn(__pte(pte)));
return IA64_FAULT;
}
physical_tlb_miss(v, vadr, type);
return IA64_FAULT;
}
} else { /* RSE fault. */
if (!vpsr.rt) {
if (unlikely(unimpl_phys_addr(vadr))) {
unimpl_daddr(v);
return IA64_FAULT;
}
physical_tlb_miss(v, vadr, type);
return IA64_FAULT;
}
}
}
try_again:
/* Search in VTLB. */
data = vtlb_lookup(v, vadr, type);
if (data != 0) {
/* Found. */
if (v->domain != dom0 && type == DSIDE_TLB) {
u64 pte;
if (misr.sp) { /* Refer to SDM Vol2 Table 4-10,4-12 */
if ((data->ma == VA_MATTR_UC) || (data->ma == VA_MATTR_UCE))
return vmx_handle_lds(regs);
}
gppa = thash_translate(data, vadr);
pte = lookup_domain_mpa(v->domain, gppa, NULL);
if (pte & _PAGE_IO) {
if (misr.sp)
panic_domain(NULL, "ld.s on I/O page not with UC attr."
" pte=0x%lx\n", data->page_flags);
if (data->pl >= ((regs->cr_ipsr >> IA64_PSR_CPL0_BIT) & 3))
emulate_io_inst(v, gppa, data->ma,
pte_pfn(__pte(pte)));
else {
vcpu_set_isr(v, misr.val);
data_access_rights(v, vadr);
}
return IA64_FAULT;
}
}
thash_vhpt_insert(v, data->page_flags, data->itir, vadr, type);
return IA64_NO_FAULT;
}
if (type == DSIDE_TLB) {
struct opt_feature* optf = &(v->domain->arch.opt_feature);
if (misr.sp)
return vmx_handle_lds(regs);
vcpu_get_rr(v, vadr, &rr);
itir = rr & (RR_RID_MASK | RR_PS_MASK);
if (!vhpt_enabled(v, vadr, misr.rs ? RSE_REF : DATA_REF)) {
/* windows use region 4 and 5 for identity mapping */
if ((optf->mask & XEN_IA64_OPTF_IDENT_MAP_REG4_FLG) &&
REGION_NUMBER(vadr) == 4 && !(regs->cr_ipsr & IA64_PSR_CPL) &&
REGION_OFFSET(vadr) <= _PAGE_PPN_MASK) {
pteval = PAGEALIGN(REGION_OFFSET(vadr), itir_ps(itir)) |
optf->im_reg4.pgprot;
if (thash_purge_and_insert(v, pteval, itir, vadr, type))
goto try_again;
return IA64_NO_FAULT;
}
if ((optf->mask & XEN_IA64_OPTF_IDENT_MAP_REG5_FLG) &&
REGION_NUMBER(vadr) == 5 && !(regs->cr_ipsr & IA64_PSR_CPL) &&
REGION_OFFSET(vadr) <= _PAGE_PPN_MASK) {
pteval = PAGEALIGN(REGION_OFFSET(vadr), itir_ps(itir)) |
optf->im_reg5.pgprot;
if (thash_purge_and_insert(v, pteval, itir, vadr, type))
goto try_again;
return IA64_NO_FAULT;
}
if (vpsr.ic) {
vcpu_set_isr(v, misr.val);
alt_dtlb(v, vadr);
} else {
nested_dtlb(v);
}
return IA64_FAULT;
}
vpta.val = vmx_vcpu_get_pta(v);
if (vpta.vf) {
/* Long format is not yet supported. */
goto inject_dtlb_fault;
}
/* avoid recursively walking (short format) VHPT */
if (!(optf->mask & XEN_IA64_OPTF_IDENT_MAP_REG4_FLG) &&
!(optf->mask & XEN_IA64_OPTF_IDENT_MAP_REG5_FLG) &&
(((vadr ^ vpta.val) << 3) >> (vpta.size + 3)) == 0) {
goto inject_dtlb_fault;
}
vhpt_adr = vmx_vcpu_thash(v, vadr);
if (!guest_vhpt_lookup(vhpt_adr, &pteval)) {
/* VHPT successfully read. */
if (!(pteval & _PAGE_P)) {
goto inject_dtlb_fault;
} else if ((pteval & _PAGE_MA_MASK) != _PAGE_MA_ST) {
thash_purge_and_insert(v, pteval, itir, vadr, DSIDE_TLB);
return IA64_NO_FAULT;
}
goto inject_dtlb_fault;
} else {
/* Can't read VHPT. */
if (vpsr.ic) {
vcpu_set_isr(v, misr.val);
dvhpt_fault(v, vadr);
return IA64_FAULT;
} else {
nested_dtlb(v);
return IA64_FAULT;
}
}
} else if (type == ISIDE_TLB) {
if (!vpsr.ic)
misr.ni = 1;
/* Don't bother with PHY_D mode (will require rr0+rr4 switches,
and certainly used only within nested TLB handler (hence TR mapped
and ic=0). */
if (!vpsr.dt)
goto inject_itlb_fault;
if (!vhpt_enabled(v, vadr, INST_REF)) {
vcpu_set_isr(v, misr.val);
alt_itlb(v, vadr);
return IA64_FAULT;
}
vpta.val = vmx_vcpu_get_pta(v);
if (vpta.vf) {
/* Long format is not yet supported. */
goto inject_itlb_fault;
}
vhpt_adr = vmx_vcpu_thash(v, vadr);
if (!guest_vhpt_lookup(vhpt_adr, &pteval)) {
/* VHPT successfully read. */
if (pteval & _PAGE_P) {
if ((pteval & _PAGE_MA_MASK) == _PAGE_MA_ST) {
goto inject_itlb_fault;
}
vcpu_get_rr(v, vadr, &rr);
itir = rr & (RR_RID_MASK | RR_PS_MASK);
thash_purge_and_insert(v, pteval, itir, vadr, ISIDE_TLB);
return IA64_NO_FAULT;
} else {
vcpu_set_isr(v, misr.val);
inst_page_not_present(v, vadr);
return IA64_FAULT;
}
} else {
vcpu_set_isr(v, misr.val);
ivhpt_fault(v, vadr);
return IA64_FAULT;
}
}
return IA64_NO_FAULT;
inject_dtlb_fault:
if (vpsr.ic) {
vcpu_set_isr(v, misr.val);
dtlb_fault(v, vadr);
} else
nested_dtlb(v);
return IA64_FAULT;
inject_itlb_fault:
vcpu_set_isr(v, misr.val);
itlb_fault(v, vadr);
return IA64_FAULT;
}
void
vmx_ia64_shadow_fault(u64 ifa, u64 isr, u64 mpa, REGS *regs)
{
struct vcpu *v = current;
struct domain *d = v->domain;
u64 gpfn, pte;
thash_data_t *data;
if (!shadow_mode_enabled(d))
goto inject_dirty_bit;
gpfn = get_gpfn_from_mfn(mpa >> PAGE_SHIFT);
data = vhpt_lookup(ifa);
if (data) {
pte = data->page_flags;
// BUG_ON((pte ^ mpa) & (_PAGE_PPN_MASK & PAGE_MASK));
if (!(pte & _PAGE_VIRT_D))
goto inject_dirty_bit;
data->page_flags = pte | _PAGE_D;
} else {
data = vtlb_lookup(v, ifa, DSIDE_TLB);
if (data) {
if (!(data->page_flags & _PAGE_VIRT_D))
goto inject_dirty_bit;
}
pte = 0;
}
/* Set the dirty bit in the bitmap. */
shadow_mark_page_dirty(d, gpfn);
/* Retry */
atomic64_inc(&d->arch.shadow_fault_count);
ia64_ptcl(ifa, PAGE_SHIFT << 2);
return;
inject_dirty_bit:
/* Reflect. no need to purge. */
VCPU(v, isr) = isr;
set_ifa_itir_iha (v, ifa, 1, 1, 1);
inject_guest_interruption(v, IA64_DIRTY_BIT_VECTOR);
return;
}
| jamesbulpin/xcp-xen-4.1 | xen/arch/ia64/vmx/vmx_fault.c | C | gpl-2.0 | 19,082 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="mixerp.png"/></td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('class_mix_e_r_p_1_1_net_1_1_front_end_1_1_services_1_1_office.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">MixERP.Net.FrontEnd.Services.Office Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="class_mix_e_r_p_1_1_net_1_1_front_end_1_1_services_1_1_office.html">MixERP.Net.FrontEnd.Services.Office</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>GetOffices</b>(string catalog) (defined in <a class="el" href="class_mix_e_r_p_1_1_net_1_1_front_end_1_1_services_1_1_office.html">MixERP.Net.FrontEnd.Services.Office</a>)</td><td class="entry"><a class="el" href="class_mix_e_r_p_1_1_net_1_1_front_end_1_1_services_1_1_office.html">MixERP.Net.FrontEnd.Services.Office</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li>
</ul>
</div>
</body>
</html>
| mixerp/mixerp | docs/api/class_mix_e_r_p_1_1_net_1_1_front_end_1_1_services_1_1_office-members.html | HTML | gpl-3.0 | 5,327 |
/* $OpenBSD: strdup.c,v 1.6 2005/08/08 08:05:37 espie Exp $ */
/*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 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 of the University 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "sys/types.h"
#include "stdlib.h"
#include "string.h"
char *strdup(const char *str)
{
size_t siz;
char *copy;
siz = strlen(str) + 1;
if ((copy = malloc(siz)) == NULL)
return(NULL);
(void)memcpy(copy, str, siz);
return(copy);
}
| amenglar/freenos | lib/libc/string/strdup.c | C | gpl-3.0 | 1,906 |
; PROLOGUE(mpn_rsh1sub_n)
; AMD64 mpn_rsh1sub_n
; Copyright 2009 Jason Moxham
; Windows Conversion Copyright 2008 Brian Gladman
;
; This file is part of the MPIR Library.
; The MPIR 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 MPIR 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 MPIR 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.
;
; (rdi,rcx)=((rsi,rcx)-(rdx,rcx))/2
; return bottom bit of difference
; subtraction treated as two compliment
%include "yasm_mac.inc"
%define reg_save_list rbx, rsi, rdi, r12
CPU Athlon64
BITS 64
FRAME_PROC mpn_rsh1sub_n, 0, reg_save_list
mov rax, r9
lea rdi, [rcx+rax*8-32]
lea rsi, [rdx+rax*8-32]
lea rdx, [r8+rax*8-32]
mov rcx, rax
mov r8, 4
sub r8, rcx
mov r12, [rsi+r8*8]
sub r12, [rdx+r8*8]
sbb rbx, rbx
mov rax, r12
and rax, 1
cmp r8, 0
jge .2
.1: mov r11, [rsi+r8*8+32]
mov r10, [rsi+r8*8+24]
add rbx, 1
mov rcx, [rsi+r8*8+8]
mov r9, [rsi+r8*8+16]
sbb rcx, [rdx+r8*8+8]
sbb r9, [rdx+r8*8+16]
sbb r10, [rdx+r8*8+24]
sbb r11, [rdx+r8*8+32]
sbb rbx, rbx
bt r11, 0
rcr r10, 1
rcr r9, 1
rcr rcx, 1
rcr r12, 1
mov [rdi+r8*8], r12
mov [rdi+r8*8+8], rcx
mov [rdi+r8*8+16], r9
mov [rdi+r8*8+24], r10
mov r12, r11
add r8, 4
jnc .1
.2: cmp r8, 2
ja .6
jz .5
jp .4
.3: mov r10, [rsi+r8*8+24]
add rbx, 1
mov rcx, [rsi+r8*8+8]
mov r9, [rsi+r8*8+16]
sbb rcx, [rdx+r8*8+8]
sbb r9, [rdx+r8*8+16]
sbb r10, [rdx+r8*8+24]
rcr r10, 1
rcr r9, 1
rcr rcx, 1
rcr r12, 1
mov [rdi+r8*8], r12
mov [rdi+r8*8+8], rcx
mov [rdi+r8*8+16], r9
mov [rdi+r8*8+24], r10
EXIT_PROC reg_save_list
xalign 16
.4: add rbx, 1
mov rcx, [rsi+r8*8+8]
mov r9, [rsi+r8*8+16]
sbb rcx, [rdx+r8*8+8]
sbb r9, [rdx+r8*8+16]
rcr r9, 1
rcr rcx, 1
rcr r12, 1
mov [rdi+r8*8], r12
mov [rdi+r8*8+8], rcx
mov [rdi+r8*8+16], r9
EXIT_PROC reg_save_list
xalign 16
.5: add rbx, 1
mov rcx, [rsi+r8*8+8]
sbb rcx, [rdx+r8*8+8]
rcr rcx, 1
rcr r12, 1
mov [rdi+r8*8], r12
mov [rdi+r8*8+8], rcx
EXIT_PROC reg_save_list
xalign 16
.6: add rbx, 1
rcr r12, 1
mov [rdi+r8*8], r12
.7: END_PROC reg_save_list
end
| jpflori/mpir | mpn/x86_64w/nehalem/rsh1sub_n.asm | Assembly | gpl-3.0 | 3,024 |
/*
* Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "inner.h"
/* see bearssl_rsa.h */
uint32_t
br_rsa_ssl_decrypt(br_rsa_private core, const br_rsa_private_key *sk,
unsigned char *data, size_t len)
{
uint32_t x;
size_t u;
/*
* A first check on length. Since this test works only on the
* buffer length, it needs not (and cannot) be constant-time.
*/
if (len < 59 || len != (sk->n_bitlen + 7) >> 3) {
return 0;
}
x = core(data, sk);
x &= EQ(data[0], 0x00);
x &= EQ(data[1], 0x02);
for (u = 2; u < (len - 49); u ++) {
x &= NEQ(data[u], 0);
}
x &= EQ(data[len - 49], 0x00);
memmove(data, data + len - 48, 48);
return x;
}
| Themaister/RetroArch | deps/bearssl-0.6/src/rsa/rsa_ssl_decrypt.c | C | gpl-3.0 | 1,751 |
// Copyright (C) 2014 The Syncthing Authors.
//
// 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/.
package events_test
import (
"fmt"
"testing"
"time"
"github.com/syncthing/syncthing/lib/events"
)
const timeout = 100 * time.Millisecond
func TestNewLogger(t *testing.T) {
l := events.NewLogger()
if l == nil {
t.Fatal("Unexpected nil Logger")
}
}
func TestSubscriber(t *testing.T) {
l := events.NewLogger()
s := l.Subscribe(0)
defer l.Unsubscribe(s)
if s == nil {
t.Fatal("Unexpected nil Subscription")
}
}
func TestTimeout(t *testing.T) {
l := events.NewLogger()
s := l.Subscribe(0)
defer l.Unsubscribe(s)
_, err := s.Poll(timeout)
if err != events.ErrTimeout {
t.Fatal("Unexpected non-Timeout error:", err)
}
}
func TestEventBeforeSubscribe(t *testing.T) {
l := events.NewLogger()
l.Log(events.DeviceConnected, "foo")
s := l.Subscribe(0)
defer l.Unsubscribe(s)
_, err := s.Poll(timeout)
if err != events.ErrTimeout {
t.Fatal("Unexpected non-Timeout error:", err)
}
}
func TestEventAfterSubscribe(t *testing.T) {
l := events.NewLogger()
s := l.Subscribe(events.AllEvents)
defer l.Unsubscribe(s)
l.Log(events.DeviceConnected, "foo")
ev, err := s.Poll(timeout)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if ev.Type != events.DeviceConnected {
t.Error("Incorrect event type", ev.Type)
}
switch v := ev.Data.(type) {
case string:
if v != "foo" {
t.Error("Incorrect Data string", v)
}
default:
t.Errorf("Incorrect Data type %#v", v)
}
}
func TestEventAfterSubscribeIgnoreMask(t *testing.T) {
l := events.NewLogger()
s := l.Subscribe(events.DeviceDisconnected)
defer l.Unsubscribe(s)
l.Log(events.DeviceConnected, "foo")
_, err := s.Poll(timeout)
if err != events.ErrTimeout {
t.Fatal("Unexpected non-Timeout error:", err)
}
}
func TestBufferOverflow(t *testing.T) {
l := events.NewLogger()
s := l.Subscribe(events.AllEvents)
defer l.Unsubscribe(s)
t0 := time.Now()
for i := 0; i < events.BufferSize*2; i++ {
l.Log(events.DeviceConnected, "foo")
}
if time.Since(t0) > timeout {
t.Fatalf("Logging took too long")
}
}
func TestUnsubscribe(t *testing.T) {
l := events.NewLogger()
s := l.Subscribe(events.AllEvents)
l.Log(events.DeviceConnected, "foo")
_, err := s.Poll(timeout)
if err != nil {
t.Fatal("Unexpected error:", err)
}
l.Unsubscribe(s)
l.Log(events.DeviceConnected, "foo")
_, err = s.Poll(timeout)
if err != events.ErrClosed {
t.Fatal("Unexpected non-Closed error:", err)
}
}
func TestIDs(t *testing.T) {
l := events.NewLogger()
s := l.Subscribe(events.AllEvents)
defer l.Unsubscribe(s)
l.Log(events.DeviceConnected, "foo")
_ = l.Subscribe(events.AllEvents)
l.Log(events.DeviceConnected, "bar")
ev, err := s.Poll(timeout)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if ev.Data.(string) != "foo" {
t.Fatal("Incorrect event:", ev)
}
id := ev.ID
ev, err = s.Poll(timeout)
if err != nil {
t.Fatal("Unexpected error:", err)
}
if ev.Data.(string) != "bar" {
t.Fatal("Incorrect event:", ev)
}
if ev.ID != id+1 {
t.Fatalf("ID not incremented (%d != %d)", ev.ID, id+1)
}
}
func TestBufferedSub(t *testing.T) {
l := events.NewLogger()
s := l.Subscribe(events.AllEvents)
defer l.Unsubscribe(s)
bs := events.NewBufferedSubscription(s, 10*events.BufferSize)
go func() {
for i := 0; i < 10*events.BufferSize; i++ {
l.Log(events.DeviceConnected, fmt.Sprintf("event-%d", i))
if i%30 == 0 {
// Give the buffer routine time to pick up the events
time.Sleep(20 * time.Millisecond)
}
}
}()
recv := 0
for recv < 10*events.BufferSize {
evs := bs.Since(recv, nil)
for _, ev := range evs {
if ev.ID != recv+1 {
t.Fatalf("Incorrect ID; %d != %d", ev.ID, recv+1)
}
recv = ev.ID
}
}
}
| alex2108/syncthing | lib/events/events_test.go | GO | mpl-2.0 | 3,935 |
# source this file (. devinstall.sh) to get exports in the right place
# then you can run graphlab from within the venv and it points to this
# development directory
# create a virtualenv (if necessary) and activate it
virtualenv venv
. venv/bin/activate
# set the export path for unity server
export GRAPHLAB_UNITY=$(pwd)/../server/unity_server
# install the package locally in development mode (so the files are symlinked and a make picks up new changes)
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install -e .
# install ipython notebook dependencies
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install "ipython[notebook]"
| iRGBit/Dato-Core | src/unity/python/devinstall.sh | Shell | agpl-3.0 | 692 |
<?php
/**
* Advanced OpenWorkflow, Automating SugarCRM.
* @package Advanced OpenWorkflow for SugarCRM
* @copyright SalesAgility Ltd http://www.salesagility.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*
* @author SalesAgility <info@salesagility.com>
*/
class actionBase
{
public $id;
public function __construct($id = '')
{
$this->id = $id;
}
/**
* @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead
*/
public function actionBase($id = '')
{
$deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->deprecated($deprecatedMessage);
} else {
trigger_error($deprecatedMessage, E_USER_DEPRECATED);
}
self::__construct($id);
}
public function loadJS()
{
return array();
}
public function edit_display($line, SugarBean $bean = null, $params = array())
{
return '';
}
public function run_action(SugarBean $bean, $params = array(), $in_save=false)
{
return true;
}
}
| lionixevolve/LionixCRM | modules/AOW_Actions/actions/actionBase.php | PHP | agpl-3.0 | 1,987 |
# Installation
### Table of Contents
* [Requirements](#requirements)
* [WARNING](#warning)
* [Cloud Foundry](#cloud-foundry)
* [Heroku](#heroku)
* [dotCloud](#dotcloud)
* [AppFog](#appfog)
* [Stand Alone Server](#standalone-server)
<hr>
# <a name="requirements"></a>Requirements
* Ruby 1.9
<hr>
# <a name="warning"></a>WARNING
We try and keep the __MASTER__ branch of the Kandan code clean and usable but it is __bleeding edge__ and can cause unpredictable results.
If you need a version of Kandan that's both __tested & stable__ then please make sure you're installing from the lastest `tagged` version of the code.
```
git clone git@github.com:kandanapp/kandan.git
cd kandan
git tag -l
git checkout <tag_name>
```
Depending on your setup you might also see the following error:
```
Building native extensions. This could take a while...
ERROR: Error installing debugger-linecache:
ERROR: Failed to build gem native extension.
/home/jrg/.rbenv/versions/1.9.3-p385/bin/ruby extconf.rb
checking for vm_core.h... no
checking for vm_core.h... no
Makefile creation failed
**************************************************************************
No source for ruby-1.9.3-p385 provided with debugger-ruby_core_source gem.
**************************************************************************
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/home/jrg/.rbenv/versions/1.9.3-p385/bin/ruby
--with-ruby-dir
--without-ruby-dir
--with-ruby-include
--without-ruby-include=${ruby-dir}/include
--with-ruby-lib
--without-ruby-lib=${ruby-dir}/lib
```
To work around it run this then attempt to re-install.
`gem install debugger-ruby_core_source`
<hr>
# <a name="cloud-foundry"></a>Cloud Foundry
You'll need a [Cloud Foundry account](https://my.cloudfoundry.com/signup) and the [vmc gem](https://rubygems.org/gems/vmc) installed. Do you `vmc target <cloud foundry host>` and `vmc login`, and then this will get you up and running:
git clone https://github.com/kandanapp/kandan.git
cd kandan
bundle install
bundle exec rake assets:precompile
vmc push my-company-chat --path . --instances 1 --mem 256M --runtime ruby19
You'll answer a few questions:
Application Deployed URL [my-company-chat.cloudfoundry.com]:
Detected a Rails Application, is this correct? [Yn]:
Creating Application: OK
Would you like to bind any services to 'my-company-chat'? [yN]: y
Would you like to use an existing provisioned service? [yN]: n
The following system services are available
1: mongodb
2: mysql
3: postgresql
4: rabbitmq
5: redis
Please select one you wish to provision: 3
Specify the name of the service [postgresql-246de]:
Creating Service: OK
Binding Service [postgresql-246de]: OK
Uploading Application:
Checking for available resources: OK
Processing resources: OK
Packing application: OK
Uploading (1M): OK
Push Status: OK
Staging Application: OK
Starting Application: OK
And Kandan should be available on your Cloud Foundry backend now!
<hr>
# <a name="heroku"></a>Heroku
You'll need to have the [heroku CLI](https://github.com/heroku/heroku) installed and to have an existing [heroku account](https://api.heroku.com/signup). Assuming that, this should work reliably on Heroku:
git clone https://github.com/kandanapp/kandan.git
cd kandan
heroku create __appname__ # appname is optional
git push heroku master
heroku run rake db:migrate kandan:bootstrap && heroku open
echo "Done, go forth and chat!"
# Not too bad
If you want emails to work (forgotten passwords, etc), you'll also need to add a Heroku email add-on to your app. For example, to add SendGrid:
heroku addons:add sendgrid:starter
After you add an email provider to your Heroku app, you'll also need to setup your production.rb file to look similar to this (using SendGrid again as an example):
config.action_mailer.default_url_options = { :host => "yourapp.herokuapp.com" } (Or whatever connected to your heroku app)
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.smtp_settings = {
address: "smtp.sendgrid.net",
port: 25,
domain: "example.com",
authentication: "plain",
user_name: ENV["SENDGRID_USERNAME"],
password: ENV["SENDGRID_PASSWORD"]
}
### Integrate Kandan on Heroku with your Amazon S3_BUCKET ( [Heroku article on AWS S3 to store static assets and file uploads](https://devcenter.heroku.com/articles/s3) ). Run the following line, replacing the the global variable values with your own:
heroku config:add S3_ACCESS_KEY_ID=abc S3_SECRET_ACCESS_KEY=xyz S3_BUCKET=bucket_name
If successful you should get a response similar to:
Setting config vars and restarting myapp... done, v12
S3_ACCESS_KEY_ID: xxx
S3_SECRET_ACCESS_KEY: xxxx
S3_BUCKET: bucket_name
Your app should be up and running now. The default admin user is `Admin` with password `kandanappadmin`, or you can sign up as another user.
<hr>
# <a name="dotcloud"></a>dotCloud
Looking for community help here.
<hr>
# <a name="appfog"></a>AppFog
You'll need an [AppFog account](https://www.appfog.com/) and the [af command line tool](https://docs.appfog.com/getting-started/af-cli) installed. Once that's all set up, login from the command line: `af login`. You'll be prompted for the username/password you set on AppFog. You're returned to your operating system's command prompt. It's not a terminal emulator.
If you want to use PostgreSQL rather than MySQL, provision the service on the Services page of the [console](https://console.appfog.com). Note the name of your database and app name on the console and substitute as appropriate.
git clone https://github.com/kandanapp/kandan.git
cd kandan
bundle install
bundle exec rake assets:precompile
af push your_app_name --path . --instances 1 --mem 256M --runtime ruby19
You'll answer a few questions; you'll probably get an error at the end about an invalid app description. That's okay, we'll fix that next:
Detected a Rails Application, is this correct? [Yn]: y
1: AWS US East - Virginia
2: AWS EU West - Ireland
3: AWS Asia SE - Singapore
4: Rackspace AZ 1 - Dallas
5: HP AZ 2 - Las Vegas
Select Infrastructure: 1
Application Deployed URL [<your_app_name>.aws.af.cm]: <your_app_name>
Memory reservation (128M, 256M, 512M, 1G, 2G) [256M]:
How many instances? [1]:
Bind existing services to '<your_app_name>'? [yN]: y
1: kandan_production
2: <your_app_name>-mysql-12781
Which one?: 1
Bind another? [yN]: n
Create services to bind to '<your_app_name>'? [yN]:
Would you like to save this configuration? [yN]: y
Manifest written to manifest.yml.
Creating Application: Error 300: Invalid application description
If you get the invalid app description, open manifest.yml in a text editor and remove the space from the description. (It defaults to Rails Application, which causes the error.) Then, at the terminal:
af update <your_app_name>
And you should also restart the app on AppFog (in the console). Then, Kandan should be available on your AppFox backend now! With your browser, visit the domain name assigned to you by AppFog (or create a CNAME record at your DNS provider to use an alternate).
<hr>
# <a name="standalone-server"></a>Stand Alone Server
If you're looking to install Kandan on a private server, or to develop locally for lemonodor fame, then here is the path you must follow, young hero:
You still need kandan (from above)
git clone https://github.com/kandanapp/kandan.git
cd kandan
Lots of the gems require other libraries:
sudo apt-get install ruby1.9.1-dev ruby-bundler libxslt-dev libxml2-dev libpq-dev libsqlite3-dev
Some gems build native extensions:
sudo apt-get install gcc g++ make
For development-mode
sudo apt-get install nodejs # (execjs needs an execution environment)
gem install execjs # (Could possibly be added to the gemfile in the assets group)
Install the required gems:
bundle install
You can use the default database.yml to get started in development. For production you'll need to edit config/database.yml to add something like this:
production:
adapter: postgresql
host: localhost
database: kandan_production
pool: 5
timeout: 5000
# You might need these depending on your Postgres auth setup.
username: kandan
password: something
Now, bootstrap the install (you can omit the db:create step if you have already created the DB referenced above):
bundle exec rake db:create db:migrate kandan:bootstrap
If you plan to serve the app directly from Thin (rather than through a proxy), you will need to configure Rails to serve assets in the production environment. In config/environments/production.rb:
config.serve_static_assets = true
Start the server
bundle exec thin start
Your app should be up and running now. The default admin user is `Admin` with password `kandanappadmin`, or you can sign up as another user.
| johanasplund/skamchat | DEPLOY.md | Markdown | agpl-3.0 | 9,584 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2008 - 2014 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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 full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// check CompressedSparsityPattern::copy constructor with offdiagonals
#include "sparsity_pattern_common.h"
int main ()
{
std::ofstream logfile("output");
logfile.setf(std::ios::fixed);
deallog << std::setprecision(3);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
copy_with_offdiagonals_2<CompressedSparsityPattern> ();
}
| johntfoster/dealii | tests/lac/compressed_sparsity_pattern_05.cc | C++ | lgpl-2.1 | 1,031 |
/*
* 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.camel.util.json;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class JsonSimpleOrderedTest {
@Test
public void testOrdered() throws Exception {
InputStream is = new FileInputStream("src/test/resources/bean.json");
String json = loadText(is);
JsonObject output = Jsoner.deserialize(json, new JsonObject());
assertNotNull(output);
// should preserve order
Map<?, ?> map = output.getMap("component");
assertTrue(map instanceof LinkedHashMap);
Iterator<?> it = map.keySet().iterator();
assertEquals("kind", it.next());
assertEquals("scheme", it.next());
assertEquals("syntax", it.next());
assertEquals("title", it.next());
assertEquals("description", it.next());
assertEquals("label", it.next());
assertEquals("deprecated", it.next());
assertEquals("deprecationNote", it.next());
assertEquals("async", it.next());
assertEquals("consumerOnly", it.next());
assertEquals("producerOnly", it.next());
assertEquals("lenientProperties", it.next());
assertEquals("javaType", it.next());
assertEquals("firstVersion", it.next());
assertEquals("groupId", it.next());
assertEquals("artifactId", it.next());
assertEquals("version", it.next());
assertFalse(it.hasNext());
}
public static String loadText(InputStream in) throws IOException {
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(in);
try {
BufferedReader reader = new BufferedReader(isr);
while (true) {
String line = reader.readLine();
if (line == null) {
line = builder.toString();
return line;
}
builder.append(line);
builder.append("\n");
}
} finally {
isr.close();
in.close();
}
}
}
| nikhilvibhav/camel | tooling/camel-util-json/src/test/java/org/apache/camel/util/json/JsonSimpleOrderedTest.java | Java | apache-2.0 | 3,327 |
// @allowJs: true
// @checkJs: true
// @noEmit: true
// @Filename: templateTagOnClasses.js
/**
* @template T
* @typedef {(t: T) => T} Id
*/
/** @template T */
class Foo {
/** @typedef {(t: T) => T} Id2 */
/** @param {T} x */
constructor (x) {
this.a = x
}
/**
*
* @param {T} x
* @param {Id<T>} y
* @param {Id2} alpha
* @return {T}
*/
foo(x, y, alpha) {
return alpha(y(x))
}
}
var f = new Foo(1)
var g = new Foo(false)
f.a = g.a
| weswigham/TypeScript | tests/cases/conformance/jsdoc/jsdocTemplateClass.ts | TypeScript | apache-2.0 | 508 |
"""Extension argument processing code
"""
__all__ = ['Message', 'NamespaceMap', 'no_default', 'registerNamespaceAlias',
'OPENID_NS', 'BARE_NS', 'OPENID1_NS', 'OPENID2_NS', 'SREG_URI',
'IDENTIFIER_SELECT']
import copy
import warnings
import urllib
from openid import oidutil
from openid import kvform
try:
ElementTree = oidutil.importElementTree()
except ImportError:
# No elementtree found, so give up, but don't fail to import,
# since we have fallbacks.
ElementTree = None
# This doesn't REALLY belong here, but where is better?
IDENTIFIER_SELECT = 'http://specs.openid.net/auth/2.0/identifier_select'
# URI for Simple Registration extension, the only commonly deployed
# OpenID 1.x extension, and so a special case
SREG_URI = 'http://openid.net/sreg/1.0'
# The OpenID 1.X namespace URI
OPENID1_NS = 'http://openid.net/signon/1.0'
THE_OTHER_OPENID1_NS = 'http://openid.net/signon/1.1'
OPENID1_NAMESPACES = OPENID1_NS, THE_OTHER_OPENID1_NS
# The OpenID 2.0 namespace URI
OPENID2_NS = 'http://specs.openid.net/auth/2.0'
# The namespace consisting of pairs with keys that are prefixed with
# "openid." but not in another namespace.
NULL_NAMESPACE = oidutil.Symbol('Null namespace')
# The null namespace, when it is an allowed OpenID namespace
OPENID_NS = oidutil.Symbol('OpenID namespace')
# The top-level namespace, excluding all pairs with keys that start
# with "openid."
BARE_NS = oidutil.Symbol('Bare namespace')
# Limit, in bytes, of identity provider and return_to URLs, including
# response payload. See OpenID 1.1 specification, Appendix D.
OPENID1_URL_LIMIT = 2047
# All OpenID protocol fields. Used to check namespace aliases.
OPENID_PROTOCOL_FIELDS = [
'ns', 'mode', 'error', 'return_to', 'contact', 'reference',
'signed', 'assoc_type', 'session_type', 'dh_modulus', 'dh_gen',
'dh_consumer_public', 'claimed_id', 'identity', 'realm',
'invalidate_handle', 'op_endpoint', 'response_nonce', 'sig',
'assoc_handle', 'trust_root', 'openid',
]
class UndefinedOpenIDNamespace(ValueError):
"""Raised if the generic OpenID namespace is accessed when there
is no OpenID namespace set for this message."""
class InvalidOpenIDNamespace(ValueError):
"""Raised if openid.ns is not a recognized value.
For recognized values, see L{Message.allowed_openid_namespaces}
"""
def __str__(self):
s = "Invalid OpenID Namespace"
if self.args:
s += " %r" % (self.args[0],)
return s
# Sentinel used for Message implementation to indicate that getArg
# should raise an exception instead of returning a default.
no_default = object()
# Global namespace / alias registration map. See
# registerNamespaceAlias.
registered_aliases = {}
class NamespaceAliasRegistrationError(Exception):
"""
Raised when an alias or namespace URI has already been registered.
"""
pass
def registerNamespaceAlias(namespace_uri, alias):
"""
Registers a (namespace URI, alias) mapping in a global namespace
alias map. Raises NamespaceAliasRegistrationError if either the
namespace URI or alias has already been registered with a
different value. This function is required if you want to use a
namespace with an OpenID 1 message.
"""
global registered_aliases
if registered_aliases.get(alias) == namespace_uri:
return
if namespace_uri in registered_aliases.values():
raise NamespaceAliasRegistrationError, \
'Namespace uri %r already registered' % (namespace_uri,)
if alias in registered_aliases:
raise NamespaceAliasRegistrationError, \
'Alias %r already registered' % (alias,)
registered_aliases[alias] = namespace_uri
class Message(object):
"""
In the implementation of this object, None represents the global
namespace as well as a namespace with no key.
@cvar namespaces: A dictionary specifying specific
namespace-URI to alias mappings that should be used when
generating namespace aliases.
@ivar ns_args: two-level dictionary of the values in this message,
grouped by namespace URI. The first level is the namespace
URI.
"""
allowed_openid_namespaces = [OPENID1_NS, THE_OTHER_OPENID1_NS, OPENID2_NS]
def __init__(self, openid_namespace=None):
"""Create an empty Message.
@raises InvalidOpenIDNamespace: if openid_namespace is not in
L{Message.allowed_openid_namespaces}
"""
self.args = {}
self.namespaces = NamespaceMap()
if openid_namespace is None:
self._openid_ns_uri = None
else:
implicit = openid_namespace in OPENID1_NAMESPACES
self.setOpenIDNamespace(openid_namespace, implicit)
def fromPostArgs(cls, args):
"""Construct a Message containing a set of POST arguments.
"""
self = cls()
# Partition into "openid." args and bare args
openid_args = {}
for key, value in args.items():
if isinstance(value, list):
raise TypeError("query dict must have one value for each key, "
"not lists of values. Query is %r" % (args,))
try:
prefix, rest = key.split('.', 1)
except ValueError:
prefix = None
if prefix != 'openid':
self.args[(BARE_NS, key)] = value
else:
openid_args[rest] = value
self._fromOpenIDArgs(openid_args)
return self
fromPostArgs = classmethod(fromPostArgs)
def fromOpenIDArgs(cls, openid_args):
"""Construct a Message from a parsed KVForm message.
@raises InvalidOpenIDNamespace: if openid.ns is not in
L{Message.allowed_openid_namespaces}
"""
self = cls()
self._fromOpenIDArgs(openid_args)
return self
fromOpenIDArgs = classmethod(fromOpenIDArgs)
def _fromOpenIDArgs(self, openid_args):
ns_args = []
# Resolve namespaces
for rest, value in openid_args.iteritems():
try:
ns_alias, ns_key = rest.split('.', 1)
except ValueError:
ns_alias = NULL_NAMESPACE
ns_key = rest
if ns_alias == 'ns':
self.namespaces.addAlias(value, ns_key)
elif ns_alias == NULL_NAMESPACE and ns_key == 'ns':
# null namespace
self.setOpenIDNamespace(value, False)
else:
ns_args.append((ns_alias, ns_key, value))
# Implicitly set an OpenID namespace definition (OpenID 1)
if not self.getOpenIDNamespace():
self.setOpenIDNamespace(OPENID1_NS, True)
# Actually put the pairs into the appropriate namespaces
for (ns_alias, ns_key, value) in ns_args:
ns_uri = self.namespaces.getNamespaceURI(ns_alias)
if ns_uri is None:
# we found a namespaced arg without a namespace URI defined
ns_uri = self._getDefaultNamespace(ns_alias)
if ns_uri is None:
ns_uri = self.getOpenIDNamespace()
ns_key = '%s.%s' % (ns_alias, ns_key)
else:
self.namespaces.addAlias(ns_uri, ns_alias, implicit=True)
self.setArg(ns_uri, ns_key, value)
def _getDefaultNamespace(self, mystery_alias):
"""OpenID 1 compatibility: look for a default namespace URI to
use for this alias."""
global registered_aliases
# Only try to map an alias to a default if it's an
# OpenID 1.x message.
if self.isOpenID1():
return registered_aliases.get(mystery_alias)
else:
return None
def setOpenIDNamespace(self, openid_ns_uri, implicit):
"""Set the OpenID namespace URI used in this message.
@raises InvalidOpenIDNamespace: if the namespace is not in
L{Message.allowed_openid_namespaces}
"""
if openid_ns_uri not in self.allowed_openid_namespaces:
raise InvalidOpenIDNamespace(openid_ns_uri)
self.namespaces.addAlias(openid_ns_uri, NULL_NAMESPACE, implicit)
self._openid_ns_uri = openid_ns_uri
def getOpenIDNamespace(self):
return self._openid_ns_uri
def isOpenID1(self):
return self.getOpenIDNamespace() in OPENID1_NAMESPACES
def isOpenID2(self):
return self.getOpenIDNamespace() == OPENID2_NS
def fromKVForm(cls, kvform_string):
"""Create a Message from a KVForm string"""
return cls.fromOpenIDArgs(kvform.kvToDict(kvform_string))
fromKVForm = classmethod(fromKVForm)
def copy(self):
return copy.deepcopy(self)
def toPostArgs(self):
"""Return all arguments with openid. in front of namespaced arguments.
"""
args = {}
# Add namespace definitions to the output
for ns_uri, alias in self.namespaces.iteritems():
if self.namespaces.isImplicit(ns_uri):
continue
if alias == NULL_NAMESPACE:
ns_key = 'openid.ns'
else:
ns_key = 'openid.ns.' + alias
args[ns_key] = oidutil.toUnicode(ns_uri).encode('UTF-8')
for (ns_uri, ns_key), value in self.args.iteritems():
key = self.getKey(ns_uri, ns_key)
# Ensure the resulting value is an UTF-8 encoded bytestring.
args[key] = oidutil.toUnicode(value).encode('UTF-8')
return args
def toArgs(self):
"""Return all namespaced arguments, failing if any
non-namespaced arguments exist."""
# FIXME - undocumented exception
post_args = self.toPostArgs()
kvargs = {}
for k, v in post_args.iteritems():
if not k.startswith('openid.'):
raise ValueError(
'This message can only be encoded as a POST, because it '
'contains arguments that are not prefixed with "openid."')
else:
kvargs[k[7:]] = v
return kvargs
def toFormMarkup(self, action_url, form_tag_attrs=None,
submit_text=u"Continue"):
"""Generate HTML form markup that contains the values in this
message, to be HTTP POSTed as x-www-form-urlencoded UTF-8.
@param action_url: The URL to which the form will be POSTed
@type action_url: str
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@type form_tag_attrs: {unicode: unicode}
@param submit_text: The text that will appear on the submit
button for this form.
@type submit_text: unicode
@returns: A string containing (X)HTML markup for a form that
encodes the values in this Message object.
@rtype: str or unicode
"""
if ElementTree is None:
raise RuntimeError('This function requires ElementTree.')
assert action_url is not None
form = ElementTree.Element(u'form')
if form_tag_attrs:
for name, attr in form_tag_attrs.iteritems():
form.attrib[name] = attr
form.attrib[u'action'] = oidutil.toUnicode(action_url)
form.attrib[u'method'] = u'post'
form.attrib[u'accept-charset'] = u'UTF-8'
form.attrib[u'enctype'] = u'application/x-www-form-urlencoded'
for name, value in self.toPostArgs().iteritems():
attrs = {u'type': u'hidden',
u'name': oidutil.toUnicode(name),
u'value': oidutil.toUnicode(value)}
form.append(ElementTree.Element(u'input', attrs))
submit = ElementTree.Element(u'input',
{u'type':'submit', u'value':oidutil.toUnicode(submit_text)})
form.append(submit)
return ElementTree.tostring(form, encoding='utf-8')
def toURL(self, base_url):
"""Generate a GET URL with the parameters in this message
attached as query parameters."""
return oidutil.appendArgs(base_url, self.toPostArgs())
def toKVForm(self):
"""Generate a KVForm string that contains the parameters in
this message. This will fail if the message contains arguments
outside of the 'openid.' prefix.
"""
return kvform.dictToKV(self.toArgs())
def toURLEncoded(self):
"""Generate an x-www-urlencoded string"""
args = self.toPostArgs().items()
args.sort()
return urllib.urlencode(args)
def _fixNS(self, namespace):
"""Convert an input value into the internally used values of
this object
@param namespace: The string or constant to convert
@type namespace: str or unicode or BARE_NS or OPENID_NS
"""
if namespace == OPENID_NS:
if self._openid_ns_uri is None:
raise UndefinedOpenIDNamespace('OpenID namespace not set')
else:
namespace = self._openid_ns_uri
if namespace != BARE_NS and type(namespace) not in [str, unicode]:
raise TypeError(
"Namespace must be BARE_NS, OPENID_NS or a string. got %r"
% (namespace,))
if namespace != BARE_NS and ':' not in namespace:
fmt = 'OpenID 2.0 namespace identifiers SHOULD be URIs. Got %r'
warnings.warn(fmt % (namespace,), DeprecationWarning)
if namespace == 'sreg':
fmt = 'Using %r instead of "sreg" as namespace'
warnings.warn(fmt % (SREG_URI,), DeprecationWarning,)
return SREG_URI
return namespace
def hasKey(self, namespace, ns_key):
namespace = self._fixNS(namespace)
return (namespace, ns_key) in self.args
def getKey(self, namespace, ns_key):
"""Get the key for a particular namespaced argument"""
namespace = self._fixNS(namespace)
if namespace == BARE_NS:
return ns_key
ns_alias = self.namespaces.getAlias(namespace)
# No alias is defined, so no key can exist
if ns_alias is None:
return None
if ns_alias == NULL_NAMESPACE:
tail = ns_key
else:
tail = '%s.%s' % (ns_alias, ns_key)
return 'openid.' + tail
def getArg(self, namespace, key, default=None):
"""Get a value for a namespaced key.
@param namespace: The namespace in the message for this key
@type namespace: str
@param key: The key to get within this namespace
@type key: str
@param default: The value to use if this key is absent from
this message. Using the special value
openid.message.no_default will result in this method
raising a KeyError instead of returning the default.
@rtype: str or the type of default
@raises KeyError: if default is no_default
@raises UndefinedOpenIDNamespace: if the message has not yet
had an OpenID namespace set
"""
namespace = self._fixNS(namespace)
args_key = (namespace, key)
try:
return self.args[args_key]
except KeyError:
if default is no_default:
raise KeyError((namespace, key))
else:
return default
def getArgs(self, namespace):
"""Get the arguments that are defined for this namespace URI
@returns: mapping from namespaced keys to values
@returntype: dict
"""
namespace = self._fixNS(namespace)
return dict([
(ns_key, value)
for ((pair_ns, ns_key), value)
in self.args.iteritems()
if pair_ns == namespace
])
def updateArgs(self, namespace, updates):
"""Set multiple key/value pairs in one call
@param updates: The values to set
@type updates: {unicode:unicode}
"""
namespace = self._fixNS(namespace)
for k, v in updates.iteritems():
self.setArg(namespace, k, v)
def setArg(self, namespace, key, value):
"""Set a single argument in this namespace"""
assert key is not None
assert value is not None
namespace = self._fixNS(namespace)
self.args[(namespace, key)] = value
if not (namespace is BARE_NS):
self.namespaces.add(namespace)
def delArg(self, namespace, key):
namespace = self._fixNS(namespace)
del self.args[(namespace, key)]
def __repr__(self):
return "<%s.%s %r>" % (self.__class__.__module__,
self.__class__.__name__,
self.args)
def __eq__(self, other):
return self.args == other.args
def __ne__(self, other):
return not (self == other)
def getAliasedArg(self, aliased_key, default=None):
if aliased_key == 'ns':
return self.getOpenIDNamespace()
if aliased_key.startswith('ns.'):
uri = self.namespaces.getNamespaceURI(aliased_key[3:])
if uri is None:
if default == no_default:
raise KeyError
else:
return default
else:
return uri
try:
alias, key = aliased_key.split('.', 1)
except ValueError:
# need more than x values to unpack
ns = None
else:
ns = self.namespaces.getNamespaceURI(alias)
if ns is None:
key = aliased_key
ns = self.getOpenIDNamespace()
return self.getArg(ns, key, default)
class NamespaceMap(object):
"""Maintains a bijective map between namespace uris and aliases.
"""
def __init__(self):
self.alias_to_namespace = {}
self.namespace_to_alias = {}
self.implicit_namespaces = []
def getAlias(self, namespace_uri):
return self.namespace_to_alias.get(namespace_uri)
def getNamespaceURI(self, alias):
return self.alias_to_namespace.get(alias)
def iterNamespaceURIs(self):
"""Return an iterator over the namespace URIs"""
return iter(self.namespace_to_alias)
def iterAliases(self):
"""Return an iterator over the aliases"""
return iter(self.alias_to_namespace)
def iteritems(self):
"""Iterate over the mapping
@returns: iterator of (namespace_uri, alias)
"""
return self.namespace_to_alias.iteritems()
def addAlias(self, namespace_uri, desired_alias, implicit=False):
"""Add an alias from this namespace URI to the desired alias
"""
# Check that desired_alias is not an openid protocol field as
# per the spec.
assert desired_alias not in OPENID_PROTOCOL_FIELDS, \
"%r is not an allowed namespace alias" % (desired_alias,)
# Check that desired_alias does not contain a period as per
# the spec.
if type(desired_alias) in [str, unicode]:
assert '.' not in desired_alias, \
"%r must not contain a dot" % (desired_alias,)
# Check that there is not a namespace already defined for
# the desired alias
current_namespace_uri = self.alias_to_namespace.get(desired_alias)
if (current_namespace_uri is not None
and current_namespace_uri != namespace_uri):
fmt = ('Cannot map %r to alias %r. '
'%r is already mapped to alias %r')
msg = fmt % (
namespace_uri,
desired_alias,
current_namespace_uri,
desired_alias)
raise KeyError(msg)
# Check that there is not already a (different) alias for
# this namespace URI
alias = self.namespace_to_alias.get(namespace_uri)
if alias is not None and alias != desired_alias:
fmt = ('Cannot map %r to alias %r. '
'It is already mapped to alias %r')
raise KeyError(fmt % (namespace_uri, desired_alias, alias))
assert (desired_alias == NULL_NAMESPACE or
type(desired_alias) in [str, unicode]), repr(desired_alias)
assert namespace_uri not in self.implicit_namespaces
self.alias_to_namespace[desired_alias] = namespace_uri
self.namespace_to_alias[namespace_uri] = desired_alias
if implicit:
self.implicit_namespaces.append(namespace_uri)
return desired_alias
def add(self, namespace_uri):
"""Add this namespace URI to the mapping, without caring what
alias it ends up with"""
# See if this namespace is already mapped to an alias
alias = self.namespace_to_alias.get(namespace_uri)
if alias is not None:
return alias
# Fall back to generating a numerical alias
i = 0
while True:
alias = 'ext' + str(i)
try:
self.addAlias(namespace_uri, alias)
except KeyError:
i += 1
else:
return alias
assert False, "Not reached"
def isDefined(self, namespace_uri):
return namespace_uri in self.namespace_to_alias
def __contains__(self, namespace_uri):
return self.isDefined(namespace_uri)
def isImplicit(self, namespace_uri):
return namespace_uri in self.implicit_namespaces
| gquirozbogner/contentbox-master | third_party/openid/message.py | Python | apache-2.0 | 21,795 |
# Apipie DSL functions.
module Apipie
# DSL is a module that provides #api, #error, #param, #error.
module DSL
module Base
attr_reader :apipie_resource_descriptions, :api_params
private
def _apipie_dsl_data
@_apipie_dsl_data ||= _apipie_dsl_data_init
end
def _apipie_dsl_data_clear
@_apipie_dsl_data = nil
end
def _apipie_dsl_data_init
@_apipie_dsl_data = {
:api => false,
:api_args => [],
:api_from_routes => nil,
:errors => [],
:params => [],
:headers => [],
:resouce_id => nil,
:short_description => nil,
:description => nil,
:examples => [],
:see => [],
:formats => nil,
:api_versions => [],
:meta => nil,
:show => true
}
end
end
module Resource
# by default, the resource id is derived from controller_name
# it can be overwritten with.
#
# resource_id "my_own_resource_id"
def resource_id(resource_id)
Apipie.set_resource_id(@controller, resource_id)
end
def name(name)
_apipie_dsl_data[:resource_name] = name
end
def api_base_url(url)
_apipie_dsl_data[:api_base_url] = url
end
def short(short)
_apipie_dsl_data[:short_description] = short
end
alias :short_description :short
def path(path)
_apipie_dsl_data[:path] = path
end
def app_info(app_info)
_apipie_dsl_data[:app_info] = app_info
end
end
module Action
def def_param_group(name, &block)
Apipie.add_param_group(self, name, &block)
end
#
# # load paths from routes and don't provide description
# api
#
def api(method, path, desc = nil, options={}) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:api] = true
_apipie_dsl_data[:api_args] << [method, path, desc, options]
end
# # load paths from routes
# api! "short description",
#
def api!(desc = nil, options={}) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:api] = true
_apipie_dsl_data[:api_from_routes] = { :desc => desc, :options =>options }
end
# Reference other similar method
#
# api :PUT, '/articles/:id'
# see "articles#create"
# def update; end
def see(*args)
return unless Apipie.active_dsl?
_apipie_dsl_data[:see] << args
end
# Show some example of what does the described
# method return.
def example(example) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:examples] << example.strip_heredoc
end
# Determine if the method should be included
# in the documentation
def show(show)
return unless Apipie.active_dsl?
_apipie_dsl_data[:show] = show
end
# Describe whole resource
#
# Example:
# api :desc => "Show user profile", :path => "/users/", :version => '1.0 - 3.4.2012'
# param :id, Fixnum, :desc => "User ID", :required => true
# desc <<-EOS
# Long description...
# EOS
def resource_description(options = {}, &block) #:doc:
return unless Apipie.active_dsl?
raise ArgumentError, "Block expected" unless block_given?
dsl_data = ResourceDescriptionDsl.eval_dsl(self, &block)
versions = dsl_data[:api_versions]
@apipie_resource_descriptions = versions.map do |version|
Apipie.define_resource_description(self, version, dsl_data)
end
Apipie.set_controller_versions(self, versions)
end
end
module Common
def api_versions(*versions)
_apipie_dsl_data[:api_versions].concat(versions)
end
alias :api_version :api_versions
# Describe the next method.
#
# Example:
# desc "print hello world"
# def hello_world
# puts "hello world"
# end
#
def desc(description) #:doc:
return unless Apipie.active_dsl?
if _apipie_dsl_data[:description]
raise "Double method description."
end
_apipie_dsl_data[:description] = description
end
alias :description :desc
alias :full_description :desc
# describe next method with document in given path
# in convension, these doc located under "#{Rails.root}/doc"
# Example:
# document "hello_world.md"
# def hello_world
# puts "hello world"
# end
def document path
content = File.open(File.join(Rails.root, Apipie.configuration.doc_path, path)).read
desc content
end
# Describe available request/response formats
#
# formats ['json', 'jsonp', 'xml']
def formats(formats) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:formats] = formats
end
# Describe additional metadata
#
# meta :author => { :name => 'John', :surname => 'Doe' }
def meta(meta) #:doc:
_apipie_dsl_data[:meta] = meta
end
# Describe possible errors
#
# Example:
# error :desc => "speaker is sleeping", :code => 500, :meta => [:some, :more, :data]
# error 500, "speaker is sleeping"
# def hello_world
# return 500 if self.speaker.sleeping?
# puts "hello world"
# end
#
def error(code_or_options, desc=nil, options={}) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:errors] << [code_or_options, desc, options]
end
def _apipie_define_validators(description)
# [re]define method only if validation is turned on
if description && (Apipie.configuration.validate == true ||
Apipie.configuration.validate == :implicitly ||
Apipie.configuration.validate == :explicitly)
_apipie_save_method_params(description.method, description.params)
unless instance_methods.include?(:apipie_validations)
define_method(:apipie_validations) do
method_params = self.class._apipie_get_method_params(action_name)
if Apipie.configuration.validate_presence?
method_params.each do |_, param|
# check if required parameters are present
raise ParamMissing.new(param.name) if param.required && !params.has_key?(param.name)
end
end
if Apipie.configuration.validate_value?
method_params.each do |_, param|
# params validations
param.validate(params[:"#{param.name}"]) if params.has_key?(param.name)
end
end
# Only allow params passed in that are defined keys in the api
# Auto skip the default params (format, controller, action)
if Apipie.configuration.validate_key?
params.reject{|k,_| %w[format controller action].include?(k.to_s) }.each_key do |param|
# params allowed
raise UnknownParam.new(param) if method_params.select {|_,p| p.name.to_s == param.to_s}.empty?
end
end
if Apipie.configuration.process_value?
@api_params ||= {}
method_params.each do |_, param|
# params processing
@api_params[param.as] = param.process_value(params[:"#{param.name}"]) if params.has_key?(param.name)
end
end
end
end
if (Apipie.configuration.validate == :implicitly || Apipie.configuration.validate == true)
old_method = instance_method(description.method)
define_method(description.method) do |*args|
apipie_validations
# run the original method code
old_method.bind(self).call(*args)
end
end
end
end
def _apipie_save_method_params(method, params)
@method_params ||= {}
@method_params[method] = params
end
def _apipie_get_method_params(method)
@method_params[method]
end
# Describe request header.
# Headers can't be validated with config.validate_presence = true
#
# Example:
# header 'ClientId', "client-id"
# def show
# render :text => headers['HTTP_CLIENT_ID']
# end
#
def header(header_name, description, options = {}) #:doc
return unless Apipie.active_dsl?
_apipie_dsl_data[:headers] << {
name: header_name,
description: description,
options: options
}
end
end
# this describes the params, it's in separate module because it's
# used in Validators as well
module Param
# Describe method's parameter
#
# Example:
# param :greeting, String, :desc => "arbitrary text", :required => true
# def hello_world(greeting)
# puts greeting
# end
#
def param(param_name, validator, desc_or_options = nil, options = {}, &block) #:doc:
return unless Apipie.active_dsl?
_apipie_dsl_data[:params] << [param_name,
validator,
desc_or_options,
options.merge(:param_group => @_current_param_group),
block]
end
# Reuses param group for this method. The definition is looked up
# in scope of this controller. If the group was defined in
# different controller, the second param can be used to specify it.
# when using action_aware parmas, you can specify :as =>
# :create or :update to explicitly say how it should behave
def param_group(name, scope_or_options = nil, options = {})
if scope_or_options.is_a? Hash
options.merge!(scope_or_options)
scope = options[:scope]
else
scope = scope_or_options
end
scope ||= _default_param_group_scope
@_current_param_group = {
:scope => scope,
:name => name,
:options => options,
:from_concern => scope.apipie_concern?
}
self.instance_exec(&Apipie.get_param_group(scope, name))
ensure
@_current_param_group = nil
end
# where the group definition should be looked up when no scope
# given. This is expected to return a controller.
def _default_param_group_scope
self
end
end
module Controller
include Apipie::DSL::Base
include Apipie::DSL::Common
include Apipie::DSL::Action
include Apipie::DSL::Param
# defines the substitutions to be made in the API paths deifned
# in concerns included. For example:
#
# There is this method defined in concern:
#
# api GET ':controller_path/:id'
# def show
# # ...
# end
#
# If you include the concern into some controller, you can
# specify the value for :controller_path like this:
#
# apipie_concern_subst(:controller_path => '/users')
# include ::Concerns::SampleController
#
# The resulting path will be '/users/:id'.
#
# It has to be specified before the concern is included.
#
# If not specified, the default predefined substitions are
#
# {:conroller_path => controller.controller_path,
# :resource_id => `resource_id_from_apipie` }
def apipie_concern_subst(subst_hash)
_apipie_concern_subst.merge!(subst_hash)
end
def _apipie_concern_subst
@_apipie_concern_subst ||= {:controller_path => self.controller_path,
:resource_id => Apipie.get_resource_name(self)}
end
def _apipie_perform_concern_subst(string)
return _apipie_concern_subst.reduce(string) do |ret, (key, val)|
ret.gsub(":#{key}", val)
end
end
def apipie_concern?
false
end
# create method api and redefine newly added method
def method_added(method_name) #:doc:
super
return if !Apipie.active_dsl? || !_apipie_dsl_data[:api]
return if _apipie_dsl_data[:api_args].blank? && _apipie_dsl_data[:api_from_routes].blank?
# remove method description if exists and create new one
Apipie.remove_method_description(self, _apipie_dsl_data[:api_versions], method_name)
description = Apipie.define_method_description(self, method_name, _apipie_dsl_data)
_apipie_dsl_data_clear
_apipie_define_validators(description)
ensure
_apipie_dsl_data_clear
end
end
module Concern
include Apipie::DSL::Base
include Apipie::DSL::Common
include Apipie::DSL::Action
include Apipie::DSL::Param
# the concern was included into a controller
def included(controller)
super
_apipie_concern_data.each do |method_name, _apipie_dsl_data|
# remove method description if exists and create new one
description = Apipie.define_method_description(controller, method_name, _apipie_dsl_data)
controller._apipie_define_validators(description)
end
end
def _apipie_concern_data
@_apipie_concern_data ||= []
end
def apipie_concern?
true
end
# create method api and redefine newly added method
def method_added(method_name) #:doc:
super
return if ! Apipie.active_dsl? || !_apipie_dsl_data[:api]
_apipie_concern_data << [method_name, _apipie_dsl_data.merge(:from_concern => true)]
ensure
_apipie_dsl_data_clear
end
end
class ResourceDescriptionDsl
include Apipie::DSL::Base
include Apipie::DSL::Common
include Apipie::DSL::Resource
include Apipie::DSL::Param
def initialize(controller)
@controller = controller
end
def _eval_dsl(&block)
instance_eval(&block)
return _apipie_dsl_data
end
# evaluates resource description DSL and returns results
def self.eval_dsl(controller, &block)
dsl_data = self.new(controller)._eval_dsl(&block)
if dsl_data[:api_versions].empty?
dsl_data[:api_versions] = Apipie.controller_versions(controller)
end
dsl_data
end
end
end # module DSL
end # module Apipie
| vassilevsky/apipie-rails | lib/apipie/dsl_definition.rb | Ruby | apache-2.0 | 14,932 |
/*
* 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 stubgenerator.traitStaticPropertiesStub;
public class JavaXImpl extends GroovyXImpl {
public static void main(String[] args) {
new JavaXImpl();
}
}
| jwagenleitner/incubator-groovy | src/test-resources/stubgenerator/traitStaticPropertiesStub/JavaXImpl.java | Java | apache-2.0 | 995 |
isClear = true;
function context(description, spec) {
describe(description, spec);
};
function build() {
$('body').append('<div id="element"></div>');
};
function buildDivTarget() {
$('body').append('<div id="hint"></div>');
};
function buildComboboxTarget() {
$('body').append(
'<select id="hint">' +
'<option value="Cancel this rating!">cancel hint default</option>' +
'<option value="cancel-hint-custom">cancel hint custom</option>' +
'<option value="">cancel number default</option>' +
'<option value="0">cancel number custom</option>' +
'<option value="bad">bad hint imutable</option>' +
'<option value="1">bad number imutable</option>' +
'<option value="targetText">targetText is setted without targetKeep</option>' +
'<option value="score: bad">targetFormat</option>' +
'</select>'
);
};
function buildTextareaTarget() {
$('body').append('<textarea id="hint"></textarea>');
};
function buildTextTarget() {
$('body').append('<input id="hint" type="text" />');
};
function clear() {
if (isClear) {
$('#element').remove();
$('#hint').remove();
}
};
describe('Raty', function() {
beforeEach(function() { build(); });
afterEach(function() { clear(); });
it ('has the right values', function() {
// given
var raty = $.fn.raty
// when
var opt = raty.defaults
// then
expect(opt.cancel).toBeFalsy();
expect(opt.cancelHint).toEqual('Cancel this rating!');
expect(opt.cancelOff).toEqual('cancel-off.png');
expect(opt.cancelOn).toEqual('cancel-on.png');
expect(opt.cancelPlace).toEqual('left');
expect(opt.click).toBeUndefined();
expect(opt.half).toBeFalsy();
expect(opt.halfShow).toBeTruthy();
expect(opt.hints).toContain('bad', 'poor', 'regular', 'good', 'gorgeous');
expect(opt.iconRange).toBeUndefined();
expect(opt.mouseover).toBeUndefined();
expect(opt.noRatedMsg).toEqual('Not rated yet!');
expect(opt.number).toBe(5);
expect(opt.path).toEqual('');
expect(opt.precision).toBeFalsy();
expect(opt.readOnly).toBeFalsy();
expect(opt.round.down).toEqual(.25);
expect(opt.round.full).toEqual(.6);
expect(opt.round.up).toEqual(.76);
expect(opt.score).toBeUndefined();
expect(opt.scoreName).toEqual('score');
expect(opt.single).toBeFalsy();
expect(opt.size).toBe(16);
expect(opt.space).toBeTruthy();
expect(opt.starHalf).toEqual('star-half.png');
expect(opt.starOff).toEqual('star-off.png');
expect(opt.starOn).toEqual('star-on.png');
expect(opt.target).toBeUndefined();
expect(opt.targetFormat).toEqual('{score}');
expect(opt.targetKeep).toBeFalsy();
expect(opt.targetText).toEqual('');
expect(opt.targetType).toEqual('hint');
expect(opt.width).toBeUndefined();
});
describe('common features', function() {
it ('is chainable', function() {
// given
var self = $('#element');
// when
var ref = self.raty();
// then
expect(ref).toBe(self);
});
it ('creates the default markup', function() {
// given
var self = $('#element');
// when
self.raty();
// then
var imgs = self.children('img'),
score = self.children('input');
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(score).toHaveAttr('type', 'hidden');
expect(score).toHaveAttr('name', 'score');
expect(score.val()).toEqual('');
});
});
describe('#star', function() {
it ('starts all off', function() {
// given
var self = $('#element');
// when
self.raty();
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
});
context('on :mouseover', function() {
it ('turns on the stars', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
// when
imgs.eq(4).mouseover();
// then
expect(imgs).toHaveAttr('src', 'star-on.png');
});
context('and :mouseout', function() {
it ('clears all stars', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
// when
imgs.eq(4).mouseover().mouseout();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
});
});
context('on rating', function() {
it ('changes the score', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
// when
imgs.eq(1).mouseover().click();
// then
expect(self.children('input')).toHaveValue(2);
});
context('on :mouseout', function() {
it ('keeps the stars on', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
// when
imgs.eq(4).mouseover().click().mouseout();
// then
expect(imgs).toHaveAttr('src', 'star-on.png');
});
});
});
});
describe('options', function() {
describe('#numberMax', function() {
it ('limits to 20 stars', function() {
// given
var self = $('#element').raty({ number: 50, score: 50 });
// when
var score = self.raty('score');
// then
expect(self.children('img').length).toEqual(20);
expect(self.children('input')).toHaveValue(20);
});
context('with custom numberMax', function() {
it ('chages the limit', function() {
// given
var self = $('#element').raty({ numberMax: 10, number: 50, score: 50 });
// when
var score = self.raty('score');
// then
expect(self.children('img').length).toEqual(10);
expect(self.children('input')).toHaveValue(10);
});
});
});
describe('#starOff', function() {
it ('changes the icons', function() {
// given
var self = $('#element');
// when
self.raty({ starOff: 'icon.png' });
// then
expect(self.children('img')).toHaveAttr('src', 'icon.png');
});
});
describe('#starOn', function() {
it ('changes the icons', function() {
// given
var self = $('#element').raty({ starOn: 'icon.png' }),
imgs = self.children('img');
// when
imgs.eq(3).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'icon.png');
expect(imgs.eq(1)).toHaveAttr('src', 'icon.png');
expect(imgs.eq(2)).toHaveAttr('src', 'icon.png');
expect(imgs.eq(3)).toHaveAttr('src', 'icon.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
});
describe('#iconRange', function() {
it ('uses icon intervals', function() {
// given
var self = $('#element');
// when
self.raty({
iconRange: [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
]
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png');
});
context('when off icon is not especified', function() {
it ('uses the :starOff icon', function() {
// given
var self = $('#element');
// when
self.raty({
iconRange: [
{ range: 2, on: 'on.png', off: 'off.png' },
{ range: 3, on: 'on.png', off: 'off.png' },
{ range: 4, on: 'on.png', off: 'off.png' },
{ range: 5, on: 'on.png' }
]
});
// then
expect(self.children('img').eq(4)).toHaveAttr('src', 'star-off.png');
});
});
context('on mouseover', function() {
it ('uses the on icon', function() {
// given
var self = $('#element').raty({
iconRange: [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
]
}),
imgs = self.children('img');
// when
imgs.eq(4).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'a.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd.png');
});
context('when on icon is not especified', function() {
it ('uses the :starOn icon', function() {
// given
var self = $('#element').raty({
iconRange: [
{ range: 2, off: 'off.png', on: 'on.png' },
{ range: 3, off: 'off.png', on: 'on.png' },
{ range: 4, off: 'off.png', on: 'on.png' },
{ range: 5, off: 'off.png' }
]
}),
imgs = self.children('img');
// when
imgs.eq(4).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'on.png');
expect(imgs.eq(1)).toHaveAttr('src', 'on.png');
expect(imgs.eq(2)).toHaveAttr('src', 'on.png');
expect(imgs.eq(3)).toHaveAttr('src', 'on.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-on.png');
});
});
});
context('on mouseout', function() {
it ('changes to off icons', function() {
// given
var self = $('#element').raty({
iconRange: [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' },
]
}),
imgs = self.children('img');
// when
imgs.eq(4).mouseover();
self.mouseleave();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png');
});
it ('keeps the score value', function() {
// given
var self = $('#element').raty({
iconRange : [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
],
score : 1
});
// when
self.children('img').eq(4).mouseover();
self.mouseleave();
// then
expect(self.children('input')).toHaveValue(1);
});
context('when off icon is not especified', function() {
it ('uses the :starOff icon', function() {
// given
var self = $('#element').raty({
iconRange: [
{ range: 2, on: 'on.png', off: 'off.png' },
{ range: 3, on: 'on.png', off: 'off.png' },
{ range: 4, on: 'on.png', off: 'off.png' },
{ range: 5, on: 'on.png' }
]
}),
img = self.children('img').eq(4);
// when
img.mouseover();
self.mouseleave();
// then
expect(img).toHaveAttr('src', 'star-off.png');
});
});
});
});
describe('#click', function() {
it ('has `this` as the self element', function() {
// given
var self = $('#element').raty({
click: function() {
$(this).data('self', this);
}
});
// when
self.children('img:first').mouseover().click();
// then
expect(self.data('self')).toBe(self);
});
it ('is called on star click', function() {
// given
var self = $('#element').raty({
click: function() {
$(this).data('clicked', true);
}
});
// when
self.children('img:first').mouseover().click();
// then
expect(self.data('clicked')).toBeTruthy();
});
it ('receives the score', function() {
// given
var self = $('#element').raty({
click: function(score) {
$(this).data('score', score);
}
});
// when
self.children('img:first').mouseover().click();
// then
expect(self.data('score')).toEqual(1);
});
context('with :cancel', function() {
it ('executes cancel click callback', function() {
// given
var self = $('#element').raty({
cancel: true,
click : function(score) {
$(this).data('score', null);
}
});
// when
self.children('.raty-cancel').mouseover().click().mouseleave();
// then
expect(self.data('score')).toBeNull();
});
});
});
describe('#score', function() {
it ('starts with value', function() {
// given
var self = $('#element');
// when
self.raty({ score: 1 });
// then
expect(self.children('input')).toHaveValue(1);
});
it ('turns on 1 stars', function() {
// given
var self = $('#element');
// when
self.raty({ score: 1 });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
it ('accepts callback', function() {
// given
var self = $('#element');
// when
self.raty({ score: function() { return 1; } });
// then
expect(self.raty('score')).toEqual(1);
});
context('with negative number', function() {
it ('gets none score', function() {
// given
var self = $('#element');
// when
self.raty({ score: -1 });
// then
expect(self.children('input').val()).toEqual('');
});
});
context('with :readOnly', function() {
it ('becomes readOnly too', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true });
// then
expect(self.children('input')).toHaveAttr('readonly', 'readonly');
});
});
});
describe('#scoreName', function() {
it ('changes the score field name', function() {
// given
var self = $('#element');
// when
self.raty({ scoreName: 'entity.score' });
// then
expect(self.children('input')).toHaveAttr('name', 'entity.score');
});
});
it ('accepts callback', function() {
// given
var self = $('#element');
// when
self.raty({ scoreName: function() { return 'custom'; } });
// then
expect(self.data('settings').scoreName).toEqual('custom');
});
describe('#readOnly', function() {
it ('Applies "Not rated yet!" on stars', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true });
// then
expect(self.children('img')).toHaveAttr('title', 'Not rated yet!');
});
it ('removes the pointer cursor', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true });
// then
expect(self).not.toHaveCss({ cursor: 'pointer' });
expect(self).not.toHaveCss({ cursor: 'default' });
});
it ('accepts callback', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: function() { return true; } });
// then
expect(self.data('settings').readOnly).toEqual(true);
});
it ('avoids trigger mouseover', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
// when
imgs.eq(1).mouseover();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
it ('avoids trigger click', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
// when
imgs.eq(1).mouseover().click().mouseleave();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
});
it ('avoids trigger mouseleave', function() {
// given
var self = $('#element').raty({
readOnly: true,
mouseout: function() {
$(this).data('mouseleave', true);
}
}),
imgs = self.children('img');
imgs.eq(1).mouseover();
// when
self.mouseleave();
// then
expect(self.data('mouseleave')).toBeFalsy();
});
context('with :score', function() {
context('as integer', function() {
it ('applies the score title on stars', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true, score: 3 });
// then
expect(self.children('img')).toHaveAttr('title', 'regular');
});
});
context('as float', function() {
it ('applies the integer score title on stars', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true, score: 3.1 });
// then
expect(self.children('img')).toHaveAttr('title', 'regular');
});
});
});
context('with :cancel', function() {
it ('hides the button', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, readOnly: true, path: '../lib/img' });
// then
expect(self.children('.raty-cancel')).toBeHidden();
});
});
});
describe('#hints', function() {
it ('changes the hints', function() {
// given
var self = $('#element');
// when
self.raty({ hints: ['1', '/', 'c', '-', '#'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 1);
expect(imgs.eq(1)).toHaveAttr('title', '/');
expect(imgs.eq(2)).toHaveAttr('title', 'c');
expect(imgs.eq(3)).toHaveAttr('title', '-');
expect(imgs.eq(4)).toHaveAttr('title', '#');
});
it ('receives the number of the star when is undefined', function() {
// given
var self = $('#element');
// when
self.raty({ hints: [undefined, 'a', 'b', 'c', 'd'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'a');
expect(imgs.eq(2)).toHaveAttr('title', 'b');
expect(imgs.eq(3)).toHaveAttr('title', 'c');
expect(imgs.eq(4)).toHaveAttr('title', 'd');
});
it ('receives empty when is empty string', function() {
// given
var self = $('#element');
// when
self.raty({ hints: ['', 'a', 'b', 'c', 'd'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', '');
expect(imgs.eq(1)).toHaveAttr('title', 'a');
expect(imgs.eq(2)).toHaveAttr('title', 'b');
expect(imgs.eq(3)).toHaveAttr('title', 'c');
expect(imgs.eq(4)).toHaveAttr('title', 'd');
});
it ('receives the number of the star when is null', function() {
// given
var self = $('#element');
// when
self.raty({ hints: [null, 'a', 'b', 'c', 'd'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 1);
expect(imgs.eq(1)).toHaveAttr('title', 'a');
expect(imgs.eq(2)).toHaveAttr('title', 'b');
expect(imgs.eq(3)).toHaveAttr('title', 'c');
expect(imgs.eq(4)).toHaveAttr('title', 'd');
});
context('whe has less hint than stars', function() {
it ('receives the default hint index', function() {
// given
var self = $('#element');
// when
self.raty({ hints: ['1', '2', '3', '4'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 1);
expect(imgs.eq(1)).toHaveAttr('title', 2);
expect(imgs.eq(2)).toHaveAttr('title', 3);
expect(imgs.eq(3)).toHaveAttr('title', 4);
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
});
});
context('whe has more stars than hints', function() {
it ('sets star number', function() {
// given
var self = $('#element');
// when
self.raty({ number: 6, hints: ['a', 'b', 'c', 'd', 'e'] });
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('title', 'a');
expect(imgs.eq(1)).toHaveAttr('title', 'b');
expect(imgs.eq(2)).toHaveAttr('title', 'c');
expect(imgs.eq(3)).toHaveAttr('title', 'd');
expect(imgs.eq(4)).toHaveAttr('title', 'e');
expect(imgs.eq(5)).toHaveAttr('title', 6);
});
});
});
describe('#mouseover', function() {
it ('receives the score as int', function() {
// given
var self = $('#element').raty({
mouseover: function(score) {
$(this).data('score', score);
}
});
// when
self.children('img:first').mouseover();
// then
expect(self.data('score')).toEqual(1);
});
it ('receives the event', function() {
// given
var self = $('#element').raty({
mouseover: function(score, evt) {
$(this).data('evt', evt);
}
});
// when
self.children('img:first').mouseover();
// then
expect(self.data('evt').type).toEqual('mouseover');
});
context('with :cancel', function() {
it ('receives null as score', function() {
// given
var self = $('#element').raty({
cancel : true,
mouseover : function(score) {
self.data('null', score);
}
});
// when
self.children('.raty-cancel').mouseover();
// then
expect(self.data('null')).toBeNull();
});
});
});
describe('#mouseout', function() {
it ('receives the score as int', function() {
// given
var self = $('#element').raty({
mouseout: function(score) {
$(this).data('score', score);
}
});
// when
self.children('img:first').mouseover().click().mouseout();
// then
expect(self.data('score')).toEqual(1);
});
it ('receives the event', function() {
// given
var self = $('#element').raty({
mouseout: function(score, evt) {
$(this).data('evt', evt);
}
});
// when
self.children('img:first').mouseover().click().mouseout();
// then
expect(self.data('evt').type).toEqual('mouseout');
});
context('without score setted', function() {
it ('pass undefined on callback', function() {
// given
var self = $('#element').raty({
cancel : true,
mouseout: function(score) {
self.data('undefined', score === undefined);
}
});
// when
self.children('img:first').mouseenter().mouseleave();
// then
expect(self.data('undefined')).toBeTruthy();
});
});
context('with :score rated', function() {
it ('pass the score on callback', function() {
// given
var self = $('#element').raty({
score : 1,
mouseout: function(score) {
self.data('score', score);
}
});
// when
self.children('img:first').mouseenter().mouseleave();
// then
expect(self.data('score')).toEqual(1);
});
});
context('with :cancel', function() {
it ('receives the event', function() {
// given
var self = $('#element').raty({
cancel : true,
mouseout: function(score, evt) {
$(this).data('evt', evt);
}
});
// when
self.children('.raty-cancel').mouseover().click().mouseout();
// then
expect(self.data('evt').type).toEqual('mouseout');
});
context('without score setted', function() {
it ('pass undefined on callback', function() {
// given
var self = $('#element').raty({
mouseout: function(score) {
self.data('undefined', score === undefined);
},
cancel : true
});
// when
self.children('.raty-cancel').mouseenter().mouseleave();
// then
expect(self.data('undefined')).toBeTruthy();
});
});
context('with :score rated', function() {
it ('pass the score on callback', function() {
// given
var self = $('#element').raty({
mouseout: function(score) {
self.data('score', score);
},
cancel : true,
score : 1
});
// when
self.children('.raty-cancel').mouseenter().mouseleave();
// then
expect(self.data('score')).toEqual(1);
});
});
});
});
describe('#number', function() {
it ('changes the number of stars', function() {
// given
var self = $('#element');
// when
self.raty({ number: 1 });
// then
expect(self.children('img').length).toEqual(1);
});
it ('accepts number as string', function() {
// given
var self = $('#element');
// when
self.raty({ number: '10' });
// then
expect(self.children('img').length).toEqual(10);
});
it ('accepts callback', function() {
// given
var self = $('#element');
// when
self.raty({ number: function() { return 1; } });
// then
expect(self.children('img').length).toEqual(1);
});
});
describe('#path', function() {
context('without last slash', function() {
it ('receives the slash', function() {
// given
var self = $('#element');
// when
self.raty({ path: 'path' });
// then
expect(self[0].opt.path).toEqual('path/');
});
});
context('with last slash', function() {
it ('keeps it', function() {
// given
var self = $('#element');
// when
self.raty({ path: 'path/' });
// then
expect(self[0].opt.path).toEqual('path/');
});
});
it ('changes the path', function() {
// given
var self = $('#element');
// when
self.raty({ path: 'path' });
// then
expect(self.children('img')).toHaveAttr('src', 'path/star-off.png');
});
context('without path', function() {
it ('sets receives empty', function() {
// given
var self = $('#element');
// when
self.raty({ path: null });
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
});
});
context('with :cancel', function() {
it ('changes the path', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, path: 'path' })
// then
expect(self.children('.raty-cancel')).toHaveAttr('src', 'path/cancel-off.png');
});
});
context('with :iconRange', function() {
it ('changes the path', function() {
// given
var self = $('#element');
// when
self.raty({
path : 'path',
iconRange: [{ range: 5 }]
});
// then
expect(self.children('img')).toHaveAttr('src', 'path/star-off.png');
});
});
});
describe('#cancelOff', function() {
it ('changes the icon', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, cancelOff: 'off.png' });
// then
expect(self.children('.raty-cancel')).toHaveAttr('src', 'off.png');
});
});
describe('#cancelOn', function() {
it ('changes the icon', function() {
// given
var self = $('#element').raty({ cancel: true, cancelOn: 'icon.png' });
// when
var cancel = self.children('.raty-cancel').mouseover();
// then
expect(cancel).toHaveAttr('src', 'icon.png');
});
});
describe('#cancelHint', function() {
it ('changes the cancel hint', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, cancelHint: 'hint' });
// then
expect(self.children('.raty-cancel')).toHaveAttr('title', 'hint');
});
});
describe('#cancelPlace', function() {
it ('changes the place off cancel button', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true, cancelPlace: 'right' });
// then
var cancel = self.children('img:last');
expect(cancel).toHaveClass('raty-cancel');
expect(cancel).toHaveAttr('title', 'Cancel this rating!');
expect(cancel).toHaveAttr('alt', 'x');
expect(cancel).toHaveAttr('src', 'cancel-off.png');
});
});
describe('#cancel', function() {
it ('creates the element', function() {
// given
var self = $('#element');
// when
self.raty({ cancel: true });
// then
var cancel = self.children('.raty-cancel');
expect(cancel).toHaveClass('raty-cancel');
expect(cancel).toHaveAttr('title', 'Cancel this rating!');
expect(cancel).toHaveAttr('alt', 'x');
expect(cancel).toHaveAttr('src', 'cancel-off.png');
});
context('on mouseover', function() {
it ('turns on', function() {
// given
var self = $('#element').raty({ cancel: true });
// when
var cancel = self.children('.raty-cancel').mouseover();
// then
expect(cancel).toHaveAttr('src', 'cancel-on.png');
});
context('with :score', function() {
it ('turns off the stars', function() {
// given
var self = $('#element').raty({ score: 3, cancel: true }),
imgs = self.children('img:not(.raty-cancel)');
// when
self.children('.raty-cancel').mouseover();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
});
});
context('when :mouseout', function() {
it ('turns on', function() {
// given
var self = $('#element').raty({ cancel: true });
// when
var cancel = self.children('.raty-cancel').mouseover().mouseout();
// then
expect(cancel).toHaveAttr('src', 'cancel-off.png');
});
context('with :score', function() {
it ('turns the star on again', function() {
// given
var self = $('#element').raty({ score: 4, cancel: true }),
imgs = self.children('img:not(.raty-cancel)');
// when
self.children('.raty-cancel').mouseover().mouseout();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(3)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
});
});
context('on click', function() {
it ('cancel the rating', function() {
// given
var self = $('#element').raty({ cancel: true, score: 1 });
// when
self.children('.raty-cancel').click().mouseout();
// then
var stars = self.children('img:not(.raty-cancel)');
expect(stars).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
});
});
context('when starts :readOnly', function() {
it ('starts hidden', function() {
// given
var self = $('#element').raty({ cancel: true, readOnly: true, path: '../img' });
// when
self.raty('readOnly', true);
// then
expect(self.children('.raty-cancel')).toBeHidden();
});
context('on click', function() {
it ('does not cancel the rating', function() {
// given
var self = $('#element').raty({ cancel: true, readOnly: true, score: 5 });
// when
self.children('.raty-cancel').click().mouseout();
// then
var stars = self.children('img:not(.raty-cancel)');
expect(stars).toHaveAttr('src', 'star-on.png');
expect(self.children('input').val()).toEqual('5');
});
});
});
context('when become :readOnly', function() {
it ('becomes hidden', function() {
// given
var self = $('#element').raty({ cancel: true, path: '../img' });
// when
self.raty('readOnly', true);
// then
expect(self.children('.raty-cancel')).toBeHidden();
});
});
});
describe('#targetType', function() {
beforeEach(function() { buildDivTarget(); });
context('with missing target', function() {
it ('throws error', function() {
// given
var self = $('#element');
// when
var lambda = function() { self.raty({ target: 'missing' }); };
// then
expect(lambda).toThrow(new Error('Target selector invalid or missing!'));
});
});
context('as hint', function() {
it ('receives the hint', function() {
// given
var self = $('#element').raty({ target: '#hint', targetType: 'hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveHtml('bad');
});
context('with :cancel', function() {
it ('receives the :cancelHint', function() {
// given
var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'hint' });
// when
self.children('.raty-cancel').mouseover();
// then
expect($('#hint')).toHaveHtml('Cancel this rating!');
});
});
});
context('as score', function() {
it ('receives the score', function() {
// given
var self = $('#element').raty({ target: '#hint', targetType: 'score' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveHtml(1);
});
context('with :cancel', function() {
it ('receives the :cancelHint', function() {
// given
var self = $('#element').raty({ cancel: true, target: '#hint', targetType: 'score' });
// when
self.children('.raty-cancel').mouseover();
// then
expect($('#hint')).toHaveHtml('Cancel this rating!');
});
});
});
});
describe('#targetText', function() {
beforeEach(function() { buildDivTarget(); });
it ('set target with none value', function() {
// given
var self = $('#element');
// when
self.raty({ target: '#hint', targetText: 'none' });
// then
expect($('#hint')).toHaveHtml('none');
});
});
describe('#targetFormat', function() {
context('with :target', function() {
beforeEach(function() { buildDivTarget(); });
it ('stars empty', function() {
// given
var self = $('#element');
// when
self.raty({ target: '#hint', targetFormat: 'score: {score}' });
// then
expect($('#hint')).toBeEmpty();
});
context('with missing score key', function() {
it ('throws error', function() {
// given
var self = $('#element');
// when
var lambda = function() { self.raty({ target: '#hint', targetFormat: '' }); };
// then
expect(lambda).toThrow(new Error('Template "{score}" missing!'));
});
});
context('on mouseover', function() {
it ('set target with format on mouseover', function() {
// given
var self = $('#element').raty({ target: '#hint', targetFormat: 'score: {score}' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveHtml('score: bad');
});
});
context('on mouseout', function() {
it ('clears the target', function() {
// given
var self = $('#element').raty({
target : '#hint',
targetFormat: 'score: {score}'
});
// when
self.children('img:first').mouseover().mouseout();
// then
expect($('#hint')).toBeEmpty();
});
context('with :targetKeep', function() {
context('without score', function() {
it ('clears the target', function() {
// given
var self = $('#element').raty({
target : '#hint',
targetFormat: 'score: {score}',
targetKeep : true
});
// when
self.children('img:first').mouseover().mouseleave();
// then
expect($('#hint')).toBeEmpty();
});
});
context('with score', function() {
it ('keeps the template', function() {
// given
var self = $('#element').raty({
score : 1,
target : '#hint',
targetFormat: 'score: {score}',
targetKeep : true
});
// when
self.children('img:first').mouseover().mouseleave();
// then
expect($('#hint')).toHaveHtml('score: bad');
});
});
});
});
});
});
describe('#precision', function() {
beforeEach(function() { buildDivTarget(); });
it ('enables the :half options', function() {
// given
var self = $('#element');
// when
self.raty({ precision: true });
// then
expect(self.data('settings').half).toBeTruthy();
});
it ('changes the :targetType to score', function() {
// given
var self = $('#element');
// when
self.raty({ precision: true });
// then
expect(self.data('settings').targetType).toEqual('score');
});
context('with :target', function() {
context('with :targetKeep', function() {
context('with :score', function() {
it ('sets the float with one fractional number', function() {
// given
var self = $('#element');
// when
self.raty({
precision : true,
score : 1.23,
target : '#hint',
targetKeep: true,
targetType: 'score'
});
// then
expect($('#hint')).toHaveHtml('1.2');
});
});
});
});
});
describe('#target', function() {
context('on mouseover', function() {
context('as div', function() {
beforeEach(function() { buildDivTarget(); });
it ('sets the hint', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveHtml('bad');
});
});
context('as text field', function() {
beforeEach(function() { buildTextTarget(); });
it ('sets the hint', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveValue('bad');
});
});
context('as textarea', function() {
beforeEach(function() { buildTextareaTarget(); });
it ('sets the hint', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveValue('bad');
});
});
context('as combobox', function() {
beforeEach(function() { buildComboboxTarget(); });
it ('sets the hint', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover();
// then
expect($('#hint')).toHaveValue('bad');
});
});
});
context('on mouseout', function() {
context('as div', function() {
beforeEach(function() { buildDivTarget(); });
it ('gets clear', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').mouseover().click().mouseleave();
// then
expect($('#hint')).toBeEmpty();
});
});
context('as textarea', function() {
beforeEach(function() { buildTextareaTarget(); });
it ('gets clear', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').click().mouseover().mouseleave();
// then
expect($('#hint')).toHaveValue('');
});
});
context('as text field', function() {
beforeEach(function() { buildTextTarget(); });
it ('gets clear', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').click().mouseover().mouseleave();
// then
expect($('#hint')).toHaveValue('');
});
});
context('as combobox', function() {
beforeEach(function() { buildComboboxTarget(); });
it ('gets clear', function() {
// given
var self = $('#element').raty({ target: '#hint' });
// when
self.children('img:first').click().mouseover().mouseleave();
// then
expect($('#hint')).toHaveValue('');
});
});
});
});
describe('#size', function() {
it ('calculate the right icon size', function() {
// given
var self = $('#element'),
size = 24,
stars = 5,
space = 4;
// when
self.raty({ size: size });
// then
expect(self.width()).toEqual((stars * size) + (stars * space));
});
context('with :cancel', function() {
it ('addes the cancel and space witdh', function() {
// given
var self = $('#element'),
size = 24,
stars = 5,
cancel = size,
space = 4;
// when
self.raty({ cancel: true, size: size });
// then
expect(self.width()).toEqual(cancel + space + (stars * size) + (stars * space));
});
});
});
describe('#space', function() {
context('when off', function() {
it ('takes off the space', function() {
// given
var self = $('#element');
size = 16,
stars = 5;
// when
self.raty({ space: false });
// then
expect(self.width()).toEqual(size * stars);
});
context('with :cancel', function() {
it ('takes off the space', function() {
// given
var self = $('#element');
size = 16,
stars = 5,
cancel = size;
// when
self.raty({ cancel: true, space: false });
// then
expect(self.width()).toEqual(cancel + (size * stars));
});
});
});
});
describe('#single', function() {
context('on mouseover', function() {
it ('turns on just one icon', function() {
// given
var self = $('#element').raty({ single: true }),
imgs = self.children('img');
// when
imgs.eq(2).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
context('with :iconRange', function() {
it ('shows just on icon', function() {
// given
var self = $('#element').raty({
single : true,
iconRange : [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
]
}),
imgs = self.children('img');
// when
imgs.eq(3).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png');
});
});
});
context('on click', function() {
context('on mouseout', function() {
it ('keeps the score', function() {
// given
var self = $('#element').raty({ single: true })
imgs = self.children('img');
// when
imgs.eq(2).mouseover().click().mouseleave();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'star-on.png');
expect(imgs.eq(3)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(4)).toHaveAttr('src', 'star-off.png');
});
context('and :iconRange', function() {
it ('keeps the score', function() {
// given
var self = $('#element').raty({
single : true,
iconRange : [
{ range: 2, on: 'a.png', off: 'a-off.png' },
{ range: 3, on: 'b.png', off: 'b-off.png' },
{ range: 4, on: 'c.png', off: 'c-off.png' },
{ range: 5, on: 'd.png', off: 'd-off.png' }
]
}),
imgs = self.children('img');
// when
imgs.eq(3).mouseover().click().mouseleave();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'a-off.png');
expect(imgs.eq(2)).toHaveAttr('src', 'b-off.png');
expect(imgs.eq(3)).toHaveAttr('src', 'c.png');
expect(imgs.eq(4)).toHaveAttr('src', 'd-off.png');
});
});
});
});
});
describe('#width', function() {
it ('set custom width', function() {
// given
var self = $('#element');
// when
self.raty({ width: 200 });
// then
expect(self.width()).toEqual(200);
});
describe('when it is false', function() {
it ('does not apply the style', function() {
// given
var self = $('#element');
// when
self.raty({ width: false });
// then
expect(self).not.toHaveCss({ width: '100px' });
});
});
describe('when :readOnly', function() {
it ('set custom width when readOnly', function() {
// given
var self = $('#element');
// when
self.raty({ readOnly: true, width: 200 });
// then
expect(self.width()).toEqual(200);
});
});
});
describe('#half', function() {
context('as false', function() {
context('#halfShow', function() {
context('as false', function() {
it ('rounds down while less the full limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : false,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .5 // score.5 < full.6 === 0
});
var imgs = self.children('img');
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(imgs.eq(1)).toHaveAttr('src', 'star-off.png');
});
it ('rounds full when equal the full limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : false,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .6 // score.6 == full.6 === 1
});
var imgs = self.children('img');
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
});
});
});
});
context('as true', function() {
context('#halfShow', function() {
context('as false', function() {
it ('ignores round down while less down limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .24 // score.24 < down.25 === 0
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('0.24');
});
it ('ignores half while greater then down limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .26 // score.26 > down.25 and score.6 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('0.26');
});
it ('ignores half while equal full limit, ignoring it', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .6 // score.6 > down.25 and score.6 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
expect(self.children('input').val()).toEqual('0.6');
});
it ('ignores half while greater than down limit and less than up limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .75 // score.75 > down.25 and score.75 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
expect(self.children('input').val()).toEqual('0.75');
});
it ('ignores full while equal or greater than up limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: false,
round : { down: .25, full: .6, up: .76 },
score : .76 // score.76 == up.76 === 1
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
});
});
context('as true', function() {
it ('rounds down while less down limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .24 // score.24 < down.25 === 0
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-off.png');
});
it ('receives half while greater then down limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .26 // score.26 > down.25 and score.6 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png');
});
it ('receives half while equal full limit, ignoring it', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .6 // score.6 > down.25 and score.6 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png');
});
it ('receives half while greater than down limit and less than up limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .75 // score.75 > down.25 and score.75 < up.76 === .5
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-half.png');
});
it ('receives full while equal or greater than up limit', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
halfShow: true,
round : { down: .25, full: .6, up: .76 },
score : .76 // score.76 == up.76 === 1
});
// then
var imgs = self.children('img');
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
});
});
});
context('with :target', function() {
beforeEach(function() { buildDivTarget(); });
context('and :precision', function() {
context('and :targetType as score', function() {
context('and :targetKeep', function() {
context('and :targetType as score', function() {
it ('set .5 increment value target with half option and no precision', function() {
// given
var self = $('#element');
// when
self.raty({
half : true,
precision : false,
score : 1.5,
target : '#hint',
targetKeep: true,
targetType: 'score'
});
// then
expect($('#hint')).toHaveHtml('1.5');
});
});
});
});
});
});
});
});
});
describe('class bind', function() {
beforeEach(function() {
$('body').append('<div class="element"></div><div class="element"></div>');
});
afterEach(function() {
$('.element').remove();
});
it ('is chainable', function() {
// given
var self = $('.element');
// when
var refs = self.raty();
// then
expect(refs.eq(0)).toBe(self.eq(0));
expect(refs.eq(1)).toBe(self.eq(1));
});
it ('creates the default markup', function() {
// given
var self = $('.element');
// when
self.raty();
// then
var imgs = self.eq(0).children('img'),
score = self.eq(0).children('input');
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(score).toHaveAttr('type', 'hidden');
expect(score).toHaveAttr('name', 'score');
expect(score.val()).toEqual('');
imgs = self.eq(1).children('img');
score = self.eq(0).children('input');
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(score).toHaveAttr('type', 'hidden');
expect(score).toHaveAttr('name', 'score');
expect(score.val()).toEqual('');
});
});
describe('functions', function() {
describe('GET #score', function() {
it ('accepts number as string', function() {
// given
var self = $('#element');
// when
self.raty({ score: '1' });
// then
expect(self.children('input')).toHaveValue(1);
});
it ('accepts float string', function() {
// given
var self = $('#element');
// when
self.raty({ score: '1.5' });
// then
expect(self.children('input')).toHaveValue(1.5);
});
context('with integer score', function() {
it ('gets as int', function() {
// given
var self = $('#element').raty({ score: 1 });
// when
var score = self.raty('score');
// then
expect(score).toEqual(1);
});
});
context('with float score', function() {
it ('gets as float', function() {
// given
var self = $('#element').raty({ score: 1.5 });
// when
var score = self.raty('score');
// then
expect(score).toEqual(1.5);
});
});
context('with score zero', function() {
it ('gets null to emulate cancel', function() {
// given
var self = $('#element').raty({ score: 0 });
// when
var score = self.raty('score');
// then
expect(score).toEqual(null);
});
});
context('with score greater than :numberMax', function() {
it ('gets the max', function() {
// given
var self = $('#element').raty({ number: 50, score: 50 });
// when
var score = self.raty('score');
// then
expect(score).toEqual(self.data('settings').numberMax);
});
});
});
describe('SET #score', function() {
it ('sets the score', function() {
// given
var self = $('#element');
// when
self.raty({ score: 1 });
// then
expect(self.raty('score')).toEqual(1);
});
describe('with :click', function() {
it ('calls the click callback', function() {
// given
var self = $('#element').raty({
click: function(score) {
$(this).data('score', score);
}
});
// when
self.raty('score', 5);
// then
expect(self.children('img')).toHaveAttr('src', 'star-on.png');
});
});
describe('without :click', function() {
it ('does not throw exception', function() {
// given
var self = $('#element').raty();
// when
var lambda = function() { self.raty('score', 1); };
// then
expect(lambda).not.toThrow(new Error('You must add the "click: function(score, evt) { }" callback.'));
});
});
describe('with :readOnly', function() {
it ('does not set the score', function() {
// given
var self = $('#element').raty({ readOnly: true });
// when
self.raty('score', 5);
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
});
});
});
describe('#set', function() {
it ('is chainable', function() {
// given
var self = $('#element').raty();
// when
var ref = self.raty('set', { number: 1 });
// then
expect(ref).toBe(self);
});
it ('changes the declared options', function() {
// given
var self = $('#element').raty();
// when
var ref = self.raty('set', { scoreName: 'change-just-it' });
// then
expect(ref.children('input')).toHaveAttr('name', 'change-just-it');
});
it ('does not change other none declared options', function() {
// given
var self = $('#element').raty({ number: 6 });
// when
var ref = self.raty('set', { scoreName: 'change-just-it' });
// then
expect(ref.children('img').length).toEqual(6);
});
context('with external bind on wrapper', function() {
it ('keeps it', function() {
// given
var self = $('#element').on('click', function() {
$(this).data('externalClick', true);
}).raty();
// when
self.raty('set', {}).click();
// then
expect(self.data('externalClick')).toBeTruthy();
});
});
context('when :readOnly by function', function() {
it ('is removes the readonly data info', function() {
// given
var self = $('#element').raty().raty('readOnly', true);
// when
var ref = self.raty('set', { readOnly: false });
// then
expect(self).not.toHaveData('readonly');
});
});
});
describe('#readOnly', function() {
context('changes to true', function() {
it ('sets score as readonly', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', true);
// then
expect(self.children('input')).toHaveAttr('readonly', 'readonly');
});
it ('removes the pointer cursor', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', true);
// then
expect(self).not.toHaveCss({ cursor: 'pointer' });
expect(self).not.toHaveCss({ cursor: 'default' });
});
it ('Applies "Not rated yet!" on stars', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', true);
// then
expect(self.children('img')).toHaveAttr('title', 'Not rated yet!');
});
it ('avoids trigger mouseover', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
self.raty('readOnly', true);
// when
imgs.eq(0).mouseover();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
it ('avoids trigger click', function() {
// given
var self = $('#element').raty(),
imgs = self.children('img');
self.raty('readOnly', true);
// when
imgs.eq(0).mouseover().click().mouseleave();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
});
context('with :score', function() {
it ('applies the score title on stars', function() {
// given
var self = $('#element').raty({ score: 1 });
// when
self.raty('readOnly', true);
// then
expect(self.children('img')).toHaveAttr('title', 'bad');
});
});
context('with :cancel', function() {
it ('hides the button', function() {
// given
var self = $('#element').raty({ cancel: true, path: '../lib/img' });
// when
self.raty('readOnly', true);
// then
expect(self.children('.raty-cancel')).toBeHidden();
});
});
context('with external bind on wrapper', function() {
it ('keeps it', function() {
// given
var self = $('#element').on('click', function() {
$(this).data('externalClick', true);
}).raty();
// when
self.raty('readOnly', true).click();
// then
expect(self.data('externalClick')).toBeTruthy();
});
});
context('with external bind on stars', function() {
it ('keeps it', function() {
// given
var self = $('#element').raty(),
star = self.children('img').first();
star.on('click', function() {
self.data('externalClick', true);
});
// when
self.raty('readOnly', true);
star.click();
// then
expect(self.data('externalClick')).toBeTruthy();
});
});
});
context('changes to false', function() {
it ('removes the :readOnly of the score', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', false);
// then
expect(self.children('input')).not.toHaveAttr('readonly', 'readonly');
});
it ('applies the pointer cursor on wrapper', function() {
// given
var self = $('#element').raty();
// when
self.raty('readOnly', false);
// then
expect(self).toHaveCss({ cursor: 'pointer' });
});
it ('Removes the "Not rated yet!" off the stars', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
// when
self.raty('readOnly', false);
// then
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
});
it ('triggers mouseover', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
self.raty('readOnly', false);
// when
imgs.eq(0).mouseover();
// then
expect(imgs.eq(0)).toHaveAttr('src', 'star-on.png');
});
it ('triggers click', function() {
// given
var self = $('#element').raty({ readOnly: true }),
imgs = self.children('img');
self.raty('readOnly', false);
// when
imgs.eq(0).mouseover().click().mouseleave();
// then
expect(imgs).toHaveAttr('src', 'star-on.png');
expect(self.children('input')).toHaveValue('1');
});
context('with :score', function() {
it ('removes the score title off the stars', function() {
// given
var self = $('#element').raty({ readOnly: true, score: 3 });
// when
self.raty('readOnly', false);
// then
var imgs = self.children('img')
expect(imgs.eq(0)).toHaveAttr('title', 'bad');
expect(imgs.eq(1)).toHaveAttr('title', 'poor');
expect(imgs.eq(2)).toHaveAttr('title', 'regular');
expect(imgs.eq(3)).toHaveAttr('title', 'good');
expect(imgs.eq(4)).toHaveAttr('title', 'gorgeous');
});
});
context('with :cancel', function() {
it ('shows the button', function() {
// given
var self = $('#element').raty({ readOnly: true, cancel: true, path: '../lib/img' });
// when
self.raty('readOnly', false);
// then
expect(self.children('.raty-cancel')).toBeVisible();
expect(self.children('.raty-cancel')).not.toHaveCss({ display: 'block' });
});
it ('rebinds the mouseover', function() {
// given
var self = $('#element').raty({ readOnly: true, cancel: true }),
cancel = self.children('.raty-cancel'),
imgs = self.children('img:not(.raty-cancel)');
// when
self.raty('readOnly', false);
cancel.mouseover();
// then
expect(cancel).toHaveAttr('src', 'cancel-on.png');
expect(imgs).toHaveAttr('src', 'star-off.png');
});
it ('rebinds the click', function() {
// given
var self = $('#element').raty({ readOnly: true, cancel: true, score: 5 }),
imgs = self.children('img:not(.raty-cancel)');
// when
self.raty('readOnly', false);
self.children('.raty-cancel').click().mouseout();
// then
expect(imgs).toHaveAttr('src', 'star-off.png');
});
});
});
});
describe('#cancel', function() {
describe('with :readOnly', function() {
it ('does not cancel', function() {
// given
var self = $('#element').raty({ readOnly: true, score: 5 });
// when
self.raty('cancel');
// then
expect(self.children('img')).toHaveAttr('src', 'star-on.png');
});
});
context('without click trigger', function() {
it ('cancel the rating', function() {
// given
var self = $('#element').raty({
score: 1,
click: function() {
$(this).data('clicked', true);
}
});
// when
self.raty('cancel');
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
expect(self.data('clicked')).toBeFalsy();
});
});
context('with click trigger', function() {
it ('cancel the rating', function() {
// given
var self = $('#element').raty({
score: 1,
click: function() {
$(this).data('clicked', true);
}
});
// when
self.raty('cancel', true);
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
expect(self.children('input').val()).toEqual('');
expect(self.data('clicked')).toBeTruthy();
});
});
context('with :target', function() {
beforeEach(function() { buildDivTarget(); });
context('and :targetKeep', function() {
it ('sets the :targetText on target', function() {
// given
var hint = $('#hint').html('dirty'),
self = $('#element').raty({
cancel : true,
target : '#hint',
targetKeep: true,
targetText: 'targetText'
});
// when
self.raty('cancel');
// then
expect(hint).toHaveHtml('targetText');
});
});
});
});
describe('#click', function() {
it ('clicks on star', function() {
// given
var self = $('#element').raty({
click: function() {
$(this).data('clicked', true);
}
});
// when
self.raty('click', 1);
// then
expect(self.children('img')).toHaveAttr('src', 'star-on.png');
expect(self.data('clicked')).toBeTruthy();
});
it ('receives the score', function() {
// given
var self = $('#element').raty({
click: function(score) {
$(this).data('score', score);
}
});
// when
self.raty('click', 1);
// then
expect(self.data('score')).toEqual(1);
});
it ('receives the event', function() {
// given
var self = $('#element').raty({
click: function(score, evt) {
$(this).data('evt', evt);
}
});
// when
self.raty('click', 1);
// then
expect(self.data('evt').type).toEqual('click');
});
describe('with :readOnly', function() {
it ('does not set the score', function() {
// given
var self = $('#element').raty({ readOnly: true });
// when
self.raty('click', 1);
// then
expect(self.children('img')).toHaveAttr('src', 'star-off.png');
});
});
context('without :click', function() {
it ('throws error', function() {
// given
var self = $('#element').raty();
// when
var lambda = function() { self.raty('click', 1); };
// then
expect(lambda).toThrow(new Error('You must add the "click: function(score, evt) { }" callback.'));
});
});
context('with :target', function() {
beforeEach(function() { buildDivTarget(); });
context('and :targetKeep', function() {
it ('sets the score on target', function() {
// given
var self = $('#element').raty({
target : '#hint',
targetKeep: true,
click : function() { }
});
// when
self.raty('click', 1);
// then
expect($('#hint')).toHaveHtml('bad');
});
});
});
});
describe('#reload', function() {
it ('is chainable', function() {
// given
var self = $('#element').raty();
// when
var ref = self.raty('reload');
// then
expect(ref).toBe(self);
});
it ('reloads with the same configuration', function() {
// given
var self = $('#element').raty({ number: 6 });
// when
var ref = self.raty('reload');
// then
expect(ref.children('img').length).toEqual(6);
});
context('when :readOnly by function', function() {
it ('is removes the readonly data info', function() {
// given
var self = $('#element').raty().raty('readOnly', true);
// when
var ref = self.raty('reload');
// then
expect(self).not.toHaveData('readonly');
});
});
});
describe('#destroy', function() {
it ('is chainable', function() {
// given
var self = $('#element').raty();
// when
var ref = self.raty('destroy');
// then
expect(ref).toBe(self);
});
it ('clear the content', function() {
// given
var self = $('#element').raty();
// when
self.raty('destroy');
// then
expect(self).toBeEmpty();
});
it ('removes the trigger mouseleave', function() {
// given
var self = $('#element').raty({
mouseout: function() {
console.log(this);
$(this).data('mouseleave', true);
}
});
self.raty('destroy');
// when
self.mouseleave();
// then
expect(self.data('mouseleave')).toBeFalsy();
});
it ('resets the style attributes', function() {
// given
var self = $('#element').css({ cursor: 'help', width: 10 }).raty();
// when
self.raty('destroy');
// then
expect(self[0].style.cursor).toEqual('help');
expect(self[0].style.width).toEqual('10px');
});
});
});
});
| cognitoedtech/assy | subdomain/offline/3rd_party/raty/spec/spec.js | JavaScript | apache-2.0 | 81,498 |
/*
* QEMU System Emulator block driver
*
* Copyright (c) 2003 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "config-host.h"
#include "qemu-common.h"
#include "trace.h"
#include "block/block_int.h"
#include "block/blockjob.h"
#include "qemu/module.h"
#include "qapi/qmp/qjson.h"
#include "sysemu/block-backend.h"
#include "sysemu/sysemu.h"
#include "qemu/notify.h"
#include "block/coroutine.h"
#include "block/qapi.h"
#include "qmp-commands.h"
#include "qemu/timer.h"
#include "qapi-event.h"
#ifdef CONFIG_BSD
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/queue.h>
#ifndef __DragonFly__
#include <sys/disk.h>
#endif
#endif
#ifdef _WIN32
#include <windows.h>
#endif
struct BdrvDirtyBitmap {
HBitmap *bitmap;
QLIST_ENTRY(BdrvDirtyBitmap) list;
};
#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
BlockCompletionFunc *cb, void *opaque);
static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
BlockCompletionFunc *cb, void *opaque);
static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
int64_t sector_num, int nb_sectors,
QEMUIOVector *iov);
static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
int64_t sector_num, int nb_sectors,
QEMUIOVector *iov);
static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
BdrvRequestFlags flags);
static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
BdrvRequestFlags flags);
static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
int64_t sector_num,
QEMUIOVector *qiov,
int nb_sectors,
BdrvRequestFlags flags,
BlockCompletionFunc *cb,
void *opaque,
bool is_write);
static void coroutine_fn bdrv_co_do_rw(void *opaque);
static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
QTAILQ_HEAD_INITIALIZER(bdrv_states);
static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
static QLIST_HEAD(, BlockDriver) bdrv_drivers =
QLIST_HEAD_INITIALIZER(bdrv_drivers);
/* If non-zero, use only whitelisted block drivers */
static int use_bdrv_whitelist;
#ifdef _WIN32
static int is_windows_drive_prefix(const char *filename)
{
return (((filename[0] >= 'a' && filename[0] <= 'z') ||
(filename[0] >= 'A' && filename[0] <= 'Z')) &&
filename[1] == ':');
}
int is_windows_drive(const char *filename)
{
if (is_windows_drive_prefix(filename) &&
filename[2] == '\0')
return 1;
if (strstart(filename, "\\\\.\\", NULL) ||
strstart(filename, "//./", NULL))
return 1;
return 0;
}
#endif
/* throttling disk I/O limits */
void bdrv_set_io_limits(BlockDriverState *bs,
ThrottleConfig *cfg)
{
int i;
throttle_config(&bs->throttle_state, cfg);
for (i = 0; i < 2; i++) {
qemu_co_enter_next(&bs->throttled_reqs[i]);
}
}
/* this function drain all the throttled IOs */
static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
{
bool drained = false;
bool enabled = bs->io_limits_enabled;
int i;
bs->io_limits_enabled = false;
for (i = 0; i < 2; i++) {
while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
drained = true;
}
}
bs->io_limits_enabled = enabled;
return drained;
}
void bdrv_io_limits_disable(BlockDriverState *bs)
{
bs->io_limits_enabled = false;
bdrv_start_throttled_reqs(bs);
throttle_destroy(&bs->throttle_state);
}
static void bdrv_throttle_read_timer_cb(void *opaque)
{
BlockDriverState *bs = opaque;
qemu_co_enter_next(&bs->throttled_reqs[0]);
}
static void bdrv_throttle_write_timer_cb(void *opaque)
{
BlockDriverState *bs = opaque;
qemu_co_enter_next(&bs->throttled_reqs[1]);
}
/* should be called before bdrv_set_io_limits if a limit is set */
void bdrv_io_limits_enable(BlockDriverState *bs)
{
assert(!bs->io_limits_enabled);
throttle_init(&bs->throttle_state,
bdrv_get_aio_context(bs),
QEMU_CLOCK_VIRTUAL,
bdrv_throttle_read_timer_cb,
bdrv_throttle_write_timer_cb,
bs);
bs->io_limits_enabled = true;
}
/* This function makes an IO wait if needed
*
* @nb_sectors: the number of sectors of the IO
* @is_write: is the IO a write
*/
static void bdrv_io_limits_intercept(BlockDriverState *bs,
unsigned int bytes,
bool is_write)
{
/* does this io must wait */
bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
/* if must wait or any request of this type throttled queue the IO */
if (must_wait ||
!qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
}
/* the IO will be executed, do the accounting */
throttle_account(&bs->throttle_state, is_write, bytes);
/* if the next request must wait -> do nothing */
if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
return;
}
/* else queue next request for execution */
qemu_co_queue_next(&bs->throttled_reqs[is_write]);
}
size_t bdrv_opt_mem_align(BlockDriverState *bs)
{
if (!bs || !bs->drv) {
/* 4k should be on the safe side */
return 4096;
}
return bs->bl.opt_mem_alignment;
}
/* check if the path starts with "<protocol>:" */
static int path_has_protocol(const char *path)
{
const char *p;
#ifdef _WIN32
if (is_windows_drive(path) ||
is_windows_drive_prefix(path)) {
return 0;
}
p = path + strcspn(path, ":/\\");
#else
p = path + strcspn(path, ":/");
#endif
return *p == ':';
}
int path_is_absolute(const char *path)
{
#ifdef _WIN32
/* specific case for names like: "\\.\d:" */
if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
return 1;
}
return (*path == '/' || *path == '\\');
#else
return (*path == '/');
#endif
}
/* if filename is absolute, just copy it to dest. Otherwise, build a
path to it by considering it is relative to base_path. URL are
supported. */
void path_combine(char *dest, int dest_size,
const char *base_path,
const char *filename)
{
const char *p, *p1;
int len;
if (dest_size <= 0)
return;
if (path_is_absolute(filename)) {
pstrcpy(dest, dest_size, filename);
} else {
p = strchr(base_path, ':');
if (p)
p++;
else
p = base_path;
p1 = strrchr(base_path, '/');
#ifdef _WIN32
{
const char *p2;
p2 = strrchr(base_path, '\\');
if (!p1 || p2 > p1)
p1 = p2;
}
#endif
if (p1)
p1++;
else
p1 = base_path;
if (p1 > p)
p = p1;
len = p - base_path;
if (len > dest_size - 1)
len = dest_size - 1;
memcpy(dest, base_path, len);
dest[len] = '\0';
pstrcat(dest, dest_size, filename);
}
}
void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
{
if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
pstrcpy(dest, sz, bs->backing_file);
} else {
path_combine(dest, sz, bs->filename, bs->backing_file);
}
}
void bdrv_register(BlockDriver *bdrv)
{
/* Block drivers without coroutine functions need emulation */
if (!bdrv->bdrv_co_readv) {
bdrv->bdrv_co_readv = bdrv_co_readv_em;
bdrv->bdrv_co_writev = bdrv_co_writev_em;
/* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
* the block driver lacks aio we need to emulate that too.
*/
if (!bdrv->bdrv_aio_readv) {
/* add AIO emulation layer */
bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
}
}
QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
}
BlockDriverState *bdrv_new_root(void)
{
BlockDriverState *bs = bdrv_new();
QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
return bs;
}
BlockDriverState *bdrv_new(void)
{
BlockDriverState *bs;
int i;
bs = g_new0(BlockDriverState, 1);
QLIST_INIT(&bs->dirty_bitmaps);
for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
QLIST_INIT(&bs->op_blockers[i]);
}
bdrv_iostatus_disable(bs);
notifier_list_init(&bs->close_notifiers);
notifier_with_return_list_init(&bs->before_write_notifiers);
qemu_co_queue_init(&bs->throttled_reqs[0]);
qemu_co_queue_init(&bs->throttled_reqs[1]);
bs->refcnt = 1;
bs->aio_context = qemu_get_aio_context();
return bs;
}
void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
{
notifier_list_add(&bs->close_notifiers, notify);
}
BlockDriver *bdrv_find_format(const char *format_name)
{
BlockDriver *drv1;
QLIST_FOREACH(drv1, &bdrv_drivers, list) {
if (!strcmp(drv1->format_name, format_name)) {
return drv1;
}
}
return NULL;
}
static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
{
static const char *whitelist_rw[] = {
CONFIG_BDRV_RW_WHITELIST
};
static const char *whitelist_ro[] = {
CONFIG_BDRV_RO_WHITELIST
};
const char **p;
if (!whitelist_rw[0] && !whitelist_ro[0]) {
return 1; /* no whitelist, anything goes */
}
for (p = whitelist_rw; *p; p++) {
if (!strcmp(drv->format_name, *p)) {
return 1;
}
}
if (read_only) {
for (p = whitelist_ro; *p; p++) {
if (!strcmp(drv->format_name, *p)) {
return 1;
}
}
}
return 0;
}
BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
bool read_only)
{
BlockDriver *drv = bdrv_find_format(format_name);
return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
}
typedef struct CreateCo {
BlockDriver *drv;
char *filename;
QemuOpts *opts;
int ret;
Error *err;
} CreateCo;
static void coroutine_fn bdrv_create_co_entry(void *opaque)
{
Error *local_err = NULL;
int ret;
CreateCo *cco = opaque;
assert(cco->drv);
ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
if (local_err) {
error_propagate(&cco->err, local_err);
}
cco->ret = ret;
}
int bdrv_create(BlockDriver *drv, const char* filename,
QemuOpts *opts, Error **errp)
{
int ret;
Coroutine *co;
CreateCo cco = {
.drv = drv,
.filename = g_strdup(filename),
.opts = opts,
.ret = NOT_DONE,
.err = NULL,
};
if (!drv->bdrv_create) {
error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
ret = -ENOTSUP;
goto out;
}
if (qemu_in_coroutine()) {
/* Fast-path if already in coroutine context */
bdrv_create_co_entry(&cco);
} else {
co = qemu_coroutine_create(bdrv_create_co_entry);
qemu_coroutine_enter(co, &cco);
while (cco.ret == NOT_DONE) {
aio_poll(qemu_get_aio_context(), true);
}
}
ret = cco.ret;
if (ret < 0) {
if (cco.err) {
error_propagate(errp, cco.err);
} else {
error_setg_errno(errp, -ret, "Could not create image");
}
}
out:
g_free(cco.filename);
return ret;
}
int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
{
BlockDriver *drv;
Error *local_err = NULL;
int ret;
drv = bdrv_find_protocol(filename, true);
if (drv == NULL) {
error_setg(errp, "Could not find protocol for file '%s'", filename);
return -ENOENT;
}
ret = bdrv_create(drv, filename, opts, &local_err);
if (local_err) {
error_propagate(errp, local_err);
}
return ret;
}
void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
{
BlockDriver *drv = bs->drv;
Error *local_err = NULL;
memset(&bs->bl, 0, sizeof(bs->bl));
if (!drv) {
return;
}
/* Take some limits from the children as a default */
if (bs->file) {
bdrv_refresh_limits(bs->file, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
} else {
bs->bl.opt_mem_alignment = 512;
}
if (bs->backing_hd) {
bdrv_refresh_limits(bs->backing_hd, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
bs->bl.opt_transfer_length =
MAX(bs->bl.opt_transfer_length,
bs->backing_hd->bl.opt_transfer_length);
bs->bl.opt_mem_alignment =
MAX(bs->bl.opt_mem_alignment,
bs->backing_hd->bl.opt_mem_alignment);
}
/* Then let the driver override it */
if (drv->bdrv_refresh_limits) {
drv->bdrv_refresh_limits(bs, errp);
}
}
/*
* Create a uniquely-named empty temporary file.
* Return 0 upon success, otherwise a negative errno value.
*/
int get_tmp_filename(char *filename, int size)
{
#ifdef _WIN32
char temp_dir[MAX_PATH];
/* GetTempFileName requires that its output buffer (4th param)
have length MAX_PATH or greater. */
assert(size >= MAX_PATH);
return (GetTempPath(MAX_PATH, temp_dir)
&& GetTempFileName(temp_dir, "qem", 0, filename)
? 0 : -GetLastError());
#else
int fd;
const char *tmpdir;
tmpdir = getenv("TMPDIR");
if (!tmpdir) {
tmpdir = "/var/tmp";
}
if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
return -EOVERFLOW;
}
fd = mkstemp(filename);
if (fd < 0) {
return -errno;
}
if (close(fd) != 0) {
unlink(filename);
return -errno;
}
return 0;
#endif
}
/*
* Detect host devices. By convention, /dev/cdrom[N] is always
* recognized as a host CDROM.
*/
static BlockDriver *find_hdev_driver(const char *filename)
{
int score_max = 0, score;
BlockDriver *drv = NULL, *d;
QLIST_FOREACH(d, &bdrv_drivers, list) {
if (d->bdrv_probe_device) {
score = d->bdrv_probe_device(filename);
if (score > score_max) {
score_max = score;
drv = d;
}
}
}
return drv;
}
BlockDriver *bdrv_find_protocol(const char *filename,
bool allow_protocol_prefix)
{
BlockDriver *drv1;
char protocol[128];
int len;
const char *p;
/* TODO Drivers without bdrv_file_open must be specified explicitly */
/*
* XXX(hch): we really should not let host device detection
* override an explicit protocol specification, but moving this
* later breaks access to device names with colons in them.
* Thanks to the brain-dead persistent naming schemes on udev-
* based Linux systems those actually are quite common.
*/
drv1 = find_hdev_driver(filename);
if (drv1) {
return drv1;
}
if (!path_has_protocol(filename) || !allow_protocol_prefix) {
return bdrv_find_format("file");
}
p = strchr(filename, ':');
assert(p != NULL);
len = p - filename;
if (len > sizeof(protocol) - 1)
len = sizeof(protocol) - 1;
memcpy(protocol, filename, len);
protocol[len] = '\0';
QLIST_FOREACH(drv1, &bdrv_drivers, list) {
if (drv1->protocol_name &&
!strcmp(drv1->protocol_name, protocol)) {
return drv1;
}
}
return NULL;
}
static int find_image_format(BlockDriverState *bs, const char *filename,
BlockDriver **pdrv, Error **errp)
{
int score, score_max;
BlockDriver *drv1, *drv;
uint8_t buf[2048];
int ret = 0;
/* Return the raw BlockDriver * to scsi-generic devices or empty drives */
if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
drv = bdrv_find_format("raw");
if (!drv) {
error_setg(errp, "Could not find raw image format");
ret = -ENOENT;
}
*pdrv = drv;
return ret;
}
ret = bdrv_pread(bs, 0, buf, sizeof(buf));
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read image for determining its "
"format");
*pdrv = NULL;
return ret;
}
score_max = 0;
drv = NULL;
QLIST_FOREACH(drv1, &bdrv_drivers, list) {
if (drv1->bdrv_probe) {
score = drv1->bdrv_probe(buf, ret, filename);
if (score > score_max) {
score_max = score;
drv = drv1;
}
}
}
if (!drv) {
error_setg(errp, "Could not determine image format: No compatible "
"driver found");
ret = -ENOENT;
}
*pdrv = drv;
return ret;
}
/**
* Set the current 'total_sectors' value
* Return 0 on success, -errno on error.
*/
static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
{
BlockDriver *drv = bs->drv;
/* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
if (bs->sg)
return 0;
/* query actual device if possible, otherwise just trust the hint */
if (drv->bdrv_getlength) {
int64_t length = drv->bdrv_getlength(bs);
if (length < 0) {
return length;
}
hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
}
bs->total_sectors = hint;
return 0;
}
/**
* Set open flags for a given discard mode
*
* Return 0 on success, -1 if the discard mode was invalid.
*/
int bdrv_parse_discard_flags(const char *mode, int *flags)
{
*flags &= ~BDRV_O_UNMAP;
if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
/* do nothing */
} else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
*flags |= BDRV_O_UNMAP;
} else {
return -1;
}
return 0;
}
/**
* Set open flags for a given cache mode
*
* Return 0 on success, -1 if the cache mode was invalid.
*/
int bdrv_parse_cache_flags(const char *mode, int *flags)
{
*flags &= ~BDRV_O_CACHE_MASK;
if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
*flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
} else if (!strcmp(mode, "directsync")) {
*flags |= BDRV_O_NOCACHE;
} else if (!strcmp(mode, "writeback")) {
*flags |= BDRV_O_CACHE_WB;
} else if (!strcmp(mode, "unsafe")) {
*flags |= BDRV_O_CACHE_WB;
*flags |= BDRV_O_NO_FLUSH;
} else if (!strcmp(mode, "writethrough")) {
/* this is the default */
} else {
return -1;
}
return 0;
}
/**
* The copy-on-read flag is actually a reference count so multiple users may
* use the feature without worrying about clobbering its previous state.
* Copy-on-read stays enabled until all users have called to disable it.
*/
void bdrv_enable_copy_on_read(BlockDriverState *bs)
{
bs->copy_on_read++;
}
void bdrv_disable_copy_on_read(BlockDriverState *bs)
{
assert(bs->copy_on_read > 0);
bs->copy_on_read--;
}
/*
* Returns the flags that a temporary snapshot should get, based on the
* originally requested flags (the originally requested image will have flags
* like a backing file)
*/
static int bdrv_temp_snapshot_flags(int flags)
{
return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
}
/*
* Returns the flags that bs->file should get, based on the given flags for
* the parent BDS
*/
static int bdrv_inherited_flags(int flags)
{
/* Enable protocol handling, disable format probing for bs->file */
flags |= BDRV_O_PROTOCOL;
/* Our block drivers take care to send flushes and respect unmap policy,
* so we can enable both unconditionally on lower layers. */
flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
/* Clear flags that only apply to the top layer */
flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
return flags;
}
/*
* Returns the flags that bs->backing_hd should get, based on the given flags
* for the parent BDS
*/
static int bdrv_backing_flags(int flags)
{
/* backing files always opened read-only */
flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
/* snapshot=on is handled on the top layer */
flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
return flags;
}
static int bdrv_open_flags(BlockDriverState *bs, int flags)
{
int open_flags = flags | BDRV_O_CACHE_WB;
/*
* Clear flags that are internal to the block layer before opening the
* image.
*/
open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
/*
* Snapshots should be writable.
*/
if (flags & BDRV_O_TEMPORARY) {
open_flags |= BDRV_O_RDWR;
}
return open_flags;
}
static void bdrv_assign_node_name(BlockDriverState *bs,
const char *node_name,
Error **errp)
{
if (!node_name) {
return;
}
/* Check for empty string or invalid characters */
if (!id_wellformed(node_name)) {
error_setg(errp, "Invalid node name");
return;
}
/* takes care of avoiding namespaces collisions */
if (blk_by_name(node_name)) {
error_setg(errp, "node-name=%s is conflicting with a device id",
node_name);
return;
}
/* takes care of avoiding duplicates node names */
if (bdrv_find_node(node_name)) {
error_setg(errp, "Duplicate node name");
return;
}
/* copy node name into the bs and insert it into the graph list */
pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
}
/*
* Common part for opening disk images and files
*
* Removes all processed options from *options.
*/
static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
QDict *options, int flags, BlockDriver *drv, Error **errp)
{
int ret, open_flags;
const char *filename;
const char *node_name = NULL;
Error *local_err = NULL;
assert(drv != NULL);
assert(bs->file == NULL);
assert(options != NULL && bs->options != options);
if (file != NULL) {
filename = file->filename;
} else {
filename = qdict_get_try_str(options, "filename");
}
if (drv->bdrv_needs_filename && !filename) {
error_setg(errp, "The '%s' block driver requires a file name",
drv->format_name);
return -EINVAL;
}
trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
node_name = qdict_get_try_str(options, "node-name");
bdrv_assign_node_name(bs, node_name, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return -EINVAL;
}
qdict_del(options, "node-name");
/* bdrv_open() with directly using a protocol as drv. This layer is already
* opened, so assign it to bs (while file becomes a closed BlockDriverState)
* and return immediately. */
if (file != NULL && drv->bdrv_file_open) {
bdrv_swap(file, bs);
return 0;
}
bs->open_flags = flags;
bs->guest_block_size = 512;
bs->request_alignment = 512;
bs->zero_beyond_eof = true;
open_flags = bdrv_open_flags(bs, flags);
bs->read_only = !(open_flags & BDRV_O_RDWR);
bs->growable = !!(flags & BDRV_O_PROTOCOL);
if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
error_setg(errp,
!bs->read_only && bdrv_is_whitelisted(drv, true)
? "Driver '%s' can only be used for read-only devices"
: "Driver '%s' is not whitelisted",
drv->format_name);
return -ENOTSUP;
}
assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
if (flags & BDRV_O_COPY_ON_READ) {
if (!bs->read_only) {
bdrv_enable_copy_on_read(bs);
} else {
error_setg(errp, "Can't use copy-on-read on read-only device");
return -EINVAL;
}
}
if (filename != NULL) {
pstrcpy(bs->filename, sizeof(bs->filename), filename);
} else {
bs->filename[0] = '\0';
}
pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
bs->drv = drv;
bs->opaque = g_malloc0(drv->instance_size);
bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
/* Open the image, either directly or using a protocol */
if (drv->bdrv_file_open) {
assert(file == NULL);
assert(!drv->bdrv_needs_filename || filename != NULL);
ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
} else {
if (file == NULL) {
error_setg(errp, "Can't use '%s' as a block driver for the "
"protocol level", drv->format_name);
ret = -EINVAL;
goto free_and_fail;
}
bs->file = file;
ret = drv->bdrv_open(bs, options, open_flags, &local_err);
}
if (ret < 0) {
if (local_err) {
error_propagate(errp, local_err);
} else if (bs->filename[0]) {
error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
} else {
error_setg_errno(errp, -ret, "Could not open image");
}
goto free_and_fail;
}
ret = refresh_total_sectors(bs, bs->total_sectors);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not refresh total sector count");
goto free_and_fail;
}
bdrv_refresh_limits(bs, &local_err);
if (local_err) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto free_and_fail;
}
assert(bdrv_opt_mem_align(bs) != 0);
assert((bs->request_alignment != 0) || bs->sg);
return 0;
free_and_fail:
bs->file = NULL;
g_free(bs->opaque);
bs->opaque = NULL;
bs->drv = NULL;
return ret;
}
static QDict *parse_json_filename(const char *filename, Error **errp)
{
QObject *options_obj;
QDict *options;
int ret;
ret = strstart(filename, "json:", &filename);
assert(ret);
options_obj = qobject_from_json(filename);
if (!options_obj) {
error_setg(errp, "Could not parse the JSON options");
return NULL;
}
if (qobject_type(options_obj) != QTYPE_QDICT) {
qobject_decref(options_obj);
error_setg(errp, "Invalid JSON object given");
return NULL;
}
options = qobject_to_qdict(options_obj);
qdict_flatten(options);
return options;
}
/*
* Fills in default options for opening images and converts the legacy
* filename/flags pair to option QDict entries.
*/
static int bdrv_fill_options(QDict **options, const char **pfilename, int flags,
BlockDriver *drv, Error **errp)
{
const char *filename = *pfilename;
const char *drvname;
bool protocol = flags & BDRV_O_PROTOCOL;
bool parse_filename = false;
Error *local_err = NULL;
/* Parse json: pseudo-protocol */
if (filename && g_str_has_prefix(filename, "json:")) {
QDict *json_options = parse_json_filename(filename, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return -EINVAL;
}
/* Options given in the filename have lower priority than options
* specified directly */
qdict_join(*options, json_options, false);
QDECREF(json_options);
*pfilename = filename = NULL;
}
/* Fetch the file name from the options QDict if necessary */
if (protocol && filename) {
if (!qdict_haskey(*options, "filename")) {
qdict_put(*options, "filename", qstring_from_str(filename));
parse_filename = true;
} else {
error_setg(errp, "Can't specify 'file' and 'filename' options at "
"the same time");
return -EINVAL;
}
}
/* Find the right block driver */
filename = qdict_get_try_str(*options, "filename");
drvname = qdict_get_try_str(*options, "driver");
if (drv) {
if (drvname) {
error_setg(errp, "Driver specified twice");
return -EINVAL;
}
drvname = drv->format_name;
qdict_put(*options, "driver", qstring_from_str(drvname));
} else {
if (!drvname && protocol) {
if (filename) {
drv = bdrv_find_protocol(filename, parse_filename);
if (!drv) {
error_setg(errp, "Unknown protocol");
return -EINVAL;
}
drvname = drv->format_name;
qdict_put(*options, "driver", qstring_from_str(drvname));
} else {
error_setg(errp, "Must specify either driver or file");
return -EINVAL;
}
} else if (drvname) {
drv = bdrv_find_format(drvname);
if (!drv) {
error_setg(errp, "Unknown driver '%s'", drvname);
return -ENOENT;
}
}
}
assert(drv || !protocol);
/* Driver-specific filename parsing */
if (drv && drv->bdrv_parse_filename && parse_filename) {
drv->bdrv_parse_filename(filename, *options, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return -EINVAL;
}
if (!drv->bdrv_needs_filename) {
qdict_del(*options, "filename");
}
}
return 0;
}
void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
{
if (bs->backing_hd) {
assert(bs->backing_blocker);
bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker);
} else if (backing_hd) {
error_setg(&bs->backing_blocker,
"device is used as backing hd of '%s'",
bdrv_get_device_name(bs));
}
bs->backing_hd = backing_hd;
if (!backing_hd) {
error_free(bs->backing_blocker);
bs->backing_blocker = NULL;
goto out;
}
bs->open_flags &= ~BDRV_O_NO_BACKING;
pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
pstrcpy(bs->backing_format, sizeof(bs->backing_format),
backing_hd->drv ? backing_hd->drv->format_name : "");
bdrv_op_block_all(bs->backing_hd, bs->backing_blocker);
/* Otherwise we won't be able to commit due to check in bdrv_commit */
bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT,
bs->backing_blocker);
out:
bdrv_refresh_limits(bs, NULL);
}
/*
* Opens the backing file for a BlockDriverState if not yet open
*
* options is a QDict of options to pass to the block drivers, or NULL for an
* empty set of options. The reference to the QDict is transferred to this
* function (even on failure), so if the caller intends to reuse the dictionary,
* it needs to use QINCREF() before calling bdrv_file_open.
*/
int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
{
char *backing_filename = g_malloc0(PATH_MAX);
int ret = 0;
BlockDriver *back_drv = NULL;
BlockDriverState *backing_hd;
Error *local_err = NULL;
if (bs->backing_hd != NULL) {
QDECREF(options);
goto free_exit;
}
/* NULL means an empty set of options */
if (options == NULL) {
options = qdict_new();
}
bs->open_flags &= ~BDRV_O_NO_BACKING;
if (qdict_haskey(options, "file.filename")) {
backing_filename[0] = '\0';
} else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
QDECREF(options);
goto free_exit;
} else {
bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX);
}
if (!bs->drv || !bs->drv->supports_backing) {
ret = -EINVAL;
error_setg(errp, "Driver doesn't support backing files");
QDECREF(options);
goto free_exit;
}
backing_hd = bdrv_new();
if (bs->backing_format[0] != '\0') {
back_drv = bdrv_find_format(bs->backing_format);
}
assert(bs->backing_hd == NULL);
ret = bdrv_open(&backing_hd,
*backing_filename ? backing_filename : NULL, NULL, options,
bdrv_backing_flags(bs->open_flags), back_drv, &local_err);
if (ret < 0) {
bdrv_unref(backing_hd);
backing_hd = NULL;
bs->open_flags |= BDRV_O_NO_BACKING;
error_setg(errp, "Could not open backing file: %s",
error_get_pretty(local_err));
error_free(local_err);
goto free_exit;
}
bdrv_set_backing_hd(bs, backing_hd);
free_exit:
g_free(backing_filename);
return ret;
}
/*
* Opens a disk image whose options are given as BlockdevRef in another block
* device's options.
*
* If allow_none is true, no image will be opened if filename is false and no
* BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
*
* bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
* That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
* itself, all options starting with "${bdref_key}." are considered part of the
* BlockdevRef.
*
* The BlockdevRef will be removed from the options QDict.
*
* To conform with the behavior of bdrv_open(), *pbs has to be NULL.
*/
int bdrv_open_image(BlockDriverState **pbs, const char *filename,
QDict *options, const char *bdref_key, int flags,
bool allow_none, Error **errp)
{
QDict *image_options;
int ret;
char *bdref_key_dot;
const char *reference;
assert(pbs);
assert(*pbs == NULL);
bdref_key_dot = g_strdup_printf("%s.", bdref_key);
qdict_extract_subqdict(options, &image_options, bdref_key_dot);
g_free(bdref_key_dot);
reference = qdict_get_try_str(options, bdref_key);
if (!filename && !reference && !qdict_size(image_options)) {
if (allow_none) {
ret = 0;
} else {
error_setg(errp, "A block device must be specified for \"%s\"",
bdref_key);
ret = -EINVAL;
}
QDECREF(image_options);
goto done;
}
ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
done:
qdict_del(options, bdref_key);
return ret;
}
int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
{
/* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
char *tmp_filename = g_malloc0(PATH_MAX + 1);
int64_t total_size;
BlockDriver *bdrv_qcow2;
QemuOpts *opts = NULL;
QDict *snapshot_options;
BlockDriverState *bs_snapshot;
Error *local_err;
int ret;
/* if snapshot, we create a temporary backing file and open it
instead of opening 'filename' directly */
/* Get the required size from the image */
total_size = bdrv_getlength(bs);
if (total_size < 0) {
ret = total_size;
error_setg_errno(errp, -total_size, "Could not get image size");
goto out;
}
/* Create the temporary image */
ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not get temporary filename");
goto out;
}
bdrv_qcow2 = bdrv_find_format("qcow2");
opts = qemu_opts_create(bdrv_qcow2->create_opts, NULL, 0,
&error_abort);
qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size);
ret = bdrv_create(bdrv_qcow2, tmp_filename, opts, &local_err);
qemu_opts_del(opts);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not create temporary overlay "
"'%s': %s", tmp_filename,
error_get_pretty(local_err));
error_free(local_err);
goto out;
}
/* Prepare a new options QDict for the temporary file */
snapshot_options = qdict_new();
qdict_put(snapshot_options, "file.driver",
qstring_from_str("file"));
qdict_put(snapshot_options, "file.filename",
qstring_from_str(tmp_filename));
bs_snapshot = bdrv_new();
ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
flags, bdrv_qcow2, &local_err);
if (ret < 0) {
error_propagate(errp, local_err);
goto out;
}
bdrv_append(bs_snapshot, bs);
out:
g_free(tmp_filename);
return ret;
}
/*
* Opens a disk image (raw, qcow2, vmdk, ...)
*
* options is a QDict of options to pass to the block drivers, or NULL for an
* empty set of options. The reference to the QDict belongs to the block layer
* after the call (even on failure), so if the caller intends to reuse the
* dictionary, it needs to use QINCREF() before calling bdrv_open.
*
* If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
* If it is not NULL, the referenced BDS will be reused.
*
* The reference parameter may be used to specify an existing block device which
* should be opened. If specified, neither options nor a filename may be given,
* nor can an existing BDS be reused (that is, *pbs has to be NULL).
*/
int bdrv_open(BlockDriverState **pbs, const char *filename,
const char *reference, QDict *options, int flags,
BlockDriver *drv, Error **errp)
{
int ret;
BlockDriverState *file = NULL, *bs;
const char *drvname;
Error *local_err = NULL;
int snapshot_flags = 0;
assert(pbs);
if (reference) {
bool options_non_empty = options ? qdict_size(options) : false;
QDECREF(options);
if (*pbs) {
error_setg(errp, "Cannot reuse an existing BDS when referencing "
"another block device");
return -EINVAL;
}
if (filename || options_non_empty) {
error_setg(errp, "Cannot reference an existing block device with "
"additional options or a new filename");
return -EINVAL;
}
bs = bdrv_lookup_bs(reference, reference, errp);
if (!bs) {
return -ENODEV;
}
bdrv_ref(bs);
*pbs = bs;
return 0;
}
if (*pbs) {
bs = *pbs;
} else {
bs = bdrv_new();
}
/* NULL means an empty set of options */
if (options == NULL) {
options = qdict_new();
}
ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err);
if (local_err) {
goto fail;
}
/* Find the right image format driver */
drv = NULL;
drvname = qdict_get_try_str(options, "driver");
if (drvname) {
drv = bdrv_find_format(drvname);
qdict_del(options, "driver");
if (!drv) {
error_setg(errp, "Unknown driver: '%s'", drvname);
ret = -EINVAL;
goto fail;
}
}
assert(drvname || !(flags & BDRV_O_PROTOCOL));
if (drv && !drv->bdrv_file_open) {
/* If the user explicitly wants a format driver here, we'll need to add
* another layer for the protocol in bs->file */
flags &= ~BDRV_O_PROTOCOL;
}
bs->options = options;
options = qdict_clone_shallow(options);
/* Open image file without format layer */
if ((flags & BDRV_O_PROTOCOL) == 0) {
if (flags & BDRV_O_RDWR) {
flags |= BDRV_O_ALLOW_RDWR;
}
if (flags & BDRV_O_SNAPSHOT) {
snapshot_flags = bdrv_temp_snapshot_flags(flags);
flags = bdrv_backing_flags(flags);
}
assert(file == NULL);
ret = bdrv_open_image(&file, filename, options, "file",
bdrv_inherited_flags(flags),
true, &local_err);
if (ret < 0) {
goto fail;
}
}
/* Image format probing */
if (!drv && file) {
ret = find_image_format(file, filename, &drv, &local_err);
if (ret < 0) {
goto fail;
}
} else if (!drv) {
error_setg(errp, "Must specify either driver or file");
ret = -EINVAL;
goto fail;
}
/* Open the image */
ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
if (ret < 0) {
goto fail;
}
if (file && (bs->file != file)) {
bdrv_unref(file);
file = NULL;
}
/* If there is a backing file, use it */
if ((flags & BDRV_O_NO_BACKING) == 0) {
QDict *backing_options;
qdict_extract_subqdict(options, &backing_options, "backing.");
ret = bdrv_open_backing_file(bs, backing_options, &local_err);
if (ret < 0) {
goto close_and_fail;
}
}
bdrv_refresh_filename(bs);
/* For snapshot=on, create a temporary qcow2 overlay. bs points to the
* temporary snapshot afterwards. */
if (snapshot_flags) {
ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
if (local_err) {
goto close_and_fail;
}
}
/* Check if any unknown options were used */
if (options && (qdict_size(options) != 0)) {
const QDictEntry *entry = qdict_first(options);
if (flags & BDRV_O_PROTOCOL) {
error_setg(errp, "Block protocol '%s' doesn't support the option "
"'%s'", drv->format_name, entry->key);
} else {
error_setg(errp, "Block format '%s' used by device '%s' doesn't "
"support the option '%s'", drv->format_name,
bdrv_get_device_name(bs), entry->key);
}
ret = -EINVAL;
goto close_and_fail;
}
if (!bdrv_key_required(bs)) {
if (bs->blk) {
blk_dev_change_media_cb(bs->blk, true);
}
} else if (!runstate_check(RUN_STATE_PRELAUNCH)
&& !runstate_check(RUN_STATE_INMIGRATE)
&& !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
error_setg(errp,
"Guest must be stopped for opening of encrypted image");
ret = -EBUSY;
goto close_and_fail;
}
QDECREF(options);
*pbs = bs;
return 0;
fail:
if (file != NULL) {
bdrv_unref(file);
}
QDECREF(bs->options);
QDECREF(options);
bs->options = NULL;
if (!*pbs) {
/* If *pbs is NULL, a new BDS has been created in this function and
needs to be freed now. Otherwise, it does not need to be closed,
since it has not really been opened yet. */
bdrv_unref(bs);
}
if (local_err) {
error_propagate(errp, local_err);
}
return ret;
close_and_fail:
/* See fail path, but now the BDS has to be always closed */
if (*pbs) {
bdrv_close(bs);
} else {
bdrv_unref(bs);
}
QDECREF(options);
if (local_err) {
error_propagate(errp, local_err);
}
return ret;
}
typedef struct BlockReopenQueueEntry {
bool prepared;
BDRVReopenState state;
QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
} BlockReopenQueueEntry;
/*
* Adds a BlockDriverState to a simple queue for an atomic, transactional
* reopen of multiple devices.
*
* bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
* already performed, or alternatively may be NULL a new BlockReopenQueue will
* be created and initialized. This newly created BlockReopenQueue should be
* passed back in for subsequent calls that are intended to be of the same
* atomic 'set'.
*
* bs is the BlockDriverState to add to the reopen queue.
*
* flags contains the open flags for the associated bs
*
* returns a pointer to bs_queue, which is either the newly allocated
* bs_queue, or the existing bs_queue being used.
*
*/
BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
BlockDriverState *bs, int flags)
{
assert(bs != NULL);
BlockReopenQueueEntry *bs_entry;
if (bs_queue == NULL) {
bs_queue = g_new0(BlockReopenQueue, 1);
QSIMPLEQ_INIT(bs_queue);
}
/* bdrv_open() masks this flag out */
flags &= ~BDRV_O_PROTOCOL;
if (bs->file) {
bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags));
}
bs_entry = g_new0(BlockReopenQueueEntry, 1);
QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
bs_entry->state.bs = bs;
bs_entry->state.flags = flags;
return bs_queue;
}
/*
* Reopen multiple BlockDriverStates atomically & transactionally.
*
* The queue passed in (bs_queue) must have been built up previous
* via bdrv_reopen_queue().
*
* Reopens all BDS specified in the queue, with the appropriate
* flags. All devices are prepared for reopen, and failure of any
* device will cause all device changes to be abandonded, and intermediate
* data cleaned up.
*
* If all devices prepare successfully, then the changes are committed
* to all devices.
*
*/
int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
{
int ret = -1;
BlockReopenQueueEntry *bs_entry, *next;
Error *local_err = NULL;
assert(bs_queue != NULL);
bdrv_drain_all();
QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
error_propagate(errp, local_err);
goto cleanup;
}
bs_entry->prepared = true;
}
/* If we reach this point, we have success and just need to apply the
* changes
*/
QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
bdrv_reopen_commit(&bs_entry->state);
}
ret = 0;
cleanup:
QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
if (ret && bs_entry->prepared) {
bdrv_reopen_abort(&bs_entry->state);
}
g_free(bs_entry);
}
g_free(bs_queue);
return ret;
}
/* Reopen a single BlockDriverState with the specified flags. */
int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
{
int ret = -1;
Error *local_err = NULL;
BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
ret = bdrv_reopen_multiple(queue, &local_err);
if (local_err != NULL) {
error_propagate(errp, local_err);
}
return ret;
}
/*
* Prepares a BlockDriverState for reopen. All changes are staged in the
* 'opaque' field of the BDRVReopenState, which is used and allocated by
* the block driver layer .bdrv_reopen_prepare()
*
* bs is the BlockDriverState to reopen
* flags are the new open flags
* queue is the reopen queue
*
* Returns 0 on success, non-zero on error. On error errp will be set
* as well.
*
* On failure, bdrv_reopen_abort() will be called to clean up any data.
* It is the responsibility of the caller to then call the abort() or
* commit() for any other BDS that have been left in a prepare() state
*
*/
int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
Error **errp)
{
int ret = -1;
Error *local_err = NULL;
BlockDriver *drv;
assert(reopen_state != NULL);
assert(reopen_state->bs->drv != NULL);
drv = reopen_state->bs->drv;
/* if we are to stay read-only, do not allow permission change
* to r/w */
if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
reopen_state->flags & BDRV_O_RDWR) {
error_set(errp, QERR_DEVICE_IS_READ_ONLY,
bdrv_get_device_name(reopen_state->bs));
goto error;
}
ret = bdrv_flush(reopen_state->bs);
if (ret) {
error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
strerror(-ret));
goto error;
}
if (drv->bdrv_reopen_prepare) {
ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
if (ret) {
if (local_err != NULL) {
error_propagate(errp, local_err);
} else {
error_setg(errp, "failed while preparing to reopen image '%s'",
reopen_state->bs->filename);
}
goto error;
}
} else {
/* It is currently mandatory to have a bdrv_reopen_prepare()
* handler for each supported drv. */
error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
drv->format_name, bdrv_get_device_name(reopen_state->bs),
"reopening of file");
ret = -1;
goto error;
}
ret = 0;
error:
return ret;
}
/*
* Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
* makes them final by swapping the staging BlockDriverState contents into
* the active BlockDriverState contents.
*/
void bdrv_reopen_commit(BDRVReopenState *reopen_state)
{
BlockDriver *drv;
assert(reopen_state != NULL);
drv = reopen_state->bs->drv;
assert(drv != NULL);
/* If there are any driver level actions to take */
if (drv->bdrv_reopen_commit) {
drv->bdrv_reopen_commit(reopen_state);
}
/* set BDS specific flags now */
reopen_state->bs->open_flags = reopen_state->flags;
reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
BDRV_O_CACHE_WB);
reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
bdrv_refresh_limits(reopen_state->bs, NULL);
}
/*
* Abort the reopen, and delete and free the staged changes in
* reopen_state
*/
void bdrv_reopen_abort(BDRVReopenState *reopen_state)
{
BlockDriver *drv;
assert(reopen_state != NULL);
drv = reopen_state->bs->drv;
assert(drv != NULL);
if (drv->bdrv_reopen_abort) {
drv->bdrv_reopen_abort(reopen_state);
}
}
void bdrv_close(BlockDriverState *bs)
{
BdrvAioNotifier *ban, *ban_next;
if (bs->job) {
block_job_cancel_sync(bs->job);
}
bdrv_drain_all(); /* complete I/O */
bdrv_flush(bs);
bdrv_drain_all(); /* in case flush left pending I/O */
notifier_list_notify(&bs->close_notifiers, bs);
if (bs->drv) {
if (bs->backing_hd) {
BlockDriverState *backing_hd = bs->backing_hd;
bdrv_set_backing_hd(bs, NULL);
bdrv_unref(backing_hd);
}
bs->drv->bdrv_close(bs);
g_free(bs->opaque);
bs->opaque = NULL;
bs->drv = NULL;
bs->copy_on_read = 0;
bs->backing_file[0] = '\0';
bs->backing_format[0] = '\0';
bs->total_sectors = 0;
bs->encrypted = 0;
bs->valid_key = 0;
bs->sg = 0;
bs->growable = 0;
bs->zero_beyond_eof = false;
QDECREF(bs->options);
bs->options = NULL;
QDECREF(bs->full_open_options);
bs->full_open_options = NULL;
if (bs->file != NULL) {
bdrv_unref(bs->file);
bs->file = NULL;
}
}
if (bs->blk) {
blk_dev_change_media_cb(bs->blk, false);
}
/*throttling disk I/O limits*/
if (bs->io_limits_enabled) {
bdrv_io_limits_disable(bs);
}
QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
g_free(ban);
}
QLIST_INIT(&bs->aio_notifiers);
}
void bdrv_close_all(void)
{
BlockDriverState *bs;
QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
AioContext *aio_context = bdrv_get_aio_context(bs);
aio_context_acquire(aio_context);
bdrv_close(bs);
aio_context_release(aio_context);
}
}
/* Check if any requests are in-flight (including throttled requests) */
static bool bdrv_requests_pending(BlockDriverState *bs)
{
if (!QLIST_EMPTY(&bs->tracked_requests)) {
return true;
}
if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
return true;
}
if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
return true;
}
if (bs->file && bdrv_requests_pending(bs->file)) {
return true;
}
if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
return true;
}
return false;
}
/*
* Wait for pending requests to complete across all BlockDriverStates
*
* This function does not flush data to disk, use bdrv_flush_all() for that
* after calling this function.
*
* Note that completion of an asynchronous I/O operation can trigger any
* number of other I/O operations on other devices---for example a coroutine
* can be arbitrarily complex and a constant flow of I/O can come until the
* coroutine is complete. Because of this, it is not possible to have a
* function to drain a single device's I/O queue.
*/
void bdrv_drain_all(void)
{
/* Always run first iteration so any pending completion BHs run */
bool busy = true;
BlockDriverState *bs;
while (busy) {
busy = false;
QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
AioContext *aio_context = bdrv_get_aio_context(bs);
bool bs_busy;
aio_context_acquire(aio_context);
bdrv_flush_io_queue(bs);
bdrv_start_throttled_reqs(bs);
bs_busy = bdrv_requests_pending(bs);
bs_busy |= aio_poll(aio_context, bs_busy);
aio_context_release(aio_context);
busy |= bs_busy;
}
}
}
/* make a BlockDriverState anonymous by removing from bdrv_state and
* graph_bdrv_state list.
Also, NULL terminate the device_name to prevent double remove */
void bdrv_make_anon(BlockDriverState *bs)
{
/*
* Take care to remove bs from bdrv_states only when it's actually
* in it. Note that bs->device_list.tqe_prev is initially null,
* and gets set to non-null by QTAILQ_INSERT_TAIL(). Establish
* the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
* resetting it to null on remove.
*/
if (bs->device_list.tqe_prev) {
QTAILQ_REMOVE(&bdrv_states, bs, device_list);
bs->device_list.tqe_prev = NULL;
}
if (bs->node_name[0] != '\0') {
QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
}
bs->node_name[0] = '\0';
}
static void bdrv_rebind(BlockDriverState *bs)
{
if (bs->drv && bs->drv->bdrv_rebind) {
bs->drv->bdrv_rebind(bs);
}
}
static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
BlockDriverState *bs_src)
{
/* move some fields that need to stay attached to the device */
/* dev info */
bs_dest->guest_block_size = bs_src->guest_block_size;
bs_dest->copy_on_read = bs_src->copy_on_read;
bs_dest->enable_write_cache = bs_src->enable_write_cache;
/* i/o throttled req */
memcpy(&bs_dest->throttle_state,
&bs_src->throttle_state,
sizeof(ThrottleState));
bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0];
bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1];
bs_dest->io_limits_enabled = bs_src->io_limits_enabled;
/* r/w error */
bs_dest->on_read_error = bs_src->on_read_error;
bs_dest->on_write_error = bs_src->on_write_error;
/* i/o status */
bs_dest->iostatus_enabled = bs_src->iostatus_enabled;
bs_dest->iostatus = bs_src->iostatus;
/* dirty bitmap */
bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps;
/* reference count */
bs_dest->refcnt = bs_src->refcnt;
/* job */
bs_dest->job = bs_src->job;
/* keep the same entry in bdrv_states */
bs_dest->device_list = bs_src->device_list;
bs_dest->blk = bs_src->blk;
memcpy(bs_dest->op_blockers, bs_src->op_blockers,
sizeof(bs_dest->op_blockers));
}
/*
* Swap bs contents for two image chains while they are live,
* while keeping required fields on the BlockDriverState that is
* actually attached to a device.
*
* This will modify the BlockDriverState fields, and swap contents
* between bs_new and bs_old. Both bs_new and bs_old are modified.
*
* bs_new must not be attached to a BlockBackend.
*
* This function does not create any image files.
*/
void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
{
BlockDriverState tmp;
/* The code needs to swap the node_name but simply swapping node_list won't
* work so first remove the nodes from the graph list, do the swap then
* insert them back if needed.
*/
if (bs_new->node_name[0] != '\0') {
QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
}
if (bs_old->node_name[0] != '\0') {
QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
}
/* bs_new must be unattached and shouldn't have anything fancy enabled */
assert(!bs_new->blk);
assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
assert(bs_new->job == NULL);
assert(bs_new->io_limits_enabled == false);
assert(!throttle_have_timer(&bs_new->throttle_state));
tmp = *bs_new;
*bs_new = *bs_old;
*bs_old = tmp;
/* there are some fields that should not be swapped, move them back */
bdrv_move_feature_fields(&tmp, bs_old);
bdrv_move_feature_fields(bs_old, bs_new);
bdrv_move_feature_fields(bs_new, &tmp);
/* bs_new must remain unattached */
assert(!bs_new->blk);
/* Check a few fields that should remain attached to the device */
assert(bs_new->job == NULL);
assert(bs_new->io_limits_enabled == false);
assert(!throttle_have_timer(&bs_new->throttle_state));
/* insert the nodes back into the graph node list if needed */
if (bs_new->node_name[0] != '\0') {
QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
}
if (bs_old->node_name[0] != '\0') {
QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
}
bdrv_rebind(bs_new);
bdrv_rebind(bs_old);
}
/*
* Add new bs contents at the top of an image chain while the chain is
* live, while keeping required fields on the top layer.
*
* This will modify the BlockDriverState fields, and swap contents
* between bs_new and bs_top. Both bs_new and bs_top are modified.
*
* bs_new must not be attached to a BlockBackend.
*
* This function does not create any image files.
*/
void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
{
bdrv_swap(bs_new, bs_top);
/* The contents of 'tmp' will become bs_top, as we are
* swapping bs_new and bs_top contents. */
bdrv_set_backing_hd(bs_top, bs_new);
}
static void bdrv_delete(BlockDriverState *bs)
{
assert(!bs->job);
assert(bdrv_op_blocker_is_empty(bs));
assert(!bs->refcnt);
assert(QLIST_EMPTY(&bs->dirty_bitmaps));
bdrv_close(bs);
/* remove from list, if necessary */
bdrv_make_anon(bs);
g_free(bs);
}
/*
* Run consistency checks on an image
*
* Returns 0 if the check could be completed (it doesn't mean that the image is
* free of errors) or -errno when an internal error occurred. The results of the
* check are stored in res.
*/
int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
{
if (bs->drv == NULL) {
return -ENOMEDIUM;
}
if (bs->drv->bdrv_check == NULL) {
return -ENOTSUP;
}
memset(res, 0, sizeof(*res));
return bs->drv->bdrv_check(bs, res, fix);
}
#define COMMIT_BUF_SECTORS 2048
/* commit COW file into the raw image */
int bdrv_commit(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
int64_t sector, total_sectors, length, backing_length;
int n, ro, open_flags;
int ret = 0;
uint8_t *buf = NULL;
char filename[PATH_MAX];
if (!drv)
return -ENOMEDIUM;
if (!bs->backing_hd) {
return -ENOTSUP;
}
if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) ||
bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) {
return -EBUSY;
}
ro = bs->backing_hd->read_only;
/* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
open_flags = bs->backing_hd->open_flags;
if (ro) {
if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
return -EACCES;
}
}
length = bdrv_getlength(bs);
if (length < 0) {
ret = length;
goto ro_cleanup;
}
backing_length = bdrv_getlength(bs->backing_hd);
if (backing_length < 0) {
ret = backing_length;
goto ro_cleanup;
}
/* If our top snapshot is larger than the backing file image,
* grow the backing file image if possible. If not possible,
* we must return an error */
if (length > backing_length) {
ret = bdrv_truncate(bs->backing_hd, length);
if (ret < 0) {
goto ro_cleanup;
}
}
total_sectors = length >> BDRV_SECTOR_BITS;
/* qemu_try_blockalign() for bs will choose an alignment that works for
* bs->backing_hd as well, so no need to compare the alignment manually. */
buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
if (buf == NULL) {
ret = -ENOMEM;
goto ro_cleanup;
}
for (sector = 0; sector < total_sectors; sector += n) {
ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
if (ret < 0) {
goto ro_cleanup;
}
if (ret) {
ret = bdrv_read(bs, sector, buf, n);
if (ret < 0) {
goto ro_cleanup;
}
ret = bdrv_write(bs->backing_hd, sector, buf, n);
if (ret < 0) {
goto ro_cleanup;
}
}
}
if (drv->bdrv_make_empty) {
ret = drv->bdrv_make_empty(bs);
if (ret < 0) {
goto ro_cleanup;
}
bdrv_flush(bs);
}
/*
* Make sure all data we wrote to the backing device is actually
* stable on disk.
*/
if (bs->backing_hd) {
bdrv_flush(bs->backing_hd);
}
ret = 0;
ro_cleanup:
qemu_vfree(buf);
if (ro) {
/* ignoring error return here */
bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
}
return ret;
}
int bdrv_commit_all(void)
{
BlockDriverState *bs;
QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
AioContext *aio_context = bdrv_get_aio_context(bs);
aio_context_acquire(aio_context);
if (bs->drv && bs->backing_hd) {
int ret = bdrv_commit(bs);
if (ret < 0) {
aio_context_release(aio_context);
return ret;
}
}
aio_context_release(aio_context);
}
return 0;
}
/**
* Remove an active request from the tracked requests list
*
* This function should be called when a tracked request is completing.
*/
static void tracked_request_end(BdrvTrackedRequest *req)
{
if (req->serialising) {
req->bs->serialising_in_flight--;
}
QLIST_REMOVE(req, list);
qemu_co_queue_restart_all(&req->wait_queue);
}
/**
* Add an active request to the tracked requests list
*/
static void tracked_request_begin(BdrvTrackedRequest *req,
BlockDriverState *bs,
int64_t offset,
unsigned int bytes, bool is_write)
{
*req = (BdrvTrackedRequest){
.bs = bs,
.offset = offset,
.bytes = bytes,
.is_write = is_write,
.co = qemu_coroutine_self(),
.serialising = false,
.overlap_offset = offset,
.overlap_bytes = bytes,
};
qemu_co_queue_init(&req->wait_queue);
QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
}
static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
{
int64_t overlap_offset = req->offset & ~(align - 1);
unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
- overlap_offset;
if (!req->serialising) {
req->bs->serialising_in_flight++;
req->serialising = true;
}
req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
}
/**
* Round a region to cluster boundaries
*/
void bdrv_round_to_clusters(BlockDriverState *bs,
int64_t sector_num, int nb_sectors,
int64_t *cluster_sector_num,
int *cluster_nb_sectors)
{
BlockDriverInfo bdi;
if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
*cluster_sector_num = sector_num;
*cluster_nb_sectors = nb_sectors;
} else {
int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
*cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
*cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
nb_sectors, c);
}
}
static int bdrv_get_cluster_size(BlockDriverState *bs)
{
BlockDriverInfo bdi;
int ret;
ret = bdrv_get_info(bs, &bdi);
if (ret < 0 || bdi.cluster_size == 0) {
return bs->request_alignment;
} else {
return bdi.cluster_size;
}
}
static bool tracked_request_overlaps(BdrvTrackedRequest *req,
int64_t offset, unsigned int bytes)
{
/* aaaa bbbb */
if (offset >= req->overlap_offset + req->overlap_bytes) {
return false;
}
/* bbbb aaaa */
if (req->overlap_offset >= offset + bytes) {
return false;
}
return true;
}
static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
{
BlockDriverState *bs = self->bs;
BdrvTrackedRequest *req;
bool retry;
bool waited = false;
if (!bs->serialising_in_flight) {
return false;
}
do {
retry = false;
QLIST_FOREACH(req, &bs->tracked_requests, list) {
if (req == self || (!req->serialising && !self->serialising)) {
continue;
}
if (tracked_request_overlaps(req, self->overlap_offset,
self->overlap_bytes))
{
/* Hitting this means there was a reentrant request, for
* example, a block driver issuing nested requests. This must
* never happen since it means deadlock.
*/
assert(qemu_coroutine_self() != req->co);
/* If the request is already (indirectly) waiting for us, or
* will wait for us as soon as it wakes up, then just go on
* (instead of producing a deadlock in the former case). */
if (!req->waiting_for) {
self->waiting_for = req;
qemu_co_queue_wait(&req->wait_queue);
self->waiting_for = NULL;
retry = true;
waited = true;
break;
}
}
}
} while (retry);
return waited;
}
/*
* Return values:
* 0 - success
* -EINVAL - backing format specified, but no file
* -ENOSPC - can't update the backing file because no space is left in the
* image file header
* -ENOTSUP - format driver doesn't support changing the backing file
*/
int bdrv_change_backing_file(BlockDriverState *bs,
const char *backing_file, const char *backing_fmt)
{
BlockDriver *drv = bs->drv;
int ret;
/* Backing file format doesn't make sense without a backing file */
if (backing_fmt && !backing_file) {
return -EINVAL;
}
if (drv->bdrv_change_backing_file != NULL) {
ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
} else {
ret = -ENOTSUP;
}
if (ret == 0) {
pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
}
return ret;
}
/*
* Finds the image layer in the chain that has 'bs' as its backing file.
*
* active is the current topmost image.
*
* Returns NULL if bs is not found in active's image chain,
* or if active == bs.
*
* Returns the bottommost base image if bs == NULL.
*/
BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
BlockDriverState *bs)
{
while (active && bs != active->backing_hd) {
active = active->backing_hd;
}
return active;
}
/* Given a BDS, searches for the base layer. */
BlockDriverState *bdrv_find_base(BlockDriverState *bs)
{
return bdrv_find_overlay(bs, NULL);
}
typedef struct BlkIntermediateStates {
BlockDriverState *bs;
QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
} BlkIntermediateStates;
/*
* Drops images above 'base' up to and including 'top', and sets the image
* above 'top' to have base as its backing file.
*
* Requires that the overlay to 'top' is opened r/w, so that the backing file
* information in 'bs' can be properly updated.
*
* E.g., this will convert the following chain:
* bottom <- base <- intermediate <- top <- active
*
* to
*
* bottom <- base <- active
*
* It is allowed for bottom==base, in which case it converts:
*
* base <- intermediate <- top <- active
*
* to
*
* base <- active
*
* If backing_file_str is non-NULL, it will be used when modifying top's
* overlay image metadata.
*
* Error conditions:
* if active == top, that is considered an error
*
*/
int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
BlockDriverState *base, const char *backing_file_str)
{
BlockDriverState *intermediate;
BlockDriverState *base_bs = NULL;
BlockDriverState *new_top_bs = NULL;
BlkIntermediateStates *intermediate_state, *next;
int ret = -EIO;
QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
QSIMPLEQ_INIT(&states_to_delete);
if (!top->drv || !base->drv) {
goto exit;
}
new_top_bs = bdrv_find_overlay(active, top);
if (new_top_bs == NULL) {
/* we could not find the image above 'top', this is an error */
goto exit;
}
/* special case of new_top_bs->backing_hd already pointing to base - nothing
* to do, no intermediate images */
if (new_top_bs->backing_hd == base) {
ret = 0;
goto exit;
}
intermediate = top;
/* now we will go down through the list, and add each BDS we find
* into our deletion queue, until we hit the 'base'
*/
while (intermediate) {
intermediate_state = g_new0(BlkIntermediateStates, 1);
intermediate_state->bs = intermediate;
QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
if (intermediate->backing_hd == base) {
base_bs = intermediate->backing_hd;
break;
}
intermediate = intermediate->backing_hd;
}
if (base_bs == NULL) {
/* something went wrong, we did not end at the base. safely
* unravel everything, and exit with error */
goto exit;
}
/* success - we can delete the intermediate states, and link top->base */
backing_file_str = backing_file_str ? backing_file_str : base_bs->filename;
ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
base_bs->drv ? base_bs->drv->format_name : "");
if (ret) {
goto exit;
}
bdrv_set_backing_hd(new_top_bs, base_bs);
QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
/* so that bdrv_close() does not recursively close the chain */
bdrv_set_backing_hd(intermediate_state->bs, NULL);
bdrv_unref(intermediate_state->bs);
}
ret = 0;
exit:
QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
g_free(intermediate_state);
}
return ret;
}
static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
size_t size)
{
int64_t len;
if (size > INT_MAX) {
return -EIO;
}
if (!bdrv_is_inserted(bs))
return -ENOMEDIUM;
if (bs->growable)
return 0;
len = bdrv_getlength(bs);
if (offset < 0)
return -EIO;
if ((offset > len) || (len - offset < size))
return -EIO;
return 0;
}
static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
int nb_sectors)
{
if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
return -EIO;
}
return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
nb_sectors * BDRV_SECTOR_SIZE);
}
typedef struct RwCo {
BlockDriverState *bs;
int64_t offset;
QEMUIOVector *qiov;
bool is_write;
int ret;
BdrvRequestFlags flags;
} RwCo;
static void coroutine_fn bdrv_rw_co_entry(void *opaque)
{
RwCo *rwco = opaque;
if (!rwco->is_write) {
rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
rwco->qiov->size, rwco->qiov,
rwco->flags);
} else {
rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
rwco->qiov->size, rwco->qiov,
rwco->flags);
}
}
/*
* Process a vectored synchronous request using coroutines
*/
static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
QEMUIOVector *qiov, bool is_write,
BdrvRequestFlags flags)
{
Coroutine *co;
RwCo rwco = {
.bs = bs,
.offset = offset,
.qiov = qiov,
.is_write = is_write,
.ret = NOT_DONE,
.flags = flags,
};
/**
* In sync call context, when the vcpu is blocked, this throttling timer
* will not fire; so the I/O throttling function has to be disabled here
* if it has been enabled.
*/
if (bs->io_limits_enabled) {
fprintf(stderr, "Disabling I/O throttling on '%s' due "
"to synchronous I/O.\n", bdrv_get_device_name(bs));
bdrv_io_limits_disable(bs);
}
if (qemu_in_coroutine()) {
/* Fast-path if already in coroutine context */
bdrv_rw_co_entry(&rwco);
} else {
AioContext *aio_context = bdrv_get_aio_context(bs);
co = qemu_coroutine_create(bdrv_rw_co_entry);
qemu_coroutine_enter(co, &rwco);
while (rwco.ret == NOT_DONE) {
aio_poll(aio_context, true);
}
}
return rwco.ret;
}
/*
* Process a synchronous request using coroutines
*/
static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
int nb_sectors, bool is_write, BdrvRequestFlags flags)
{
QEMUIOVector qiov;
struct iovec iov = {
.iov_base = (void *)buf,
.iov_len = nb_sectors * BDRV_SECTOR_SIZE,
};
if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
return -EINVAL;
}
qemu_iovec_init_external(&qiov, &iov, 1);
return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
&qiov, is_write, flags);
}
/* return < 0 if error. See bdrv_write() for the return codes */
int bdrv_read(BlockDriverState *bs, int64_t sector_num,
uint8_t *buf, int nb_sectors)
{
return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
}
/* Just like bdrv_read(), but with I/O throttling temporarily disabled */
int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
uint8_t *buf, int nb_sectors)
{
bool enabled;
int ret;
enabled = bs->io_limits_enabled;
bs->io_limits_enabled = false;
ret = bdrv_read(bs, sector_num, buf, nb_sectors);
bs->io_limits_enabled = enabled;
return ret;
}
/* Return < 0 if error. Important errors are:
-EIO generic I/O error (may happen for all errors)
-ENOMEDIUM No media inserted.
-EINVAL Invalid sector number or nb_sectors
-EACCES Trying to write a read-only device
*/
int bdrv_write(BlockDriverState *bs, int64_t sector_num,
const uint8_t *buf, int nb_sectors)
{
return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
}
int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, BdrvRequestFlags flags)
{
return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
BDRV_REQ_ZERO_WRITE | flags);
}
/*
* Completely zero out a block device with the help of bdrv_write_zeroes.
* The operation is sped up by checking the block status and only writing
* zeroes to the device if they currently do not return zeroes. Optional
* flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
*
* Returns < 0 on error, 0 on success. For error codes see bdrv_write().
*/
int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
{
int64_t target_sectors, ret, nb_sectors, sector_num = 0;
int n;
target_sectors = bdrv_nb_sectors(bs);
if (target_sectors < 0) {
return target_sectors;
}
for (;;) {
nb_sectors = target_sectors - sector_num;
if (nb_sectors <= 0) {
return 0;
}
if (nb_sectors > INT_MAX) {
nb_sectors = INT_MAX;
}
ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
if (ret < 0) {
error_report("error getting block status at sector %" PRId64 ": %s",
sector_num, strerror(-ret));
return ret;
}
if (ret & BDRV_BLOCK_ZERO) {
sector_num += n;
continue;
}
ret = bdrv_write_zeroes(bs, sector_num, n, flags);
if (ret < 0) {
error_report("error writing zeroes at sector %" PRId64 ": %s",
sector_num, strerror(-ret));
return ret;
}
sector_num += n;
}
}
int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
{
QEMUIOVector qiov;
struct iovec iov = {
.iov_base = (void *)buf,
.iov_len = bytes,
};
int ret;
if (bytes < 0) {
return -EINVAL;
}
qemu_iovec_init_external(&qiov, &iov, 1);
ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
if (ret < 0) {
return ret;
}
return bytes;
}
int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
{
int ret;
ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
if (ret < 0) {
return ret;
}
return qiov->size;
}
int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
const void *buf, int bytes)
{
QEMUIOVector qiov;
struct iovec iov = {
.iov_base = (void *) buf,
.iov_len = bytes,
};
if (bytes < 0) {
return -EINVAL;
}
qemu_iovec_init_external(&qiov, &iov, 1);
return bdrv_pwritev(bs, offset, &qiov);
}
/*
* Writes to the file and ensures that no writes are reordered across this
* request (acts as a barrier)
*
* Returns 0 on success, -errno in error cases.
*/
int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
const void *buf, int count)
{
int ret;
ret = bdrv_pwrite(bs, offset, buf, count);
if (ret < 0) {
return ret;
}
/* No flush needed for cache modes that already do it */
if (bs->enable_write_cache) {
bdrv_flush(bs);
}
return 0;
}
static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
{
/* Perform I/O through a temporary buffer so that users who scribble over
* their read buffer while the operation is in progress do not end up
* modifying the image file. This is critical for zero-copy guest I/O
* where anything might happen inside guest memory.
*/
void *bounce_buffer;
BlockDriver *drv = bs->drv;
struct iovec iov;
QEMUIOVector bounce_qiov;
int64_t cluster_sector_num;
int cluster_nb_sectors;
size_t skip_bytes;
int ret;
/* Cover entire cluster so no additional backing file I/O is required when
* allocating cluster in the image file.
*/
bdrv_round_to_clusters(bs, sector_num, nb_sectors,
&cluster_sector_num, &cluster_nb_sectors);
trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
cluster_sector_num, cluster_nb_sectors);
iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
if (bounce_buffer == NULL) {
ret = -ENOMEM;
goto err;
}
qemu_iovec_init_external(&bounce_qiov, &iov, 1);
ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
&bounce_qiov);
if (ret < 0) {
goto err;
}
if (drv->bdrv_co_write_zeroes &&
buffer_is_zero(bounce_buffer, iov.iov_len)) {
ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
cluster_nb_sectors, 0);
} else {
/* This does not change the data on the disk, it is not necessary
* to flush even in cache=writethrough mode.
*/
ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
&bounce_qiov);
}
if (ret < 0) {
/* It might be okay to ignore write errors for guest requests. If this
* is a deliberate copy-on-read then we don't want to ignore the error.
* Simply report it in all cases.
*/
goto err;
}
skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
nb_sectors * BDRV_SECTOR_SIZE);
err:
qemu_vfree(bounce_buffer);
return ret;
}
/*
* Forwards an already correctly aligned request to the BlockDriver. This
* handles copy on read and zeroing after EOF; any other features must be
* implemented by the caller.
*/
static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
int64_t align, QEMUIOVector *qiov, int flags)
{
BlockDriver *drv = bs->drv;
int ret;
int64_t sector_num = offset >> BDRV_SECTOR_BITS;
unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
assert(!qiov || bytes == qiov->size);
/* Handle Copy on Read and associated serialisation */
if (flags & BDRV_REQ_COPY_ON_READ) {
/* If we touch the same cluster it counts as an overlap. This
* guarantees that allocating writes will be serialized and not race
* with each other for the same cluster. For example, in copy-on-read
* it ensures that the CoR read and write operations are atomic and
* guest writes cannot interleave between them. */
mark_request_serialising(req, bdrv_get_cluster_size(bs));
}
wait_serialising_requests(req);
if (flags & BDRV_REQ_COPY_ON_READ) {
int pnum;
ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
if (ret < 0) {
goto out;
}
if (!ret || pnum != nb_sectors) {
ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
goto out;
}
}
/* Forward the request to the BlockDriver */
if (!(bs->zero_beyond_eof && bs->growable)) {
ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
} else {
/* Read zeros after EOF of growable BDSes */
int64_t total_sectors, max_nb_sectors;
total_sectors = bdrv_nb_sectors(bs);
if (total_sectors < 0) {
ret = total_sectors;
goto out;
}
max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
align >> BDRV_SECTOR_BITS);
if (max_nb_sectors > 0) {
QEMUIOVector local_qiov;
size_t local_sectors;
max_nb_sectors = MIN(max_nb_sectors, SIZE_MAX / BDRV_SECTOR_BITS);
local_sectors = MIN(max_nb_sectors, nb_sectors);
qemu_iovec_init(&local_qiov, qiov->niov);
qemu_iovec_concat(&local_qiov, qiov, 0,
local_sectors * BDRV_SECTOR_SIZE);
ret = drv->bdrv_co_readv(bs, sector_num, local_sectors,
&local_qiov);
qemu_iovec_destroy(&local_qiov);
} else {
ret = 0;
}
/* Reading beyond end of file is supposed to produce zeroes */
if (ret == 0 && total_sectors < sector_num + nb_sectors) {
uint64_t offset = MAX(0, total_sectors - sector_num);
uint64_t bytes = (sector_num + nb_sectors - offset) *
BDRV_SECTOR_SIZE;
qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
}
}
out:
return ret;
}
/*
* Handle a read request in coroutine context
*/
static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
BdrvRequestFlags flags)
{
BlockDriver *drv = bs->drv;
BdrvTrackedRequest req;
/* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
uint8_t *head_buf = NULL;
uint8_t *tail_buf = NULL;
QEMUIOVector local_qiov;
bool use_local_qiov = false;
int ret;
if (!drv) {
return -ENOMEDIUM;
}
if (bdrv_check_byte_request(bs, offset, bytes)) {
return -EIO;
}
if (bs->copy_on_read) {
flags |= BDRV_REQ_COPY_ON_READ;
}
/* throttling disk I/O */
if (bs->io_limits_enabled) {
bdrv_io_limits_intercept(bs, bytes, false);
}
/* Align read if necessary by padding qiov */
if (offset & (align - 1)) {
head_buf = qemu_blockalign(bs, align);
qemu_iovec_init(&local_qiov, qiov->niov + 2);
qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
use_local_qiov = true;
bytes += offset & (align - 1);
offset = offset & ~(align - 1);
}
if ((offset + bytes) & (align - 1)) {
if (!use_local_qiov) {
qemu_iovec_init(&local_qiov, qiov->niov + 1);
qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
use_local_qiov = true;
}
tail_buf = qemu_blockalign(bs, align);
qemu_iovec_add(&local_qiov, tail_buf,
align - ((offset + bytes) & (align - 1)));
bytes = ROUND_UP(bytes, align);
}
tracked_request_begin(&req, bs, offset, bytes, false);
ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
use_local_qiov ? &local_qiov : qiov,
flags);
tracked_request_end(&req);
if (use_local_qiov) {
qemu_iovec_destroy(&local_qiov);
qemu_vfree(head_buf);
qemu_vfree(tail_buf);
}
return ret;
}
static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
BdrvRequestFlags flags)
{
if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
return -EINVAL;
}
return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
}
int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, QEMUIOVector *qiov)
{
trace_bdrv_co_readv(bs, sector_num, nb_sectors);
return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
}
int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
{
trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
BDRV_REQ_COPY_ON_READ);
}
/* if no limit is specified in the BlockLimits use a default
* of 32768 512-byte sectors (16 MiB) per request.
*/
#define MAX_WRITE_ZEROES_DEFAULT 32768
static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
{
BlockDriver *drv = bs->drv;
QEMUIOVector qiov;
struct iovec iov = {0};
int ret = 0;
int max_write_zeroes = bs->bl.max_write_zeroes ?
bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
while (nb_sectors > 0 && !ret) {
int num = nb_sectors;
/* Align request. Block drivers can expect the "bulk" of the request
* to be aligned.
*/
if (bs->bl.write_zeroes_alignment
&& num > bs->bl.write_zeroes_alignment) {
if (sector_num % bs->bl.write_zeroes_alignment != 0) {
/* Make a small request up to the first aligned sector. */
num = bs->bl.write_zeroes_alignment;
num -= sector_num % bs->bl.write_zeroes_alignment;
} else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
/* Shorten the request to the last aligned sector. num cannot
* underflow because num > bs->bl.write_zeroes_alignment.
*/
num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
}
}
/* limit request size */
if (num > max_write_zeroes) {
num = max_write_zeroes;
}
ret = -ENOTSUP;
/* First try the efficient write zeroes operation */
if (drv->bdrv_co_write_zeroes) {
ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
}
if (ret == -ENOTSUP) {
/* Fall back to bounce buffer if write zeroes is unsupported */
iov.iov_len = num * BDRV_SECTOR_SIZE;
if (iov.iov_base == NULL) {
iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE);
if (iov.iov_base == NULL) {
ret = -ENOMEM;
goto fail;
}
memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
}
qemu_iovec_init_external(&qiov, &iov, 1);
ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
/* Keep bounce buffer around if it is big enough for all
* all future requests.
*/
if (num < max_write_zeroes) {
qemu_vfree(iov.iov_base);
iov.iov_base = NULL;
}
}
sector_num += num;
nb_sectors -= num;
}
fail:
qemu_vfree(iov.iov_base);
return ret;
}
/*
* Forwards an already correctly aligned write request to the BlockDriver.
*/
static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
QEMUIOVector *qiov, int flags)
{
BlockDriver *drv = bs->drv;
bool waited;
int ret;
int64_t sector_num = offset >> BDRV_SECTOR_BITS;
unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
assert(!qiov || bytes == qiov->size);
waited = wait_serialising_requests(req);
assert(!waited || !req->serialising);
assert(req->overlap_offset <= offset);
assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
!(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&
qemu_iovec_is_zero(qiov)) {
flags |= BDRV_REQ_ZERO_WRITE;
if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
flags |= BDRV_REQ_MAY_UNMAP;
}
}
if (ret < 0) {
/* Do nothing, write notifier decided to fail this request */
} else if (flags & BDRV_REQ_ZERO_WRITE) {
BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
} else {
BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
}
BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
if (ret == 0 && !bs->enable_write_cache) {
ret = bdrv_co_flush(bs);
}
bdrv_set_dirty(bs, sector_num, nb_sectors);
block_acct_highest_sector(&bs->stats, sector_num, nb_sectors);
if (bs->growable && ret >= 0) {
bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
}
return ret;
}
/*
* Handle a write request in coroutine context
*/
static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
BdrvRequestFlags flags)
{
BdrvTrackedRequest req;
/* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
uint8_t *head_buf = NULL;
uint8_t *tail_buf = NULL;
QEMUIOVector local_qiov;
bool use_local_qiov = false;
int ret;
if (!bs->drv) {
return -ENOMEDIUM;
}
if (bs->read_only) {
return -EACCES;
}
if (bdrv_check_byte_request(bs, offset, bytes)) {
return -EIO;
}
/* throttling disk I/O */
if (bs->io_limits_enabled) {
bdrv_io_limits_intercept(bs, bytes, true);
}
/*
* Align write if necessary by performing a read-modify-write cycle.
* Pad qiov with the read parts and be sure to have a tracked request not
* only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
*/
tracked_request_begin(&req, bs, offset, bytes, true);
if (offset & (align - 1)) {
QEMUIOVector head_qiov;
struct iovec head_iov;
mark_request_serialising(&req, align);
wait_serialising_requests(&req);
head_buf = qemu_blockalign(bs, align);
head_iov = (struct iovec) {
.iov_base = head_buf,
.iov_len = align,
};
qemu_iovec_init_external(&head_qiov, &head_iov, 1);
BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
align, &head_qiov, 0);
if (ret < 0) {
goto fail;
}
BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
qemu_iovec_init(&local_qiov, qiov->niov + 2);
qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
use_local_qiov = true;
bytes += offset & (align - 1);
offset = offset & ~(align - 1);
}
if ((offset + bytes) & (align - 1)) {
QEMUIOVector tail_qiov;
struct iovec tail_iov;
size_t tail_bytes;
bool waited;
mark_request_serialising(&req, align);
waited = wait_serialising_requests(&req);
assert(!waited || !use_local_qiov);
tail_buf = qemu_blockalign(bs, align);
tail_iov = (struct iovec) {
.iov_base = tail_buf,
.iov_len = align,
};
qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
align, &tail_qiov, 0);
if (ret < 0) {
goto fail;
}
BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
if (!use_local_qiov) {
qemu_iovec_init(&local_qiov, qiov->niov + 1);
qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
use_local_qiov = true;
}
tail_bytes = (offset + bytes) & (align - 1);
qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
bytes = ROUND_UP(bytes, align);
}
ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
use_local_qiov ? &local_qiov : qiov,
flags);
fail:
tracked_request_end(&req);
if (use_local_qiov) {
qemu_iovec_destroy(&local_qiov);
}
qemu_vfree(head_buf);
qemu_vfree(tail_buf);
return ret;
}
static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
BdrvRequestFlags flags)
{
if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
return -EINVAL;
}
return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
}
int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, QEMUIOVector *qiov)
{
trace_bdrv_co_writev(bs, sector_num, nb_sectors);
return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
}
int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
int64_t sector_num, int nb_sectors,
BdrvRequestFlags flags)
{
trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
if (!(bs->open_flags & BDRV_O_UNMAP)) {
flags &= ~BDRV_REQ_MAY_UNMAP;
}
return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
BDRV_REQ_ZERO_WRITE | flags);
}
/**
* Truncate file to 'offset' bytes (needed only for file protocols)
*/
int bdrv_truncate(BlockDriverState *bs, int64_t offset)
{
BlockDriver *drv = bs->drv;
int ret;
if (!drv)
return -ENOMEDIUM;
if (!drv->bdrv_truncate)
return -ENOTSUP;
if (bs->read_only)
return -EACCES;
ret = drv->bdrv_truncate(bs, offset);
if (ret == 0) {
ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
if (bs->blk) {
blk_dev_resize_cb(bs->blk);
}
}
return ret;
}
/**
* Length of a allocated file in bytes. Sparse files are counted by actual
* allocated space. Return < 0 if error or unknown.
*/
int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
if (!drv) {
return -ENOMEDIUM;
}
if (drv->bdrv_get_allocated_file_size) {
return drv->bdrv_get_allocated_file_size(bs);
}
if (bs->file) {
return bdrv_get_allocated_file_size(bs->file);
}
return -ENOTSUP;
}
/**
* Return number of sectors on success, -errno on error.
*/
int64_t bdrv_nb_sectors(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
if (!drv)
return -ENOMEDIUM;
if (drv->has_variable_length) {
int ret = refresh_total_sectors(bs, bs->total_sectors);
if (ret < 0) {
return ret;
}
}
return bs->total_sectors;
}
/**
* Return length in bytes on success, -errno on error.
* The length is always a multiple of BDRV_SECTOR_SIZE.
*/
int64_t bdrv_getlength(BlockDriverState *bs)
{
int64_t ret = bdrv_nb_sectors(bs);
return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
}
/* return 0 as number of sectors if no device present or error */
void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
{
int64_t nb_sectors = bdrv_nb_sectors(bs);
*nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
}
void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
BlockdevOnError on_write_error)
{
bs->on_read_error = on_read_error;
bs->on_write_error = on_write_error;
}
BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
{
return is_read ? bs->on_read_error : bs->on_write_error;
}
BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
{
BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
switch (on_err) {
case BLOCKDEV_ON_ERROR_ENOSPC:
return (error == ENOSPC) ?
BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
case BLOCKDEV_ON_ERROR_STOP:
return BLOCK_ERROR_ACTION_STOP;
case BLOCKDEV_ON_ERROR_REPORT:
return BLOCK_ERROR_ACTION_REPORT;
case BLOCKDEV_ON_ERROR_IGNORE:
return BLOCK_ERROR_ACTION_IGNORE;
default:
abort();
}
}
static void send_qmp_error_event(BlockDriverState *bs,
BlockErrorAction action,
bool is_read, int error)
{
BlockErrorAction ac;
ac = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
qapi_event_send_block_io_error(bdrv_get_device_name(bs), ac, action,
bdrv_iostatus_is_enabled(bs),
error == ENOSPC, strerror(error),
&error_abort);
}
/* This is done by device models because, while the block layer knows
* about the error, it does not know whether an operation comes from
* the device or the block layer (from a job, for example).
*/
void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
bool is_read, int error)
{
assert(error >= 0);
if (action == BLOCK_ERROR_ACTION_STOP) {
/* First set the iostatus, so that "info block" returns an iostatus
* that matches the events raised so far (an additional error iostatus
* is fine, but not a lost one).
*/
bdrv_iostatus_set_err(bs, error);
/* Then raise the request to stop the VM and the event.
* qemu_system_vmstop_request_prepare has two effects. First,
* it ensures that the STOP event always comes after the
* BLOCK_IO_ERROR event. Second, it ensures that even if management
* can observe the STOP event and do a "cont" before the STOP
* event is issued, the VM will not stop. In this case, vm_start()
* also ensures that the STOP/RESUME pair of events is emitted.
*/
qemu_system_vmstop_request_prepare();
send_qmp_error_event(bs, action, is_read, error);
qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
} else {
send_qmp_error_event(bs, action, is_read, error);
}
}
int bdrv_is_read_only(BlockDriverState *bs)
{
return bs->read_only;
}
int bdrv_is_sg(BlockDriverState *bs)
{
return bs->sg;
}
int bdrv_enable_write_cache(BlockDriverState *bs)
{
return bs->enable_write_cache;
}
void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
{
bs->enable_write_cache = wce;
/* so a reopen() will preserve wce */
if (wce) {
bs->open_flags |= BDRV_O_CACHE_WB;
} else {
bs->open_flags &= ~BDRV_O_CACHE_WB;
}
}
int bdrv_is_encrypted(BlockDriverState *bs)
{
if (bs->backing_hd && bs->backing_hd->encrypted)
return 1;
return bs->encrypted;
}
int bdrv_key_required(BlockDriverState *bs)
{
BlockDriverState *backing_hd = bs->backing_hd;
if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
return 1;
return (bs->encrypted && !bs->valid_key);
}
int bdrv_set_key(BlockDriverState *bs, const char *key)
{
int ret;
if (bs->backing_hd && bs->backing_hd->encrypted) {
ret = bdrv_set_key(bs->backing_hd, key);
if (ret < 0)
return ret;
if (!bs->encrypted)
return 0;
}
if (!bs->encrypted) {
return -EINVAL;
} else if (!bs->drv || !bs->drv->bdrv_set_key) {
return -ENOMEDIUM;
}
ret = bs->drv->bdrv_set_key(bs, key);
if (ret < 0) {
bs->valid_key = 0;
} else if (!bs->valid_key) {
bs->valid_key = 1;
if (bs->blk) {
/* call the change callback now, we skipped it on open */
blk_dev_change_media_cb(bs->blk, true);
}
}
return ret;
}
const char *bdrv_get_format_name(BlockDriverState *bs)
{
return bs->drv ? bs->drv->format_name : NULL;
}
static int qsort_strcmp(const void *a, const void *b)
{
return strcmp(a, b);
}
void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
void *opaque)
{
BlockDriver *drv;
int count = 0;
int i;
const char **formats = NULL;
QLIST_FOREACH(drv, &bdrv_drivers, list) {
if (drv->format_name) {
bool found = false;
int i = count;
while (formats && i && !found) {
found = !strcmp(formats[--i], drv->format_name);
}
if (!found) {
formats = g_renew(const char *, formats, count + 1);
formats[count++] = drv->format_name;
}
}
}
qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
for (i = 0; i < count; i++) {
it(opaque, formats[i]);
}
g_free(formats);
}
/* This function is to find block backend bs */
/* TODO convert callers to blk_by_name(), then remove */
BlockDriverState *bdrv_find(const char *name)
{
BlockBackend *blk = blk_by_name(name);
return blk ? blk_bs(blk) : NULL;
}
/* This function is to find a node in the bs graph */
BlockDriverState *bdrv_find_node(const char *node_name)
{
BlockDriverState *bs;
assert(node_name);
QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
if (!strcmp(node_name, bs->node_name)) {
return bs;
}
}
return NULL;
}
/* Put this QMP function here so it can access the static graph_bdrv_states. */
BlockDeviceInfoList *bdrv_named_nodes_list(void)
{
BlockDeviceInfoList *list, *entry;
BlockDriverState *bs;
list = NULL;
QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
entry = g_malloc0(sizeof(*entry));
entry->value = bdrv_block_device_info(bs);
entry->next = list;
list = entry;
}
return list;
}
BlockDriverState *bdrv_lookup_bs(const char *device,
const char *node_name,
Error **errp)
{
BlockBackend *blk;
BlockDriverState *bs;
if (device) {
blk = blk_by_name(device);
if (blk) {
return blk_bs(blk);
}
}
if (node_name) {
bs = bdrv_find_node(node_name);
if (bs) {
return bs;
}
}
error_setg(errp, "Cannot find device=%s nor node_name=%s",
device ? device : "",
node_name ? node_name : "");
return NULL;
}
/* If 'base' is in the same chain as 'top', return true. Otherwise,
* return false. If either argument is NULL, return false. */
bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
{
while (top && top != base) {
top = top->backing_hd;
}
return top != NULL;
}
BlockDriverState *bdrv_next(BlockDriverState *bs)
{
if (!bs) {
return QTAILQ_FIRST(&bdrv_states);
}
return QTAILQ_NEXT(bs, device_list);
}
/* TODO check what callers really want: bs->node_name or blk_name() */
const char *bdrv_get_device_name(const BlockDriverState *bs)
{
return bs->blk ? blk_name(bs->blk) : "";
}
int bdrv_get_flags(BlockDriverState *bs)
{
return bs->open_flags;
}
int bdrv_flush_all(void)
{
BlockDriverState *bs;
int result = 0;
QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
AioContext *aio_context = bdrv_get_aio_context(bs);
int ret;
aio_context_acquire(aio_context);
ret = bdrv_flush(bs);
if (ret < 0 && !result) {
result = ret;
}
aio_context_release(aio_context);
}
return result;
}
int bdrv_has_zero_init_1(BlockDriverState *bs)
{
return 1;
}
int bdrv_has_zero_init(BlockDriverState *bs)
{
assert(bs->drv);
/* If BS is a copy on write image, it is initialized to
the contents of the base image, which may not be zeroes. */
if (bs->backing_hd) {
return 0;
}
if (bs->drv->bdrv_has_zero_init) {
return bs->drv->bdrv_has_zero_init(bs);
}
/* safe default */
return 0;
}
bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
{
BlockDriverInfo bdi;
if (bs->backing_hd) {
return false;
}
if (bdrv_get_info(bs, &bdi) == 0) {
return bdi.unallocated_blocks_are_zero;
}
return false;
}
bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
{
BlockDriverInfo bdi;
if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
return false;
}
if (bdrv_get_info(bs, &bdi) == 0) {
return bdi.can_write_zeroes_with_unmap;
}
return false;
}
typedef struct BdrvCoGetBlockStatusData {
BlockDriverState *bs;
BlockDriverState *base;
int64_t sector_num;
int nb_sectors;
int *pnum;
int64_t ret;
bool done;
} BdrvCoGetBlockStatusData;
/*
* Returns true iff the specified sector is present in the disk image. Drivers
* not implementing the functionality are assumed to not support backing files,
* hence all their sectors are reported as allocated.
*
* If 'sector_num' is beyond the end of the disk image the return value is 0
* and 'pnum' is set to 0.
*
* 'pnum' is set to the number of sectors (including and immediately following
* the specified sector) that are known to be in the same
* allocated/unallocated state.
*
* 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
* beyond the end of the disk image it will be clamped.
*/
static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
int64_t sector_num,
int nb_sectors, int *pnum)
{
int64_t total_sectors;
int64_t n;
int64_t ret, ret2;
total_sectors = bdrv_nb_sectors(bs);
if (total_sectors < 0) {
return total_sectors;
}
if (sector_num >= total_sectors) {
*pnum = 0;
return 0;
}
n = total_sectors - sector_num;
if (n < nb_sectors) {
nb_sectors = n;
}
if (!bs->drv->bdrv_co_get_block_status) {
*pnum = nb_sectors;
ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
if (bs->drv->protocol_name) {
ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
}
return ret;
}
ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
if (ret < 0) {
*pnum = 0;
return ret;
}
if (ret & BDRV_BLOCK_RAW) {
assert(ret & BDRV_BLOCK_OFFSET_VALID);
return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
*pnum, pnum);
}
if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
ret |= BDRV_BLOCK_ALLOCATED;
}
if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
if (bdrv_unallocated_blocks_are_zero(bs)) {
ret |= BDRV_BLOCK_ZERO;
} else if (bs->backing_hd) {
BlockDriverState *bs2 = bs->backing_hd;
int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
ret |= BDRV_BLOCK_ZERO;
}
}
}
if (bs->file &&
(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
(ret & BDRV_BLOCK_OFFSET_VALID)) {
int file_pnum;
ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
*pnum, &file_pnum);
if (ret2 >= 0) {
/* Ignore errors. This is just providing extra information, it
* is useful but not necessary.
*/
if (!file_pnum) {
/* !file_pnum indicates an offset at or beyond the EOF; it is
* perfectly valid for the format block driver to point to such
* offsets, so catch it and mark everything as zero */
ret |= BDRV_BLOCK_ZERO;
} else {
/* Limit request to the range reported by the protocol driver */
*pnum = file_pnum;
ret |= (ret2 & BDRV_BLOCK_ZERO);
}
}
}
return ret;
}
/* Coroutine wrapper for bdrv_get_block_status() */
static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
{
BdrvCoGetBlockStatusData *data = opaque;
BlockDriverState *bs = data->bs;
data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
data->pnum);
data->done = true;
}
/*
* Synchronous wrapper around bdrv_co_get_block_status().
*
* See bdrv_co_get_block_status() for details.
*/
int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, int *pnum)
{
Coroutine *co;
BdrvCoGetBlockStatusData data = {
.bs = bs,
.sector_num = sector_num,
.nb_sectors = nb_sectors,
.pnum = pnum,
.done = false,
};
if (qemu_in_coroutine()) {
/* Fast-path if already in coroutine context */
bdrv_get_block_status_co_entry(&data);
} else {
AioContext *aio_context = bdrv_get_aio_context(bs);
co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
qemu_coroutine_enter(co, &data);
while (!data.done) {
aio_poll(aio_context, true);
}
}
return data.ret;
}
int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, int *pnum)
{
int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
if (ret < 0) {
return ret;
}
return !!(ret & BDRV_BLOCK_ALLOCATED);
}
/*
* Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
*
* Return true if the given sector is allocated in any image between
* BASE and TOP (inclusive). BASE can be NULL to check if the given
* sector is allocated in any image of the chain. Return false otherwise.
*
* 'pnum' is set to the number of sectors (including and immediately following
* the specified sector) that are known to be in the same
* allocated/unallocated state.
*
*/
int bdrv_is_allocated_above(BlockDriverState *top,
BlockDriverState *base,
int64_t sector_num,
int nb_sectors, int *pnum)
{
BlockDriverState *intermediate;
int ret, n = nb_sectors;
intermediate = top;
while (intermediate && intermediate != base) {
int pnum_inter;
ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
&pnum_inter);
if (ret < 0) {
return ret;
} else if (ret) {
*pnum = pnum_inter;
return 1;
}
/*
* [sector_num, nb_sectors] is unallocated on top but intermediate
* might have
*
* [sector_num+x, nr_sectors] allocated.
*/
if (n > pnum_inter &&
(intermediate == top ||
sector_num + pnum_inter < intermediate->total_sectors)) {
n = pnum_inter;
}
intermediate = intermediate->backing_hd;
}
*pnum = n;
return 0;
}
const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
{
if (bs->backing_hd && bs->backing_hd->encrypted)
return bs->backing_file;
else if (bs->encrypted)
return bs->filename;
else
return NULL;
}
void bdrv_get_backing_filename(BlockDriverState *bs,
char *filename, int filename_size)
{
pstrcpy(filename, filename_size, bs->backing_file);
}
int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
const uint8_t *buf, int nb_sectors)
{
BlockDriver *drv = bs->drv;
if (!drv)
return -ENOMEDIUM;
if (!drv->bdrv_write_compressed)
return -ENOTSUP;
if (bdrv_check_request(bs, sector_num, nb_sectors))
return -EIO;
assert(QLIST_EMPTY(&bs->dirty_bitmaps));
return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
}
int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
{
BlockDriver *drv = bs->drv;
if (!drv)
return -ENOMEDIUM;
if (!drv->bdrv_get_info)
return -ENOTSUP;
memset(bdi, 0, sizeof(*bdi));
return drv->bdrv_get_info(bs, bdi);
}
ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
if (drv && drv->bdrv_get_specific_info) {
return drv->bdrv_get_specific_info(bs);
}
return NULL;
}
int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
int64_t pos, int size)
{
QEMUIOVector qiov;
struct iovec iov = {
.iov_base = (void *) buf,
.iov_len = size,
};
qemu_iovec_init_external(&qiov, &iov, 1);
return bdrv_writev_vmstate(bs, &qiov, pos);
}
int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
{
BlockDriver *drv = bs->drv;
if (!drv) {
return -ENOMEDIUM;
} else if (drv->bdrv_save_vmstate) {
return drv->bdrv_save_vmstate(bs, qiov, pos);
} else if (bs->file) {
return bdrv_writev_vmstate(bs->file, qiov, pos);
}
return -ENOTSUP;
}
int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
int64_t pos, int size)
{
BlockDriver *drv = bs->drv;
if (!drv)
return -ENOMEDIUM;
if (drv->bdrv_load_vmstate)
return drv->bdrv_load_vmstate(bs, buf, pos, size);
if (bs->file)
return bdrv_load_vmstate(bs->file, buf, pos, size);
return -ENOTSUP;
}
void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
{
if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
return;
}
bs->drv->bdrv_debug_event(bs, event);
}
int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
const char *tag)
{
while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
bs = bs->file;
}
if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
}
return -ENOTSUP;
}
int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
{
while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
bs = bs->file;
}
if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
}
return -ENOTSUP;
}
int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
{
while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
bs = bs->file;
}
if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
return bs->drv->bdrv_debug_resume(bs, tag);
}
return -ENOTSUP;
}
bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
{
while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
bs = bs->file;
}
if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
return bs->drv->bdrv_debug_is_suspended(bs, tag);
}
return false;
}
int bdrv_is_snapshot(BlockDriverState *bs)
{
return !!(bs->open_flags & BDRV_O_SNAPSHOT);
}
/* backing_file can either be relative, or absolute, or a protocol. If it is
* relative, it must be relative to the chain. So, passing in bs->filename
* from a BDS as backing_file should not be done, as that may be relative to
* the CWD rather than the chain. */
BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
const char *backing_file)
{
char *filename_full = NULL;
char *backing_file_full = NULL;
char *filename_tmp = NULL;
int is_protocol = 0;
BlockDriverState *curr_bs = NULL;
BlockDriverState *retval = NULL;
if (!bs || !bs->drv || !backing_file) {
return NULL;
}
filename_full = g_malloc(PATH_MAX);
backing_file_full = g_malloc(PATH_MAX);
filename_tmp = g_malloc(PATH_MAX);
is_protocol = path_has_protocol(backing_file);
for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
/* If either of the filename paths is actually a protocol, then
* compare unmodified paths; otherwise make paths relative */
if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
if (strcmp(backing_file, curr_bs->backing_file) == 0) {
retval = curr_bs->backing_hd;
break;
}
} else {
/* If not an absolute filename path, make it relative to the current
* image's filename path */
path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
backing_file);
/* We are going to compare absolute pathnames */
if (!realpath(filename_tmp, filename_full)) {
continue;
}
/* We need to make sure the backing filename we are comparing against
* is relative to the current image filename (or absolute) */
path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
curr_bs->backing_file);
if (!realpath(filename_tmp, backing_file_full)) {
continue;
}
if (strcmp(backing_file_full, filename_full) == 0) {
retval = curr_bs->backing_hd;
break;
}
}
}
g_free(filename_full);
g_free(backing_file_full);
g_free(filename_tmp);
return retval;
}
int bdrv_get_backing_file_depth(BlockDriverState *bs)
{
if (!bs->drv) {
return 0;
}
if (!bs->backing_hd) {
return 0;
}
return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
}
/**************************************************************/
/* async I/Os */
BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
QEMUIOVector *qiov, int nb_sectors,
BlockCompletionFunc *cb, void *opaque)
{
trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
cb, opaque, false);
}
BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
QEMUIOVector *qiov, int nb_sectors,
BlockCompletionFunc *cb, void *opaque)
{
trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
cb, opaque, true);
}
BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque)
{
trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
BDRV_REQ_ZERO_WRITE | flags,
cb, opaque, true);
}
typedef struct MultiwriteCB {
int error;
int num_requests;
int num_callbacks;
struct {
BlockCompletionFunc *cb;
void *opaque;
QEMUIOVector *free_qiov;
} callbacks[];
} MultiwriteCB;
static void multiwrite_user_cb(MultiwriteCB *mcb)
{
int i;
for (i = 0; i < mcb->num_callbacks; i++) {
mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
if (mcb->callbacks[i].free_qiov) {
qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
}
g_free(mcb->callbacks[i].free_qiov);
}
}
static void multiwrite_cb(void *opaque, int ret)
{
MultiwriteCB *mcb = opaque;
trace_multiwrite_cb(mcb, ret);
if (ret < 0 && !mcb->error) {
mcb->error = ret;
}
mcb->num_requests--;
if (mcb->num_requests == 0) {
multiwrite_user_cb(mcb);
g_free(mcb);
}
}
static int multiwrite_req_compare(const void *a, const void *b)
{
const BlockRequest *req1 = a, *req2 = b;
/*
* Note that we can't simply subtract req2->sector from req1->sector
* here as that could overflow the return value.
*/
if (req1->sector > req2->sector) {
return 1;
} else if (req1->sector < req2->sector) {
return -1;
} else {
return 0;
}
}
/*
* Takes a bunch of requests and tries to merge them. Returns the number of
* requests that remain after merging.
*/
static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
int num_reqs, MultiwriteCB *mcb)
{
int i, outidx;
// Sort requests by start sector
qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
// Check if adjacent requests touch the same clusters. If so, combine them,
// filling up gaps with zero sectors.
outidx = 0;
for (i = 1; i < num_reqs; i++) {
int merge = 0;
int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
// Handle exactly sequential writes and overlapping writes.
if (reqs[i].sector <= oldreq_last) {
merge = 1;
}
if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
merge = 0;
}
if (merge) {
size_t size;
QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
qemu_iovec_init(qiov,
reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
// Add the first request to the merged one. If the requests are
// overlapping, drop the last sectors of the first request.
size = (reqs[i].sector - reqs[outidx].sector) << 9;
qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
// We should need to add any zeros between the two requests
assert (reqs[i].sector <= oldreq_last);
// Add the second request
qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
// Add tail of first request, if necessary
if (qiov->size < reqs[outidx].qiov->size) {
qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size,
reqs[outidx].qiov->size - qiov->size);
}
reqs[outidx].nb_sectors = qiov->size >> 9;
reqs[outidx].qiov = qiov;
mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
} else {
outidx++;
reqs[outidx].sector = reqs[i].sector;
reqs[outidx].nb_sectors = reqs[i].nb_sectors;
reqs[outidx].qiov = reqs[i].qiov;
}
}
return outidx + 1;
}
/*
* Submit multiple AIO write requests at once.
*
* On success, the function returns 0 and all requests in the reqs array have
* been submitted. In error case this function returns -1, and any of the
* requests may or may not be submitted yet. In particular, this means that the
* callback will be called for some of the requests, for others it won't. The
* caller must check the error field of the BlockRequest to wait for the right
* callbacks (if error != 0, no callback will be called).
*
* The implementation may modify the contents of the reqs array, e.g. to merge
* requests. However, the fields opaque and error are left unmodified as they
* are used to signal failure for a single request to the caller.
*/
int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
{
MultiwriteCB *mcb;
int i;
/* don't submit writes if we don't have a medium */
if (bs->drv == NULL) {
for (i = 0; i < num_reqs; i++) {
reqs[i].error = -ENOMEDIUM;
}
return -1;
}
if (num_reqs == 0) {
return 0;
}
// Create MultiwriteCB structure
mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
mcb->num_requests = 0;
mcb->num_callbacks = num_reqs;
for (i = 0; i < num_reqs; i++) {
mcb->callbacks[i].cb = reqs[i].cb;
mcb->callbacks[i].opaque = reqs[i].opaque;
}
// Check for mergable requests
num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
/* Run the aio requests. */
mcb->num_requests = num_reqs;
for (i = 0; i < num_reqs; i++) {
bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
reqs[i].nb_sectors, reqs[i].flags,
multiwrite_cb, mcb,
true);
}
return 0;
}
void bdrv_aio_cancel(BlockAIOCB *acb)
{
qemu_aio_ref(acb);
bdrv_aio_cancel_async(acb);
while (acb->refcnt > 1) {
if (acb->aiocb_info->get_aio_context) {
aio_poll(acb->aiocb_info->get_aio_context(acb), true);
} else if (acb->bs) {
aio_poll(bdrv_get_aio_context(acb->bs), true);
} else {
abort();
}
}
qemu_aio_unref(acb);
}
/* Async version of aio cancel. The caller is not blocked if the acb implements
* cancel_async, otherwise we do nothing and let the request normally complete.
* In either case the completion callback must be called. */
void bdrv_aio_cancel_async(BlockAIOCB *acb)
{
if (acb->aiocb_info->cancel_async) {
acb->aiocb_info->cancel_async(acb);
}
}
/**************************************************************/
/* async block device emulation */
typedef struct BlockAIOCBSync {
BlockAIOCB common;
QEMUBH *bh;
int ret;
/* vector translation state */
QEMUIOVector *qiov;
uint8_t *bounce;
int is_write;
} BlockAIOCBSync;
static const AIOCBInfo bdrv_em_aiocb_info = {
.aiocb_size = sizeof(BlockAIOCBSync),
};
static void bdrv_aio_bh_cb(void *opaque)
{
BlockAIOCBSync *acb = opaque;
if (!acb->is_write && acb->ret >= 0) {
qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
}
qemu_vfree(acb->bounce);
acb->common.cb(acb->common.opaque, acb->ret);
qemu_bh_delete(acb->bh);
acb->bh = NULL;
qemu_aio_unref(acb);
}
static BlockAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
int64_t sector_num,
QEMUIOVector *qiov,
int nb_sectors,
BlockCompletionFunc *cb,
void *opaque,
int is_write)
{
BlockAIOCBSync *acb;
acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
acb->is_write = is_write;
acb->qiov = qiov;
acb->bounce = qemu_try_blockalign(bs, qiov->size);
acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb);
if (acb->bounce == NULL) {
acb->ret = -ENOMEM;
} else if (is_write) {
qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
} else {
acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
}
qemu_bh_schedule(acb->bh);
return &acb->common;
}
static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
BlockCompletionFunc *cb, void *opaque)
{
return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
}
static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
BlockCompletionFunc *cb, void *opaque)
{
return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
}
typedef struct BlockAIOCBCoroutine {
BlockAIOCB common;
BlockRequest req;
bool is_write;
bool *done;
QEMUBH* bh;
} BlockAIOCBCoroutine;
static const AIOCBInfo bdrv_em_co_aiocb_info = {
.aiocb_size = sizeof(BlockAIOCBCoroutine),
};
static void bdrv_co_em_bh(void *opaque)
{
BlockAIOCBCoroutine *acb = opaque;
acb->common.cb(acb->common.opaque, acb->req.error);
qemu_bh_delete(acb->bh);
qemu_aio_unref(acb);
}
/* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
static void coroutine_fn bdrv_co_do_rw(void *opaque)
{
BlockAIOCBCoroutine *acb = opaque;
BlockDriverState *bs = acb->common.bs;
if (!acb->is_write) {
acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
} else {
acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
}
acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
qemu_bh_schedule(acb->bh);
}
static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
int64_t sector_num,
QEMUIOVector *qiov,
int nb_sectors,
BdrvRequestFlags flags,
BlockCompletionFunc *cb,
void *opaque,
bool is_write)
{
Coroutine *co;
BlockAIOCBCoroutine *acb;
acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
acb->req.sector = sector_num;
acb->req.nb_sectors = nb_sectors;
acb->req.qiov = qiov;
acb->req.flags = flags;
acb->is_write = is_write;
co = qemu_coroutine_create(bdrv_co_do_rw);
qemu_coroutine_enter(co, acb);
return &acb->common;
}
static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
{
BlockAIOCBCoroutine *acb = opaque;
BlockDriverState *bs = acb->common.bs;
acb->req.error = bdrv_co_flush(bs);
acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
qemu_bh_schedule(acb->bh);
}
BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
BlockCompletionFunc *cb, void *opaque)
{
trace_bdrv_aio_flush(bs, opaque);
Coroutine *co;
BlockAIOCBCoroutine *acb;
acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
qemu_coroutine_enter(co, acb);
return &acb->common;
}
static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
{
BlockAIOCBCoroutine *acb = opaque;
BlockDriverState *bs = acb->common.bs;
acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
qemu_bh_schedule(acb->bh);
}
BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,
int64_t sector_num, int nb_sectors,
BlockCompletionFunc *cb, void *opaque)
{
Coroutine *co;
BlockAIOCBCoroutine *acb;
trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
acb->req.sector = sector_num;
acb->req.nb_sectors = nb_sectors;
co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
qemu_coroutine_enter(co, acb);
return &acb->common;
}
void bdrv_init(void)
{
module_call_init(MODULE_INIT_BLOCK);
}
void bdrv_init_with_whitelist(void)
{
use_bdrv_whitelist = 1;
bdrv_init();
}
void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
BlockCompletionFunc *cb, void *opaque)
{
BlockAIOCB *acb;
acb = g_slice_alloc(aiocb_info->aiocb_size);
acb->aiocb_info = aiocb_info;
acb->bs = bs;
acb->cb = cb;
acb->opaque = opaque;
acb->refcnt = 1;
return acb;
}
void qemu_aio_ref(void *p)
{
BlockAIOCB *acb = p;
acb->refcnt++;
}
void qemu_aio_unref(void *p)
{
BlockAIOCB *acb = p;
assert(acb->refcnt > 0);
if (--acb->refcnt == 0) {
g_slice_free1(acb->aiocb_info->aiocb_size, acb);
}
}
/**************************************************************/
/* Coroutine block device emulation */
typedef struct CoroutineIOCompletion {
Coroutine *coroutine;
int ret;
} CoroutineIOCompletion;
static void bdrv_co_io_em_complete(void *opaque, int ret)
{
CoroutineIOCompletion *co = opaque;
co->ret = ret;
qemu_coroutine_enter(co->coroutine, NULL);
}
static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
int nb_sectors, QEMUIOVector *iov,
bool is_write)
{
CoroutineIOCompletion co = {
.coroutine = qemu_coroutine_self(),
};
BlockAIOCB *acb;
if (is_write) {
acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
bdrv_co_io_em_complete, &co);
} else {
acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
bdrv_co_io_em_complete, &co);
}
trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
if (!acb) {
return -EIO;
}
qemu_coroutine_yield();
return co.ret;
}
static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
int64_t sector_num, int nb_sectors,
QEMUIOVector *iov)
{
return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
}
static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
int64_t sector_num, int nb_sectors,
QEMUIOVector *iov)
{
return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
}
static void coroutine_fn bdrv_flush_co_entry(void *opaque)
{
RwCo *rwco = opaque;
rwco->ret = bdrv_co_flush(rwco->bs);
}
int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
{
int ret;
if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
return 0;
}
/* Write back cached data to the OS even with cache=unsafe */
BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
if (bs->drv->bdrv_co_flush_to_os) {
ret = bs->drv->bdrv_co_flush_to_os(bs);
if (ret < 0) {
return ret;
}
}
/* But don't actually force it to the disk with cache=unsafe */
if (bs->open_flags & BDRV_O_NO_FLUSH) {
goto flush_parent;
}
BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
if (bs->drv->bdrv_co_flush_to_disk) {
ret = bs->drv->bdrv_co_flush_to_disk(bs);
} else if (bs->drv->bdrv_aio_flush) {
BlockAIOCB *acb;
CoroutineIOCompletion co = {
.coroutine = qemu_coroutine_self(),
};
acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
if (acb == NULL) {
ret = -EIO;
} else {
qemu_coroutine_yield();
ret = co.ret;
}
} else {
/*
* Some block drivers always operate in either writethrough or unsafe
* mode and don't support bdrv_flush therefore. Usually qemu doesn't
* know how the server works (because the behaviour is hardcoded or
* depends on server-side configuration), so we can't ensure that
* everything is safe on disk. Returning an error doesn't work because
* that would break guests even if the server operates in writethrough
* mode.
*
* Let's hope the user knows what he's doing.
*/
ret = 0;
}
if (ret < 0) {
return ret;
}
/* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
* in the case of cache=unsafe, so there are no useless flushes.
*/
flush_parent:
return bdrv_co_flush(bs->file);
}
void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
{
Error *local_err = NULL;
int ret;
if (!bs->drv) {
return;
}
if (!(bs->open_flags & BDRV_O_INCOMING)) {
return;
}
bs->open_flags &= ~BDRV_O_INCOMING;
if (bs->drv->bdrv_invalidate_cache) {
bs->drv->bdrv_invalidate_cache(bs, &local_err);
} else if (bs->file) {
bdrv_invalidate_cache(bs->file, &local_err);
}
if (local_err) {
error_propagate(errp, local_err);
return;
}
ret = refresh_total_sectors(bs, bs->total_sectors);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not refresh total sector count");
return;
}
}
void bdrv_invalidate_cache_all(Error **errp)
{
BlockDriverState *bs;
Error *local_err = NULL;
QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
AioContext *aio_context = bdrv_get_aio_context(bs);
aio_context_acquire(aio_context);
bdrv_invalidate_cache(bs, &local_err);
aio_context_release(aio_context);
if (local_err) {
error_propagate(errp, local_err);
return;
}
}
}
int bdrv_flush(BlockDriverState *bs)
{
Coroutine *co;
RwCo rwco = {
.bs = bs,
.ret = NOT_DONE,
};
if (qemu_in_coroutine()) {
/* Fast-path if already in coroutine context */
bdrv_flush_co_entry(&rwco);
} else {
AioContext *aio_context = bdrv_get_aio_context(bs);
co = qemu_coroutine_create(bdrv_flush_co_entry);
qemu_coroutine_enter(co, &rwco);
while (rwco.ret == NOT_DONE) {
aio_poll(aio_context, true);
}
}
return rwco.ret;
}
typedef struct DiscardCo {
BlockDriverState *bs;
int64_t sector_num;
int nb_sectors;
int ret;
} DiscardCo;
static void coroutine_fn bdrv_discard_co_entry(void *opaque)
{
DiscardCo *rwco = opaque;
rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
}
/* if no limit is specified in the BlockLimits use a default
* of 32768 512-byte sectors (16 MiB) per request.
*/
#define MAX_DISCARD_DEFAULT 32768
int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
int nb_sectors)
{
int max_discard;
if (!bs->drv) {
return -ENOMEDIUM;
} else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
return -EIO;
} else if (bs->read_only) {
return -EROFS;
}
bdrv_reset_dirty(bs, sector_num, nb_sectors);
/* Do nothing if disabled. */
if (!(bs->open_flags & BDRV_O_UNMAP)) {
return 0;
}
if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
return 0;
}
max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT;
while (nb_sectors > 0) {
int ret;
int num = nb_sectors;
/* align request */
if (bs->bl.discard_alignment &&
num >= bs->bl.discard_alignment &&
sector_num % bs->bl.discard_alignment) {
if (num > bs->bl.discard_alignment) {
num = bs->bl.discard_alignment;
}
num -= sector_num % bs->bl.discard_alignment;
}
/* limit request size */
if (num > max_discard) {
num = max_discard;
}
if (bs->drv->bdrv_co_discard) {
ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
} else {
BlockAIOCB *acb;
CoroutineIOCompletion co = {
.coroutine = qemu_coroutine_self(),
};
acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
bdrv_co_io_em_complete, &co);
if (acb == NULL) {
return -EIO;
} else {
qemu_coroutine_yield();
ret = co.ret;
}
}
if (ret && ret != -ENOTSUP) {
return ret;
}
sector_num += num;
nb_sectors -= num;
}
return 0;
}
int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
{
Coroutine *co;
DiscardCo rwco = {
.bs = bs,
.sector_num = sector_num,
.nb_sectors = nb_sectors,
.ret = NOT_DONE,
};
if (qemu_in_coroutine()) {
/* Fast-path if already in coroutine context */
bdrv_discard_co_entry(&rwco);
} else {
AioContext *aio_context = bdrv_get_aio_context(bs);
co = qemu_coroutine_create(bdrv_discard_co_entry);
qemu_coroutine_enter(co, &rwco);
while (rwco.ret == NOT_DONE) {
aio_poll(aio_context, true);
}
}
return rwco.ret;
}
/**************************************************************/
/* removable device support */
/**
* Return TRUE if the media is present
*/
int bdrv_is_inserted(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
if (!drv)
return 0;
if (!drv->bdrv_is_inserted)
return 1;
return drv->bdrv_is_inserted(bs);
}
/**
* Return whether the media changed since the last call to this
* function, or -ENOTSUP if we don't know. Most drivers don't know.
*/
int bdrv_media_changed(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
if (drv && drv->bdrv_media_changed) {
return drv->bdrv_media_changed(bs);
}
return -ENOTSUP;
}
/**
* If eject_flag is TRUE, eject the media. Otherwise, close the tray
*/
void bdrv_eject(BlockDriverState *bs, bool eject_flag)
{
BlockDriver *drv = bs->drv;
const char *device_name;
if (drv && drv->bdrv_eject) {
drv->bdrv_eject(bs, eject_flag);
}
device_name = bdrv_get_device_name(bs);
if (device_name[0] != '\0') {
qapi_event_send_device_tray_moved(device_name,
eject_flag, &error_abort);
}
}
/**
* Lock or unlock the media (if it is locked, the user won't be able
* to eject it manually).
*/
void bdrv_lock_medium(BlockDriverState *bs, bool locked)
{
BlockDriver *drv = bs->drv;
trace_bdrv_lock_medium(bs, locked);
if (drv && drv->bdrv_lock_medium) {
drv->bdrv_lock_medium(bs, locked);
}
}
/* needed for generic scsi interface */
int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
{
BlockDriver *drv = bs->drv;
if (drv && drv->bdrv_ioctl)
return drv->bdrv_ioctl(bs, req, buf);
return -ENOTSUP;
}
BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
unsigned long int req, void *buf,
BlockCompletionFunc *cb, void *opaque)
{
BlockDriver *drv = bs->drv;
if (drv && drv->bdrv_aio_ioctl)
return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
return NULL;
}
void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
{
bs->guest_block_size = align;
}
void *qemu_blockalign(BlockDriverState *bs, size_t size)
{
return qemu_memalign(bdrv_opt_mem_align(bs), size);
}
void *qemu_blockalign0(BlockDriverState *bs, size_t size)
{
return memset(qemu_blockalign(bs, size), 0, size);
}
void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
{
size_t align = bdrv_opt_mem_align(bs);
/* Ensure that NULL is never returned on success */
assert(align > 0);
if (size == 0) {
size = align;
}
return qemu_try_memalign(align, size);
}
void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
{
void *mem = qemu_try_blockalign(bs, size);
if (mem) {
memset(mem, 0, size);
}
return mem;
}
/*
* Check if all memory in this vector is sector aligned.
*/
bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
{
int i;
size_t alignment = bdrv_opt_mem_align(bs);
for (i = 0; i < qiov->niov; i++) {
if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
return false;
}
if (qiov->iov[i].iov_len % alignment) {
return false;
}
}
return true;
}
BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity,
Error **errp)
{
int64_t bitmap_size;
BdrvDirtyBitmap *bitmap;
assert((granularity & (granularity - 1)) == 0);
granularity >>= BDRV_SECTOR_BITS;
assert(granularity);
bitmap_size = bdrv_nb_sectors(bs);
if (bitmap_size < 0) {
error_setg_errno(errp, -bitmap_size, "could not get length of device");
errno = -bitmap_size;
return NULL;
}
bitmap = g_new0(BdrvDirtyBitmap, 1);
bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
return bitmap;
}
void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
{
BdrvDirtyBitmap *bm, *next;
QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
if (bm == bitmap) {
QLIST_REMOVE(bitmap, list);
hbitmap_free(bitmap->bitmap);
g_free(bitmap);
return;
}
}
}
BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
{
BdrvDirtyBitmap *bm;
BlockDirtyInfoList *list = NULL;
BlockDirtyInfoList **plist = &list;
QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
info->count = bdrv_get_dirty_count(bs, bm);
info->granularity =
((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
entry->value = info;
*plist = entry;
plist = &entry->next;
}
return list;
}
int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
{
if (bitmap) {
return hbitmap_get(bitmap->bitmap, sector);
} else {
return 0;
}
}
void bdrv_dirty_iter_init(BlockDriverState *bs,
BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
{
hbitmap_iter_init(hbi, bitmap->bitmap, 0);
}
void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
int nr_sectors)
{
BdrvDirtyBitmap *bitmap;
QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
}
}
void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
{
BdrvDirtyBitmap *bitmap;
QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
}
}
int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
{
return hbitmap_count(bitmap->bitmap);
}
/* Get a reference to bs */
void bdrv_ref(BlockDriverState *bs)
{
bs->refcnt++;
}
/* Release a previously grabbed reference to bs.
* If after releasing, reference count is zero, the BlockDriverState is
* deleted. */
void bdrv_unref(BlockDriverState *bs)
{
if (!bs) {
return;
}
assert(bs->refcnt > 0);
if (--bs->refcnt == 0) {
bdrv_delete(bs);
}
}
struct BdrvOpBlocker {
Error *reason;
QLIST_ENTRY(BdrvOpBlocker) list;
};
bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
{
BdrvOpBlocker *blocker;
assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
if (!QLIST_EMPTY(&bs->op_blockers[op])) {
blocker = QLIST_FIRST(&bs->op_blockers[op]);
if (errp) {
error_setg(errp, "Device '%s' is busy: %s",
bdrv_get_device_name(bs),
error_get_pretty(blocker->reason));
}
return true;
}
return false;
}
void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
{
BdrvOpBlocker *blocker;
assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
blocker = g_new0(BdrvOpBlocker, 1);
blocker->reason = reason;
QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
}
void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
{
BdrvOpBlocker *blocker, *next;
assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
if (blocker->reason == reason) {
QLIST_REMOVE(blocker, list);
g_free(blocker);
}
}
}
void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
{
int i;
for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
bdrv_op_block(bs, i, reason);
}
}
void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
{
int i;
for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
bdrv_op_unblock(bs, i, reason);
}
}
bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
{
int i;
for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
if (!QLIST_EMPTY(&bs->op_blockers[i])) {
return false;
}
}
return true;
}
void bdrv_iostatus_enable(BlockDriverState *bs)
{
bs->iostatus_enabled = true;
bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
}
/* The I/O status is only enabled if the drive explicitly
* enables it _and_ the VM is configured to stop on errors */
bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
{
return (bs->iostatus_enabled &&
(bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
bs->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
}
void bdrv_iostatus_disable(BlockDriverState *bs)
{
bs->iostatus_enabled = false;
}
void bdrv_iostatus_reset(BlockDriverState *bs)
{
if (bdrv_iostatus_is_enabled(bs)) {
bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
if (bs->job) {
block_job_iostatus_reset(bs->job);
}
}
}
void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
{
assert(bdrv_iostatus_is_enabled(bs));
if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
BLOCK_DEVICE_IO_STATUS_FAILED;
}
}
void bdrv_img_create(const char *filename, const char *fmt,
const char *base_filename, const char *base_fmt,
char *options, uint64_t img_size, int flags,
Error **errp, bool quiet)
{
QemuOptsList *create_opts = NULL;
QemuOpts *opts = NULL;
const char *backing_fmt, *backing_file;
int64_t size;
BlockDriver *drv, *proto_drv;
BlockDriver *backing_drv = NULL;
Error *local_err = NULL;
int ret = 0;
/* Find driver and parse its options */
drv = bdrv_find_format(fmt);
if (!drv) {
error_setg(errp, "Unknown file format '%s'", fmt);
return;
}
proto_drv = bdrv_find_protocol(filename, true);
if (!proto_drv) {
error_setg(errp, "Unknown protocol '%s'", filename);
return;
}
create_opts = qemu_opts_append(create_opts, drv->create_opts);
create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
/* Create parameter list with default values */
opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size);
/* Parse -o options */
if (options) {
if (qemu_opts_do_parse(opts, options, NULL) != 0) {
error_setg(errp, "Invalid options for file format '%s'", fmt);
goto out;
}
}
if (base_filename) {
if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
error_setg(errp, "Backing file not supported for file format '%s'",
fmt);
goto out;
}
}
if (base_fmt) {
if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
error_setg(errp, "Backing file format not supported for file "
"format '%s'", fmt);
goto out;
}
}
backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
if (backing_file) {
if (!strcmp(filename, backing_file)) {
error_setg(errp, "Error: Trying to create an image with the "
"same filename as the backing file");
goto out;
}
}
backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
if (backing_fmt) {
backing_drv = bdrv_find_format(backing_fmt);
if (!backing_drv) {
error_setg(errp, "Unknown backing file format '%s'",
backing_fmt);
goto out;
}
}
// The size for the image must always be specified, with one exception:
// If we are using a backing file, we can obtain the size from there
size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
if (size == -1) {
if (backing_file) {
BlockDriverState *bs;
int64_t size;
int back_flags;
/* backing files always opened read-only */
back_flags =
flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
bs = NULL;
ret = bdrv_open(&bs, backing_file, NULL, NULL, back_flags,
backing_drv, &local_err);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not open '%s': %s",
backing_file,
error_get_pretty(local_err));
error_free(local_err);
local_err = NULL;
goto out;
}
size = bdrv_getlength(bs);
if (size < 0) {
error_setg_errno(errp, -size, "Could not get size of '%s'",
backing_file);
bdrv_unref(bs);
goto out;
}
qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size);
bdrv_unref(bs);
} else {
error_setg(errp, "Image creation needs a size parameter");
goto out;
}
}
if (!quiet) {
printf("Formatting '%s', fmt=%s ", filename, fmt);
qemu_opts_print(opts);
puts("");
}
ret = bdrv_create(drv, filename, opts, &local_err);
if (ret == -EFBIG) {
/* This is generally a better message than whatever the driver would
* deliver (especially because of the cluster_size_hint), since that
* is most probably not much different from "image too large". */
const char *cluster_size_hint = "";
if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
cluster_size_hint = " (try using a larger cluster size)";
}
error_setg(errp, "The image size is too large for file format '%s'"
"%s", fmt, cluster_size_hint);
error_free(local_err);
local_err = NULL;
}
out:
qemu_opts_del(opts);
qemu_opts_free(create_opts);
if (local_err) {
error_propagate(errp, local_err);
}
}
AioContext *bdrv_get_aio_context(BlockDriverState *bs)
{
return bs->aio_context;
}
void bdrv_detach_aio_context(BlockDriverState *bs)
{
BdrvAioNotifier *baf;
if (!bs->drv) {
return;
}
QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
baf->detach_aio_context(baf->opaque);
}
if (bs->io_limits_enabled) {
throttle_detach_aio_context(&bs->throttle_state);
}
if (bs->drv->bdrv_detach_aio_context) {
bs->drv->bdrv_detach_aio_context(bs);
}
if (bs->file) {
bdrv_detach_aio_context(bs->file);
}
if (bs->backing_hd) {
bdrv_detach_aio_context(bs->backing_hd);
}
bs->aio_context = NULL;
}
void bdrv_attach_aio_context(BlockDriverState *bs,
AioContext *new_context)
{
BdrvAioNotifier *ban;
if (!bs->drv) {
return;
}
bs->aio_context = new_context;
if (bs->backing_hd) {
bdrv_attach_aio_context(bs->backing_hd, new_context);
}
if (bs->file) {
bdrv_attach_aio_context(bs->file, new_context);
}
if (bs->drv->bdrv_attach_aio_context) {
bs->drv->bdrv_attach_aio_context(bs, new_context);
}
if (bs->io_limits_enabled) {
throttle_attach_aio_context(&bs->throttle_state, new_context);
}
QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
ban->attached_aio_context(new_context, ban->opaque);
}
}
void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
{
bdrv_drain_all(); /* ensure there are no in-flight requests */
bdrv_detach_aio_context(bs);
/* This function executes in the old AioContext so acquire the new one in
* case it runs in a different thread.
*/
aio_context_acquire(new_context);
bdrv_attach_aio_context(bs, new_context);
aio_context_release(new_context);
}
void bdrv_add_aio_context_notifier(BlockDriverState *bs,
void (*attached_aio_context)(AioContext *new_context, void *opaque),
void (*detach_aio_context)(void *opaque), void *opaque)
{
BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
*ban = (BdrvAioNotifier){
.attached_aio_context = attached_aio_context,
.detach_aio_context = detach_aio_context,
.opaque = opaque
};
QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
}
void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
void (*attached_aio_context)(AioContext *,
void *),
void (*detach_aio_context)(void *),
void *opaque)
{
BdrvAioNotifier *ban, *ban_next;
QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
if (ban->attached_aio_context == attached_aio_context &&
ban->detach_aio_context == detach_aio_context &&
ban->opaque == opaque)
{
QLIST_REMOVE(ban, list);
g_free(ban);
return;
}
}
abort();
}
void bdrv_add_before_write_notifier(BlockDriverState *bs,
NotifierWithReturn *notifier)
{
notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
}
int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts)
{
if (!bs->drv->bdrv_amend_options) {
return -ENOTSUP;
}
return bs->drv->bdrv_amend_options(bs, opts);
}
/* This function will be called by the bdrv_recurse_is_first_non_filter method
* of block filter and by bdrv_is_first_non_filter.
* It is used to test if the given bs is the candidate or recurse more in the
* node graph.
*/
bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
BlockDriverState *candidate)
{
/* return false if basic checks fails */
if (!bs || !bs->drv) {
return false;
}
/* the code reached a non block filter driver -> check if the bs is
* the same as the candidate. It's the recursion termination condition.
*/
if (!bs->drv->is_filter) {
return bs == candidate;
}
/* Down this path the driver is a block filter driver */
/* If the block filter recursion method is defined use it to recurse down
* the node graph.
*/
if (bs->drv->bdrv_recurse_is_first_non_filter) {
return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
}
/* the driver is a block filter but don't allow to recurse -> return false
*/
return false;
}
/* This function checks if the candidate is the first non filter bs down it's
* bs chain. Since we don't have pointers to parents it explore all bs chains
* from the top. Some filters can choose not to pass down the recursion.
*/
bool bdrv_is_first_non_filter(BlockDriverState *candidate)
{
BlockDriverState *bs;
/* walk down the bs forest recursively */
QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
bool perm;
/* try to recurse in this top level bs */
perm = bdrv_recurse_is_first_non_filter(bs, candidate);
/* candidate is the first non filter */
if (perm) {
return true;
}
}
return false;
}
BlockDriverState *check_to_replace_node(const char *node_name, Error **errp)
{
BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
if (!to_replace_bs) {
error_setg(errp, "Node name '%s' not found", node_name);
return NULL;
}
if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
return NULL;
}
/* We don't want arbitrary node of the BDS chain to be replaced only the top
* most non filter in order to prevent data corruption.
* Another benefit is that this tests exclude backing files which are
* blocked by the backing blockers.
*/
if (!bdrv_is_first_non_filter(to_replace_bs)) {
error_setg(errp, "Only top most non filter can be replaced");
return NULL;
}
return to_replace_bs;
}
void bdrv_io_plug(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
if (drv && drv->bdrv_io_plug) {
drv->bdrv_io_plug(bs);
} else if (bs->file) {
bdrv_io_plug(bs->file);
}
}
void bdrv_io_unplug(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
if (drv && drv->bdrv_io_unplug) {
drv->bdrv_io_unplug(bs);
} else if (bs->file) {
bdrv_io_unplug(bs->file);
}
}
void bdrv_flush_io_queue(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
if (drv && drv->bdrv_flush_io_queue) {
drv->bdrv_flush_io_queue(bs);
} else if (bs->file) {
bdrv_flush_io_queue(bs->file);
}
}
static bool append_open_options(QDict *d, BlockDriverState *bs)
{
const QDictEntry *entry;
bool found_any = false;
for (entry = qdict_first(bs->options); entry;
entry = qdict_next(bs->options, entry))
{
/* Only take options for this level and exclude all non-driver-specific
* options */
if (!strchr(qdict_entry_key(entry), '.') &&
strcmp(qdict_entry_key(entry), "node-name"))
{
qobject_incref(qdict_entry_value(entry));
qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
found_any = true;
}
}
return found_any;
}
/* Updates the following BDS fields:
* - exact_filename: A filename which may be used for opening a block device
* which (mostly) equals the given BDS (even without any
* other options; so reading and writing must return the same
* results, but caching etc. may be different)
* - full_open_options: Options which, when given when opening a block device
* (without a filename), result in a BDS (mostly)
* equalling the given one
* - filename: If exact_filename is set, it is copied here. Otherwise,
* full_open_options is converted to a JSON object, prefixed with
* "json:" (for use through the JSON pseudo protocol) and put here.
*/
void bdrv_refresh_filename(BlockDriverState *bs)
{
BlockDriver *drv = bs->drv;
QDict *opts;
if (!drv) {
return;
}
/* This BDS's file name will most probably depend on its file's name, so
* refresh that first */
if (bs->file) {
bdrv_refresh_filename(bs->file);
}
if (drv->bdrv_refresh_filename) {
/* Obsolete information is of no use here, so drop the old file name
* information before refreshing it */
bs->exact_filename[0] = '\0';
if (bs->full_open_options) {
QDECREF(bs->full_open_options);
bs->full_open_options = NULL;
}
drv->bdrv_refresh_filename(bs);
} else if (bs->file) {
/* Try to reconstruct valid information from the underlying file */
bool has_open_options;
bs->exact_filename[0] = '\0';
if (bs->full_open_options) {
QDECREF(bs->full_open_options);
bs->full_open_options = NULL;
}
opts = qdict_new();
has_open_options = append_open_options(opts, bs);
/* If no specific options have been given for this BDS, the filename of
* the underlying file should suffice for this one as well */
if (bs->file->exact_filename[0] && !has_open_options) {
strcpy(bs->exact_filename, bs->file->exact_filename);
}
/* Reconstructing the full options QDict is simple for most format block
* drivers, as long as the full options are known for the underlying
* file BDS. The full options QDict of that file BDS should somehow
* contain a representation of the filename, therefore the following
* suffices without querying the (exact_)filename of this BDS. */
if (bs->file->full_open_options) {
qdict_put_obj(opts, "driver",
QOBJECT(qstring_from_str(drv->format_name)));
QINCREF(bs->file->full_open_options);
qdict_put_obj(opts, "file", QOBJECT(bs->file->full_open_options));
bs->full_open_options = opts;
} else {
QDECREF(opts);
}
} else if (!bs->full_open_options && qdict_size(bs->options)) {
/* There is no underlying file BDS (at least referenced by BDS.file),
* so the full options QDict should be equal to the options given
* specifically for this block device when it was opened (plus the
* driver specification).
* Because those options don't change, there is no need to update
* full_open_options when it's already set. */
opts = qdict_new();
append_open_options(opts, bs);
qdict_put_obj(opts, "driver",
QOBJECT(qstring_from_str(drv->format_name)));
if (bs->exact_filename[0]) {
/* This may not work for all block protocol drivers (some may
* require this filename to be parsed), but we have to find some
* default solution here, so just include it. If some block driver
* does not support pure options without any filename at all or
* needs some special format of the options QDict, it needs to
* implement the driver-specific bdrv_refresh_filename() function.
*/
qdict_put_obj(opts, "filename",
QOBJECT(qstring_from_str(bs->exact_filename)));
}
bs->full_open_options = opts;
}
if (bs->exact_filename[0]) {
pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
} else if (bs->full_open_options) {
QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
snprintf(bs->filename, sizeof(bs->filename), "json:%s",
qstring_get_str(json));
QDECREF(json);
}
}
/* This accessor function purpose is to allow the device models to access the
* BlockAcctStats structure embedded inside a BlockDriverState without being
* aware of the BlockDriverState structure layout.
* It will go away when the BlockAcctStats structure will be moved inside
* the device models.
*/
BlockAcctStats *bdrv_get_stats(BlockDriverState *bs)
{
return &bs->stats;
}
| AnttiLukats/orp | third-party/qemu-orp/block.c | C | apache-2.0 | 173,814 |
package org.apache.maven.artifact.manager;
/*
* 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.
*/
import java.util.List;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.authentication.AuthenticationInfo;
import org.apache.maven.wagon.proxy.ProxyInfo;
/**
* Manages <a href="https://maven.apache.org/wagon">Wagon</a> related operations in Maven.
*
* @author <a href="michal.maczka@dimatics.com">Michal Maczka </a>
*/
@Deprecated
public interface WagonManager
extends org.apache.maven.repository.legacy.WagonManager
{
/**
* this method is only here for backward compat (project-info-reports:dependencies)
* the default implementation will return an empty AuthenticationInfo
*/
AuthenticationInfo getAuthenticationInfo( String id );
ProxyInfo getProxy( String protocol );
void getArtifact( Artifact artifact, ArtifactRepository repository )
throws TransferFailedException, ResourceDoesNotExistException;
void getArtifact( Artifact artifact, List<ArtifactRepository> remoteRepositories )
throws TransferFailedException, ResourceDoesNotExistException;
ArtifactRepository getMirrorRepository( ArtifactRepository repository );
}
| lbndev/maven | maven-compat/src/main/java/org/apache/maven/artifact/manager/WagonManager.java | Java | apache-2.0 | 2,151 |
# Overview
Module Name: Scaleable Analytics Adapter
Module Type: Analytics Adapter
Maintainer: chris@scaleable.ai
# Description
Analytics adapter for scaleable.ai. Contact team@scaleable.ai for more information or to sign up for analytics.
# Implementation Code
```
pbjs.enableAnalytics({
provider: 'scaleable',
options: {
site: '' // Contact Scaleable to receive your unique site id
}
});
```
| varashellov/Prebid.js | modules/scaleableAnalyticsAdapter.md | Markdown | apache-2.0 | 409 |
<?php
/*
* $Id: SizeSelector.php 526 2009-08-11 12:11:17Z mrook $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
/**
* Selector that filters files based on their size.
*
* @author Hans Lellelid <hans@xmpl.org> (Phing)
* @author Bruce Atherton <bruce@callenish.com> (Ant)
* @package phing.types.selectors
*/
class SizeSelector extends BaseExtendSelector {
private $size = -1;
private $multiplier = 1;
private $sizelimit = -1;
private $cmp = 2;
const SIZE_KEY = "value";
const UNITS_KEY = "units";
const WHEN_KEY = "when";
private static $sizeComparisons = array("less", "more", "equal");
private static $byteUnits = array("K", "k", "kilo", "KILO",
"Ki", "KI", "ki", "kibi", "KIBI",
"M", "m", "mega", "MEGA",
"Mi", "MI", "mi", "mebi", "MEBI",
"G", "g", "giga", "GIGA",
"Gi", "GI", "gi", "gibi", "GIBI",
"T", "t", "tera", "TERA",
/* You wish! */ "Ti", "TI", "ti", "tebi", "TEBI"
);
public function toString() {
$buf = "{sizeselector value: ";
$buf .= $this->sizelimit;
$buf .= "compare: ";
if ($this->cmp === 0) {
$buf .= "less";
} elseif ($this->cmp === 1) {
$buf .= "more";
} else {
$buf .= "equal";
}
$buf .= "}";
return $buf;
}
/**
* A size selector needs to know what size to base its selecting on.
* This will be further modified by the multiplier to get an
* actual size limit.
*
* @param size the size to select against expressed in units
*/
public function setValue($size) {
$this->size = $size;
if (($this->multiplier !== 0) && ($this->size > -1)) {
$this->sizelimit = $size * $this->multiplier;
}
}
/**
* Sets the units to use for the comparison. This is a little
* complicated because common usage has created standards that
* play havoc with capitalization rules. Thus, some people will
* use "K" for indicating 1000's, when the SI standard calls for
* "k". Others have tried to introduce "K" as a multiple of 1024,
* but that falls down when you reach "M", since "m" is already
* defined as 0.001.
* <p>
* To get around this complexity, a number of standards bodies
* have proposed the 2^10 standard, and at least one has adopted
* it. But we are still left with a populace that isn't clear on
* how capitalization should work.
* <p>
* We therefore ignore capitalization as much as possible.
* Completely mixed case is not possible, but all upper and lower
* forms are accepted for all long and short forms. Since we have
* no need to work with the 0.001 case, this practice works here.
* <p>
* This function translates all the long and short forms that a
* unit prefix can occur in and translates them into a single
* multiplier.
*
* @param $units The units to compare the size to.
* @return void
*/
public function setUnits($units) {
$i = array_search($units, self::$byteUnits, true);
if ($i === false) $i = -1; // make it java-like
$this->multiplier = 0;
if (($i > -1) && ($i < 4)) {
$this->multiplier = 1000;
} elseif (($i > 3) && ($i < 9)) {
$this->multiplier = 1024;
} elseif (($i > 8) && ($i < 13)) {
$this->multiplier = 1000000;
} elseif (($i > 12) && ($i < 18)) {
$this->multiplier = 1048576;
} elseif (($i > 17) && ($i < 22)) {
$this->multiplier = 1000000000;
} elseif (($i > 21) && ($i < 27)) {
$this->multiplier = 1073741824;
} elseif (($i > 26) && ($i < 31)) {
$this->multiplier = 1000000000000;
} elseif (($i > 30) && ($i < 36)) {
$this->multiplier = 1099511627776;
}
if (($this->multiplier > 0) && ($this->size > -1)) {
$this->sizelimit = $this->size * $this->multiplier;
}
}
/**
* This specifies when the file should be selected, whether it be
* when the file matches a particular size, when it is smaller,
* or whether it is larger.
*
* @param cmp The comparison to perform, an EnumeratedAttribute
*/
public function setWhen($cmp) {
$c = array_search($cmp, self::$sizeComparisons, true);
if ($c !== false) {
$this->cmp = $c;
}
}
/**
* When using this as a custom selector, this method will be called.
* It translates each parameter into the appropriate setXXX() call.
*
* @param parameters the complete set of parameters for this selector
*/
public function setParameters($parameters) {
parent::setParameters($parameters);
if ($parameters !== null) {
for ($i = 0, $size=count($parameters); $i < $size; $i++) {
$paramname = $parameters[$i]->getName();
switch(strtolower($paramname)) {
case self::SIZE_KEY:
try {
$this->setValue($parameters[$i]->getValue());
} catch (Exception $nfe) {
$this->setError("Invalid size setting "
. $parameters[$i]->getValue());
}
break;
case self::UNITS_KEY:
$this->setUnits($parameters[$i]->getValue());
break;
case self::WHEN_KEY:
$this->setWhen($parameters[$i]->getValue());
break;
default:
$this->setError("Invalid parameter " . $paramname);
}
}
}
}
/**
* <p>Checks to make sure all settings are kosher. In this case, it
* means that the size attribute has been set (to a positive value),
* that the multiplier has a valid setting, and that the size limit
* is valid. Since the latter is a calculated value, this can only
* fail due to a programming error.
* </p>
* <p>If a problem is detected, the setError() method is called.
* </p>
*/
public function verifySettings() {
if ($this->size < 0) {
$this->setError("The value attribute is required, and must be positive");
} elseif ($this->multiplier < 1) {
$this->setError("Invalid Units supplied, must be K,Ki,M,Mi,G,Gi,T,or Ti");
} elseif ($this->sizelimit < 0) {
$this->setError("Internal error: Code is not setting sizelimit correctly");
}
}
/**
* The heart of the matter. This is where the selector gets to decide
* on the inclusion of a file in a particular fileset.
*
* @param basedir A PhingFile object for the base directory
* @param filename The name of the file to check
* @param file A PhingFile object for this filename
* @return whether the file should be selected or not
*/
public function isSelected(PhingFile $basedir, $filename, PhingFile $file) {
$this->validate();
// Directory size never selected for
if ($file->isDirectory()) {
return true;
}
if ($this->cmp === 0) {
return ($file->length() < $this->sizelimit);
} elseif ($this->cmp === 1) {
return ($file->length() > $this->sizelimit);
} else {
return ($file->length() === $this->sizelimit);
}
}
}
| ArcherCraftStore/ArcherVMPeridot | php/pear/phing/types/selectors/SizeSelector.php | PHP | apache-2.0 | 8,816 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), hosted at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* Accurate Software Design, LLC.
* Portions created by the Initial Developer are Copyright (C) 2006-2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* See listed authors below.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chee.archive.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4chee.archive.common.PPSStatus;
import org.dcm4chee.archive.conf.AttributeFilter;
import org.dcm4chee.archive.util.DicomObjectUtils;
/**
* @author Damien Evans <damien.daddy@gmail.com>
* @author Justin Falk <jfalkmu@gmail.com>
* @author Gunter Zeilinger <gunterze@gmail.com>
* @version $Revision$ $Date$
* @since Feb 29, 2008
*/
@Entity
@Table(name = "mpps")
public class MPPS extends BaseEntity implements Serializable {
private static final long serialVersionUID = -599495313070741738L;
@Column(name = "created_time")
private Date createdTime;
@Column(name = "updated_time")
private Date updatedTime;
@Column(name = "mpps_iuid", unique = true, nullable = false)
private String sopInstanceUID;
@Column(name = "pps_start")
private Date startDateTime;
@Column(name = "station_aet")
private String performedStationAET;
@Column(name = "modality")
private String modality;
@Column(name = "accession_no")
private String accessionNumber;
@Column(name = "mpps_status", nullable = false)
private PPSStatus status;
// JPA definition in orm.xml
private byte[] encodedAttributes;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "drcode_fk")
private Code discontinuationReasonCode;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "patient_fk")
private Patient patient;
@OneToMany(mappedBy = "modalityPerformedProcedureStep", fetch = FetchType.LAZY)
private Set<Series> series;
public Date getCreatedTime() {
return createdTime;
}
public Date getUpdatedTime() {
return updatedTime;
}
public String getSopInstanceUID() {
return sopInstanceUID;
}
public Date getStartDateTime() {
return startDateTime;
}
public String getPerformedStationAET() {
return performedStationAET;
}
public String getModality() {
return modality;
}
public String getAccessionNumber() {
return accessionNumber;
}
public PPSStatus getStatus() {
return status;
}
public byte[] getEncodedAttributes() {
return encodedAttributes;
}
public Code getDiscontinuationReasonCode() {
return discontinuationReasonCode;
}
public void setDiscontinuationReasonCode(Code discontinuationReasonCode) {
this.discontinuationReasonCode = discontinuationReasonCode;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public Set<Series> getSeries() {
return series;
}
public void setSeries(Set<Series> series) {
this.series = series;
}
@Override
public String toString() {
return "MPPS[pk=" + pk
+ ", iuid=" + sopInstanceUID
+ ", status=" + status
+ ", accno=" + accessionNumber
+ ", start=" + startDateTime
+ ", mod=" + modality
+ ", aet=" + performedStationAET
+ "]";
}
public void onPrePersist() {
createdTime = new Date();
}
public void onPreUpdate() {
updatedTime = new Date();
}
public DicomObject getAttributes() {
return DicomObjectUtils.decode(encodedAttributes);
}
public void setAttributes(DicomObject attrs) {
this.sopInstanceUID = attrs.getString(Tag.SOPInstanceUID);
this.startDateTime = attrs.getDate(
Tag.PerformedProcedureStepStartDate,
Tag.PerformedProcedureStepStartTime);
this.performedStationAET = attrs.getString(Tag.PerformedStationAETitle);
this.modality = attrs.getString(Tag.Modality);
this.accessionNumber = attrs.getString(new int[] {
Tag.ScheduledStepAttributesSequence, 0, Tag.AccessionNumber });
if (this.accessionNumber == null)
this.accessionNumber = attrs.getString(Tag.AccessionNumber);
this.status = PPSStatus.valueOf(attrs.getString(
Tag.PerformedProcedureStepStatus).replace(' ', '_'));
this.encodedAttributes = DicomObjectUtils.encode(AttributeFilter.getExcludePatientAttributeFilter().filter(attrs),
UID.DeflatedExplicitVRLittleEndian);
}
}
| medicayun/medicayundicom | dcm4chee-arc3-entities/trunk/src/main/java/org/dcm4chee/archive/entity/MPPS.java | Java | apache-2.0 | 6,621 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<link rel="up" title="FatFs" href="../00index_j.html">
<link rel="alternate" hreflang="en" title="English" href="../en/dstat.html">
<link rel="stylesheet" href="../css_j.css" type="text/css" media="screen" title="ELM Default">
<title>FatFs - disk_status</title>
</head>
<body>
<div class="para func">
<h2>disk_status</h2>
<p>ストレージ デバイスの状態を取得します。</p>
<pre>
DSTATUS disk_status (
BYTE <span class="arg">pdrv</span> <span class="c">/* [IN] 物理ドライブ番号 */</span>
);
</pre>
</div>
<div class="para arg">
<h4>引数</h4>
<dl class="par">
<dt>pdrv</dt>
<dd>対象のデバイスを識別する物理ドライブ番号(0-9)が指定されます。物理ドライブが1台のときは、常に0になります。</dd>
</dl>
</div>
<div class="para ret">
<h4>戻り値</h4>
<p>現在のストレージ デバイスの状態を次のフラグの組み合わせ値で返します。</p>
<dl class="ret">
<dt>STA_NOINIT</dt>
<dd>デバイスが初期化されていないことを示すフラグ。システム リセットやメディアの取り外し等でセットされ、<tt>disk_initialize</tt>関数の正常終了でクリア、失敗でセットされます。メディア交換は非同期に発生するイベントなので、過去にメディア交換があった場合もこのフラグに反映させる必要があります。FatFsモジュールは、このフラグを参照してマウント動作が必要かどうかを判断します。</dd>
<dt>STA_NODISK</dt>
<dd>メディアが存在しないことを示すフラグ。メディアが取り外されている間はセットされ、セットされている間はクリアされます。固定ディスクでは常にクリアします。なお、このフラグはFatFsモジュールでは参照されません。</dd>
<dt>STA_PROTECT</dt>
<dd>メディアがライト プロテクトされていることを示すフラグ。ライト プロテクト機能をサポートしないときは、常にクリアします。リード オンリ構成では参照されません。</dd>
</dl>
</div>
<p class="foot"><a href="../00index_j.html">戻る</a></p>
</body>
</html>
| WarlockD/arm-cortex-v7-unix | stm32f746g-disco_hal_lib/Utilities/FatFs/doc/ja/dstat.html | HTML | apache-2.0 | 2,446 |
/*
* 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.
*/
/**
* Implementations of serializer and derserializer interfaces.
*/
package org.apache.reef.wake.avro.impl;
| markusweimer/incubator-reef | lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/avro/impl/package-info.java | Java | apache-2.0 | 920 |
/**
* 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.hadoop.hdfs.server.datanode.fsdataset.impl;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.Uninterruptibles;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.EnumSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.hadoop.fs.StorageType.RAM_DISK;
import static org.apache.hadoop.hdfs.DFSConfigKeys.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class TestLazyPersistFiles extends LazyPersistTestCase {
private static final int THREADPOOL_SIZE = 10;
/**
* Append to lazy persist file is denied.
* @throws IOException
*/
@Test
public void testAppendIsDenied() throws IOException {
getClusterBuilder().build();
final String METHOD_NAME = GenericTestUtils.getMethodName();
Path path = new Path("/" + METHOD_NAME + ".dat");
makeTestFile(path, BLOCK_SIZE, true);
try {
client.append(path.toString(), BUFFER_LENGTH,
EnumSet.of(CreateFlag.APPEND), null, null).close();
fail("Append to LazyPersist file did not fail as expected");
} catch (Throwable t) {
LOG.info("Got expected exception ", t);
}
}
/**
* Truncate to lazy persist file is denied.
* @throws IOException
*/
@Test
public void testTruncateIsDenied() throws IOException {
getClusterBuilder().build();
final String METHOD_NAME = GenericTestUtils.getMethodName();
Path path = new Path("/" + METHOD_NAME + ".dat");
makeTestFile(path, BLOCK_SIZE, true);
try {
client.truncate(path.toString(), BLOCK_SIZE/2);
fail("Truncate to LazyPersist file did not fail as expected");
} catch (Throwable t) {
LOG.info("Got expected exception ", t);
}
}
/**
* If one or more replicas of a lazyPersist file are lost, then the file
* must be discarded by the NN, instead of being kept around as a
* 'corrupt' file.
*/
@Test
public void testCorruptFilesAreDiscarded()
throws IOException, InterruptedException, TimeoutException {
getClusterBuilder().setRamDiskReplicaCapacity(2).build();
final String METHOD_NAME = GenericTestUtils.getMethodName();
Path path1 = new Path("/" + METHOD_NAME + ".01.dat");
makeTestFile(path1, BLOCK_SIZE, true);
ensureFileReplicasOnStorageType(path1, RAM_DISK);
// Stop the DataNode and sleep for the time it takes the NN to
// detect the DN as being dead.
cluster.shutdownDataNodes();
Thread.sleep(30000L);
assertThat(cluster.getNamesystem().getNumDeadDataNodes(), is(1));
// Next, wait for the redundancy monitor to mark the file as corrupt.
Thread.sleep(2 * DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_DEFAULT * 1000);
// Wait for the LazyPersistFileScrubber to run
Thread.sleep(2 * LAZY_WRITE_FILE_SCRUBBER_INTERVAL_SEC * 1000);
// Ensure that path1 does not exist anymore, whereas path2 does.
assert(!fs.exists(path1));
// We should have zero blocks that needs replication i.e. the one
// belonging to path2.
assertThat(cluster.getNameNode()
.getNamesystem()
.getBlockManager()
.getLowRedundancyBlocksCount(),
is(0L));
}
@Test
public void testDisableLazyPersistFileScrubber()
throws IOException, InterruptedException, TimeoutException {
getClusterBuilder().setRamDiskReplicaCapacity(2).disableScrubber().build();
final String METHOD_NAME = GenericTestUtils.getMethodName();
Path path1 = new Path("/" + METHOD_NAME + ".01.dat");
makeTestFile(path1, BLOCK_SIZE, true);
ensureFileReplicasOnStorageType(path1, RAM_DISK);
// Stop the DataNode and sleep for the time it takes the NN to
// detect the DN as being dead.
cluster.shutdownDataNodes();
Thread.sleep(30000L);
// Next, wait for the redundancy monitor to mark the file as corrupt.
Thread.sleep(2 * DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_DEFAULT * 1000);
// Wait for the LazyPersistFileScrubber to run
Thread.sleep(2 * LAZY_WRITE_FILE_SCRUBBER_INTERVAL_SEC * 1000);
// Ensure that path1 exist.
Assert.assertTrue(fs.exists(path1));
}
/**
* If NN restarted then lazyPersist files should not deleted
*/
@Test
public void testFileShouldNotDiscardedIfNNRestarted()
throws IOException, InterruptedException, TimeoutException {
getClusterBuilder().setRamDiskReplicaCapacity(2).build();
final String METHOD_NAME = GenericTestUtils.getMethodName();
Path path1 = new Path("/" + METHOD_NAME + ".01.dat");
makeTestFile(path1, BLOCK_SIZE, true);
ensureFileReplicasOnStorageType(path1, RAM_DISK);
cluster.shutdownDataNodes();
cluster.restartNameNodes();
// wait for the redundancy monitor to mark the file as corrupt.
Thread.sleep(2 * DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_DEFAULT * 1000);
Long corruptBlkCount = (long) Iterators.size(cluster.getNameNode()
.getNamesystem().getBlockManager().getCorruptReplicaBlockIterator());
// Check block detected as corrupted
assertThat(corruptBlkCount, is(1L));
// Ensure path1 exist.
Assert.assertTrue(fs.exists(path1));
}
/**
* Concurrent read from the same node and verify the contents.
*/
@Test
public void testConcurrentRead()
throws Exception {
getClusterBuilder().setRamDiskReplicaCapacity(2).build();
final String METHOD_NAME = GenericTestUtils.getMethodName();
final Path path1 = new Path("/" + METHOD_NAME + ".dat");
final int SEED = 0xFADED;
final int NUM_TASKS = 5;
makeRandomTestFile(path1, BLOCK_SIZE, true, SEED);
ensureFileReplicasOnStorageType(path1, RAM_DISK);
//Read from multiple clients
final CountDownLatch latch = new CountDownLatch(NUM_TASKS);
final AtomicBoolean testFailed = new AtomicBoolean(false);
Runnable readerRunnable = new Runnable() {
@Override
public void run() {
try {
Assert.assertTrue(verifyReadRandomFile(path1, BLOCK_SIZE, SEED));
} catch (Throwable e) {
LOG.error("readerRunnable error", e);
testFailed.set(true);
} finally {
latch.countDown();
}
}
};
Thread threads[] = new Thread[NUM_TASKS];
for (int i = 0; i < NUM_TASKS; i++) {
threads[i] = new Thread(readerRunnable);
threads[i].start();
}
Thread.sleep(500);
for (int i = 0; i < NUM_TASKS; i++) {
Uninterruptibles.joinUninterruptibly(threads[i]);
}
Assert.assertFalse(testFailed.get());
}
/**
* Concurrent write with eviction
* RAM_DISK can hold 9 replicas
* 4 threads each write 5 replicas
* @throws IOException
* @throws InterruptedException
*/
@Test
public void testConcurrentWrites()
throws IOException, InterruptedException {
getClusterBuilder().setRamDiskReplicaCapacity(9).build();
final String METHOD_NAME = GenericTestUtils.getMethodName();
final int SEED = 0xFADED;
final int NUM_WRITERS = 4;
final int NUM_WRITER_PATHS = 5;
Path paths[][] = new Path[NUM_WRITERS][NUM_WRITER_PATHS];
for (int i = 0; i < NUM_WRITERS; i++) {
paths[i] = new Path[NUM_WRITER_PATHS];
for (int j = 0; j < NUM_WRITER_PATHS; j++) {
paths[i][j] =
new Path("/" + METHOD_NAME + ".Writer" + i + ".File." + j + ".dat");
}
}
final CountDownLatch latch = new CountDownLatch(NUM_WRITERS);
final AtomicBoolean testFailed = new AtomicBoolean(false);
ExecutorService executor = Executors.newFixedThreadPool(THREADPOOL_SIZE);
for (int i = 0; i < NUM_WRITERS; i++) {
Runnable writer = new WriterRunnable(i, paths[i], SEED, latch, testFailed);
executor.execute(writer);
}
Thread.sleep(3 * LAZY_WRITER_INTERVAL_SEC * 1000);
triggerBlockReport();
// Stop executor from adding new tasks to finish existing threads in queue
latch.await();
assertThat(testFailed.get(), is(false));
}
class WriterRunnable implements Runnable {
private final int id;
private final Path paths[];
private final int seed;
private CountDownLatch latch;
private AtomicBoolean bFail;
public WriterRunnable(int threadIndex, Path[] paths,
int seed, CountDownLatch latch,
AtomicBoolean bFail) {
id = threadIndex;
this.paths = paths;
this.seed = seed;
this.latch = latch;
this.bFail = bFail;
System.out.println("Creating Writer: " + id);
}
public void run() {
System.out.println("Writer " + id + " starting... ");
int i = 0;
try {
for (i = 0; i < paths.length; i++) {
makeRandomTestFile(paths[i], BLOCK_SIZE, true, seed);
// eviction may faiL when all blocks are not persisted yet.
// ensureFileReplicasOnStorageType(paths[i], RAM_DISK);
}
} catch (IOException e) {
bFail.set(true);
LOG.error("Writer exception: writer id:" + id +
" testfile: " + paths[i].toString() +
" " + e);
} finally {
latch.countDown();
}
}
}
}
| dennishuo/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/TestLazyPersistFiles.java | Java | apache-2.0 | 10,335 |
/*
* 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.solr.update.processor;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.util.plugin.PluginInfoInitialized;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.SolrException;
import org.apache.solr.core.PluginInfo;
import org.apache.solr.core.SolrCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.ArrayList;
/**
* Manages a chain of UpdateRequestProcessorFactories.
* <p>
* Chains can be configured via solrconfig.xml using the following syntax...
* </p>
* <pre class="prettyprint">
* <updateRequestProcessorChain name="key" default="true">
* <processor class="package.Class1" />
* <processor class="package.Class2" >
* <str name="someInitParam1">value</str>
* <int name="someInitParam2">42</int>
* </processor>
* <processor class="solr.LogUpdateProcessorFactory" >
* <int name="maxNumToLog">100</int>
* </processor>
* <processor class="solr.RunUpdateProcessorFactory" />
* </updateRequestProcessorChain>
* </pre>
* <p>
* Multiple Chains can be defined, each with a distinct name. The name of
* a chain used to handle an update request may be specified using the request
* param <code>update.chain</code>. If no chain is explicitly selected
* by name, then Solr will attempt to determine a default chain:
* </p>
* <ul>
* <li>A single configured chain may explicitly be declared with
* <code>default="true"</code> (see example above)</li>
* <li>If no chain is explicitly declared as the default, Solr will look for
* any chain that does not have a name, and treat it as the default</li>
* <li>As a last resort, Solr will create an implicit default chain
* consisting of:<ul>
* <li>{@link LogUpdateProcessorFactory}</li>
* <li>{@link DistributedUpdateProcessorFactory}</li>
* <li>{@link RunUpdateProcessorFactory}</li>
* </ul></li>
* </ul>
*
* <p>
* Allmost all processor chains should end with an instance of
* <code>RunUpdateProcessorFactory</code> unless the user is explicitly
* executing the update commands in an alternative custom
* <code>UpdateRequestProcessorFactory</code>. If a chain includes
* <code>RunUpdateProcessorFactory</code> but does not include a
* <code>DistributingUpdateProcessorFactory</code>, it will be added
* automatically by {@link #init init()}.
* </p>
*
* @see UpdateRequestProcessorFactory
* @see #init
* @see #createProcessor
* @since solr 1.3
*/
public final class UpdateRequestProcessorChain implements PluginInfoInitialized
{
public final static Logger log = LoggerFactory.getLogger(UpdateRequestProcessorChain.class);
private UpdateRequestProcessorFactory[] chain;
private final SolrCore solrCore;
public UpdateRequestProcessorChain(SolrCore solrCore) {
this.solrCore = solrCore;
}
/**
* Initializes the chain using the factories specified by the <code>PluginInfo</code>.
* if the chain includes the <code>RunUpdateProcessorFactory</code>, but
* does not include an implementation of the
* <code>DistributingUpdateProcessorFactory</code> interface, then an
* instance of <code>DistributedUpdateProcessorFactory</code> will be
* injected immediately prior to the <code>RunUpdateProcessorFactory</code>.
*
* @see DistributingUpdateProcessorFactory
* @see RunUpdateProcessorFactory
* @see DistributedUpdateProcessorFactory
*/
@Override
public void init(PluginInfo info) {
final String infomsg = "updateRequestProcessorChain \"" +
(null != info.name ? info.name : "") + "\"" +
(info.isDefault() ? " (default)" : "");
log.info("creating " + infomsg);
// wrap in an ArrayList so we know we know we can do fast index lookups
// and that add(int,Object) is supported
List<UpdateRequestProcessorFactory> list = new ArrayList
(solrCore.initPlugins(info.getChildren("processor"),UpdateRequestProcessorFactory.class,null));
if(list.isEmpty()){
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
infomsg + " require at least one processor");
}
int numDistrib = 0;
int runIndex = -1;
// hi->lo incase multiple run instances, add before first one
// (no idea why someone might use multiple run instances, but just in case)
for (int i = list.size()-1; 0 <= i; i--) {
UpdateRequestProcessorFactory factory = list.get(i);
if (factory instanceof DistributingUpdateProcessorFactory) {
numDistrib++;
}
if (factory instanceof RunUpdateProcessorFactory) {
runIndex = i;
}
}
if (1 < numDistrib) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
infomsg + " may not contain more then one " +
"instance of DistributingUpdateProcessorFactory");
}
if (0 <= runIndex && 0 == numDistrib) {
// by default, add distrib processor immediately before run
DistributedUpdateProcessorFactory distrib
= new DistributedUpdateProcessorFactory();
distrib.init(new NamedList());
list.add(runIndex, distrib);
log.info("inserting DistributedUpdateProcessorFactory into " + infomsg);
}
chain = list.toArray(new UpdateRequestProcessorFactory[list.size()]);
}
/**
* Creates a chain backed directly by the specified array. Modifications to
* the array will affect future calls to <code>createProcessor</code>
*/
public UpdateRequestProcessorChain( UpdateRequestProcessorFactory[] chain,
SolrCore solrCore) {
this.chain = chain;
this.solrCore = solrCore;
}
/**
* Uses the factories in this chain to creates a new
* <code>UpdateRequestProcessor</code> instance specific for this request.
* If the <code>DISTRIB_UPDATE_PARAM</code> is present in the request and is
* non-blank, then any factory in this chain prior to the instance of
* <code>{@link DistributingUpdateProcessorFactory}</code> will be skipped,
* except for the log update processor factory.
*
* @see UpdateRequestProcessorFactory#getInstance
* @see DistributingUpdateProcessorFactory#DISTRIB_UPDATE_PARAM
*/
public UpdateRequestProcessor createProcessor(SolrQueryRequest req,
SolrQueryResponse rsp)
{
UpdateRequestProcessor processor = null;
UpdateRequestProcessor last = null;
final String distribPhase = req.getParams().get(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM);
final boolean skipToDistrib = distribPhase != null;
boolean afterDistrib = true; // we iterate backwards, so true to start
for (int i = chain.length-1; i>=0; i--) {
UpdateRequestProcessorFactory factory = chain[i];
if (skipToDistrib) {
if (afterDistrib) {
if (factory instanceof DistributingUpdateProcessorFactory) {
afterDistrib = false;
}
} else if (!(factory instanceof UpdateRequestProcessorFactory.RunAlways)) {
// skip anything that doesn't have the marker interface
continue;
}
}
processor = factory.getInstance(req, rsp, last);
last = processor == null ? last : processor;
}
return last;
}
/**
* Returns the underlying array of factories used in this chain.
* Modifications to the array will affect future calls to
* <code>createProcessor</code>
*/
public UpdateRequestProcessorFactory[] getFactories() {
return chain;
}
}
| williamchengit/TestRepo | solr/core/src/java/org/apache/solr/update/processor/UpdateRequestProcessorChain.java | Java | apache-2.0 | 8,567 |
/*
* Copyright 2016-present Open Networking Laboratory
*
* 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.onosproject.pim.cli;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.pim.impl.PimInterface;
import org.onosproject.pim.impl.PimInterfaceService;
import java.util.Set;
/**
* Lists the interfaces where PIM is enabled.
*/
@Command(scope = "onos", name = "pim-interfaces",
description = "Lists the interfaces where PIM is enabled")
public class PimInterfacesListCommand extends AbstractShellCommand {
private static final String FORMAT = "interfaceName=%s, holdTime=%s, priority=%s, genId=%s";
private static final String ROUTE_FORMAT = " %s";
@Override
protected void execute() {
PimInterfaceService interfaceService = get(PimInterfaceService.class);
Set<PimInterface> interfaces = interfaceService.getPimInterfaces();
interfaces.forEach(pimIntf -> {
print(FORMAT, pimIntf.getInterface().name(),
pimIntf.getHoldtime(), pimIntf.getPriority(),
pimIntf.getGenerationId());
pimIntf.getRoutes().forEach(route -> print(ROUTE_FORMAT, route));
});
}
}
| donNewtonAlpha/onos | apps/pim/src/main/java/org/onosproject/pim/cli/PimInterfacesListCommand.java | Java | apache-2.0 | 1,782 |
// Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for the editor prerequisites page.
*/
describe('Signup controller', function() {
describe('SignupCtrl', function() {
var scope, ctrl, $httpBackend, rootScope, mockAlertsService, urlParams;
beforeEach(module('oppia', GLOBALS.TRANSLATOR_PROVIDER_FOR_TESTS));
beforeEach(inject(function(_$httpBackend_, $http, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/signuphandler/data').respond({
username: 'myUsername',
has_agreed_to_latest_terms: false
});
rootScope = $rootScope;
mockAlertsService = {
addWarning: function() {}
};
spyOn(mockAlertsService, 'addWarning');
scope = {
getUrlParams: function() {
return {
return_url: 'return_url'
};
}
};
ctrl = $controller('Signup', {
$scope: scope,
$http: $http,
$rootScope: rootScope,
alertsService: mockAlertsService
});
}));
it('should show warning if user has not agreed to terms', function() {
scope.submitPrerequisitesForm(false, null);
expect(mockAlertsService.addWarning).toHaveBeenCalledWith(
'I18N_SIGNUP_ERROR_MUST_AGREE_TO_TERMS');
});
it('should get data correctly from the server', function() {
$httpBackend.flush();
expect(scope.username).toBe('myUsername');
expect(scope.hasAgreedToLatestTerms).toBe(false);
});
it('should show a loading message until the data is retrieved', function() {
expect(rootScope.loadingMessage).toBe('I18N_SIGNUP_LOADING');
$httpBackend.flush();
expect(rootScope.loadingMessage).toBeFalsy();
});
it('should show warning if terms are not agreed to', function() {
scope.submitPrerequisitesForm(false, '');
expect(mockAlertsService.addWarning).toHaveBeenCalledWith(
'I18N_SIGNUP_ERROR_MUST_AGREE_TO_TERMS');
});
it('should show warning if no username provided', function() {
scope.updateWarningText('');
expect(scope.warningI18nCode).toEqual('I18N_SIGNUP_ERROR_NO_USERNAME');
scope.submitPrerequisitesForm(false);
expect(scope.warningI18nCode).toEqual('I18N_SIGNUP_ERROR_NO_USERNAME');
});
it('should show warning if username is too long', function() {
scope.updateWarningText(
'abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba');
expect(scope.warningI18nCode).toEqual(
'I18N_SIGNUP_ERROR_USERNAME_MORE_50_CHARS');
});
it('should show warning if username has non-alphanumeric characters',
function() {
scope.updateWarningText('a-a');
expect(scope.warningI18nCode).toEqual(
'I18N_SIGNUP_ERROR_USERNAME_ONLY_ALPHANUM');
});
it('should show warning if username has \'admin\' in it', function() {
scope.updateWarningText('administrator');
expect(scope.warningI18nCode).toEqual(
'I18N_SIGNUP_ERROR_USERNAME_WITH_ADMIN');
});
});
});
| mit0110/oppia | core/templates/dev/head/profile/SignupSpec.js | JavaScript | apache-2.0 | 3,641 |
(function (enyo, scope) {
/**
* The {@link enyo.RepeaterChildSupport} [mixin]{@glossary mixin} contains methods and
* properties that are automatically applied to all children of {@link enyo.DataRepeater}
* to assist in selection support. (See {@link enyo.DataRepeater} for details on how to
* use selection support.) This mixin also [adds]{@link enyo.Repeater#decorateEvent} the
* `model`, `child` ([control]{@link enyo.Control} instance), and `index` properties to
* all [events]{@glossary event} emitted from the repeater's children.
*
* @mixin enyo.RepeaterChildSupport
* @public
*/
enyo.RepeaterChildSupport = {
/*
* @private
*/
name: 'RepeaterChildSupport',
/**
* Indicates whether the current child is selected in the [repeater]{@link enyo.DataRepeater}.
*
* @type {Boolean}
* @default false
* @public
*/
selected: false,
/*
* @method
* @private
*/
selectedChanged: enyo.inherit(function (sup) {
return function () {
if (this.repeater.selection) {
this.addRemoveClass(this.selectedClass || 'selected', this.selected);
// for efficiency purposes, we now directly call this method as opposed to
// forcing a synchronous event dispatch
var idx = this.repeater.collection.indexOf(this.model);
if (this.selected && !this.repeater.isSelected(this.model)) {
this.repeater.select(idx);
} else if (!this.selected && this.repeater.isSelected(this.model)) {
this.repeater.deselect(idx);
}
}
sup.apply(this, arguments);
};
}),
/*
* @method
* @private
*/
decorateEvent: enyo.inherit(function (sup) {
return function (sender, event) {
event.model = this.model;
event.child = this;
event.index = this.repeater.collection.indexOf(this.model);
sup.apply(this, arguments);
};
}),
/*
* @private
*/
_selectionHandler: function () {
if (this.repeater.selection && !this.get('disabled')) {
if (!this.repeater.groupSelection || !this.selected) {
this.set('selected', !this.selected);
}
}
},
/**
* Deliberately used to supersede the default method and set
* [owner]{@link enyo.Component#owner} to this [control]{@link enyo.Control} so that there
* are no name collisions in the instance [owner]{@link enyo.Component#owner}, and also so
* that [bindings]{@link enyo.Binding} will correctly map to names.
*
* @method
* @private
*/
createClientComponents: enyo.inherit(function () {
return function (components) {
this.createComponents(components, {owner: this});
};
}),
/**
* Used so that we don't stomp on any built-in handlers for the `ontap`
* {@glossary event}.
*
* @method
* @private
*/
dispatchEvent: enyo.inherit(function (sup) {
return function (name, event, sender) {
if (!event._fromRepeaterChild) {
if (!!~enyo.indexOf(name, this.repeater.selectionEvents)) {
this._selectionHandler();
event._fromRepeaterChild = true;
}
}
return sup.apply(this, arguments);
};
}),
/*
* @method
* @private
*/
constructed: enyo.inherit(function (sup) {
return function () {
sup.apply(this, arguments);
var r = this.repeater,
s = r.selectionProperty;
// this property will only be set if the instance of the repeater needs
// to track the selected state from the view and model and keep them in sync
if (s) {
var bnd = this.binding({
from: 'model.' + s,
to: 'selected',
oneWay: false/*,
kind: enyo.BooleanBinding*/
});
this._selectionBindingId = bnd.euid;
}
};
}),
/*
* @method
* @private
*/
destroy: enyo.inherit(function (sup) {
return function () {
if (this._selectionBindingId) {
var b$ = enyo.Binding.find(this._selectionBindingId);
if (b$) {
b$.destroy();
}
}
sup.apply(this, arguments);
};
}),
/*
* @private
*/
_selectionBindingId: null
};
})(enyo, this);
| KyleMaas/org.webosports.app.maps | enyo/source/ui/data/RepeaterChildSupport.js | JavaScript | apache-2.0 | 3,961 |
/*
Copyright 2019 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.
*/
package csidriver
import (
"testing"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/validation/field"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
utilfeature "k8s.io/apiserver/pkg/util/feature"
featuregatetesting "k8s.io/component-base/featuregate/testing"
"k8s.io/kubernetes/pkg/apis/storage"
"k8s.io/kubernetes/pkg/features"
)
func getValidCSIDriver(name string) *storage.CSIDriver {
enabled := true
return &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
},
}
}
func TestCSIDriverStrategy(t *testing.T) {
ctx := genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{
APIGroup: "storage.k8s.io",
APIVersion: "v1",
Resource: "csidrivers",
})
if Strategy.NamespaceScoped() {
t.Errorf("CSIDriver must not be namespace scoped")
}
if Strategy.AllowCreateOnUpdate() {
t.Errorf("CSIDriver should not allow create on update")
}
csiDriver := getValidCSIDriver("valid-csidriver")
Strategy.PrepareForCreate(ctx, csiDriver)
errs := Strategy.Validate(ctx, csiDriver)
if len(errs) != 0 {
t.Errorf("unexpected error validating %v", errs)
}
// Update of spec is disallowed
newCSIDriver := csiDriver.DeepCopy()
attachNotRequired := false
newCSIDriver.Spec.AttachRequired = &attachNotRequired
Strategy.PrepareForUpdate(ctx, newCSIDriver, csiDriver)
errs = Strategy.ValidateUpdate(ctx, newCSIDriver, csiDriver)
if len(errs) == 0 {
t.Errorf("Expected a validation error")
}
}
func TestCSIDriverPrepareForCreate(t *testing.T) {
ctx := genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{
APIGroup: "storage.k8s.io",
APIVersion: "v1",
Resource: "csidrivers",
})
attachRequired := true
podInfoOnMount := true
storageCapacity := true
tests := []struct {
name string
withCapacity bool
withInline bool
}{
{
name: "inline enabled",
withInline: true,
},
{
name: "inline disabled",
withInline: false,
},
{
name: "capacity enabled",
withCapacity: true,
},
{
name: "capacity disabled",
withCapacity: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIStorageCapacity, test.withCapacity)()
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIInlineVolume, test.withInline)()
csiDriver := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoOnMount,
StorageCapacity: &storageCapacity,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecyclePersistent,
},
},
}
Strategy.PrepareForCreate(ctx, csiDriver)
errs := Strategy.Validate(ctx, csiDriver)
if len(errs) != 0 {
t.Errorf("unexpected validating errors: %v", errs)
}
if test.withCapacity {
if csiDriver.Spec.StorageCapacity == nil || *csiDriver.Spec.StorageCapacity != storageCapacity {
t.Errorf("StorageCapacity modified: %v", csiDriver.Spec.StorageCapacity)
}
} else {
if csiDriver.Spec.StorageCapacity != nil {
t.Errorf("StorageCapacity not stripped: %v", csiDriver.Spec.StorageCapacity)
}
}
if test.withInline {
if len(csiDriver.Spec.VolumeLifecycleModes) != 1 {
t.Errorf("VolumeLifecycleModes modified: %v", csiDriver.Spec)
}
} else {
if len(csiDriver.Spec.VolumeLifecycleModes) != 0 {
t.Errorf("VolumeLifecycleModes not stripped: %v", csiDriver.Spec)
}
}
})
}
}
func TestCSIDriverPrepareForUpdate(t *testing.T) {
ctx := genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{
APIGroup: "storage.k8s.io",
APIVersion: "v1",
Resource: "csidrivers",
})
attachRequired := true
podInfoOnMount := true
driverWithoutModes := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoOnMount,
},
}
driverWithPersistent := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoOnMount,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecyclePersistent,
},
},
}
driverWithEphemeral := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &attachRequired,
PodInfoOnMount: &podInfoOnMount,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecycleEphemeral,
},
},
}
enabled := true
disabled := false
driverWithoutCapacity := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
}
driverWithCapacityEnabled := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
StorageCapacity: &enabled,
},
}
driverWithCapacityDisabled := &storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
StorageCapacity: &disabled,
},
}
var resultEmpty []storage.VolumeLifecycleMode
resultPersistent := []storage.VolumeLifecycleMode{storage.VolumeLifecyclePersistent}
resultEphemeral := []storage.VolumeLifecycleMode{storage.VolumeLifecycleEphemeral}
tests := []struct {
name string
old, update *storage.CSIDriver
withCapacity, withoutCapacity *bool
withInline, withoutInline []storage.VolumeLifecycleMode
}{
{
name: "before: no capacity, update: no capacity",
old: driverWithoutCapacity,
update: driverWithoutCapacity,
withCapacity: nil,
withoutCapacity: nil,
},
{
name: "before: no capacity, update: enabled",
old: driverWithoutCapacity,
update: driverWithCapacityEnabled,
withCapacity: &enabled,
withoutCapacity: nil,
},
{
name: "before: capacity enabled, update: disabled",
old: driverWithCapacityEnabled,
update: driverWithCapacityDisabled,
withCapacity: &disabled,
withoutCapacity: &disabled,
},
{
name: "before: capacity enabled, update: no capacity",
old: driverWithCapacityEnabled,
update: driverWithoutCapacity,
withCapacity: nil,
withoutCapacity: nil,
},
{
name: "before: no mode, update: no mode",
old: driverWithoutModes,
update: driverWithoutModes,
withInline: resultEmpty,
withoutInline: resultEmpty,
},
{
name: "before: no mode, update: persistent",
old: driverWithoutModes,
update: driverWithPersistent,
withInline: resultPersistent,
withoutInline: resultEmpty,
},
{
name: "before: persistent, update: ephemeral",
old: driverWithPersistent,
update: driverWithEphemeral,
withInline: resultEphemeral,
withoutInline: resultEphemeral,
},
{
name: "before: persistent, update: no mode",
old: driverWithPersistent,
update: driverWithoutModes,
withInline: resultEmpty,
withoutInline: resultEmpty,
},
}
runAll := func(t *testing.T, withCapacity, withInline bool) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIStorageCapacity, withCapacity)()
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIInlineVolume, withInline)()
csiDriver := test.update.DeepCopy()
Strategy.PrepareForUpdate(ctx, csiDriver, test.old)
if withCapacity {
require.Equal(t, test.withCapacity, csiDriver.Spec.StorageCapacity)
} else {
require.Equal(t, test.withoutCapacity, csiDriver.Spec.StorageCapacity)
}
if withInline {
require.Equal(t, test.withInline, csiDriver.Spec.VolumeLifecycleModes)
} else {
require.Equal(t, test.withoutInline, csiDriver.Spec.VolumeLifecycleModes)
}
})
}
}
t.Run("with capacity", func(t *testing.T) {
runAll(t, true, false)
})
t.Run("without capacity", func(t *testing.T) {
runAll(t, false, false)
})
t.Run("with inline volumes", func(t *testing.T) {
runAll(t, false, true)
})
t.Run("without inline volumes", func(t *testing.T) {
runAll(t, false, false)
})
}
func TestCSIDriverValidation(t *testing.T) {
enabled := true
disabled := true
tests := []struct {
name string
csiDriver *storage.CSIDriver
expectError bool
}{
{
"valid csidriver",
getValidCSIDriver("foo"),
false,
},
{
"true for all flags",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
},
},
false,
},
{
"false for all flags",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &disabled,
PodInfoOnMount: &disabled,
StorageCapacity: &disabled,
},
},
false,
},
{
"invalid driver name",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "*foo#",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
},
},
true,
},
{
"invalid volume mode",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecycleMode("no-such-mode"),
},
},
},
true,
},
{
"persistent volume mode",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecyclePersistent,
},
},
},
false,
},
{
"ephemeral volume mode",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecycleEphemeral,
},
},
},
false,
},
{
"both volume modes",
&storage.CSIDriver{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
},
Spec: storage.CSIDriverSpec{
AttachRequired: &enabled,
PodInfoOnMount: &enabled,
StorageCapacity: &enabled,
VolumeLifecycleModes: []storage.VolumeLifecycleMode{
storage.VolumeLifecyclePersistent,
storage.VolumeLifecycleEphemeral,
},
},
},
false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
testValidation := func(csiDriver *storage.CSIDriver, apiVersion string) field.ErrorList {
ctx := genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{
APIGroup: "storage.k8s.io",
APIVersion: "v1",
Resource: "csidrivers",
})
return Strategy.Validate(ctx, csiDriver)
}
err := testValidation(test.csiDriver, "v1")
if len(err) > 0 && !test.expectError {
t.Errorf("Validation of v1 object failed: %+v", err)
}
if len(err) == 0 && test.expectError {
t.Errorf("Validation of v1 object unexpectedly succeeded")
}
})
}
}
| johscheuer/kubernetes | pkg/registry/storage/csidriver/strategy_test.go | GO | apache-2.0 | 12,773 |
<html>
<head>
<title>Check Box</title>
</head>
<body>
<input type="checkbox" id="opt1" value="Option 1" CHECKED> Option 1
<input type="checkbox" name="opt2" value="value2"> Option 2
<input type="checkbox" name="opt2" value="value3" CHECKED> Option 3
<input type="text" id="text1" />
</body>
</html> | rahulkavale/scalatest | webapp/find-checkbox.html | HTML | apache-2.0 | 311 |
This project uses the Natural Language API in a servlet to perform sentiment
analysis on text submitted by a user.


To run this example, first make sure your `GOOGLE_APPLICATION_CREDENTIALS`
environment variable is set and that you've enabled the
[Natural Language API](https://console.developers.google.com/apis/library/language.googleapis.com),
and then execute this command:
```bash
mvn package appengine:run
```
Then navigate to `http://localhost:8080`.
| googleinterns/step148-2020 | walkthroughs/week-4-libraries/sentiment-analysis/examples/sentiment-analyzer/README.md | Markdown | apache-2.0 | 554 |
#!/usr/bin/env bash
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
set -e
. ./test-lib.sh
setup_initsvn
setup_gitsvn
(
set -e
cd git-svn
git checkout -q -b work
echo "some work done on a branch" >> test
git add test; git commit -q -m "branch work"
echo "some other work done on a branch" >> test
git add test; git commit -q -m "branch work"
test_expect_success "git-cl upload wants a server" \
"$GIT_CL upload 2>&1 | grep -q 'You must configure'"
git config rietveld.server localhost:10000
test_expect_success "git-cl status has no issue" \
"$GIT_CL_STATUS | grep -q 'no issue'"
# Prevent the editor from coming up when you upload.
export GIT_EDITOR=$(which true)
test_expect_success "upload succeeds (needs a server running on localhost)" \
"$GIT_CL upload -m test master | grep -q 'Issue created'"
test_expect_success "git-cl status now knows the issue" \
"$GIT_CL_STATUS | grep -q 'Issue number'"
# Push a description to this URL.
URL=$($GIT_CL_STATUS | sed -ne '/Issue number/s/[^(]*(\(.*\))/\1/p')
curl --cookie dev_appserver_login="test@example.com:False" \
--data-urlencode subject="test" \
--data-urlencode description="foo-quux" \
--data-urlencode xsrf_token="$(print_xsrf_token)" \
$URL/edit
test_expect_success "git-cl dcommits ok" \
"$GIT_CL dcommit -f"
git checkout -q master
git svn -q rebase >/dev/null 2>&1
test_expect_success "dcommitted code has proper description" \
"git show | grep -q 'foo-quux'"
test_expect_success "issue no longer has a branch" \
"$GIT_CL_STATUS | grep -q 'work : None'"
test_expect_success "upstream svn has our commit" \
"svn log $REPO_URL 2>/dev/null | grep -q 'foo-quux'"
)
SUCCESS=$?
cleanup
if [ $SUCCESS == 0 ]; then
echo PASS
fi
| G-P-S/depot_tools | tests/basic.sh | Shell | bsd-3-clause | 1,929 |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/css/gopherface.css" />
</head>
<body>
<h1>GopherFace - Video Preview</h1>
<div class="sectionContainer">
<div class="imageContainer">
<img src="{{.thumbnailPath}}">
</div>
<div class="videoContainer">
<video loop autoplay width="720">
<source src="{{.videoPath}}" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
</body>
</html>
| GolangAce/gocodelab | gopherfaceq/templates/videopreview.html | HTML | bsd-3-clause | 473 |
#ifndef COLLECT_VIEW_H
#define COLLECT_VIEW_H
#include "contiki-conf.h"
#include "net/linkaddr.h"
#include "net/rime/collect.h"
struct collect_view_data_msg {
uint16_t len;
uint16_t clock;
uint16_t timesynch_time;
uint16_t cpu;
uint16_t lpm;
uint16_t transmit;
uint16_t listen;
uint16_t parent;
uint16_t parent_etx;
uint16_t current_rtmetric;
uint16_t num_neighbors;
uint16_t beacon_interval;
uint16_t sensors[10];
};
void collect_view_construct_message(struct collect_view_data_msg *msg,
const linkaddr_t *parent,
uint16_t etx_to_parent,
uint16_t current_rtmetric,
uint16_t num_neighbors,
uint16_t beacon_interval);
void collect_view_arch_read_sensors(struct collect_view_data_msg *msg);
#endif /* COLLECT_VIEW_H */
| miarcompanies/sdn-wise-contiki | contiki/apps/collect-view/collect-view.h | C | bsd-3-clause | 929 |
<style>
li:first-letter { color: red; }
li.green:first-letter { color: green; }
</style>
<ul style="font-family: Ahem; font-size: 100px; -webkit-font-smoothing: none;">
<li id="target">a</li>
</ul>
<script>
document.body.offsetTop;
document.getElementById("target").className = "green";
</script>
| nwjs/blink | LayoutTests/fast/dynamic/first-letter-after-list-marker.html | HTML | bsd-3-clause | 317 |
#ifndef ALIPRIMARYPIONCUTS_H
#define ALIPRIMARYPIONCUTS_H
// Class handling all kinds of selection cuts for primary
// Authors: Svein Lindal, Daniel Lohner *
#include "AliAODpidUtil.h"
#include "AliAODTrack.h"
#include "AliESDtrack.h"
#include "AliVTrack.h"
#include "AliAODTrack.h"
#include "AliMCEvent.h"
#include "AliAnalysisCuts.h"
#include "AliESDtrackCuts.h"
#include "TH1F.h"
class AliESDEvent;
class AliAODEvent;
class AliConversionPhotonBase;
class AliKFVertex;
class AliKFParticle;
class TH1F;
class TH2F;
class AliPIDResponse;
class AliAnalysisCuts;
class iostream;
class TList;
class AliAnalysisManager;
using namespace std;
class AliPrimaryPionCuts : public AliAnalysisCuts {
public:
enum cutIds {
kEtaCut,
kClsITSCut,
kClsTPCCut,
kDCACut,
kPtCut,
kPidedxSigmaITSCut,
kPidedxSigmaTPCCut,
kPiTOFSigmaPID,
kMassCut,
kNCuts
};
enum pionCuts {
kPionIn=0,
kNoTracks,
kTrackCuts,
kdEdxCuts,
kPionOut
};
Bool_t SetCutIds(TString cutString);
Int_t fCuts[kNCuts];
Bool_t SetCut(cutIds cutID, Int_t cut);
Bool_t UpdateCutString();
static const char * fgkCutNames[kNCuts];
Bool_t InitializeCutsFromCutString(const TString analysisCutSelection);
AliPrimaryPionCuts(const char *name="PionCuts", const char * title="Pion Cuts");
virtual ~AliPrimaryPionCuts(); //virtual destructor
virtual Bool_t IsSelected(TObject* /*obj*/){return kTRUE;}
virtual Bool_t IsSelected(TList* /*list*/) {return kTRUE;}
TString GetCutNumber();
// Cut Selection
Bool_t PionIsSelectedMC(Int_t labelParticle,AliMCEvent *mcEvent);
Bool_t TrackIsSelected(AliESDtrack* lTrack);
Bool_t PionIsSelected(AliESDtrack* lTrack);
static AliPrimaryPionCuts * GetStandardCuts2010PbPb();
static AliPrimaryPionCuts * GetStandardCuts2010pp();
Bool_t InitPIDResponse();
void SetPIDResponse(AliPIDResponse * pidResponse) {fPIDResponse = pidResponse;}
AliPIDResponse * GetPIDResponse() { return fPIDResponse;}
void PrintCuts();
void PrintCutsWithValues();
void SetLightOutput( Bool_t flag ){fDoLightOutput = flag; return;}
void InitCutHistograms(TString name="",Bool_t preCut = kTRUE,TString cutName="");
void SetFillCutHistograms(TString name="",Bool_t preCut = kTRUE,TString cutName=""){if(!fHistograms){InitCutHistograms(name,preCut,cutName);};}
TList *GetCutHistograms(){return fHistograms;}
static AliVTrack * GetTrack(AliVEvent * event, Int_t label);
///Cut functions
Bool_t dEdxCuts(AliVTrack * track);
Bool_t SetTPCdEdxCutPionLine(Int_t pidedxSigmaCut);
Bool_t SetITSdEdxCutPionLine(Int_t ededxSigmaCut);
Bool_t SetITSClusterCut(Int_t clsITSCut);
Bool_t SetTPCClusterCut(Int_t clsTPCCut);
Bool_t SetEtaCut(Int_t etaCut);
Bool_t SetPtCut(Int_t ptCut);
Bool_t SetDCACut(Int_t dcaCut);
void SetEtaShift(Double_t etaShift){fEtaShift = etaShift;}
Bool_t SetTOFPionPIDCut(Int_t TOFelectronPID);
Bool_t SetMassCut(Int_t massCut);
Double_t GetMassCut(){return fMassCut;}
// Request Flags
Double_t GetEtaCut(){ return fEtaCut;}
Double_t GetNFindableClustersTPC(AliESDtrack* lTrack);
Bool_t DoWeights(){return fDoWeights;}
Bool_t DoMassCut(){return fDoMassCut;}
protected:
TList *fHistograms;
Bool_t fDoLightOutput; ///< switch for running light output, kFALSE -> normal mode, kTRUE -> light mode
AliPIDResponse *fPIDResponse;
AliESDtrackCuts *fEsdTrackCuts;
Double_t fEtaCut; //eta cutç
Double_t fEtaShift;
Bool_t fDoEtaCut;
Double_t fPtCut;
Double_t fMinClsTPC; // minimum clusters in the TPC
Double_t fChi2PerClsTPC; // maximum Chi2 per cluster in the TPC
Bool_t fRequireTPCRefit; // require a refit in the TPC
Double_t fMinClsTPCToF; // minimum clusters to findable clusters
Bool_t fDodEdxSigmaITSCut; // flag to use the dEdxCut ITS based on sigmas
Bool_t fDodEdxSigmaTPCCut; // flag to use the dEdxCut TPC based on sigmas
Bool_t fDoTOFsigmaCut; // flag to use TOF pid cut RRnewTOF
Double_t fPIDnSigmaAbovePionLineITS; // sigma cut ITS
Double_t fPIDnSigmaBelowPionLineITS; // sigma cut ITS
Double_t fPIDnSigmaAbovePionLineTPC; // sigma cut TPC
Double_t fPIDnSigmaBelowPionLineTPC; // sigma cut TPC
Double_t fPIDnSigmaAbovePionLineTOF; // sigma cut TOF
Double_t fPIDnSigmaBelowPionLineTOF; // sigma cut TOF
Bool_t fUseCorrectedTPCClsInfo; // flag to use corrected tpc cl info
Bool_t fUseTOFpid; // flag to use tof pid
Bool_t fRequireTOF; //flg to analyze only tracks with TOF signal
Bool_t fDoMassCut;
Double_t fMassCut;
Bool_t fDoWeights;
Double_t fMaxDCAToVertexZ;
// Histograms
TObjString *fCutString; // cut number used for analysis
TString fCutStringRead;
TH1F *fHistCutIndex; // bookkeeping for cuts
TH1F *fHistdEdxCuts; // bookkeeping for dEdx cuts
TH2F *fHistITSdEdxbefore; // ITS dEdx before cuts
TH2F *fHistITSdEdxafter;
TH2F *fHistTPCdEdxbefore; // TPC dEdx before cuts
TH2F *fHistTPCdEdxafter; // TPC dEdx after cuts
TH2F *fHistTPCdEdxSignalbefore; //TPC dEdx signal before
TH2F *fHistTPCdEdxSignalafter; //TPC dEdx signal after
TH2F *fHistTOFbefore; // TOF after cuts
TH2F *fHistTOFafter; // TOF after cuts
TH2F *fHistTrackDCAxyPtbefore;
TH2F *fHistTrackDCAxyPtafter;
TH2F *fHistTrackDCAzPtbefore;
TH2F *fHistTrackDCAzPtafter;
TH2F *fHistTrackNFindClsPtTPCbefore;
TH2F *fHistTrackNFindClsPtTPCafter;
TString fStringITSClusterCut;
private:
AliPrimaryPionCuts(const AliPrimaryPionCuts&); // not implemented
AliPrimaryPionCuts& operator=(const AliPrimaryPionCuts&); // not implemented
ClassDef(AliPrimaryPionCuts,6)
};
#endif
| AudreyFrancisco/AliPhysics | PWGGA/GammaConv/AliPrimaryPionCuts.h | C | bsd-3-clause | 5,614 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Db\RowGateway;
use Zend\Db\RowGateway\RowGateway;
class AbstractRowGatewayTest extends \PHPUnit_Framework_TestCase
{
protected $mockAdapter = null;
/** @var RowGateway */
protected $rowGateway = null;
protected $mockResult = null;
public function setup()
{
// mock the adapter, driver, and parts
$mockResult = $this->getMock('Zend\Db\Adapter\Driver\ResultInterface');
$mockResult->expects($this->any())->method('getAffectedRows')->will($this->returnValue(1));
$this->mockResult = $mockResult;
$mockStatement = $this->getMock('Zend\Db\Adapter\Driver\StatementInterface');
$mockStatement->expects($this->any())->method('execute')->will($this->returnValue($mockResult));
$mockConnection = $this->getMock('Zend\Db\Adapter\Driver\ConnectionInterface');
$mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface');
$mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($mockStatement));
$mockDriver->expects($this->any())->method('getConnection')->will($this->returnValue($mockConnection));
// setup mock adapter
$this->mockAdapter = $this->getMock('Zend\Db\Adapter\Adapter', null, array($mockDriver));
$this->rowGateway = $this->getMockForAbstractClass('Zend\Db\RowGateway\AbstractRowGateway');
$rgPropertyValues = array(
'primaryKeyColumn' => 'id',
'table' => 'foo',
'sql' => new \Zend\Db\Sql\Sql($this->mockAdapter)
);
$this->setRowGatewayState($rgPropertyValues);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::offsetSet
*/
public function testOffsetSet()
{
// If we set with an index, both getters should retrieve the same value:
$this->rowGateway['testColumn'] = 'test';
$this->assertEquals('test', $this->rowGateway->testColumn);
$this->assertEquals('test', $this->rowGateway['testColumn']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::__set
*/
public function test__set()
{
// If we set with a property, both getters should retrieve the same value:
$this->rowGateway->testColumn = 'test';
$this->assertEquals('test', $this->rowGateway->testColumn);
$this->assertEquals('test', $this->rowGateway['testColumn']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::__isset
*/
public function test__isset()
{
// Test isset before and after assigning to a property:
$this->assertFalse(isset($this->rowGateway->foo));
$this->rowGateway->foo = 'bar';
$this->assertTrue(isset($this->rowGateway->foo));
}
/**
* @covers Zend\Db\RowGateway\RowGateway::offsetExists
*/
public function testOffsetExists()
{
// Test isset before and after assigning to an index:
$this->assertFalse(isset($this->rowGateway['foo']));
$this->rowGateway['foo'] = 'bar';
$this->assertTrue(isset($this->rowGateway['foo']));
}
/**
* @covers Zend\Db\RowGateway\RowGateway::__unset
*/
public function test__unset()
{
$this->rowGateway->foo = 'bar';
$this->assertEquals('bar', $this->rowGateway->foo);
unset($this->rowGateway->foo);
$this->assertEmpty($this->rowGateway->foo);
$this->assertEmpty($this->rowGateway['foo']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::offsetUnset
*/
public function testOffsetUnset()
{
$this->rowGateway['foo'] = 'bar';
$this->assertEquals('bar', $this->rowGateway['foo']);
unset($this->rowGateway['foo']);
$this->assertEmpty($this->rowGateway->foo);
$this->assertEmpty($this->rowGateway['foo']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::offsetGet
*/
public function testOffsetGet()
{
// If we set with an index, both getters should retrieve the same value:
$this->rowGateway['testColumn'] = 'test';
$this->assertEquals('test', $this->rowGateway->testColumn);
$this->assertEquals('test', $this->rowGateway['testColumn']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::__get
*/
public function test__get()
{
// If we set with a property, both getters should retrieve the same value:
$this->rowGateway->testColumn = 'test';
$this->assertEquals('test', $this->rowGateway->testColumn);
$this->assertEquals('test', $this->rowGateway['testColumn']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::save
*/
public function testSaveInsert()
{
// test insert
$this->mockResult->expects($this->any())->method('current')->will($this->returnValue(array('id' => 5, 'name' => 'foo')));
$this->mockResult->expects($this->any())->method('getGeneratedValue')->will($this->returnValue(5));
$this->rowGateway->populate(array('name' => 'foo'));
$this->rowGateway->save();
$this->assertEquals(5, $this->rowGateway->id);
$this->assertEquals(5, $this->rowGateway['id']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::save
*/
public function testSaveInsertMultiKey()
{
$this->rowGateway = $this->getMockForAbstractClass('Zend\Db\RowGateway\AbstractRowGateway');
$mockSql = $this->getMockForAbstractClass('Zend\Db\Sql\Sql', array($this->mockAdapter));
$rgPropertyValues = array(
'primaryKeyColumn' => array('one', 'two'),
'table' => 'foo',
'sql' => $mockSql
);
$this->setRowGatewayState($rgPropertyValues);
// test insert
$this->mockResult->expects($this->any())->method('current')->will($this->returnValue(array('one' => 'foo', 'two' => 'bar')));
// @todo Need to assert that $where was filled in
$refRowGateway = new \ReflectionObject($this->rowGateway);
$refRowGatewayProp = $refRowGateway->getProperty('primaryKeyData');
$refRowGatewayProp->setAccessible(true);
$this->rowGateway->populate(array('one' => 'foo', 'two' => 'bar'));
$this->assertNull($refRowGatewayProp->getValue($this->rowGateway));
// save should setup the primaryKeyData
$this->rowGateway->save();
$this->assertEquals(array('one' => 'foo', 'two' => 'bar'), $refRowGatewayProp->getValue($this->rowGateway));
}
/**
* @covers Zend\Db\RowGateway\RowGateway::save
*/
public function testSaveUpdate()
{
// test update
$this->mockResult->expects($this->any())->method('current')->will($this->returnValue(array('id' => 6, 'name' => 'foo')));
$this->rowGateway->populate(array('id' => 6, 'name' => 'foo'), true);
$this->rowGateway->save();
$this->assertEquals(6, $this->rowGateway['id']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::save
*/
public function testSaveUpdateChangingPrimaryKey()
{
// this mock is the select to be used to re-fresh the rowobject's data
$selectMock = $this->getMock('Zend\Db\Sql\Select', array('where'));
$selectMock->expects($this->once())
->method('where')
->with($this->equalTo(array('id' => 7)))
->will($this->returnValue($selectMock));
$sqlMock = $this->getMock('Zend\Db\Sql\Sql', array('select'), array($this->mockAdapter));
$sqlMock->expects($this->any())
->method('select')
->will($this->returnValue($selectMock));
$this->setRowGatewayState(array('sql' => $sqlMock));
// original mock returning updated data
$this->mockResult->expects($this->any())
->method('current')
->will($this->returnValue(array('id' => 7, 'name' => 'fooUpdated')));
// populate forces an update in save(), seeds with original data (from db)
$this->rowGateway->populate(array('id' => 6, 'name' => 'foo'), true);
$this->rowGateway->id = 7;
$this->rowGateway->save();
$this->assertEquals(array('id' => 7, 'name' => 'fooUpdated'), $this->rowGateway->toArray());
}
/**
* @covers Zend\Db\RowGateway\RowGateway::delete
*/
public function testDelete()
{
$this->rowGateway->foo = 'bar';
$affectedRows = $this->rowGateway->delete();
$this->assertFalse($this->rowGateway->rowExistsInDatabase());
$this->assertEquals(1, $affectedRows);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::populate
* @covers Zend\Db\RowGateway\RowGateway::rowExistsInDatabase
*/
public function testPopulate()
{
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'));
$this->assertEquals(5, $this->rowGateway['id']);
$this->assertEquals('foo', $this->rowGateway['name']);
$this->assertFalse($this->rowGateway->rowExistsInDatabase());
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'), true);
$this->assertTrue($this->rowGateway->rowExistsInDatabase());
}
/**
* @covers Zend\Db\RowGateway\RowGateway::processPrimaryKeyData
*/
public function testProcessPrimaryKeyData()
{
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'), true);
$this->setExpectedException('Zend\Db\RowGateway\Exception\RuntimeException', 'a known key id was not found');
$this->rowGateway->populate(array('boo' => 5, 'name' => 'foo'), true);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::count
*/
public function testCount()
{
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'), true);
$this->assertEquals(2, $this->rowGateway->count());
}
/**
* @covers Zend\Db\RowGateway\RowGateway::toArray
*/
public function testToArray()
{
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'), true);
$this->assertEquals(array('id' => 5, 'name' => 'foo'), $this->rowGateway->toArray());
}
protected function setRowGatewayState(array $properties)
{
$refRowGateway = new \ReflectionObject($this->rowGateway);
foreach ($properties as $rgPropertyName => $rgPropertyValue) {
$refRowGatewayProp = $refRowGateway->getProperty($rgPropertyName);
$refRowGatewayProp->setAccessible(true);
$refRowGatewayProp->setValue($this->rowGateway, $rgPropertyValue);
}
}
}
| patrickgo29/ZF2-Tutorial | vendor/ZF2/tests/ZendTest/Db/RowGateway/AbstractRowGatewayTest.php | PHP | bsd-3-clause | 10,859 |
import scala.scalajs.js
import scala.scalajs.js.Dynamic.global
import org.scalajs.jasminetest.JasmineTest
object ElementCreatorTest extends JasmineTest {
describe("ElementCreator") {
it("should be able to create an element in the body") {
// create the element
ElementCreator.create()
// jquery would make this easier, but I wanted to
// only use pure html in the test itself
val body = global.document.getElementsByTagName("body")
.asInstanceOf[js.Array[js.Dynamic]].head
// the Scala.js DOM API would make this easier
expect(body.lastChild.tagName.toString == "H1").toBeTruthy
expect(body.lastChild.innerHTML.toString == "Test").toBeTruthy
}
}
}
| doron123/scala-js | examples/testing/src/test/scala/ElementCreatorTest.scala | Scala | bsd-3-clause | 722 |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from cpp_namespace_environment import CppNamespaceEnvironment
from model import Model, UnixName
from schema_loader import SchemaLoader
def _GenerateFilenames(full_namespace):
# Try to find the file defining the namespace. Eg. for
# nameSpace.sub_name_space.Type' the following heuristics looks for:
# 1. name_space_sub_name_space.json,
# 2. name_space_sub_name_space.idl,
# 3. sub_name_space.json,
# 4. sub_name_space.idl,
# 5. etc.
sub_namespaces = full_namespace.split('.')
filenames = [ ]
basename = None
for namespace in reversed(sub_namespaces):
if basename is not None:
basename = UnixName(namespace + '.' + basename)
else:
basename = UnixName(namespace)
for ext in ['json', 'idl']:
filenames.append('%s.%s' % (basename, ext))
return filenames
class NamespaceResolver(object):
'''Resolves a type name into the namespace the type belongs to.
- |root| path to the root directory.
- |path| path to the directory with the API header files, relative to the
root.
- |include_rules| List containing tuples with (path, cpp_namespace_pattern)
used when searching for types.
- |cpp_namespace_pattern| Default namespace pattern
'''
def __init__(self, root, path, include_rules, cpp_namespace_pattern):
self._root = root
self._include_rules = [(path, cpp_namespace_pattern)] + include_rules
def ResolveNamespace(self, full_namespace):
'''Returns the model.Namespace object associated with the |full_namespace|,
or None if one can't be found.
'''
filenames = _GenerateFilenames(full_namespace)
for path, cpp_namespace in self._include_rules:
cpp_namespace_environment = None
if cpp_namespace:
cpp_namespace_environment = CppNamespaceEnvironment(cpp_namespace)
for filename in reversed(filenames):
filepath = os.path.join(path, filename);
if os.path.exists(os.path.join(self._root, filepath)):
schema = SchemaLoader(self._root).LoadSchema(filepath)[0]
return Model().AddNamespace(
schema,
filepath,
environment=cpp_namespace_environment)
return None
def ResolveType(self, full_name, default_namespace):
'''Returns the model.Namespace object where the type with the given
|full_name| is defined, or None if one can't be found.
'''
name_parts = full_name.rsplit('.', 1)
if len(name_parts) == 1:
if full_name not in default_namespace.types:
return None
return default_namespace
full_namespace, type_name = full_name.rsplit('.', 1)
namespace = self.ResolveNamespace(full_namespace)
if namespace and type_name in namespace.types:
return namespace
return None
| scheib/chromium | tools/json_schema_compiler/namespace_resolver.py | Python | bsd-3-clause | 2,904 |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: src/proto/grpc/testing/test.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Grpc.Testing {
/// <summary>Holder for reflection information generated from src/proto/grpc/testing/test.proto</summary>
public static partial class TestReflection {
#region Descriptor
/// <summary>File descriptor for src/proto/grpc/testing/test.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TestReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiFzcmMvcHJvdG8vZ3JwYy90ZXN0aW5nL3Rlc3QucHJvdG8SDGdycGMudGVz",
"dGluZxoic3JjL3Byb3RvL2dycGMvdGVzdGluZy9lbXB0eS5wcm90bxolc3Jj",
"L3Byb3RvL2dycGMvdGVzdGluZy9tZXNzYWdlcy5wcm90bzLLBQoLVGVzdFNl",
"cnZpY2USNQoJRW1wdHlDYWxsEhMuZ3JwYy50ZXN0aW5nLkVtcHR5GhMuZ3Jw",
"Yy50ZXN0aW5nLkVtcHR5EkYKCVVuYXJ5Q2FsbBIbLmdycGMudGVzdGluZy5T",
"aW1wbGVSZXF1ZXN0GhwuZ3JwYy50ZXN0aW5nLlNpbXBsZVJlc3BvbnNlEk8K",
"EkNhY2hlYWJsZVVuYXJ5Q2FsbBIbLmdycGMudGVzdGluZy5TaW1wbGVSZXF1",
"ZXN0GhwuZ3JwYy50ZXN0aW5nLlNpbXBsZVJlc3BvbnNlEmwKE1N0cmVhbWlu",
"Z091dHB1dENhbGwSKC5ncnBjLnRlc3RpbmcuU3RyZWFtaW5nT3V0cHV0Q2Fs",
"bFJlcXVlc3QaKS5ncnBjLnRlc3RpbmcuU3RyZWFtaW5nT3V0cHV0Q2FsbFJl",
"c3BvbnNlMAESaQoSU3RyZWFtaW5nSW5wdXRDYWxsEicuZ3JwYy50ZXN0aW5n",
"LlN0cmVhbWluZ0lucHV0Q2FsbFJlcXVlc3QaKC5ncnBjLnRlc3RpbmcuU3Ry",
"ZWFtaW5nSW5wdXRDYWxsUmVzcG9uc2UoARJpCg5GdWxsRHVwbGV4Q2FsbBIo",
"LmdycGMudGVzdGluZy5TdHJlYW1pbmdPdXRwdXRDYWxsUmVxdWVzdBopLmdy",
"cGMudGVzdGluZy5TdHJlYW1pbmdPdXRwdXRDYWxsUmVzcG9uc2UoATABEmkK",
"DkhhbGZEdXBsZXhDYWxsEiguZ3JwYy50ZXN0aW5nLlN0cmVhbWluZ091dHB1",
"dENhbGxSZXF1ZXN0GikuZ3JwYy50ZXN0aW5nLlN0cmVhbWluZ091dHB1dENh",
"bGxSZXNwb25zZSgBMAESPQoRVW5pbXBsZW1lbnRlZENhbGwSEy5ncnBjLnRl",
"c3RpbmcuRW1wdHkaEy5ncnBjLnRlc3RpbmcuRW1wdHkyVQoUVW5pbXBsZW1l",
"bnRlZFNlcnZpY2USPQoRVW5pbXBsZW1lbnRlZENhbGwSEy5ncnBjLnRlc3Rp",
"bmcuRW1wdHkaEy5ncnBjLnRlc3RpbmcuRW1wdHkyiQEKEFJlY29ubmVjdFNl",
"cnZpY2USOwoFU3RhcnQSHS5ncnBjLnRlc3RpbmcuUmVjb25uZWN0UGFyYW1z",
"GhMuZ3JwYy50ZXN0aW5nLkVtcHR5EjgKBFN0b3ASEy5ncnBjLnRlc3Rpbmcu",
"RW1wdHkaGy5ncnBjLnRlc3RpbmcuUmVjb25uZWN0SW5mb2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Grpc.Testing.EmptyReflection.Descriptor, global::Grpc.Testing.MessagesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null));
}
#endregion
}
}
#endregion Designer generated code
| endlessm/chromium-browser | third_party/grpc/src/src/csharp/Grpc.IntegrationTesting/Test.cs | C# | bsd-3-clause | 3,118 |
/* SPDX-License-Identifier: GPL-2.0 */
/* Marvell OcteonTx2 CGX driver
*
* Copyright (C) 2018 Marvell.
*
*/
#ifndef CGX_H
#define CGX_H
#include "mbox.h"
#include "cgx_fw_if.h"
#include "rpm.h"
/* PCI device IDs */
#define PCI_DEVID_OCTEONTX2_CGX 0xA059
/* PCI BAR nos */
#define PCI_CFG_REG_BAR_NUM 0
#define CGX_ID_MASK 0x7
#define MAX_LMAC_PER_CGX 4
#define MAX_DMAC_ENTRIES_PER_CGX 32
#define CGX_FIFO_LEN 65536 /* 64K for both Rx & Tx */
#define CGX_OFFSET(x) ((x) * MAX_LMAC_PER_CGX)
/* Registers */
#define CGXX_CMRX_CFG 0x00
#define CMR_P2X_SEL_MASK GENMASK_ULL(61, 59)
#define CMR_P2X_SEL_SHIFT 59ULL
#define CMR_P2X_SEL_NIX0 1ULL
#define CMR_P2X_SEL_NIX1 2ULL
#define CMR_EN BIT_ULL(55)
#define DATA_PKT_TX_EN BIT_ULL(53)
#define DATA_PKT_RX_EN BIT_ULL(54)
#define CGX_LMAC_TYPE_SHIFT 40
#define CGX_LMAC_TYPE_MASK 0xF
#define CGXX_CMRX_INT 0x040
#define FW_CGX_INT BIT_ULL(1)
#define CGXX_CMRX_INT_ENA_W1S 0x058
#define CGXX_CMRX_RX_ID_MAP 0x060
#define CGXX_CMRX_RX_STAT0 0x070
#define CGXX_CMRX_RX_LMACS 0x128
#define CGXX_CMRX_RX_DMAC_CTL0 (0x1F8 + mac_ops->csr_offset)
#define CGX_DMAC_CTL0_CAM_ENABLE BIT_ULL(3)
#define CGX_DMAC_CAM_ACCEPT BIT_ULL(3)
#define CGX_DMAC_MCAST_MODE_CAM BIT_ULL(2)
#define CGX_DMAC_MCAST_MODE BIT_ULL(1)
#define CGX_DMAC_BCAST_MODE BIT_ULL(0)
#define CGXX_CMRX_RX_DMAC_CAM0 (0x200 + mac_ops->csr_offset)
#define CGX_DMAC_CAM_ADDR_ENABLE BIT_ULL(48)
#define CGX_DMAC_CAM_ENTRY_LMACID GENMASK_ULL(50, 49)
#define CGXX_CMRX_RX_DMAC_CAM1 0x400
#define CGX_RX_DMAC_ADR_MASK GENMASK_ULL(47, 0)
#define CGXX_CMRX_TX_STAT0 0x700
#define CGXX_SCRATCH0_REG 0x1050
#define CGXX_SCRATCH1_REG 0x1058
#define CGX_CONST 0x2000
#define CGX_CONST_RXFIFO_SIZE GENMASK_ULL(23, 0)
#define CGXX_SPUX_CONTROL1 0x10000
#define CGXX_SPUX_LNX_FEC_CORR_BLOCKS 0x10700
#define CGXX_SPUX_LNX_FEC_UNCORR_BLOCKS 0x10800
#define CGXX_SPUX_RSFEC_CORR 0x10088
#define CGXX_SPUX_RSFEC_UNCORR 0x10090
#define CGXX_SPUX_CONTROL1_LBK BIT_ULL(14)
#define CGXX_GMP_PCS_MRX_CTL 0x30000
#define CGXX_GMP_PCS_MRX_CTL_LBK BIT_ULL(14)
#define CGXX_SMUX_RX_FRM_CTL 0x20020
#define CGX_SMUX_RX_FRM_CTL_CTL_BCK BIT_ULL(3)
#define CGX_SMUX_RX_FRM_CTL_PTP_MODE BIT_ULL(12)
#define CGXX_GMP_GMI_RXX_FRM_CTL 0x38028
#define CGX_GMP_GMI_RXX_FRM_CTL_CTL_BCK BIT_ULL(3)
#define CGX_GMP_GMI_RXX_FRM_CTL_PTP_MODE BIT_ULL(12)
#define CGXX_SMUX_TX_CTL 0x20178
#define CGXX_SMUX_TX_PAUSE_PKT_TIME 0x20110
#define CGXX_SMUX_TX_PAUSE_PKT_INTERVAL 0x20120
#define CGXX_GMP_GMI_TX_PAUSE_PKT_TIME 0x38230
#define CGXX_GMP_GMI_TX_PAUSE_PKT_INTERVAL 0x38248
#define CGX_SMUX_TX_CTL_L2P_BP_CONV BIT_ULL(7)
#define CGXX_CMR_RX_OVR_BP 0x130
#define CGX_CMR_RX_OVR_BP_EN(X) BIT_ULL(((X) + 8))
#define CGX_CMR_RX_OVR_BP_BP(X) BIT_ULL(((X) + 4))
#define CGX_COMMAND_REG CGXX_SCRATCH1_REG
#define CGX_EVENT_REG CGXX_SCRATCH0_REG
#define CGX_CMD_TIMEOUT 2200 /* msecs */
#define DEFAULT_PAUSE_TIME 0x7FF
#define CGX_LMAC_FWI 0
enum cgx_nix_stat_type {
NIX_STATS_RX,
NIX_STATS_TX,
};
enum LMAC_TYPE {
LMAC_MODE_SGMII = 0,
LMAC_MODE_XAUI = 1,
LMAC_MODE_RXAUI = 2,
LMAC_MODE_10G_R = 3,
LMAC_MODE_40G_R = 4,
LMAC_MODE_QSGMII = 6,
LMAC_MODE_25G_R = 7,
LMAC_MODE_50G_R = 8,
LMAC_MODE_100G_R = 9,
LMAC_MODE_USXGMII = 10,
LMAC_MODE_MAX,
};
struct cgx_link_event {
struct cgx_link_user_info link_uinfo;
u8 cgx_id;
u8 lmac_id;
};
/**
* struct cgx_event_cb
* @notify_link_chg: callback for link change notification
* @data: data passed to callback function
*/
struct cgx_event_cb {
int (*notify_link_chg)(struct cgx_link_event *event, void *data);
void *data;
};
extern struct pci_driver cgx_driver;
int cgx_get_cgxcnt_max(void);
int cgx_get_cgxid(void *cgxd);
int cgx_get_lmac_cnt(void *cgxd);
void *cgx_get_pdata(int cgx_id);
int cgx_set_pkind(void *cgxd, u8 lmac_id, int pkind);
int cgx_lmac_evh_register(struct cgx_event_cb *cb, void *cgxd, int lmac_id);
int cgx_lmac_evh_unregister(void *cgxd, int lmac_id);
int cgx_get_tx_stats(void *cgxd, int lmac_id, int idx, u64 *tx_stat);
int cgx_get_rx_stats(void *cgxd, int lmac_id, int idx, u64 *rx_stat);
int cgx_lmac_rx_tx_enable(void *cgxd, int lmac_id, bool enable);
int cgx_lmac_tx_enable(void *cgxd, int lmac_id, bool enable);
int cgx_lmac_addr_set(u8 cgx_id, u8 lmac_id, u8 *mac_addr);
int cgx_lmac_addr_reset(u8 cgx_id, u8 lmac_id);
u64 cgx_lmac_addr_get(u8 cgx_id, u8 lmac_id);
int cgx_lmac_addr_add(u8 cgx_id, u8 lmac_id, u8 *mac_addr);
int cgx_lmac_addr_del(u8 cgx_id, u8 lmac_id, u8 index);
int cgx_lmac_addr_max_entries_get(u8 cgx_id, u8 lmac_id);
void cgx_lmac_promisc_config(int cgx_id, int lmac_id, bool enable);
void cgx_lmac_enadis_rx_pause_fwding(void *cgxd, int lmac_id, bool enable);
int cgx_lmac_internal_loopback(void *cgxd, int lmac_id, bool enable);
int cgx_get_link_info(void *cgxd, int lmac_id,
struct cgx_link_user_info *linfo);
int cgx_lmac_linkup_start(void *cgxd);
int cgx_get_fwdata_base(u64 *base);
int cgx_lmac_get_pause_frm(void *cgxd, int lmac_id,
u8 *tx_pause, u8 *rx_pause);
int cgx_lmac_set_pause_frm(void *cgxd, int lmac_id,
u8 tx_pause, u8 rx_pause);
void cgx_lmac_ptp_config(void *cgxd, int lmac_id, bool enable);
u8 cgx_lmac_get_p2x(int cgx_id, int lmac_id);
int cgx_set_fec(u64 fec, int cgx_id, int lmac_id);
int cgx_get_fec_stats(void *cgxd, int lmac_id, struct cgx_fec_stats_rsp *rsp);
int cgx_get_phy_fec_stats(void *cgxd, int lmac_id);
int cgx_set_link_mode(void *cgxd, struct cgx_set_link_mode_args args,
int cgx_id, int lmac_id);
u64 cgx_features_get(void *cgxd);
struct mac_ops *get_mac_ops(void *cgxd);
int cgx_get_nr_lmacs(void *cgxd);
u8 cgx_get_lmacid(void *cgxd, u8 lmac_index);
unsigned long cgx_get_lmac_bmap(void *cgxd);
void cgx_lmac_write(int cgx_id, int lmac_id, u64 offset, u64 val);
u64 cgx_lmac_read(int cgx_id, int lmac_id, u64 offset);
int cgx_lmac_addr_update(u8 cgx_id, u8 lmac_id, u8 *mac_addr, u8 index);
u64 cgx_read_dmac_ctrl(void *cgxd, int lmac_id);
u64 cgx_read_dmac_entry(void *cgxd, int index);
#endif /* CGX_H */
| tprrt/linux-stable | drivers/net/ethernet/marvell/octeontx2/af/cgx.h | C | gpl-2.0 | 6,050 |
/*!
* Copyright (c) 2015, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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 of Salesforce.com 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var vows = require('vows');
var assert = require('assert');
var async = require('async');
var tough = require('../lib/cookie');
var Cookie = tough.Cookie;
var CookieJar = tough.CookieJar;
var atNow = Date.now();
function at(offset) {
return {now: new Date(atNow + offset)};
}
vows
.describe('Regression tests')
.addBatch({
"Issue 1": {
topic: function () {
var cj = new CookieJar();
cj.setCookie('hello=world; path=/some/path/', 'http://domain/some/path/file', function (err, cookie) {
this.callback(err, {cj: cj, cookie: cookie});
}.bind(this));
},
"stored a cookie": function (t) {
assert.ok(t.cookie);
},
"getting it back": {
topic: function (t) {
t.cj.getCookies('http://domain/some/path/file', function (err, cookies) {
this.callback(err, {cj: t.cj, cookies: cookies || []});
}.bind(this));
},
"got one cookie": function (t) {
assert.lengthOf(t.cookies, 1);
},
"it's the right one": function (t) {
var c = t.cookies[0];
assert.equal(c.key, 'hello');
assert.equal(c.value, 'world');
}
}
}
})
.addBatch({
"trailing semi-colon set into cj": {
topic: function () {
var cb = this.callback;
var cj = new CookieJar();
var ex = 'http://www.example.com';
var tasks = [];
tasks.push(function (next) {
cj.setCookie('broken_path=testme; path=/;', ex, at(-1), next);
});
tasks.push(function (next) {
cj.setCookie('b=2; Path=/;;;;', ex, at(-1), next);
});
async.parallel(tasks, function (err, cookies) {
cb(null, {
cj: cj,
cookies: cookies
});
});
},
"check number of cookies": function (t) {
assert.lengthOf(t.cookies, 2, "didn't set");
},
"check *broken_path* was set properly": function (t) {
assert.equal(t.cookies[0].key, "broken_path");
assert.equal(t.cookies[0].value, "testme");
assert.equal(t.cookies[0].path, "/");
},
"check *b* was set properly": function (t) {
assert.equal(t.cookies[1].key, "b");
assert.equal(t.cookies[1].value, "2");
assert.equal(t.cookies[1].path, "/");
},
"retrieve the cookie": {
topic: function (t) {
var cb = this.callback;
t.cj.getCookies('http://www.example.com', {}, function (err, cookies) {
t.cookies = cookies;
cb(err, t);
});
},
"get the cookie": function (t) {
assert.lengthOf(t.cookies, 2);
assert.equal(t.cookies[0].key, 'broken_path');
assert.equal(t.cookies[0].value, 'testme');
assert.equal(t.cookies[1].key, "b");
assert.equal(t.cookies[1].value, "2");
assert.equal(t.cookies[1].path, "/");
}
}
}
})
.addBatch({
"tough-cookie throws exception on malformed URI (GH-32)": {
topic: function () {
var url = "http://www.example.com/?test=100%";
var cj = new CookieJar();
cj.setCookieSync("Test=Test", url);
return cj.getCookieStringSync(url);
},
"cookies are set": function (cookieStr) {
assert.strictEqual(cookieStr, "Test=Test");
}
}
})
.export(module);
| vendavo/yowie | yowie-web/node_modules/bower/node_modules/request/node_modules/tough-cookie/test/regression_test.js | JavaScript | mit | 4,995 |
<?php
return [
'Names' => [
'CDF' => [
0 => 'FC',
1 => 'franc congolais',
],
],
];
| Nyholm/symfony | src/Symfony/Component/Intl/Resources/data/currencies/fr_CD.php | PHP | mit | 132 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.StreamAnalytics.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.StreamAnalytics;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines headers for Update operation.
/// </summary>
public partial class FunctionsUpdateHeaders
{
/// <summary>
/// Initializes a new instance of the FunctionsUpdateHeaders class.
/// </summary>
public FunctionsUpdateHeaders()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the FunctionsUpdateHeaders class.
/// </summary>
/// <param name="eTag">The current entity tag for the function. This is
/// an opaque string. You can use it to detect whether the resource has
/// changed between requests. You can also use it in the If-Match or
/// If-None-Match headers for write operations for optimistic
/// concurrency.</param>
public FunctionsUpdateHeaders(string eTag = default(string))
{
ETag = eTag;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the current entity tag for the function. This is an
/// opaque string. You can use it to detect whether the resource has
/// changed between requests. You can also use it in the If-Match or
/// If-None-Match headers for write operations for optimistic
/// concurrency.
/// </summary>
[JsonProperty(PropertyName = "ETag")]
public string ETag { get; set; }
}
}
| DheerendraRathor/azure-sdk-for-net | src/SDKs/StreamAnalytics/Management.StreamAnalytics/Generated/Models/FunctionsUpdateHeaders.cs | C# | mit | 2,128 |
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Promise = require('bluebird');
var MongoClient = require('mongodb');
function defaultSerializeFunction(session) {
// Copy each property of the session to a new object
var obj = {};
var prop = void 0;
for (prop in session) {
if (prop === 'cookie') {
// Convert the cookie instance to an object, if possible
// This gets rid of the duplicate object under session.cookie.data property
obj.cookie = session.cookie.toJSON ? session.cookie.toJSON() : session.cookie;
} else {
obj[prop] = session[prop];
}
}
return obj;
}
function computeTransformFunctions(options, defaultStringify) {
if (options.serialize || options.unserialize) {
return {
serialize: options.serialize || defaultSerializeFunction,
unserialize: options.unserialize || function (x) {
return x;
}
};
}
if (options.stringify === false || defaultStringify === false) {
return {
serialize: defaultSerializeFunction,
unserialize: function (x) {
return x;
}
};
}
if (options.stringify === true || defaultStringify === true) {
return {
serialize: JSON.stringify,
unserialize: JSON.parse
};
}
}
module.exports = function connectMongo(connect) {
var Store = connect.Store || connect.session.Store;
var MemoryStore = connect.MemoryStore || connect.session.MemoryStore;
var MongoStore = function (_Store) {
_inherits(MongoStore, _Store);
function MongoStore(options) {
_classCallCheck(this, MongoStore);
options = options || {};
/* Fallback */
if (options.fallbackMemory && MemoryStore) {
var _ret;
return _ret = new MemoryStore(), _possibleConstructorReturn(_this, _ret);
}
/* Options */
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(MongoStore).call(this, options));
_this.ttl = options.ttl || 1209600; // 14 days
_this.collectionName = options.collection || 'sessions';
_this.autoRemove = options.autoRemove || 'native';
_this.autoRemoveInterval = options.autoRemoveInterval || 10;
_this.transformFunctions = computeTransformFunctions(options, true);
_this.options = options;
_this.changeState('init');
var newConnectionCallback = function (err, db) {
if (err) {
_this.connectionFailed(err);
} else {
_this.handleNewConnectionAsync(db);
}
};
if (options.url) {
// New native connection using url + mongoOptions
MongoClient.connect(options.url, options.mongoOptions || {}, newConnectionCallback);
} else if (options.mongooseConnection) {
// Re-use existing or upcoming mongoose connection
if (options.mongooseConnection.readyState === 1) {
_this.handleNewConnectionAsync(options.mongooseConnection.db);
} else {
options.mongooseConnection.once('open', function () {
return _this.handleNewConnectionAsync(options.mongooseConnection.db);
});
}
} else if (options.db && options.db.listCollections) {
// Re-use existing or upcoming native connection
if (options.db.openCalled || options.db.openCalled === undefined) {
// openCalled is undefined in mongodb@2.x
_this.handleNewConnectionAsync(options.db);
} else {
options.db.open(newConnectionCallback);
}
} else if (options.dbPromise) {
options.dbPromise.then(function (db) {
return _this.handleNewConnectionAsync(db);
}).catch(function (err) {
return _this.connectionFailed(err);
});
} else {
throw new Error('Connection strategy not found');
}
_this.changeState('connecting');
return _this;
}
_createClass(MongoStore, [{
key: 'connectionFailed',
value: function connectionFailed(err) {
this.changeState('disconnected');
throw err;
}
}, {
key: 'handleNewConnectionAsync',
value: function handleNewConnectionAsync(db) {
var _this2 = this;
this.db = db;
return this.setCollection(db.collection(this.collectionName)).setAutoRemoveAsync().then(function () {
return _this2.changeState('connected');
});
}
}, {
key: 'setAutoRemoveAsync',
value: function setAutoRemoveAsync() {
var _this3 = this;
switch (this.autoRemove) {
case 'native':
return this.collection.ensureIndexAsync({ expires: 1 }, { expireAfterSeconds: 0 });
case 'interval':
var removeQuery = { expires: { $lt: new Date() } };
this.timer = setInterval(function () {
return _this3.collection.remove(removeQuery, { w: 0 });
}, this.autoRemoveInterval * 1000 * 60);
this.timer.unref();
return Promise.resolve();
default:
return Promise.resolve();
}
}
}, {
key: 'changeState',
value: function changeState(newState) {
if (newState !== this.state) {
this.state = newState;
this.emit(newState);
}
}
}, {
key: 'setCollection',
value: function setCollection(collection) {
if (this.timer) {
clearInterval(this.timer);
}
this.collectionReadyPromise = undefined;
this.collection = collection;
// Promisify used collection methods
['count', 'findOne', 'remove', 'drop', 'update', 'ensureIndex'].forEach(function (method) {
collection[method + 'Async'] = Promise.promisify(collection[method], collection);
});
return this;
}
}, {
key: 'collectionReady',
value: function collectionReady() {
var _this4 = this;
var promise = this.collectionReadyPromise;
if (!promise) {
promise = new Promise(function (resolve, reject) {
switch (_this4.state) {
case 'connected':
resolve(_this4.collection);
break;
case 'connecting':
_this4.once('connected', function () {
return resolve(_this4.collection);
});
break;
case 'disconnected':
reject(new Error('Not connected'));
break;
}
});
this.collectionReadyPromise = promise;
}
return promise;
}
}, {
key: 'computeStorageId',
value: function computeStorageId(sessionId) {
if (this.options.transformId && typeof this.options.transformId === 'function') {
return this.options.transformId(sessionId);
} else {
return sessionId;
}
}
/* Public API */
}, {
key: 'get',
value: function get(sid, callback) {
var _this5 = this;
return this.collectionReady().then(function (collection) {
return collection.findOneAsync({
_id: _this5.computeStorageId(sid),
$or: [{ expires: { $exists: false } }, { expires: { $gt: new Date() } }]
});
}).then(function (session) {
if (session) {
var s = _this5.transformFunctions.unserialize(session.session);
if (_this5.options.touchAfter > 0 && session.lastModified) {
s.lastModified = session.lastModified;
}
_this5.emit('touch', sid);
return s;
}
}).nodeify(callback);
}
}, {
key: 'set',
value: function set(sid, session, callback) {
var _this6 = this;
// removing the lastModified prop from the session object before update
if (this.options.touchAfter > 0 && session && session.lastModified) {
delete session.lastModified;
}
var s;
try {
s = { _id: this.computeStorageId(sid), session: this.transformFunctions.serialize(session) };
} catch (err) {
return callback(err);
}
if (session && session.cookie && session.cookie.expires) {
s.expires = new Date(session.cookie.expires);
} else {
// If there's no expiration date specified, it is
// browser-session cookie or there is no cookie at all,
// as per the connect docs.
//
// So we set the expiration to two-weeks from now
// - as is common practice in the industry (e.g Django) -
// or the default specified in the options.
s.expires = new Date(Date.now() + this.ttl * 1000);
}
if (this.options.touchAfter > 0) {
s.lastModified = new Date();
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this6.computeStorageId(sid) }, s, { upsert: true });
}).then(function () {
return _this6.emit('set', sid);
}).nodeify(callback);
}
}, {
key: 'touch',
value: function touch(sid, session, callback) {
var _this7 = this;
var updateFields = {},
touchAfter = this.options.touchAfter * 1000,
lastModified = session.lastModified ? session.lastModified.getTime() : 0,
currentDate = new Date();
// if the given options has a touchAfter property, check if the
// current timestamp - lastModified timestamp is bigger than
// the specified, if it's not, don't touch the session
if (touchAfter > 0 && lastModified > 0) {
var timeElapsed = currentDate.getTime() - session.lastModified;
if (timeElapsed < touchAfter) {
return callback();
} else {
updateFields.lastModified = currentDate;
}
}
if (session && session.cookie && session.cookie.expires) {
updateFields.expires = new Date(session.cookie.expires);
} else {
updateFields.expires = new Date(Date.now() + this.ttl * 1000);
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this7.computeStorageId(sid) }, { $set: updateFields });
}).then(function (result) {
if (result.nModified === 0) {
throw new Error('Unable to find the session to touch');
} else {
_this7.emit('touch', sid);
}
}).nodeify(callback);
}
}, {
key: 'destroy',
value: function destroy(sid, callback) {
var _this8 = this;
return this.collectionReady().then(function (collection) {
return collection.removeAsync({ _id: _this8.computeStorageId(sid) });
}).then(function () {
return _this8.emit('destroy', sid);
}).nodeify(callback);
}
}, {
key: 'length',
value: function length(callback) {
return this.collectionReady().then(function (collection) {
return collection.countAsync({});
}).nodeify(callback);
}
}, {
key: 'clear',
value: function clear(callback) {
return this.collectionReady().then(function (collection) {
return collection.dropAsync();
}).nodeify(callback);
}
}, {
key: 'close',
value: function close() {
if (this.db) {
this.db.close();
}
}
}]);
return MongoStore;
}(Store);
return MongoStore;
}; | luoshichang/learnNode | node_modules/connect-mongo/src-es5/index.js | JavaScript | mit | 15,400 |
use blog::Post;
fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
assert_eq!("", post.content());
post.request_review();
assert_eq!("", post.content());
post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}
| KaiserY/trpl-zh-cn | listings/ch17-oop/listing-17-18/src/main.rs | Rust | mit | 302 |
from __future__ import division, absolute_import, print_function
import sys
import collections
import pickle
import warnings
from os import path
import numpy as np
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_equal, assert_array_equal,
assert_array_almost_equal, assert_raises, assert_warns
)
class TestFromrecords(TestCase):
def test_fromrecords(self):
r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]],
names='col1,col2,col3')
assert_equal(r[0].item(), (456, 'dbe', 1.2))
assert_equal(r['col1'].dtype.kind, 'i')
if sys.version_info[0] >= 3:
assert_equal(r['col2'].dtype.kind, 'U')
assert_equal(r['col2'].dtype.itemsize, 12)
else:
assert_equal(r['col2'].dtype.kind, 'S')
assert_equal(r['col2'].dtype.itemsize, 3)
assert_equal(r['col3'].dtype.kind, 'f')
def test_fromrecords_0len(self):
""" Verify fromrecords works with a 0-length input """
dtype = [('a', np.float), ('b', np.float)]
r = np.rec.fromrecords([], dtype=dtype)
assert_equal(r.shape, (0,))
def test_fromrecords_2d(self):
data = [
[(1, 2), (3, 4), (5, 6)],
[(6, 5), (4, 3), (2, 1)]
]
expected_a = [[1, 3, 5], [6, 4, 2]]
expected_b = [[2, 4, 6], [5, 3, 1]]
# try with dtype
r1 = np.rec.fromrecords(data, dtype=[('a', int), ('b', int)])
assert_equal(r1['a'], expected_a)
assert_equal(r1['b'], expected_b)
# try with names
r2 = np.rec.fromrecords(data, names=['a', 'b'])
assert_equal(r2['a'], expected_a)
assert_equal(r2['b'], expected_b)
assert_equal(r1, r2)
def test_method_array(self):
r = np.rec.array(b'abcdefg' * 100, formats='i2,a3,i4', shape=3, byteorder='big')
assert_equal(r[1].item(), (25444, b'efg', 1633837924))
def test_method_array2(self):
r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
(6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
assert_equal(r[1].item(), (2, 22.0, b'b'))
def test_recarray_slices(self):
r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
(6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
assert_equal(r[1::2][1].item(), (4, 44.0, b'd'))
def test_recarray_fromarrays(self):
x1 = np.array([1, 2, 3, 4])
x2 = np.array(['a', 'dd', 'xyz', '12'])
x3 = np.array([1.1, 2, 3, 4])
r = np.rec.fromarrays([x1, x2, x3], names='a,b,c')
assert_equal(r[1].item(), (2, 'dd', 2.0))
x1[1] = 34
assert_equal(r.a, np.array([1, 2, 3, 4]))
def test_recarray_fromfile(self):
data_dir = path.join(path.dirname(__file__), 'data')
filename = path.join(data_dir, 'recarray_from_file.fits')
fd = open(filename, 'rb')
fd.seek(2880 * 2)
r1 = np.rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big')
fd.seek(2880 * 2)
r2 = np.rec.array(fd, formats='f8,i4,a5', shape=3, byteorder='big')
fd.close()
assert_equal(r1, r2)
def test_recarray_from_obj(self):
count = 10
a = np.zeros(count, dtype='O')
b = np.zeros(count, dtype='f8')
c = np.zeros(count, dtype='f8')
for i in range(len(a)):
a[i] = list(range(1, 10))
mine = np.rec.fromarrays([a, b, c], names='date,data1,data2')
for i in range(len(a)):
assert_((mine.date[i] == list(range(1, 10))))
assert_((mine.data1[i] == 0.0))
assert_((mine.data2[i] == 0.0))
def test_recarray_from_repr(self):
a = np.array([(1,'ABC'), (2, "DEF")],
dtype=[('foo', int), ('bar', 'S4')])
recordarr = np.rec.array(a)
recarr = a.view(np.recarray)
recordview = a.view(np.dtype((np.record, a.dtype)))
recordarr_r = eval("numpy." + repr(recordarr), {'numpy': np})
recarr_r = eval("numpy." + repr(recarr), {'numpy': np})
recordview_r = eval("numpy." + repr(recordview), {'numpy': np})
assert_equal(type(recordarr_r), np.recarray)
assert_equal(recordarr_r.dtype.type, np.record)
assert_equal(recordarr, recordarr_r)
assert_equal(type(recarr_r), np.recarray)
assert_equal(recarr_r.dtype.type, np.record)
assert_equal(recarr, recarr_r)
assert_equal(type(recordview_r), np.ndarray)
assert_equal(recordview.dtype.type, np.record)
assert_equal(recordview, recordview_r)
def test_recarray_views(self):
a = np.array([(1,'ABC'), (2, "DEF")],
dtype=[('foo', int), ('bar', 'S4')])
b = np.array([1,2,3,4,5], dtype=np.int64)
#check that np.rec.array gives right dtypes
assert_equal(np.rec.array(a).dtype.type, np.record)
assert_equal(type(np.rec.array(a)), np.recarray)
assert_equal(np.rec.array(b).dtype.type, np.int64)
assert_equal(type(np.rec.array(b)), np.recarray)
#check that viewing as recarray does the same
assert_equal(a.view(np.recarray).dtype.type, np.record)
assert_equal(type(a.view(np.recarray)), np.recarray)
assert_equal(b.view(np.recarray).dtype.type, np.int64)
assert_equal(type(b.view(np.recarray)), np.recarray)
#check that view to non-structured dtype preserves type=np.recarray
r = np.rec.array(np.ones(4, dtype="f4,i4"))
rv = r.view('f8').view('f4,i4')
assert_equal(type(rv), np.recarray)
assert_equal(rv.dtype.type, np.record)
#check that getitem also preserves np.recarray and np.record
r = np.rec.array(np.ones(4, dtype=[('a', 'i4'), ('b', 'i4'),
('c', 'i4,i4')]))
assert_equal(r['c'].dtype.type, np.record)
assert_equal(type(r['c']), np.recarray)
# suppress deprecation warning in 1.12 (remove in 1.13)
with assert_warns(FutureWarning):
assert_equal(r[['a', 'b']].dtype.type, np.record)
assert_equal(type(r[['a', 'b']]), np.recarray)
#and that it preserves subclasses (gh-6949)
class C(np.recarray):
pass
c = r.view(C)
assert_equal(type(c['c']), C)
# check that accessing nested structures keep record type, but
# not for subarrays, non-void structures, non-structured voids
test_dtype = [('a', 'f4,f4'), ('b', 'V8'), ('c', ('f4',2)),
('d', ('i8', 'i4,i4'))]
r = np.rec.array([((1,1), b'11111111', [1,1], 1),
((1,1), b'11111111', [1,1], 1)], dtype=test_dtype)
assert_equal(r.a.dtype.type, np.record)
assert_equal(r.b.dtype.type, np.void)
assert_equal(r.c.dtype.type, np.float32)
assert_equal(r.d.dtype.type, np.int64)
# check the same, but for views
r = np.rec.array(np.ones(4, dtype='i4,i4'))
assert_equal(r.view('f4,f4').dtype.type, np.record)
assert_equal(r.view(('i4',2)).dtype.type, np.int32)
assert_equal(r.view('V8').dtype.type, np.void)
assert_equal(r.view(('i8', 'i4,i4')).dtype.type, np.int64)
#check that we can undo the view
arrs = [np.ones(4, dtype='f4,i4'), np.ones(4, dtype='f8')]
for arr in arrs:
rec = np.rec.array(arr)
# recommended way to view as an ndarray:
arr2 = rec.view(rec.dtype.fields or rec.dtype, np.ndarray)
assert_equal(arr2.dtype.type, arr.dtype.type)
assert_equal(type(arr2), type(arr))
def test_recarray_repr(self):
# make sure non-structured dtypes also show up as rec.array
a = np.array(np.ones(4, dtype='f8'))
assert_(repr(np.rec.array(a)).startswith('rec.array'))
# check that the 'np.record' part of the dtype isn't shown
a = np.rec.array(np.ones(3, dtype='i4,i4'))
assert_equal(repr(a).find('numpy.record'), -1)
a = np.rec.array(np.ones(3, dtype='i4'))
assert_(repr(a).find('dtype=int32') != -1)
def test_recarray_from_names(self):
ra = np.rec.array([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
(0, ' ', 0.40000000596046448, 0)],
names='c1, c2, c3, c4')
pa = np.rec.fromrecords([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
(0, ' ', 0.40000000596046448, 0)],
names='c1, c2, c3, c4')
assert_(ra.dtype == pa.dtype)
assert_(ra.shape == pa.shape)
for k in range(len(ra)):
assert_(ra[k].item() == pa[k].item())
def test_recarray_conflict_fields(self):
ra = np.rec.array([(1, 'abc', 2.3), (2, 'xyz', 4.2),
(3, 'wrs', 1.3)],
names='field, shape, mean')
ra.mean = [1.1, 2.2, 3.3]
assert_array_almost_equal(ra['mean'], [1.1, 2.2, 3.3])
assert_(type(ra.mean) is type(ra.var))
ra.shape = (1, 3)
assert_(ra.shape == (1, 3))
ra.shape = ['A', 'B', 'C']
assert_array_equal(ra['shape'], [['A', 'B', 'C']])
ra.field = 5
assert_array_equal(ra['field'], [[5, 5, 5]])
assert_(isinstance(ra.field, collections.Callable))
def test_fromrecords_with_explicit_dtype(self):
a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')],
dtype=[('a', int), ('b', np.object)])
assert_equal(a.a, [1, 2])
assert_equal(a[0].a, 1)
assert_equal(a.b, ['a', 'bbb'])
assert_equal(a[-1].b, 'bbb')
#
ndtype = np.dtype([('a', int), ('b', np.object)])
a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=ndtype)
assert_equal(a.a, [1, 2])
assert_equal(a[0].a, 1)
assert_equal(a.b, ['a', 'bbb'])
assert_equal(a[-1].b, 'bbb')
def test_recarray_stringtypes(self):
# Issue #3993
a = np.array([('abc ', 1), ('abc', 2)],
dtype=[('foo', 'S4'), ('bar', int)])
a = a.view(np.recarray)
assert_equal(a.foo[0] == a.foo[1], False)
def test_recarray_returntypes(self):
qux_fields = {'C': (np.dtype('S5'), 0), 'D': (np.dtype('S5'), 6)}
a = np.rec.array([('abc ', (1,1), 1, ('abcde', 'fgehi')),
('abc', (2,3), 1, ('abcde', 'jklmn'))],
dtype=[('foo', 'S4'),
('bar', [('A', int), ('B', int)]),
('baz', int), ('qux', qux_fields)])
assert_equal(type(a.foo), np.ndarray)
assert_equal(type(a['foo']), np.ndarray)
assert_equal(type(a.bar), np.recarray)
assert_equal(type(a['bar']), np.recarray)
assert_equal(a.bar.dtype.type, np.record)
assert_equal(type(a['qux']), np.recarray)
assert_equal(a.qux.dtype.type, np.record)
assert_equal(dict(a.qux.dtype.fields), qux_fields)
assert_equal(type(a.baz), np.ndarray)
assert_equal(type(a['baz']), np.ndarray)
assert_equal(type(a[0].bar), np.record)
assert_equal(type(a[0]['bar']), np.record)
assert_equal(a[0].bar.A, 1)
assert_equal(a[0].bar['A'], 1)
assert_equal(a[0]['bar'].A, 1)
assert_equal(a[0]['bar']['A'], 1)
assert_equal(a[0].qux.D, b'fgehi')
assert_equal(a[0].qux['D'], b'fgehi')
assert_equal(a[0]['qux'].D, b'fgehi')
assert_equal(a[0]['qux']['D'], b'fgehi')
def test_zero_width_strings(self):
# Test for #6430, based on the test case from #1901
cols = [['test'] * 3, [''] * 3]
rec = np.rec.fromarrays(cols)
assert_equal(rec['f0'], ['test', 'test', 'test'])
assert_equal(rec['f1'], ['', '', ''])
dt = np.dtype([('f0', '|S4'), ('f1', '|S')])
rec = np.rec.fromarrays(cols, dtype=dt)
assert_equal(rec.itemsize, 4)
assert_equal(rec['f0'], [b'test', b'test', b'test'])
assert_equal(rec['f1'], [b'', b'', b''])
class TestRecord(TestCase):
def setUp(self):
self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)],
dtype=[("col1", "<i4"),
("col2", "<i4"),
("col3", "<i4")])
def test_assignment1(self):
a = self.data
assert_equal(a.col1[0], 1)
a[0].col1 = 0
assert_equal(a.col1[0], 0)
def test_assignment2(self):
a = self.data
assert_equal(a.col1[0], 1)
a.col1[0] = 0
assert_equal(a.col1[0], 0)
def test_invalid_assignment(self):
a = self.data
def assign_invalid_column(x):
x[0].col5 = 1
self.assertRaises(AttributeError, assign_invalid_column, a)
def test_nonwriteable_setfield(self):
# gh-8171
r = np.rec.array([(0,), (1,)], dtype=[('f', 'i4')])
r.flags.writeable = False
with assert_raises(ValueError):
r.f = [2, 3]
with assert_raises(ValueError):
r.setfield([2,3], *r.dtype.fields['f'])
def test_out_of_order_fields(self):
"""Ticket #1431."""
# this test will be invalid in 1.13
# suppress deprecation warning in 1.12 (remove in 1.13)
with assert_warns(FutureWarning):
x = self.data[['col1', 'col2']]
y = self.data[['col2', 'col1']]
assert_equal(x[0][0], y[0][1])
def test_pickle_1(self):
# Issue #1529
a = np.array([(1, [])], dtype=[('a', np.int32), ('b', np.int32, 0)])
assert_equal(a, pickle.loads(pickle.dumps(a)))
assert_equal(a[0], pickle.loads(pickle.dumps(a[0])))
def test_pickle_2(self):
a = self.data
assert_equal(a, pickle.loads(pickle.dumps(a)))
assert_equal(a[0], pickle.loads(pickle.dumps(a[0])))
def test_pickle_3(self):
# Issue #7140
a = self.data
pa = pickle.loads(pickle.dumps(a[0]))
assert_(pa.flags.c_contiguous)
assert_(pa.flags.f_contiguous)
assert_(pa.flags.writeable)
assert_(pa.flags.aligned)
def test_objview_record(self):
# https://github.com/numpy/numpy/issues/2599
dt = np.dtype([('foo', 'i8'), ('bar', 'O')])
r = np.zeros((1,3), dtype=dt).view(np.recarray)
r.foo = np.array([1, 2, 3]) # TypeError?
# https://github.com/numpy/numpy/issues/3256
ra = np.recarray((2,), dtype=[('x', object), ('y', float), ('z', int)])
with assert_warns(FutureWarning):
ra[['x','y']] # TypeError?
def test_record_scalar_setitem(self):
# https://github.com/numpy/numpy/issues/3561
rec = np.recarray(1, dtype=[('x', float, 5)])
rec[0].x = 1
assert_equal(rec[0].x, np.ones(5))
def test_missing_field(self):
# https://github.com/numpy/numpy/issues/4806
arr = np.zeros((3,), dtype=[('x', int), ('y', int)])
assert_raises(ValueError, lambda: arr[['nofield']])
def test_find_duplicate():
l1 = [1, 2, 3, 4, 5, 6]
assert_(np.rec.find_duplicate(l1) == [])
l2 = [1, 2, 1, 4, 5, 6]
assert_(np.rec.find_duplicate(l2) == [1])
l3 = [1, 2, 1, 4, 1, 6, 2, 3]
assert_(np.rec.find_duplicate(l3) == [1, 2])
l3 = [2, 2, 1, 4, 1, 6, 2, 3]
assert_(np.rec.find_duplicate(l3) == [2, 1])
if __name__ == "__main__":
run_module_suite()
| mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/numpy/core/tests/test_records.py | Python | mit | 15,635 |
// 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.
/*
The present file format
Present files have the following format. The first non-blank non-comment
line is the title, so the header looks like
Title of document
Subtitle of document
15:04 2 Jan 2006
Tags: foo, bar, baz
<blank line>
Author Name
Job title, Company
joe@example.com
http://url/
@twitter_name
The subtitle, date, and tags lines are optional.
The date line may be written without a time:
2 Jan 2006
In this case, the time will be interpreted as 10am UTC on that date.
The tags line is a comma-separated list of tags that may be used to categorize
the document.
The author section may contain a mixture of text, twitter names, and links.
For slide presentations, only the plain text lines will be displayed on the
first slide.
Multiple presenters may be specified, separated by a blank line.
After that come slides/sections, each after a blank line:
* Title of slide or section (must have asterisk)
Some Text
** Subsection
- bullets
- more bullets
- a bullet with
*** Sub-subsection
Some More text
Preformatted text
is indented (however you like)
Further Text, including invocations like:
.code x.go /^func main/,/^}/
.play y.go
.image image.jpg
.background image.jpg
.iframe http://foo
.link http://foo label
.html file.html
.caption _Gopher_ by [[http://www.reneefrench.com][Renée French]]
Again, more text
Blank lines are OK (not mandatory) after the title and after the
text. Text, bullets, and .code etc. are all optional; title is
not.
Lines starting with # in column 1 are commentary.
Fonts:
Within the input for plain text or lists, text bracketed by font
markers will be presented in italic, bold, or program font.
Marker characters are _ (italic), * (bold) and ` (program font).
Unmatched markers appear as plain text.
Within marked text, a single marker character becomes a space
and a doubled single marker quotes the marker character.
_italic_
*bold*
`program`
_this_is_all_italic_
_Why_use_scoped__ptr_? Use plain ***ptr* instead.
Inline links:
Links can be included in any text with the form [[url][label]], or
[[url]] to use the URL itself as the label.
Functions:
A number of template functions are available through invocations
in the input text. Each such invocation contains a period as the
first character on the line, followed immediately by the name of
the function, followed by any arguments. A typical invocation might
be
.play demo.go /^func show/,/^}/
(except that the ".play" must be at the beginning of the line and
not be indented like this.)
Here follows a description of the functions:
code:
Injects program source into the output by extracting code from files
and injecting them as HTML-escaped <pre> blocks. The argument is
a file name followed by an optional address that specifies what
section of the file to display. The address syntax is similar in
its simplest form to that of ed, but comes from sam and is more
general. See
http://plan9.bell-labs.com/sys/doc/sam/sam.html Table II
for full details. The displayed block is always rounded out to a
full line at both ends.
If no pattern is present, the entire file is displayed.
Any line in the program that ends with the four characters
OMIT
is deleted from the source before inclusion, making it easy
to write things like
.code test.go /START OMIT/,/END OMIT/
to find snippets like this
tedious_code = boring_function()
// START OMIT
interesting_code = fascinating_function()
// END OMIT
and see only this:
interesting_code = fascinating_function()
Also, inside the displayed text a line that ends
// HL
will be highlighted in the display; the 'h' key in the browser will
toggle extra emphasis of any highlighted lines. A highlighting mark
may have a suffix word, such as
// HLxxx
Such highlights are enabled only if the code invocation ends with
"HL" followed by the word:
.code test.go /^type Foo/,/^}/ HLxxx
The .code function may take one or more flags immediately preceding
the filename. This command shows test.go in an editable text area:
.code -edit test.go
This command shows test.go with line numbers:
.code -numbers test.go
play:
The function "play" is the same as "code" but puts a button
on the displayed source so the program can be run from the browser.
Although only the selected text is shown, all the source is included
in the HTML output so it can be presented to the compiler.
link:
Create a hyperlink. The syntax is 1 or 2 space-separated arguments.
The first argument is always the HTTP URL. If there is a second
argument, it is the text label to display for this link.
.link http://golang.org golang.org
image:
The template uses the function "image" to inject picture files.
The syntax is simple: 1 or 3 space-separated arguments.
The first argument is always the file name.
If there are more arguments, they are the height and width;
both must be present, or substituted with an underscore.
Replacing a dimension argument with the underscore parameter
preserves the aspect ratio of the image when scaling.
.image images/betsy.jpg 100 200
.image images/janet.jpg _ 300
video:
The template uses the function "video" to inject video files.
The syntax is simple: 2 or 4 space-separated arguments.
The first argument is always the file name.
The second argument is always the file content-type.
If there are more arguments, they are the height and width;
both must be present, or substituted with an underscore.
Replacing a dimension argument with the underscore parameter
preserves the aspect ratio of the video when scaling.
.video videos/evangeline.mp4 video/mp4 400 600
.video videos/mabel.ogg video/ogg 500 _
background:
The template uses the function "background" to set the background image for
a slide. The only argument is the file name of the image.
.background images/susan.jpg
caption:
The template uses the function "caption" to inject figure captions.
The text after ".caption" is embedded in a figcaption element after
processing styling and links as in standard text lines.
.caption _Gopher_ by [[http://www.reneefrench.com][Renée French]]
iframe:
The function "iframe" injects iframes (pages inside pages).
Its syntax is the same as that of image.
html:
The function html includes the contents of the specified file as
unescaped HTML. This is useful for including custom HTML elements
that cannot be created using only the slide format.
It is your responsibilty to make sure the included HTML is valid and safe.
.html file.html
*/
package present // import "golang.org/x/tools/present"
| cmars/tools | vendor/src/golang.org/x/tools/present/doc.go | GO | mit | 6,713 |
## How does Bootstrap's test suite work?
Bootstrap uses [QUnit](https://qunitjs.com/), a powerful, easy-to-use JavaScript unit test framework. Each plugin has a file dedicated to its tests in `unit/<plugin-name>.js`.
* `unit/` contains the unit test files for each Bootstrap plugin.
* `vendor/` contains third-party testing-related code (QUnit and jQuery).
* `visual/` contains "visual" tests which are run interactively in real browsers and require manual verification by humans.
To run the unit test suite via [Karma](http://karma-runner.github.io/), run `npm run js-test`.
To run the unit test suite via a real web browser, open `index.html` in the browser.
## How do I add a new unit test?
1. Locate and open the file dedicated to the plugin which you need to add tests to (`unit/<plugin-name>.js`).
2. Review the [QUnit API Documentation](https://api.qunitjs.com/) and use the existing tests as references for how to structure your new tests.
3. Write the necessary unit test(s) for the new or revised functionality.
4. Run `npm run js-test` to see the results of your newly-added test(s).
**Note:** Your new unit tests should fail before your changes are applied to the plugin, and should pass after your changes are applied to the plugin.
## What should a unit test look like?
* Each test should have a unique name clearly stating what unit is being tested.
* Each test should test only one unit per test, although one test can include several assertions. Create multiple tests for multiple units of functionality.
* Each test should begin with [`assert.expect`](https://api.qunitjs.com/assert/expect/) to ensure that the expected assertions are run.
* Each test should follow the project's [JavaScript Code Guidelines](https://github.com/twbs/bootstrap/blob/master/CONTRIBUTING.md#js)
### Example tests
```javascript
// Synchronous test
QUnit.test('should describe the unit being tested', function (assert) {
assert.expect(1)
var templateHTML = '<div class="alert alert-danger fade show">'
+ '<a class="close" href="#" data-dismiss="alert">×</a>'
+ '<p><strong>Template necessary for the test.</p>'
+ '</div>'
var $alert = $(templateHTML).appendTo('#qunit-fixture').bootstrapAlert()
$alert.find('.close').trigger('click')
// Make assertion
assert.strictEqual($alert.hasClass('show'), false, 'remove .show class on .close click')
})
// Asynchronous test
QUnit.test('should describe the unit being tested', function (assert) {
assert.expect(1)
var done = assert.async()
$('<div title="tooltip title"></div>')
.appendTo('#qunit-fixture')
.on('shown.bs.tooltip', function () {
assert.ok(true, '"shown" event was fired after calling "show"')
done()
})
.bootstrapTooltip('show')
})
```
| mattrobineau/dotnetsignals | src/Stories/wwwroot/lib/bootstrap/js/tests/README.md | Markdown | mit | 2,769 |
import * as RSVP from 'rsvp';
import { backburner, _rsvpErrorQueue } from '@ember/runloop';
import { getDispatchOverride } from '@ember/-internals/error-handling';
import { assert } from '@ember/debug';
RSVP.configure('async', (callback, promise) => {
backburner.schedule('actions', null, callback, promise);
});
RSVP.configure('after', cb => {
backburner.schedule(_rsvpErrorQueue, null, cb);
});
RSVP.on('error', onerrorDefault);
export function onerrorDefault(reason) {
let error = errorFor(reason);
if (error) {
let overrideDispatch = getDispatchOverride();
if (overrideDispatch) {
overrideDispatch(error);
} else {
throw error;
}
}
}
function errorFor(reason) {
if (!reason) return;
if (reason.errorThrown) {
return unwrapErrorThrown(reason);
}
if (reason.name === 'UnrecognizedURLError') {
assert(`The URL '${reason.message}' did not match any routes in your application`, false);
return;
}
if (reason.name === 'TransitionAborted') {
return;
}
return reason;
}
function unwrapErrorThrown(reason) {
let error = reason.errorThrown;
if (typeof error === 'string') {
error = new Error(error);
}
Object.defineProperty(error, '__reason_with_error_thrown__', {
value: reason,
enumerable: false,
});
return error;
}
export default RSVP;
| bekzod/ember.js | packages/@ember/-internals/runtime/lib/ext/rsvp.js | JavaScript | mit | 1,339 |
#include <stdio.h>
#include "Halide.h"
using namespace Halide;
// Override Halide's malloc and free
size_t custom_malloc_size = 0;
void *my_malloc(void *user_context, size_t x) {
custom_malloc_size = x;
void *orig = malloc(x+32);
void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
((void **)ptr)[-1] = orig;
return ptr;
}
void my_free(void *user_context, void *ptr) {
free(((void**)ptr)[-1]);
}
int main(int argc, char **argv) {
Var x, y;
{
Func f, g;
f(x, y) = x;
g(x, y) = f(x-1, y) + f(x, y-1);
f.store_root().compute_at(g, x);
g.set_custom_allocator(my_malloc, my_free);
Image<int> im = g.realize(1000, 1000);
// Should fold by a factor of two, but sliding window analysis makes it round up to 4.
if (custom_malloc_size == 0 || custom_malloc_size > 1002*4*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1002*4*sizeof(int)));
return -1;
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(2*x, 2*y) + g(2*x+1, 2*y+1);
// Each instance of f uses a non-overlapping 2x2 box of
// g. Should be able to fold storage of g down to a stack
// allocation.
g.compute_at(f, x).store_root();
f.set_custom_allocator(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size != 0) {
printf("There should not have been a heap allocation\n");
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = (2*x) * (2*y) + (2*x+1) * (2*y+1);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(x, 2*y) + g(x+3, 2*y+1);
// Each instance of f uses a non-overlapping 2-scanline slice
// of g in y, and is a stencil over x. Should be able to fold
// both x and y.
g.compute_at(f, x).store_root();
f.set_custom_allocator(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size != 0) {
printf("There should not have been a heap allocation\n");
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = x * (2*y) + (x+3) * (2*y+1);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(2*x, y) + g(2*x+1, y+3);
// Each instance of f uses a non-overlapping 2-scanline slice
// of g in x, and is a stencil over y. We can't fold in x due
// to the stencil in y. We need to keep around entire
// scanlines.
g.compute_at(f, x).store_root();
f.set_custom_allocator(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size == 0 || custom_malloc_size > 2*1002*4*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1002*4*sizeof(int)));
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = (2*x) * y + (2*x+1) * (y+3);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(x, y);
Var yo, yi;
f.bound(y, 0, (f.output_buffer().height()/8)*8).split(y, yo, yi, 8);
g.compute_at(f, yo).store_root();
// The split logic shouldn't interfere with the ability to
// fold f down to an 8-scanline allocation, but it's only
// correct to fold if we know the output height is a multiple
// of the split factor.
f.set_custom_allocator(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size == 0 || custom_malloc_size > 1000*8*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1000*8*sizeof(int)));
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = x*y;
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
printf("Success!\n");
return 0;
}
| dan-tull/Halide | test/correctness/storage_folding.cpp | C++ | mit | 5,268 |
//-----------------------------------------------------------------------
// <copyright file="ProjectItemInstance_Tests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Tests for ProjectItemInstance public members</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.UnitTests.OM.Instance
{
/// <summary>
/// Tests for ProjectItemInstance public members
/// </summary>
[TestClass]
public class ProjectItemInstance_Tests
{
/// <summary>
/// The number of built-in metadata for items.
/// </summary>
public const int BuiltInMetadataCount = 15;
/// <summary>
/// Basic ProjectItemInstance without metadata
/// </summary>
[TestMethod]
public void AccessorsWithoutMetadata()
{
ProjectItemInstance item = GetItemInstance();
Assert.AreEqual("i", item.ItemType);
Assert.AreEqual("i1", item.EvaluatedInclude);
Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext());
}
/// <summary>
/// Basic ProjectItemInstance with metadata
/// </summary>
[TestMethod]
public void AccessorsWithMetadata()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m1", "v0");
item.SetMetadata("m1", "v1");
item.SetMetadata("m2", "v2");
Assert.AreEqual("m1", item.GetMetadata("m1").Name);
Assert.AreEqual("m2", item.GetMetadata("m2").Name);
Assert.AreEqual("v1", item.GetMetadataValue("m1"));
Assert.AreEqual("v2", item.GetMetadataValue("m2"));
}
/// <summary>
/// Get metadata not present
/// </summary>
[TestMethod]
public void GetMissingMetadata()
{
ProjectItemInstance item = GetItemInstance();
Assert.AreEqual(null, item.GetMetadata("X"));
Assert.AreEqual(String.Empty, item.GetMetadataValue("X"));
}
/// <summary>
/// Set include
/// </summary>
[TestMethod]
public void SetInclude()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = "i1b";
Assert.AreEqual("i1b", item.EvaluatedInclude);
}
/// <summary>
/// Set include to empty string
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SetInvalidEmptyInclude()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = String.Empty;
}
/// <summary>
/// Set include to invalid null value
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SetInvalidNullInclude()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = null;
}
/// <summary>
/// Create an item with a metadatum that has a null value
/// </summary>
[TestMethod]
public void CreateItemWithNullMetadataValue()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
IDictionary<string, string> metadata = new Dictionary<string, string>();
metadata.Add("m", null);
ProjectItemInstance item = projectInstance.AddItem("i", "i1", metadata);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value
/// </summary>
[TestMethod]
public void SetMetadata()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", "m1");
Assert.AreEqual("m1", item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value to empty string
/// </summary>
[TestMethod]
public void SetMetadataEmptyString()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", String.Empty);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value to null value -- this is allowed, but
/// internally converted to the empty string.
/// </summary>
[TestMethod]
public void SetNullMetadataValue()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", null);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata with invalid empty name
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SetInvalidNullMetadataName()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata(null, "m1");
}
/// <summary>
/// Set metadata with invalid empty name
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SetInvalidEmptyMetadataName()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata(String.Empty, "m1");
}
/// <summary>
/// Cast to ITaskItem
/// </summary>
[TestMethod]
public void CastToITaskItem()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", "m1");
ITaskItem taskItem = (ITaskItem)item;
Assert.AreEqual(item.EvaluatedInclude, taskItem.ItemSpec);
Assert.AreEqual(1 + BuiltInMetadataCount, taskItem.MetadataCount);
Assert.AreEqual(1 + BuiltInMetadataCount, taskItem.MetadataNames.Count);
Assert.AreEqual("m1", taskItem.GetMetadata("m"));
taskItem.SetMetadata("m", "m2");
Assert.AreEqual("m2", item.GetMetadataValue("m"));
}
/// <summary>
/// Creates a ProjectItemInstance and casts it to ITaskItem2; makes sure that all escaped information is
/// maintained correctly. Also creates a new Microsoft.Build.Utilities.TaskItem from the ProjectItemInstance
/// and verifies that none of the information is lost.
/// </summary>
[TestMethod]
public void ITaskItem2Operations()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
ProjectItemInstance item = projectInstance.AddItem("EscapedItem", "esca%20ped%3bitem");
item.SetMetadata("m", "m1");
item.SetMetadata("m;", "m%3b1");
ITaskItem2 taskItem = (ITaskItem2)item;
Assert.AreEqual(taskItem.EvaluatedIncludeEscaped, "esca%20ped%3bitem");
Assert.AreEqual(taskItem.ItemSpec, "esca ped;item");
Assert.AreEqual(taskItem.GetMetadata("m;"), "m;1");
Assert.AreEqual(taskItem.GetMetadataValueEscaped("m;"), "m%3b1");
Assert.AreEqual(taskItem.GetMetadataValueEscaped("m"), "m1");
Assert.AreEqual(taskItem.EvaluatedIncludeEscaped, "esca%20ped%3bitem");
Assert.AreEqual(taskItem.ItemSpec, "esca ped;item");
ITaskItem2 taskItem2 = new Microsoft.Build.Utilities.TaskItem(taskItem);
taskItem2.SetMetadataValueLiteral("m;", "m;2");
Assert.AreEqual(taskItem2.GetMetadataValueEscaped("m;"), "m%3b2");
Assert.AreEqual(taskItem2.GetMetadata("m;"), "m;2");
IDictionary<string, string> taskItem2Metadata = (IDictionary<string, string>)taskItem2.CloneCustomMetadata();
Assert.AreEqual(3, taskItem2Metadata.Count);
foreach (KeyValuePair<string, string> pair in taskItem2Metadata)
{
if (pair.Key.Equals("m"))
{
Assert.AreEqual("m1", pair.Value);
}
if (pair.Key.Equals("m;"))
{
Assert.AreEqual("m;2", pair.Value);
}
if (pair.Key.Equals("OriginalItemSpec"))
{
Assert.AreEqual("esca ped;item", pair.Value);
}
}
IDictionary<string, string> taskItem2MetadataEscaped = (IDictionary<string, string>)taskItem2.CloneCustomMetadataEscaped();
Assert.AreEqual(3, taskItem2MetadataEscaped.Count);
foreach (KeyValuePair<string, string> pair in taskItem2MetadataEscaped)
{
if (pair.Key.Equals("m"))
{
Assert.AreEqual("m1", pair.Value);
}
if (pair.Key.Equals("m;"))
{
Assert.AreEqual("m%3b2", pair.Value);
}
if (pair.Key.Equals("OriginalItemSpec"))
{
Assert.AreEqual("esca%20ped%3bitem", pair.Value);
}
}
}
/// <summary>
/// Cast to ITaskItem
/// </summary>
[TestMethod]
public void CastToITaskItemNoMetadata()
{
ProjectItemInstance item = GetItemInstance();
ITaskItem taskItem = (ITaskItem)item;
Assert.AreEqual(0 + BuiltInMetadataCount, taskItem.MetadataCount);
Assert.AreEqual(0 + BuiltInMetadataCount, taskItem.MetadataNames.Count);
Assert.AreEqual(String.Empty, taskItem.GetMetadata("m"));
}
/*
* We must repeat all the evaluation-related tests here,
* to exercise the path that evaluates directly to instance objects.
* Although the Evaluator class is shared, its interactions with the two
* different item classes could be different, and shouldn't be.
*/
/// <summary>
/// No metadata, simple case
/// </summary>
[TestMethod]
public void NoMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'/>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i", item.ItemType);
Assert.AreEqual("i1", item.EvaluatedInclude);
Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext());
Assert.AreEqual(0 + BuiltInMetadataCount, Helpers.MakeList(item.MetadataNames).Count);
Assert.AreEqual(0 + BuiltInMetadataCount, item.MetadataCount);
}
/// <summary>
/// Read off metadata
/// </summary>
[TestMethod]
public void ReadMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m1>v1</m1>
<m2>v2</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
var itemMetadata = Helpers.MakeList(item.Metadata);
Assert.AreEqual(2, itemMetadata.Count);
Assert.AreEqual("m1", itemMetadata[0].Name);
Assert.AreEqual("m2", itemMetadata[1].Name);
Assert.AreEqual("v1", itemMetadata[0].EvaluatedValue);
Assert.AreEqual("v2", itemMetadata[1].EvaluatedValue);
Assert.AreEqual(itemMetadata[0], item.GetMetadata("m1"));
Assert.AreEqual(itemMetadata[1], item.GetMetadata("m2"));
}
/// <summary>
/// Create a new Microsoft.Build.Utilities.TaskItem from the ProjectItemInstance where the ProjectItemInstance
/// has item definition metadata on it.
///
/// Verify the Utilities task item gets the expanded metadata from the ItemDefintionGroup.
/// </summary>
[TestMethod]
public void InstanceItemToUtilItemIDG()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m0>;x86;</m0>
<m1>%(FileName).extension</m1>
<m2>;%(FileName).extension;</m2>
<m3>v1</m3>
<m4>%3bx86%3b</m4>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='foo.proj'/>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Microsoft.Build.Utilities.TaskItem taskItem = new Microsoft.Build.Utilities.TaskItem(item);
Assert.AreEqual(";x86;", taskItem.GetMetadata("m0"));
Assert.AreEqual("foo.extension", taskItem.GetMetadata("m1"));
Assert.AreEqual(";foo.extension;", taskItem.GetMetadata("m2"));
Assert.AreEqual("v1", taskItem.GetMetadata("m3"));
Assert.AreEqual(";x86;", taskItem.GetMetadata("m4"));
}
/// <summary>
/// Get metadata values inherited from item definitions
/// </summary>
[TestMethod]
public void GetMetadataValuesFromDefinition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m0>v0</m0>
<m1>v1</m1>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='i1'>
<m1>v1b</m1>
<m2>v2</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("v0", item.GetMetadataValue("m0"));
Assert.AreEqual("v1b", item.GetMetadataValue("m1"));
Assert.AreEqual("v2", item.GetMetadataValue("m2"));
Assert.AreEqual(3, Helpers.MakeList(item.Metadata).Count);
Assert.AreEqual(3 + BuiltInMetadataCount, Helpers.MakeList(item.MetadataNames).Count);
Assert.AreEqual(3 + BuiltInMetadataCount, item.MetadataCount);
}
/// <summary>
/// Exclude against an include with item vectors in it
/// </summary>
[TestMethod]
public void ExcludeWithIncludeVector()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='a;b;c'>
</i>
</ItemGroup>
<ItemGroup>
<i Include='x;y;z;@(i);u;v;w' Exclude='b;y;v'>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
// Should contain a, b, c, x, z, a, c, u, w
Assert.AreEqual(9, items.Count);
AssertEvaluatedIncludes(items, new string[] { "a", "b", "c", "x", "z", "a", "c", "u", "w" });
}
/// <summary>
/// Exclude with item vectors against an include with item vectors in it
/// </summary>
[TestMethod]
public void ExcludeVectorWithIncludeVector()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='a;b;c'>
</i>
<j Include='b;y;v' />
</ItemGroup>
<ItemGroup>
<i Include='x;y;z;@(i);u;v;w' Exclude='x;@(j);w'>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
// Should contain a, b, c, z, a, c, u
Assert.AreEqual(7, items.Count);
AssertEvaluatedIncludes(items, new string[] { "a", "b", "c", "z", "a", "c", "u" });
}
/// <summary>
/// Metadata on items can refer to metadata above
/// </summary>
[TestMethod]
public void MetadataReferringToMetadataAbove()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m1>v1</m1>
<m2>%(m1);v2;%(m0)</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
var itemMetadata = Helpers.MakeList(item.Metadata);
Assert.AreEqual(2, itemMetadata.Count);
Assert.AreEqual("v1;v2;", item.GetMetadataValue("m2"));
}
/// <summary>
/// Built-in metadata should work, too.
/// NOTE: To work properly, this should batch. This is a temporary "patch" to make it work for now.
/// It will only give correct results if there is exactly one item in the Include. Otherwise Batching would be needed.
/// </summary>
[TestMethod]
public void BuiltInMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i1", item.GetMetadataValue("m"));
}
/// <summary>
/// Qualified built in metadata should work
/// </summary>
[TestMethod]
public void BuiltInQualifiedMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(i.Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i1", item.GetMetadataValue("m"));
}
/// <summary>
/// Mis-qualified built in metadata should not work
/// </summary>
[TestMethod]
public void BuiltInMisqualifiedMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(j.Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Metadata condition should work correctly with built-in metadata
/// </summary>
[TestMethod]
public void BuiltInMetadataInMetadataCondition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m Condition=""'%(Identity)'=='i1'"">m1</m>
<n Condition=""'%(Identity)'=='i2'"">n1</n>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("m1", item.GetMetadataValue("m"));
Assert.AreEqual(String.Empty, item.GetMetadataValue("n"));
}
/// <summary>
/// Metadata on item condition not allowed (currently)
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void BuiltInMetadataInItemCondition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1' Condition=""'%(Identity)'=='i1'/>
</ItemGroup>
</Project>
";
GetOneItem(content);
}
/// <summary>
/// Two items should each get their own values for built-in metadata
/// </summary>
[TestMethod]
public void BuiltInMetadataTwoItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1.cpp;c:\bar\i2.cpp'>
<m>%(Filename).obj</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i1.obj", items[0].GetMetadataValue("m"));
Assert.AreEqual(@"i2.obj", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Items from another list, but with different metadata
/// </summary>
[TestMethod]
public void DifferentMetadataItemsFromOtherList()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'>
<m>m1</m>
</h>
<h Include='h1'/>
<i Include='@(h)'>
<m>%(m)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"m1", items[0].GetMetadataValue("m"));
Assert.AreEqual(String.Empty, items[1].GetMetadataValue("m"));
}
/// <summary>
/// Items from another list, but with different metadata
/// </summary>
[TestMethod]
public void DifferentBuiltInMetadataItemsFromOtherList()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0.x'/>
<h Include='h1.y'/>
<i Include='@(h)'>
<m>%(extension)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@".x", items[0].GetMetadataValue("m"));
Assert.AreEqual(@".y", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Two items coming from a transform
/// </summary>
[TestMethod]
public void BuiltInMetadataTransformInInclude()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include=""@(h->'%(Identity).baz')"">
<m>%(Filename)%(Extension).obj</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"h0.baz.obj", items[0].GetMetadataValue("m"));
Assert.AreEqual(@"h1.baz.obj", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Transform in the metadata value; no bare metadata involved
/// </summary>
[TestMethod]
public void BuiltInMetadataTransformInMetadataValue()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include='i0'/>
<i Include='i1;i2'>
<m>@(i);@(h->'%(Filename)')</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i0;h0;h1", items[1].GetMetadataValue("m"));
Assert.AreEqual(@"i0;h0;h1", items[2].GetMetadataValue("m"));
}
/// <summary>
/// Transform in the metadata value; bare metadata involved
/// </summary>
[TestMethod]
public void BuiltInMetadataTransformInMetadataValueBareMetadataPresent()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include='i0.x'/>
<i Include='i1.y;i2'>
<m>@(i);@(h->'%(Filename)');%(Extension)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i0.x;h0;h1;.y", items[1].GetMetadataValue("m"));
Assert.AreEqual(@"i0.x;h0;h1;", items[2].GetMetadataValue("m"));
}
/// <summary>
/// Metadata on items can refer to item lists
/// </summary>
[TestMethod]
public void MetadataValueReferringToItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<i Include='i0'/>
<i Include='i1'>
<m1>@(h);@(i)</m1>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("h0;i0", items[1].GetMetadataValue("m1"));
}
/// <summary>
/// Metadata on items' conditions can refer to item lists
/// </summary>
[TestMethod]
public void MetadataConditionReferringToItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<i Include='i0'/>
<i Include='i1'>
<m1 Condition=""'@(h)'=='h0' and '@(i)'=='i0'"">v1</m1>
<m2 Condition=""'@(h)'!='h0' or '@(i)'!='i0'"">v2</m2>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("v1", items[1].GetMetadataValue("m1"));
Assert.AreEqual(String.Empty, items[1].GetMetadataValue("m2"));
}
/// <summary>
/// Metadata on items' conditions can refer to other metadata
/// </summary>
[TestMethod]
public void MetadataConditionReferringToMetadataOnSameItem()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m0>0</m0>
<m1 Condition=""'%(m0)'=='0'"">1</m1>
<m2 Condition=""'%(m0)'=='3'"">2</m2>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("0", items[0].GetMetadataValue("m0"));
Assert.AreEqual("1", items[0].GetMetadataValue("m1"));
Assert.AreEqual(String.Empty, items[0].GetMetadataValue("m2"));
}
/// <summary>
/// Gets the first item of type 'i'
/// </summary>
private static ProjectItemInstance GetOneItem(string content)
{
return GetItems(content)[0];
}
/// <summary>
/// Get all items of type 'i'
/// </summary>
private static IList<ProjectItemInstance> GetItems(string content)
{
ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectInstance project = new ProjectInstance(xml);
return Helpers.MakeList(project.GetItems("i"));
}
/// <summary>
/// Asserts that the list of items has the specified includes.
/// </summary>
private static void AssertEvaluatedIncludes(IList<ProjectItemInstance> items, string[] includes)
{
for (int i = 0; i < includes.Length; i++)
{
Assert.AreEqual(includes[i], items[i].EvaluatedInclude);
}
}
/// <summary>
/// Get a single item instance
/// </summary>
private static ProjectItemInstance GetItemInstance()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
ProjectItemInstance item = projectInstance.AddItem("i", "i1");
return item;
}
}
}
| MetSystem/msbuild | src/XMakeBuildEngine/UnitTestsPublicOM/Instance/ProjectItemInstance_Tests.cs | C# | mit | 32,125 |
/**
@module ember
@submodule ember-runtime
*/
import Ember from 'ember-metal/core';
import { Mixin } from 'ember-metal/mixin';
import { get } from 'ember-metal/property_get';
import { deprecateProperty } from 'ember-metal/deprecate_property';
/**
`Ember.ActionHandler` is available on some familiar classes including
`Ember.Route`, `Ember.View`, `Ember.Component`, and `Ember.Controller`.
(Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`,
and `Ember.Route` and available to the above classes through
inheritance.)
@class ActionHandler
@namespace Ember
@private
*/
var ActionHandler = Mixin.create({
mergedProperties: ['actions'],
/**
The collection of functions, keyed by name, available on this
`ActionHandler` as action targets.
These functions will be invoked when a matching `{{action}}` is triggered
from within a template and the application's current route is this route.
Actions can also be invoked from other parts of your application
via `ActionHandler#send`.
The `actions` hash will inherit action handlers from
the `actions` hash defined on extended parent classes
or mixins rather than just replace the entire hash, e.g.:
```js
App.CanDisplayBanner = Ember.Mixin.create({
actions: {
displayBanner: function(msg) {
// ...
}
}
});
App.WelcomeRoute = Ember.Route.extend(App.CanDisplayBanner, {
actions: {
playMusic: function() {
// ...
}
}
});
// `WelcomeRoute`, when active, will be able to respond
// to both actions, since the actions hash is merged rather
// then replaced when extending mixins / parent classes.
this.send('displayBanner');
this.send('playMusic');
```
Within a Controller, Route, View or Component's action handler,
the value of the `this` context is the Controller, Route, View or
Component object:
```js
App.SongRoute = Ember.Route.extend({
actions: {
myAction: function() {
this.controllerFor("song");
this.transitionTo("other.route");
...
}
}
});
```
It is also possible to call `this._super.apply(this, arguments)` from within an
action handler if it overrides a handler defined on a parent
class or mixin:
Take for example the following routes:
```js
App.DebugRoute = Ember.Mixin.create({
actions: {
debugRouteInformation: function() {
console.debug("trololo");
}
}
});
App.AnnoyingDebugRoute = Ember.Route.extend(App.DebugRoute, {
actions: {
debugRouteInformation: function() {
// also call the debugRouteInformation of mixed in App.DebugRoute
this._super.apply(this, arguments);
// show additional annoyance
window.alert(...);
}
}
});
```
## Bubbling
By default, an action will stop bubbling once a handler defined
on the `actions` hash handles it. To continue bubbling the action,
you must return `true` from the handler:
```js
App.Router.map(function() {
this.route("album", function() {
this.route("song");
});
});
App.AlbumRoute = Ember.Route.extend({
actions: {
startPlaying: function() {
}
}
});
App.AlbumSongRoute = Ember.Route.extend({
actions: {
startPlaying: function() {
// ...
if (actionShouldAlsoBeTriggeredOnParentRoute) {
return true;
}
}
}
});
```
@property actions
@type Object
@default null
@public
*/
/**
Triggers a named action on the `ActionHandler`. Any parameters
supplied after the `actionName` string will be passed as arguments
to the action target function.
If the `ActionHandler` has its `target` property set, actions may
bubble to the `target`. Bubbling happens when an `actionName` can
not be found in the `ActionHandler`'s `actions` hash or if the
action target function returns `true`.
Example
```js
App.WelcomeRoute = Ember.Route.extend({
actions: {
playTheme: function() {
this.send('playMusic', 'theme.mp3');
},
playMusic: function(track) {
// ...
}
}
});
```
@method send
@param {String} actionName The action to trigger
@param {*} context a context to send with the action
@public
*/
send(actionName, ...args) {
var target;
if (this.actions && this.actions[actionName]) {
var shouldBubble = this.actions[actionName].apply(this, args) === true;
if (!shouldBubble) { return; }
}
if (target = get(this, 'target')) {
Ember.assert('The `target` for ' + this + ' (' + target +
') does not have a `send` method', typeof target.send === 'function');
target.send(...arguments);
}
}
});
export default ActionHandler;
export function deprecateUnderscoreActions(factory) {
deprecateProperty(factory.prototype, '_actions', 'actions', {
id: 'ember-runtime.action-handler-_actions', until: '3.0.0'
});
}
| artfuldodger/ember.js | packages/ember-runtime/lib/mixins/action_handler.js | JavaScript | mit | 5,224 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Diagnostics;
using System.Resources;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.Shared;
namespace Microsoft.Build.Tasks
{
/// <summary>
/// Returns paths to the frameworks SDK.
/// </summary>
public class GetFrameworkSdkPath : TaskExtension
{
#region Properties
private static string s_path;
private static string s_version20Path;
private static string s_version35Path;
private static string s_version40Path;
private static string s_version45Path;
private static string s_version451Path;
private static string s_version46Path;
/// <summary>
/// The path to the latest .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string Path
{
get
{
if (s_path == null)
{
s_path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.VersionLatest, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.VersionLatest, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.VersionLatest, VisualStudioVersion.VersionLatest)
);
s_path = String.Empty;
}
else
{
s_path = FileUtilities.EnsureTrailingSlash(s_path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_path);
}
}
return s_path;
}
set
{
// Does nothing; for backwards compatibility only
}
}
/// <summary>
/// The path to the v2.0 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion20Path
{
get
{
if (s_version20Path == null)
{
s_version20Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version20);
if (String.IsNullOrEmpty(s_version20Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version20),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version20)
);
s_version20Path = String.Empty;
}
else
{
s_version20Path = FileUtilities.EnsureTrailingSlash(s_version20Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version20Path);
}
}
return s_version20Path;
}
}
/// <summary>
/// The path to the v3.5 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion35Path
{
get
{
if (s_version35Path == null)
{
s_version35Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version35Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest)
);
s_version35Path = String.Empty;
}
else
{
s_version35Path = FileUtilities.EnsureTrailingSlash(s_version35Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version35Path);
}
}
return s_version35Path;
}
}
/// <summary>
/// The path to the v4.0 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion40Path
{
get
{
if (s_version40Path == null)
{
s_version40Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version40Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest)
);
s_version40Path = String.Empty;
}
else
{
s_version40Path = FileUtilities.EnsureTrailingSlash(s_version40Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version40Path);
}
}
return s_version40Path;
}
}
/// <summary>
/// The path to the v4.5 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion45Path
{
get
{
if (s_version45Path == null)
{
s_version45Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version45Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest)
);
s_version45Path = String.Empty;
}
else
{
s_version45Path = FileUtilities.EnsureTrailingSlash(s_version45Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version45Path);
}
}
return s_version45Path;
}
}
/// <summary>
/// The path to the v4.5.1 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion451Path
{
get
{
if (s_version451Path == null)
{
s_version451Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version451Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest)
);
s_version451Path = String.Empty;
}
else
{
s_version451Path = FileUtilities.EnsureTrailingSlash(s_version451Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version451Path);
}
}
return s_version451Path;
}
}
/// <summary>
/// The path to the v4.6 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
/// </summary>
[Output]
public string FrameworkSdkVersion46Path
{
get
{
if (s_version46Path == null)
{
s_version46Path = ToolLocationHelper.GetPathToDotNetFrameworkSdk(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version46Path))
{
Log.LogMessageFromResources(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest),
ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest)
);
s_version46Path = String.Empty;
}
else
{
s_version46Path = FileUtilities.EnsureTrailingSlash(s_version46Path);
Log.LogMessageFromResources(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version46Path);
}
}
return s_version46Path;
}
}
#endregion
#region ITask Members
/// <summary>
/// Get the SDK.
/// </summary>
/// <returns>true</returns>
public override bool Execute()
{
//Does Nothing: getters do all the work
return true;
}
#endregion
}
}
| MetSystem/msbuild | src/XMakeTasks/GetFrameworkSDKPath.cs | C# | mit | 11,946 |
"use strict";
// copied from http://www.broofa.com/Tools/Math.uuid.js
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
exports.uuid = function () {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i==8 || i==13 || i==18 || i==23) {
uuid[i] = '-';
}
else if (i==14) {
uuid[i] = '4';
}
else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
};
exports.in_array = function (item, array) {
return (array.indexOf(item) != -1);
};
exports.sort_keys = function (obj) {
return Object.keys(obj).sort();
};
exports.uniq = function (arr) {
var out = [];
var o = 0;
for (var i=0,l=arr.length; i < l; i++) {
if (out.length === 0) {
out.push(arr[i]);
}
else if (out[o] != arr[i]) {
out.push(arr[i]);
o++;
}
}
return out;
}
exports.ISODate = function (d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _monnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function _pad (num, n, p) {
var s = '' + num;
p = p || '0';
while (s.length < n) s = p + s;
return s;
}
exports.pad = _pad;
exports.date_to_str = function (d) {
return _daynames[d.getDay()] + ', ' + _pad(d.getDate(),2) + ' ' +
_monnames[d.getMonth()] + ' ' + d.getFullYear() + ' ' +
_pad(d.getHours(),2) + ':' + _pad(d.getMinutes(),2) + ':' + _pad(d.getSeconds(),2) +
' ' + d.toString().match(/\sGMT([+-]\d+)/)[1];
}
exports.decode_qp = function (line) {
line = line.replace(/\r\n/g,"\n").replace(/[ \t]+\r?\n/g,"\n");
if (! /=/.test(line)) {
// this may be a pointless optimisation...
return new Buffer(line);
}
line = line.replace(/=\n/mg, '');
var buf = new Buffer(line.length);
var pos = 0;
for (var i=0,l=line.length; i < l; i++) {
if (line[i] === '=' &&
/=[0-9a-fA-F]{2}/.test(line[i] + line[i+1] + line[i+2])) {
i++;
buf[pos] = parseInt(line[i] + line[i+1], 16);
i++;
}
else {
buf[pos] = line.charCodeAt(i);
}
pos++;
}
return buf.slice(0, pos);
}
function _char_to_qp (ch) {
return "=" + _pad(ch.charCodeAt(0).toString(16).toUpperCase(), 2);
}
// Shameless attempt to copy from Perl's MIME::QuotedPrint::Perl code.
exports.encode_qp = function (str) {
str = str.replace(/([^\ \t\n!"#\$%&'()*+,\-.\/0-9:;<>?\@A-Z\[\\\]^_`a-z{|}~])/g, function (orig, p1) {
return _char_to_qp(p1);
}).replace(/([ \t]+)$/gm, function (orig, p1) {
return p1.split('').map(_char_to_qp).join('');
});
// Now shorten lines to 76 chars, but don't break =XX encodes.
// Method: iterate over to char 73.
// If char 74, 75 or 76 is = we need to break before the =.
// Otherwise break at 76.
var cur_length = 0;
var out = '';
for (var i=0; i<str.length; i++) {
if (str[i] === '\n') {
out += '\n';
cur_length = 0;
continue;
}
cur_length++;
if (cur_length <= 73) {
out += str[i];
}
else if (cur_length > 73 && cur_length < 76) {
if (str[i] === '=') {
out += '=\n=';
cur_length = 1;
}
else {
out += str[i];
}
}
else {
// Otherwise got to char 76
// Don't insert '=\n' if end of string or next char is already \n:
if ((i === (str.length - 1)) || (str[i+1] === '\n')) {
out += str[i];
}
else {
out += '=\n' + str[i];
cur_length = 1;
}
}
}
return out;
}
var versions = process.version.split('.'),
version = Number(versions[0].substring(1)),
subversion = Number(versions[1]);
exports.existsSync = require((version > 0 || subversion >= 8) ? 'fs' : 'path').existsSync;
exports.indexOfLF = function (buf, maxlength) {
for (var i=0; i<buf.length; i++) {
if (maxlength && (i === maxlength)) break;
if (buf[i] === 0x0a) return i;
}
return -1;
}
| lucciano/Haraka | utils.js | JavaScript | mit | 4,778 |
require 'spec_helper'
require 'puppet/transaction'
require 'puppet_spec/compiler'
require 'matchers/relationship_graph_matchers'
require 'matchers/include_in_order'
require 'matchers/resource'
describe Puppet::Transaction::AdditionalResourceGenerator do
include PuppetSpec::Compiler
include PuppetSpec::Files
include RelationshipGraphMatchers
include Matchers::Resource
let(:prioritizer) { Puppet::Graph::SequentialPrioritizer.new }
def find_vertex(graph, type, title)
graph.vertices.find {|v| v.type == type and v.title == title}
end
Puppet::Type.newtype(:generator) do
include PuppetSpec::Compiler
newparam(:name) do
isnamevar
end
newparam(:kind) do
defaultto :eval_generate
newvalues(:eval_generate, :generate)
end
newparam(:code)
def respond_to?(method_name)
method_name == self[:kind] || super
end
def eval_generate
eval_code
end
def generate
eval_code
end
def eval_code
if self[:code]
compile_to_ral(self[:code]).resources.select { |r| r.ref =~ /Notify/ }
else
[]
end
end
end
context "when applying eval_generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
eval_generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should add a sentinel whit for the resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
find_vertex(graph, :whit, "completed_thing").must be_a(Puppet::Type.type(:whit))
end
it "should replace dependencies on the resource with dependencies on the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
notify { last: require => Generator['thing'] }
MANIFEST
expect(graph).to enforce_order_with_edge(
'Whit[completed_thing]', 'Notify[last]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[hello]')
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[goodbye]')
end
it "should add an edge from each generated resource to the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Notify[hello]', 'Whit[completed_thing]')
expect(graph).to enforce_order_with_edge(
'Notify[goodbye]', 'Whit[completed_thing]')
end
it "should add an edge from the resource to the sentinel" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Whit[completed_thing]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
code => 'notify { hello: }'
}
}
include container
MANIFEST
eval_generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to contain_resources_equally('Generator[thing]', 'Notify[hello]')
end
it "should return false if an error occurred when generating resources" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'fail("not a good generation")'
}
MANIFEST
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph_for(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
end
it "should return true if resources were generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph_for(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(true)
end
it "should not add a sentinel if no resources are generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing: }
MANIFEST
relationship_graph = relationship_graph_for(catalog)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
expect(find_vertex(relationship_graph, :whit, "completed_thing")).to be_nil
end
it "orders generated resources with the generator" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = relationships_after_eval_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
def relationships_after_eval_generating(manifest, resource_to_generate)
catalog = compile_to_ral(manifest)
relationship_graph = relationship_graph_for(catalog)
eval_generate_resources_in(catalog, relationship_graph, resource_to_generate)
relationship_graph
end
def eval_generate_resources_in(catalog, relationship_graph, resource_to_generate)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.eval_generate(catalog.resource(resource_to_generate))
end
end
context "when applying generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
MANIFEST
generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
}
include container
MANIFEST
generate_resources_in(catalog, relationship_graph_for(catalog), 'Generator[thing]')
expect(catalog).to contain_resources_equally('Generator[thing]', 'Notify[hello]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[hello]')
expect(graph).to enforce_order_with_edge(
'Generator[thing]', 'Notify[goodbye]')
end
it "orders generated resources with the generator" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
kind => generate,
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = relationships_after_generating(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(order_resources_traversed_in(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
def relationships_after_generating(manifest, resource_to_generate)
catalog = compile_to_ral(manifest)
relationship_graph = relationship_graph_for(catalog)
generate_resources_in(catalog, relationship_graph, resource_to_generate)
relationship_graph
end
def generate_resources_in(catalog, relationship_graph, resource_to_generate)
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, relationship_graph, prioritizer)
generator.generate_additional_resources(catalog.resource(resource_to_generate))
end
end
def relationship_graph_for(catalog)
relationship_graph = Puppet::Graph::RelationshipGraph.new(prioritizer)
relationship_graph.populate_from(catalog)
relationship_graph
end
def order_resources_traversed_in(relationships)
order_seen = []
relationships.traverse { |resource| order_seen << resource.ref }
order_seen
end
RSpec::Matchers.define :contain_resources_equally do |*resource_refs|
match do |catalog|
@containers = resource_refs.collect do |resource_ref|
catalog.container_of(catalog.resource(resource_ref)).ref
end
@containers.all? { |resource_ref| resource_ref == @containers[0] }
end
def failure_message_for_should
"expected #{@expected.join(', ')} to all be contained in the same resource but the containment was #{@expected.zip(@containers).collect { |(res, container)| res + ' => ' + container }.join(', ')}"
end
end
end
| thejonanshow/my-boxen | vendor/bundle/ruby/2.3.0/gems/puppet-3.8.7/spec/unit/transaction/additional_resource_generator_spec.rb | Ruby | mit | 13,674 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>0.9.6: type_vec3.hpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logo.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">0.9.6
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.8 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_885cc87fac2d91e269af0a5a959fa5f6.html">E:</a></li><li class="navelem"><a class="el" href="dir_153b03dd71a7bff437c38ec53cb2e014.html">Source</a></li><li class="navelem"><a class="el" href="dir_0c6652232a835be54bedd6cfd7502504.html">G-Truc</a></li><li class="navelem"><a class="el" href="dir_e2c7faa62a52820b5be8795affd6e495.html">glm</a></li><li class="navelem"><a class="el" href="dir_5cf96241cdcf6779b80e104875f9716f.html">glm</a></li><li class="navelem"><a class="el" href="dir_9b22c367036d391e575f56d067c9855b.html">detail</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">type_vec3.hpp</div> </div>
</div><!--header-->
<div class="contents">
<a href="a00134.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> </div>
<div class="line"><a name="l00033"></a><span class="lineno"> 33</span> <span class="preprocessor">#pragma once</span></div>
<div class="line"><a name="l00034"></a><span class="lineno"> 34</span> </div>
<div class="line"><a name="l00035"></a><span class="lineno"> 35</span> <span class="comment">//#include "../fwd.hpp"</span></div>
<div class="line"><a name="l00036"></a><span class="lineno"> 36</span> <span class="preprocessor">#include "<a class="code" href="a00131.html">type_vec.hpp</a>"</span></div>
<div class="line"><a name="l00037"></a><span class="lineno"> 37</span> <span class="preprocessor">#ifdef GLM_SWIZZLE</span></div>
<div class="line"><a name="l00038"></a><span class="lineno"> 38</span> <span class="preprocessor"># if GLM_HAS_ANONYMOUS_UNION</span></div>
<div class="line"><a name="l00039"></a><span class="lineno"> 39</span> <span class="preprocessor"># include "<a class="code" href="a00004.html">_swizzle.hpp</a>"</span></div>
<div class="line"><a name="l00040"></a><span class="lineno"> 40</span> <span class="preprocessor"># else</span></div>
<div class="line"><a name="l00041"></a><span class="lineno"> 41</span> <span class="preprocessor"># include "<a class="code" href="a00005.html">_swizzle_func.hpp</a>"</span></div>
<div class="line"><a name="l00042"></a><span class="lineno"> 42</span> <span class="preprocessor"># endif</span></div>
<div class="line"><a name="l00043"></a><span class="lineno"> 43</span> <span class="preprocessor">#endif //GLM_SWIZZLE</span></div>
<div class="line"><a name="l00044"></a><span class="lineno"> 44</span> <span class="preprocessor">#include <cstddef></span></div>
<div class="line"><a name="l00045"></a><span class="lineno"> 45</span> </div>
<div class="line"><a name="l00046"></a><span class="lineno"> 46</span> <span class="keyword">namespace </span><a class="code" href="a00145.html">glm</a></div>
<div class="line"><a name="l00047"></a><span class="lineno"> 47</span> {</div>
<div class="line"><a name="l00048"></a><span class="lineno"> 48</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P = defaultp></div>
<div class="line"><a name="l00049"></a><span class="lineno"> 49</span>  <span class="keyword">struct </span>tvec3</div>
<div class="line"><a name="l00050"></a><span class="lineno"> 50</span>  { </div>
<div class="line"><a name="l00052"></a><span class="lineno"> 52</span>  <span class="comment">// Implementation detail</span></div>
<div class="line"><a name="l00053"></a><span class="lineno"> 53</span> </div>
<div class="line"><a name="l00054"></a><span class="lineno"> 54</span>  <span class="keyword">typedef</span> tvec3<T, P> type;</div>
<div class="line"><a name="l00055"></a><span class="lineno"> 55</span>  <span class="keyword">typedef</span> tvec3<bool, P> bool_type;</div>
<div class="line"><a name="l00056"></a><span class="lineno"> 56</span>  <span class="keyword">typedef</span> T value_type;</div>
<div class="line"><a name="l00057"></a><span class="lineno"> 57</span> </div>
<div class="line"><a name="l00059"></a><span class="lineno"> 59</span>  <span class="comment">// Data</span></div>
<div class="line"><a name="l00060"></a><span class="lineno"> 60</span> </div>
<div class="line"><a name="l00061"></a><span class="lineno"> 61</span> <span class="preprocessor"># if GLM_HAS_ANONYMOUS_UNION</span></div>
<div class="line"><a name="l00062"></a><span class="lineno"> 62</span>  <span class="keyword">union</span></div>
<div class="line"><a name="l00063"></a><span class="lineno"> 63</span>  {</div>
<div class="line"><a name="l00064"></a><span class="lineno"> 64</span>  <span class="keyword">struct</span>{ T x, y, z; };</div>
<div class="line"><a name="l00065"></a><span class="lineno"> 65</span>  <span class="keyword">struct</span>{ T r, g, b; };</div>
<div class="line"><a name="l00066"></a><span class="lineno"> 66</span>  <span class="keyword">struct</span>{ T s, t, p; };</div>
<div class="line"><a name="l00067"></a><span class="lineno"> 67</span> </div>
<div class="line"><a name="l00068"></a><span class="lineno"> 68</span> <span class="preprocessor"># ifdef GLM_SWIZZLE</span></div>
<div class="line"><a name="l00069"></a><span class="lineno"> 69</span>  _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, x, y, z)</div>
<div class="line"><a name="l00070"></a><span class="lineno"> 70</span>  _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, r, g, b)</div>
<div class="line"><a name="l00071"></a><span class="lineno"> 71</span>  _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, s, t, p)</div>
<div class="line"><a name="l00072"></a><span class="lineno"> 72</span>  _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, x, y, z)</div>
<div class="line"><a name="l00073"></a><span class="lineno"> 73</span>  _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, r, g, b)</div>
<div class="line"><a name="l00074"></a><span class="lineno"> 74</span>  _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, s, t, p)</div>
<div class="line"><a name="l00075"></a><span class="lineno"> 75</span>  _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, x, y, z)</div>
<div class="line"><a name="l00076"></a><span class="lineno"> 76</span>  _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, r, g, b)</div>
<div class="line"><a name="l00077"></a><span class="lineno"> 77</span>  _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, s, t, p)</div>
<div class="line"><a name="l00078"></a><span class="lineno"> 78</span> <span class="preprocessor"># endif//GLM_SWIZZLE</span></div>
<div class="line"><a name="l00079"></a><span class="lineno"> 79</span>  };</div>
<div class="line"><a name="l00080"></a><span class="lineno"> 80</span> <span class="preprocessor"># else</span></div>
<div class="line"><a name="l00081"></a><span class="lineno"> 81</span>  <span class="keyword">union </span>{ T x, r, s; };</div>
<div class="line"><a name="l00082"></a><span class="lineno"> 82</span>  <span class="keyword">union </span>{ T y, g, t; };</div>
<div class="line"><a name="l00083"></a><span class="lineno"> 83</span>  <span class="keyword">union </span>{ T z, b, p; };</div>
<div class="line"><a name="l00084"></a><span class="lineno"> 84</span> </div>
<div class="line"><a name="l00085"></a><span class="lineno"> 85</span> <span class="preprocessor"># ifdef GLM_SWIZZLE</span></div>
<div class="line"><a name="l00086"></a><span class="lineno"> 86</span>  GLM_SWIZZLE_GEN_VEC_FROM_VEC3(T, P, tvec3, tvec2, tvec3, tvec4)</div>
<div class="line"><a name="l00087"></a><span class="lineno"> 87</span> <span class="preprocessor"># endif//GLM_SWIZZLE</span></div>
<div class="line"><a name="l00088"></a><span class="lineno"> 88</span> <span class="preprocessor"># endif//GLM_LANG</span></div>
<div class="line"><a name="l00089"></a><span class="lineno"> 89</span> </div>
<div class="line"><a name="l00091"></a><span class="lineno"> 91</span>  <span class="comment">// Component accesses</span></div>
<div class="line"><a name="l00092"></a><span class="lineno"> 92</span> </div>
<div class="line"><a name="l00093"></a><span class="lineno"> 93</span> <span class="preprocessor"># ifdef GLM_FORCE_SIZE_FUNC</span></div>
<div class="line"><a name="l00094"></a><span class="lineno"> 94</span>  <span class="keyword">typedef</span> <span class="keywordtype">size_t</span> size_type;</div>
<div class="line"><a name="l00096"></a><span class="lineno"> 96</span>  GLM_FUNC_DECL GLM_CONSTEXPR size_type size() <span class="keyword">const</span>;</div>
<div class="line"><a name="l00097"></a><span class="lineno"> 97</span> </div>
<div class="line"><a name="l00098"></a><span class="lineno"> 98</span>  GLM_FUNC_DECL T & operator[](size_type i);</div>
<div class="line"><a name="l00099"></a><span class="lineno"> 99</span>  GLM_FUNC_DECL T <span class="keyword">const</span> & operator[](size_type i) <span class="keyword">const</span>;</div>
<div class="line"><a name="l00100"></a><span class="lineno"> 100</span> <span class="preprocessor"># else</span></div>
<div class="line"><a name="l00101"></a><span class="lineno"> 101</span>  <span class="keyword">typedef</span> length_t length_type;</div>
<div class="line"><a name="l00103"></a><span class="lineno"> 103</span>  GLM_FUNC_DECL GLM_CONSTEXPR length_type <a class="code" href="a00151.html#ga18d45e3d4c7705e67ccfabd99e521604">length</a>() <span class="keyword">const</span>;</div>
<div class="line"><a name="l00104"></a><span class="lineno"> 104</span> </div>
<div class="line"><a name="l00105"></a><span class="lineno"> 105</span>  GLM_FUNC_DECL T & operator[](length_type i);</div>
<div class="line"><a name="l00106"></a><span class="lineno"> 106</span>  GLM_FUNC_DECL T <span class="keyword">const</span> & operator[](length_type i) <span class="keyword">const</span>;</div>
<div class="line"><a name="l00107"></a><span class="lineno"> 107</span> <span class="preprocessor"># endif//GLM_FORCE_SIZE_FUNC</span></div>
<div class="line"><a name="l00108"></a><span class="lineno"> 108</span> </div>
<div class="line"><a name="l00110"></a><span class="lineno"> 110</span>  <span class="comment">// Implicit basic constructors</span></div>
<div class="line"><a name="l00111"></a><span class="lineno"> 111</span> </div>
<div class="line"><a name="l00112"></a><span class="lineno"> 112</span>  GLM_FUNC_DECL tvec3();</div>
<div class="line"><a name="l00113"></a><span class="lineno"> 113</span>  <span class="keyword">template</span> <precision Q></div>
<div class="line"><a name="l00114"></a><span class="lineno"> 114</span>  GLM_FUNC_DECL tvec3(tvec3<T, Q> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00115"></a><span class="lineno"> 115</span> </div>
<div class="line"><a name="l00117"></a><span class="lineno"> 117</span>  <span class="comment">// Explicit basic constructors</span></div>
<div class="line"><a name="l00118"></a><span class="lineno"> 118</span> </div>
<div class="line"><a name="l00119"></a><span class="lineno"> 119</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(ctor);</div>
<div class="line"><a name="l00120"></a><span class="lineno"> 120</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00121"></a><span class="lineno"> 121</span>  GLM_FUNC_DECL tvec3(T <span class="keyword">const</span> & a, T <span class="keyword">const</span> & b, T <span class="keyword">const</span> & c);</div>
<div class="line"><a name="l00122"></a><span class="lineno"> 122</span> </div>
<div class="line"><a name="l00124"></a><span class="lineno"> 124</span>  <span class="comment">// Conversion scalar constructors</span></div>
<div class="line"><a name="l00125"></a><span class="lineno"> 125</span> </div>
<div class="line"><a name="l00127"></a><span class="lineno"> 127</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, <span class="keyword">typename</span> C></div>
<div class="line"><a name="l00128"></a><span class="lineno"> 128</span>  GLM_FUNC_DECL tvec3(A <span class="keyword">const</span> & a, B <span class="keyword">const</span> & b, C <span class="keyword">const</span> & c);</div>
<div class="line"><a name="l00129"></a><span class="lineno"> 129</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, <span class="keyword">typename</span> C></div>
<div class="line"><a name="l00130"></a><span class="lineno"> 130</span>  GLM_FUNC_DECL tvec3(tvec1<A, P> <span class="keyword">const</span> & a, tvec1<B, P> <span class="keyword">const</span> & b, tvec1<C, P> <span class="keyword">const</span> & c);</div>
<div class="line"><a name="l00131"></a><span class="lineno"> 131</span> </div>
<div class="line"><a name="l00133"></a><span class="lineno"> 133</span>  <span class="comment">// Conversion vector constructors</span></div>
<div class="line"><a name="l00134"></a><span class="lineno"> 134</span> </div>
<div class="line"><a name="l00136"></a><span class="lineno"> 136</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, precision Q></div>
<div class="line"><a name="l00137"></a><span class="lineno"> 137</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec2<A, Q> <span class="keyword">const</span> & a, B <span class="keyword">const</span> & b);</div>
<div class="line"><a name="l00139"></a><span class="lineno"> 139</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, precision Q></div>
<div class="line"><a name="l00140"></a><span class="lineno"> 140</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec2<A, Q> <span class="keyword">const</span> & a, tvec1<B, Q> <span class="keyword">const</span> & b);</div>
<div class="line"><a name="l00142"></a><span class="lineno"> 142</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, precision Q></div>
<div class="line"><a name="l00143"></a><span class="lineno"> 143</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(A <span class="keyword">const</span> & a, tvec2<B, Q> <span class="keyword">const</span> & b);</div>
<div class="line"><a name="l00145"></a><span class="lineno"> 145</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, precision Q></div>
<div class="line"><a name="l00146"></a><span class="lineno"> 146</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec1<A, Q> <span class="keyword">const</span> & a, tvec2<B, Q> <span class="keyword">const</span> & b);</div>
<div class="line"><a name="l00148"></a><span class="lineno"> 148</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U, precision Q></div>
<div class="line"><a name="l00149"></a><span class="lineno"> 149</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec4<U, Q> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00150"></a><span class="lineno"> 150</span> </div>
<div class="line"><a name="l00151"></a><span class="lineno"> 151</span> <span class="preprocessor"># ifdef GLM_FORCE_EXPLICIT_CTOR</span></div>
<div class="line"><a name="l00152"></a><span class="lineno"> 152</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U, precision Q></div>
<div class="line"><a name="l00154"></a><span class="lineno"> 154</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec3<U, Q> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00155"></a><span class="lineno"> 155</span> <span class="preprocessor"># else</span></div>
<div class="line"><a name="l00156"></a><span class="lineno"> 156</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U, precision Q></div>
<div class="line"><a name="l00158"></a><span class="lineno"> 158</span>  GLM_FUNC_DECL tvec3(tvec3<U, Q> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00159"></a><span class="lineno"> 159</span> <span class="preprocessor"># endif</span></div>
<div class="line"><a name="l00160"></a><span class="lineno"> 160</span> </div>
<div class="line"><a name="l00162"></a><span class="lineno"> 162</span>  <span class="comment">// Swizzle constructors</span></div>
<div class="line"><a name="l00163"></a><span class="lineno"> 163</span> </div>
<div class="line"><a name="l00164"></a><span class="lineno"> 164</span> <span class="preprocessor"># if GLM_HAS_ANONYMOUS_UNION && defined(GLM_SWIZZLE)</span></div>
<div class="line"><a name="l00165"></a><span class="lineno"> 165</span>  <span class="keyword">template</span> <<span class="keywordtype">int</span> E0, <span class="keywordtype">int</span> E1, <span class="keywordtype">int</span> E2></div>
<div class="line"><a name="l00166"></a><span class="lineno"> 166</span>  GLM_FUNC_DECL tvec3(detail::_swizzle<3, T, P, tvec3<T, P>, E0, E1, E2, -1> <span class="keyword">const</span> & that)</div>
<div class="line"><a name="l00167"></a><span class="lineno"> 167</span>  {</div>
<div class="line"><a name="l00168"></a><span class="lineno"> 168</span>  *<span class="keyword">this</span> = that();</div>
<div class="line"><a name="l00169"></a><span class="lineno"> 169</span>  }</div>
<div class="line"><a name="l00170"></a><span class="lineno"> 170</span> </div>
<div class="line"><a name="l00171"></a><span class="lineno"> 171</span>  <span class="keyword">template</span> <<span class="keywordtype">int</span> E0, <span class="keywordtype">int</span> E1></div>
<div class="line"><a name="l00172"></a><span class="lineno"> 172</span>  GLM_FUNC_DECL tvec3(detail::_swizzle<2, T, P, tvec2<T, P>, E0, E1, -1, -2> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s)</div>
<div class="line"><a name="l00173"></a><span class="lineno"> 173</span>  {</div>
<div class="line"><a name="l00174"></a><span class="lineno"> 174</span>  *<span class="keyword">this</span> = tvec3<T, P>(v(), s);</div>
<div class="line"><a name="l00175"></a><span class="lineno"> 175</span>  }</div>
<div class="line"><a name="l00176"></a><span class="lineno"> 176</span> </div>
<div class="line"><a name="l00177"></a><span class="lineno"> 177</span>  <span class="keyword">template</span> <<span class="keywordtype">int</span> E0, <span class="keywordtype">int</span> E1></div>
<div class="line"><a name="l00178"></a><span class="lineno"> 178</span>  GLM_FUNC_DECL tvec3(T <span class="keyword">const</span> & s, detail::_swizzle<2, T, P, tvec2<T, P>, E0, E1, -1, -2> <span class="keyword">const</span> & v)</div>
<div class="line"><a name="l00179"></a><span class="lineno"> 179</span>  {</div>
<div class="line"><a name="l00180"></a><span class="lineno"> 180</span>  *<span class="keyword">this</span> = tvec3<T, P>(s, v());</div>
<div class="line"><a name="l00181"></a><span class="lineno"> 181</span>  }</div>
<div class="line"><a name="l00182"></a><span class="lineno"> 182</span> <span class="preprocessor"># endif// GLM_HAS_ANONYMOUS_UNION && defined(GLM_SWIZZLE)</span></div>
<div class="line"><a name="l00183"></a><span class="lineno"> 183</span> </div>
<div class="line"><a name="l00185"></a><span class="lineno"> 185</span>  <span class="comment">// Unary arithmetic operators</span></div>
<div class="line"><a name="l00186"></a><span class="lineno"> 186</span> </div>
<div class="line"><a name="l00187"></a><span class="lineno"> 187</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00188"></a><span class="lineno"> 188</span>  GLM_FUNC_DECL tvec3<T, P> & operator=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00189"></a><span class="lineno"> 189</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00190"></a><span class="lineno"> 190</span>  GLM_FUNC_DECL tvec3<T, P> & operator+=(U s);</div>
<div class="line"><a name="l00191"></a><span class="lineno"> 191</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00192"></a><span class="lineno"> 192</span>  GLM_FUNC_DECL tvec3<T, P> & operator+=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00193"></a><span class="lineno"> 193</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00194"></a><span class="lineno"> 194</span>  GLM_FUNC_DECL tvec3<T, P> & operator+=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00195"></a><span class="lineno"> 195</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00196"></a><span class="lineno"> 196</span>  GLM_FUNC_DECL tvec3<T, P> & operator-=(U s);</div>
<div class="line"><a name="l00197"></a><span class="lineno"> 197</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00198"></a><span class="lineno"> 198</span>  GLM_FUNC_DECL tvec3<T, P> & operator-=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00199"></a><span class="lineno"> 199</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00200"></a><span class="lineno"> 200</span>  GLM_FUNC_DECL tvec3<T, P> & operator-=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00201"></a><span class="lineno"> 201</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00202"></a><span class="lineno"> 202</span>  GLM_FUNC_DECL tvec3<T, P> & operator*=(U s);</div>
<div class="line"><a name="l00203"></a><span class="lineno"> 203</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00204"></a><span class="lineno"> 204</span>  GLM_FUNC_DECL tvec3<T, P> & operator*=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00205"></a><span class="lineno"> 205</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00206"></a><span class="lineno"> 206</span>  GLM_FUNC_DECL tvec3<T, P> & operator*=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00207"></a><span class="lineno"> 207</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00208"></a><span class="lineno"> 208</span>  GLM_FUNC_DECL tvec3<T, P> & operator/=(U s);</div>
<div class="line"><a name="l00209"></a><span class="lineno"> 209</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00210"></a><span class="lineno"> 210</span>  GLM_FUNC_DECL tvec3<T, P> & operator/=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00211"></a><span class="lineno"> 211</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00212"></a><span class="lineno"> 212</span>  GLM_FUNC_DECL tvec3<T, P> & operator/=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00213"></a><span class="lineno"> 213</span> </div>
<div class="line"><a name="l00215"></a><span class="lineno"> 215</span>  <span class="comment">// Increment and decrement operators</span></div>
<div class="line"><a name="l00216"></a><span class="lineno"> 216</span> </div>
<div class="line"><a name="l00217"></a><span class="lineno"> 217</span>  GLM_FUNC_DECL tvec3<T, P> & operator++();</div>
<div class="line"><a name="l00218"></a><span class="lineno"> 218</span>  GLM_FUNC_DECL tvec3<T, P> & operator--();</div>
<div class="line"><a name="l00219"></a><span class="lineno"> 219</span>  GLM_FUNC_DECL tvec3<T, P> operator++(<span class="keywordtype">int</span>);</div>
<div class="line"><a name="l00220"></a><span class="lineno"> 220</span>  GLM_FUNC_DECL tvec3<T, P> operator--(<span class="keywordtype">int</span>);</div>
<div class="line"><a name="l00221"></a><span class="lineno"> 221</span> </div>
<div class="line"><a name="l00223"></a><span class="lineno"> 223</span>  <span class="comment">// Unary bit operators</span></div>
<div class="line"><a name="l00224"></a><span class="lineno"> 224</span> </div>
<div class="line"><a name="l00225"></a><span class="lineno"> 225</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00226"></a><span class="lineno"> 226</span>  GLM_FUNC_DECL tvec3<T, P> & operator%=(U s);</div>
<div class="line"><a name="l00227"></a><span class="lineno"> 227</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00228"></a><span class="lineno"> 228</span>  GLM_FUNC_DECL tvec3<T, P> & operator%=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00229"></a><span class="lineno"> 229</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00230"></a><span class="lineno"> 230</span>  GLM_FUNC_DECL tvec3<T, P> & operator%=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00231"></a><span class="lineno"> 231</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00232"></a><span class="lineno"> 232</span>  GLM_FUNC_DECL tvec3<T, P> & operator&=(U s);</div>
<div class="line"><a name="l00233"></a><span class="lineno"> 233</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00234"></a><span class="lineno"> 234</span>  GLM_FUNC_DECL tvec3<T, P> & operator&=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00235"></a><span class="lineno"> 235</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00236"></a><span class="lineno"> 236</span>  GLM_FUNC_DECL tvec3<T, P> & operator&=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00237"></a><span class="lineno"> 237</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00238"></a><span class="lineno"> 238</span>  GLM_FUNC_DECL tvec3<T, P> & operator|=(U s);</div>
<div class="line"><a name="l00239"></a><span class="lineno"> 239</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00240"></a><span class="lineno"> 240</span>  GLM_FUNC_DECL tvec3<T, P> & operator|=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00241"></a><span class="lineno"> 241</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00242"></a><span class="lineno"> 242</span>  GLM_FUNC_DECL tvec3<T, P> & operator|=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00243"></a><span class="lineno"> 243</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00244"></a><span class="lineno"> 244</span>  GLM_FUNC_DECL tvec3<T, P> & operator^=(U s);</div>
<div class="line"><a name="l00245"></a><span class="lineno"> 245</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00246"></a><span class="lineno"> 246</span>  GLM_FUNC_DECL tvec3<T, P> & operator^=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00247"></a><span class="lineno"> 247</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00248"></a><span class="lineno"> 248</span>  GLM_FUNC_DECL tvec3<T, P> & operator^=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00249"></a><span class="lineno"> 249</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00250"></a><span class="lineno"> 250</span>  GLM_FUNC_DECL tvec3<T, P> & operator<<=(U s);</div>
<div class="line"><a name="l00251"></a><span class="lineno"> 251</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00252"></a><span class="lineno"> 252</span>  GLM_FUNC_DECL tvec3<T, P> & operator<<=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00253"></a><span class="lineno"> 253</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00254"></a><span class="lineno"> 254</span>  GLM_FUNC_DECL tvec3<T, P> & operator<<=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00255"></a><span class="lineno"> 255</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00256"></a><span class="lineno"> 256</span>  GLM_FUNC_DECL tvec3<T, P> & operator>>=(U s);</div>
<div class="line"><a name="l00257"></a><span class="lineno"> 257</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00258"></a><span class="lineno"> 258</span>  GLM_FUNC_DECL tvec3<T, P> & operator>>=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00259"></a><span class="lineno"> 259</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00260"></a><span class="lineno"> 260</span>  GLM_FUNC_DECL tvec3<T, P> & operator>>=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00261"></a><span class="lineno"> 261</span>  };</div>
<div class="line"><a name="l00262"></a><span class="lineno"> 262</span> </div>
<div class="line"><a name="l00263"></a><span class="lineno"> 263</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00264"></a><span class="lineno"> 264</span>  GLM_FUNC_DECL tvec3<T, P> operator+(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00265"></a><span class="lineno"> 265</span> </div>
<div class="line"><a name="l00266"></a><span class="lineno"> 266</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00267"></a><span class="lineno"> 267</span>  GLM_FUNC_DECL tvec3<T, P> operator+(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00268"></a><span class="lineno"> 268</span> </div>
<div class="line"><a name="l00269"></a><span class="lineno"> 269</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00270"></a><span class="lineno"> 270</span>  GLM_FUNC_DECL tvec3<T, P> operator+(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00271"></a><span class="lineno"> 271</span> </div>
<div class="line"><a name="l00272"></a><span class="lineno"> 272</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00273"></a><span class="lineno"> 273</span>  GLM_FUNC_DECL tvec3<T, P> operator+(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00274"></a><span class="lineno"> 274</span> </div>
<div class="line"><a name="l00275"></a><span class="lineno"> 275</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00276"></a><span class="lineno"> 276</span>  GLM_FUNC_DECL tvec3<T, P> operator+(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00277"></a><span class="lineno"> 277</span> </div>
<div class="line"><a name="l00278"></a><span class="lineno"> 278</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00279"></a><span class="lineno"> 279</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00280"></a><span class="lineno"> 280</span> </div>
<div class="line"><a name="l00281"></a><span class="lineno"> 281</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00282"></a><span class="lineno"> 282</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00283"></a><span class="lineno"> 283</span> </div>
<div class="line"><a name="l00284"></a><span class="lineno"> 284</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00285"></a><span class="lineno"> 285</span>  GLM_FUNC_DECL tvec3<T, P> operator-(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00286"></a><span class="lineno"> 286</span> </div>
<div class="line"><a name="l00287"></a><span class="lineno"> 287</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00288"></a><span class="lineno"> 288</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00289"></a><span class="lineno"> 289</span> </div>
<div class="line"><a name="l00290"></a><span class="lineno"> 290</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00291"></a><span class="lineno"> 291</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00292"></a><span class="lineno"> 292</span> </div>
<div class="line"><a name="l00293"></a><span class="lineno"> 293</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00294"></a><span class="lineno"> 294</span>  GLM_FUNC_DECL tvec3<T, P> operator*(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00295"></a><span class="lineno"> 295</span> </div>
<div class="line"><a name="l00296"></a><span class="lineno"> 296</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00297"></a><span class="lineno"> 297</span>  GLM_FUNC_DECL tvec3<T, P> operator*(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00298"></a><span class="lineno"> 298</span> </div>
<div class="line"><a name="l00299"></a><span class="lineno"> 299</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00300"></a><span class="lineno"> 300</span>  GLM_FUNC_DECL tvec3<T, P> operator*(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00301"></a><span class="lineno"> 301</span> </div>
<div class="line"><a name="l00302"></a><span class="lineno"> 302</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00303"></a><span class="lineno"> 303</span>  GLM_FUNC_DECL tvec3<T, P> operator*(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00304"></a><span class="lineno"> 304</span> </div>
<div class="line"><a name="l00305"></a><span class="lineno"> 305</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00306"></a><span class="lineno"> 306</span>  GLM_FUNC_DECL tvec3<T, P> operator*(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00307"></a><span class="lineno"> 307</span> </div>
<div class="line"><a name="l00308"></a><span class="lineno"> 308</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00309"></a><span class="lineno"> 309</span>  GLM_FUNC_DECL tvec3<T, P> operator/(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00310"></a><span class="lineno"> 310</span> </div>
<div class="line"><a name="l00311"></a><span class="lineno"> 311</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00312"></a><span class="lineno"> 312</span>  GLM_FUNC_DECL tvec3<T, P> operator/(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00313"></a><span class="lineno"> 313</span> </div>
<div class="line"><a name="l00314"></a><span class="lineno"> 314</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00315"></a><span class="lineno"> 315</span>  GLM_FUNC_DECL tvec3<T, P> operator/(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00316"></a><span class="lineno"> 316</span> </div>
<div class="line"><a name="l00317"></a><span class="lineno"> 317</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00318"></a><span class="lineno"> 318</span>  GLM_FUNC_DECL tvec3<T, P> operator/(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00319"></a><span class="lineno"> 319</span> </div>
<div class="line"><a name="l00320"></a><span class="lineno"> 320</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00321"></a><span class="lineno"> 321</span>  GLM_FUNC_DECL tvec3<T, P> operator/(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00322"></a><span class="lineno"> 322</span> </div>
<div class="line"><a name="l00323"></a><span class="lineno"> 323</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00324"></a><span class="lineno"> 324</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00325"></a><span class="lineno"> 325</span> </div>
<div class="line"><a name="l00326"></a><span class="lineno"> 326</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00327"></a><span class="lineno"> 327</span>  GLM_FUNC_DECL tvec3<T, P> operator%(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00328"></a><span class="lineno"> 328</span> </div>
<div class="line"><a name="l00329"></a><span class="lineno"> 329</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00330"></a><span class="lineno"> 330</span>  GLM_FUNC_DECL tvec3<T, P> operator%(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00331"></a><span class="lineno"> 331</span> </div>
<div class="line"><a name="l00332"></a><span class="lineno"> 332</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00333"></a><span class="lineno"> 333</span>  GLM_FUNC_DECL tvec3<T, P> operator%(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00334"></a><span class="lineno"> 334</span> </div>
<div class="line"><a name="l00335"></a><span class="lineno"> 335</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00336"></a><span class="lineno"> 336</span>  GLM_FUNC_DECL tvec3<T, P> operator%(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00337"></a><span class="lineno"> 337</span> </div>
<div class="line"><a name="l00338"></a><span class="lineno"> 338</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00339"></a><span class="lineno"> 339</span>  GLM_FUNC_DECL tvec3<T, P> operator%(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00340"></a><span class="lineno"> 340</span> </div>
<div class="line"><a name="l00341"></a><span class="lineno"> 341</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00342"></a><span class="lineno"> 342</span>  GLM_FUNC_DECL tvec3<T, P> operator&(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00343"></a><span class="lineno"> 343</span> </div>
<div class="line"><a name="l00344"></a><span class="lineno"> 344</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00345"></a><span class="lineno"> 345</span>  GLM_FUNC_DECL tvec3<T, P> operator&(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00346"></a><span class="lineno"> 346</span> </div>
<div class="line"><a name="l00347"></a><span class="lineno"> 347</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00348"></a><span class="lineno"> 348</span>  GLM_FUNC_DECL tvec3<T, P> operator&(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00349"></a><span class="lineno"> 349</span> </div>
<div class="line"><a name="l00350"></a><span class="lineno"> 350</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00351"></a><span class="lineno"> 351</span>  GLM_FUNC_DECL tvec3<T, P> operator&(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00352"></a><span class="lineno"> 352</span> </div>
<div class="line"><a name="l00353"></a><span class="lineno"> 353</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00354"></a><span class="lineno"> 354</span>  GLM_FUNC_DECL tvec3<T, P> operator&(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00355"></a><span class="lineno"> 355</span> </div>
<div class="line"><a name="l00356"></a><span class="lineno"> 356</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00357"></a><span class="lineno"> 357</span>  GLM_FUNC_DECL tvec3<T, P> operator|(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00358"></a><span class="lineno"> 358</span> </div>
<div class="line"><a name="l00359"></a><span class="lineno"> 359</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00360"></a><span class="lineno"> 360</span>  GLM_FUNC_DECL tvec3<T, P> operator|(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00361"></a><span class="lineno"> 361</span> </div>
<div class="line"><a name="l00362"></a><span class="lineno"> 362</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00363"></a><span class="lineno"> 363</span>  GLM_FUNC_DECL tvec3<T, P> operator|(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00364"></a><span class="lineno"> 364</span> </div>
<div class="line"><a name="l00365"></a><span class="lineno"> 365</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00366"></a><span class="lineno"> 366</span>  GLM_FUNC_DECL tvec3<T, P> operator|(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00367"></a><span class="lineno"> 367</span> </div>
<div class="line"><a name="l00368"></a><span class="lineno"> 368</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00369"></a><span class="lineno"> 369</span>  GLM_FUNC_DECL tvec3<T, P> operator|(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00370"></a><span class="lineno"> 370</span> </div>
<div class="line"><a name="l00371"></a><span class="lineno"> 371</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00372"></a><span class="lineno"> 372</span>  GLM_FUNC_DECL tvec3<T, P> operator^(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00373"></a><span class="lineno"> 373</span> </div>
<div class="line"><a name="l00374"></a><span class="lineno"> 374</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00375"></a><span class="lineno"> 375</span>  GLM_FUNC_DECL tvec3<T, P> operator^(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00376"></a><span class="lineno"> 376</span> </div>
<div class="line"><a name="l00377"></a><span class="lineno"> 377</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00378"></a><span class="lineno"> 378</span>  GLM_FUNC_DECL tvec3<T, P> operator^(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00379"></a><span class="lineno"> 379</span> </div>
<div class="line"><a name="l00380"></a><span class="lineno"> 380</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00381"></a><span class="lineno"> 381</span>  GLM_FUNC_DECL tvec3<T, P> operator^(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00382"></a><span class="lineno"> 382</span> </div>
<div class="line"><a name="l00383"></a><span class="lineno"> 383</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00384"></a><span class="lineno"> 384</span>  GLM_FUNC_DECL tvec3<T, P> operator^(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00385"></a><span class="lineno"> 385</span> </div>
<div class="line"><a name="l00386"></a><span class="lineno"> 386</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00387"></a><span class="lineno"> 387</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00388"></a><span class="lineno"> 388</span> </div>
<div class="line"><a name="l00389"></a><span class="lineno"> 389</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00390"></a><span class="lineno"> 390</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00391"></a><span class="lineno"> 391</span> </div>
<div class="line"><a name="l00392"></a><span class="lineno"> 392</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00393"></a><span class="lineno"> 393</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(T const & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00394"></a><span class="lineno"> 394</span> </div>
<div class="line"><a name="l00395"></a><span class="lineno"> 395</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00396"></a><span class="lineno"> 396</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00397"></a><span class="lineno"> 397</span> </div>
<div class="line"><a name="l00398"></a><span class="lineno"> 398</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00399"></a><span class="lineno"> 399</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00400"></a><span class="lineno"> 400</span> </div>
<div class="line"><a name="l00401"></a><span class="lineno"> 401</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00402"></a><span class="lineno"> 402</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00403"></a><span class="lineno"> 403</span> </div>
<div class="line"><a name="l00404"></a><span class="lineno"> 404</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00405"></a><span class="lineno"> 405</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00406"></a><span class="lineno"> 406</span> </div>
<div class="line"><a name="l00407"></a><span class="lineno"> 407</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00408"></a><span class="lineno"> 408</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00409"></a><span class="lineno"> 409</span> </div>
<div class="line"><a name="l00410"></a><span class="lineno"> 410</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00411"></a><span class="lineno"> 411</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00412"></a><span class="lineno"> 412</span> </div>
<div class="line"><a name="l00413"></a><span class="lineno"> 413</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00414"></a><span class="lineno"> 414</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00415"></a><span class="lineno"> 415</span> </div>
<div class="line"><a name="l00416"></a><span class="lineno"> 416</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P> </div>
<div class="line"><a name="l00417"></a><span class="lineno"> 417</span>  GLM_FUNC_DECL tvec3<T, P> operator~(tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00418"></a><span class="lineno"> 418</span> }<span class="comment">//namespace glm</span></div>
<div class="line"><a name="l00419"></a><span class="lineno"> 419</span> </div>
<div class="line"><a name="l00420"></a><span class="lineno"> 420</span> <span class="preprocessor">#ifndef GLM_EXTERNAL_TEMPLATE</span></div>
<div class="line"><a name="l00421"></a><span class="lineno"> 421</span> <span class="preprocessor">#include "type_vec3.inl"</span></div>
<div class="line"><a name="l00422"></a><span class="lineno"> 422</span> <span class="preprocessor">#endif//GLM_EXTERNAL_TEMPLATE</span></div>
<div class="ttc" id="a00005_html"><div class="ttname"><a href="a00005.html">_swizzle_func.hpp</a></div><div class="ttdoc">OpenGL Mathematics (glm.g-truc.net) </div></div>
<div class="ttc" id="a00151_html_ga18d45e3d4c7705e67ccfabd99e521604"><div class="ttname"><a href="a00151.html#ga18d45e3d4c7705e67ccfabd99e521604">glm::length</a></div><div class="ttdeci">GLM_FUNC_DECL T length(vecType< T, P > const &x)</div><div class="ttdoc">Returns the length of x, i.e., sqrt(x * x). </div></div>
<div class="ttc" id="a00145_html"><div class="ttname"><a href="a00145.html">glm</a></div><div class="ttdef"><b>Definition:</b> <a href="a00003_source.html#l00039">_noise.hpp:39</a></div></div>
<div class="ttc" id="a00131_html"><div class="ttname"><a href="a00131.html">type_vec.hpp</a></div><div class="ttdoc">OpenGL Mathematics (glm.g-truc.net) </div></div>
<div class="ttc" id="a00004_html"><div class="ttname"><a href="a00004.html">_swizzle.hpp</a></div><div class="ttdoc">OpenGL Mathematics (glm.g-truc.net) </div></div>
</div><!-- fragment --></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.8
</small></address>
</body>
</html>
| ronsaldo/loden | thirdparty/glm/doc/api/a00134_source.html | HTML | mit | 67,346 |
// Learn more about configuring this file at <https://theintern.github.io/intern/#configuration>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites
define({
// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
// specified browser environments in the `environments` array below as well. See
// <https://theintern.github.io/intern/#option-capabilities> for links to the different capabilities options for
// different services.
// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
maxConcurrency: 2,
// Non-functional test suite(s) to run in each browser
suites: [ 'tests/plugin' ],
// A regular expression matching URLs to files that should not be included in code coverage analysis
excludeInstrumentation: /^(?:tests|node_modules)\//
});
| brendanlacroix/polish-no-added-typography | tests/intern.js | JavaScript | mit | 1,011 |
import {LooseParser} from "./state"
import {isDummy} from "./parseutil"
import {tokTypes as tt} from ".."
const lp = LooseParser.prototype
lp.checkLVal = function(expr) {
if (!expr) return expr
switch (expr.type) {
case "Identifier":
case "MemberExpression":
return expr
case "ParenthesizedExpression":
expr.expression = this.checkLVal(expr.expression)
return expr
default:
return this.dummyIdent()
}
}
lp.parseExpression = function(noIn) {
let start = this.storeCurrentPos()
let expr = this.parseMaybeAssign(noIn)
if (this.tok.type === tt.comma) {
let node = this.startNodeAt(start)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
lp.parseParenExpression = function() {
this.pushCx()
this.expect(tt.parenL)
let val = this.parseExpression()
this.popCx()
this.expect(tt.parenR)
return val
}
lp.parseMaybeAssign = function(noIn) {
if (this.toks.isContextual("yield")) {
let node = this.startNode()
this.next()
if (this.semicolon() || this.canInsertSemicolon() || (this.tok.type != tt.star && !this.tok.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign()
}
return this.finishNode(node, "YieldExpression")
}
let start = this.storeCurrentPos()
let left = this.parseMaybeConditional(noIn)
if (this.tok.type.isAssign) {
let node = this.startNodeAt(start)
node.operator = this.tok.value
node.left = this.tok.type === tt.eq ? this.toAssignable(left) : this.checkLVal(left)
this.next()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "AssignmentExpression")
}
return left
}
lp.parseMaybeConditional = function(noIn) {
let start = this.storeCurrentPos()
let expr = this.parseExprOps(noIn)
if (this.eat(tt.question)) {
let node = this.startNodeAt(start)
node.test = expr
node.consequent = this.parseMaybeAssign()
node.alternate = this.expect(tt.colon) ? this.parseMaybeAssign(noIn) : this.dummyIdent()
return this.finishNode(node, "ConditionalExpression")
}
return expr
}
lp.parseExprOps = function(noIn) {
let start = this.storeCurrentPos()
let indent = this.curIndent, line = this.curLineStart
return this.parseExprOp(this.parseMaybeUnary(false), start, -1, noIn, indent, line)
}
lp.parseExprOp = function(left, start, minPrec, noIn, indent, line) {
if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) return left
let prec = this.tok.type.binop
if (prec != null && (!noIn || this.tok.type !== tt._in)) {
if (prec > minPrec) {
let node = this.startNodeAt(start)
node.left = left
node.operator = this.tok.value
this.next()
if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) {
node.right = this.dummyIdent()
} else {
let rightStart = this.storeCurrentPos()
node.right = this.parseExprOp(this.parseMaybeUnary(false), rightStart, prec, noIn, indent, line)
}
this.finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression")
return this.parseExprOp(node, start, minPrec, noIn, indent, line)
}
}
return left
}
lp.parseMaybeUnary = function(sawUnary) {
let start = this.storeCurrentPos(), expr
if (this.tok.type.prefix) {
let node = this.startNode(), update = this.tok.type === tt.incDec
if (!update) sawUnary = true
node.operator = this.tok.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary(true)
if (update) node.argument = this.checkLVal(node.argument)
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
} else if (this.tok.type === tt.ellipsis) {
let node = this.startNode()
this.next()
node.argument = this.parseMaybeUnary(sawUnary)
expr = this.finishNode(node, "SpreadElement")
} else {
expr = this.parseExprSubscripts()
while (this.tok.type.postfix && !this.canInsertSemicolon()) {
let node = this.startNodeAt(start)
node.operator = this.tok.value
node.prefix = false
node.argument = this.checkLVal(expr)
this.next()
expr = this.finishNode(node, "UpdateExpression")
}
}
if (!sawUnary && this.eat(tt.starstar)) {
let node = this.startNodeAt(start)
node.operator = "**"
node.left = expr
node.right = this.parseMaybeUnary(false)
return this.finishNode(node, "BinaryExpression")
}
return expr
}
lp.parseExprSubscripts = function() {
let start = this.storeCurrentPos()
return this.parseSubscripts(this.parseExprAtom(), start, false, this.curIndent, this.curLineStart)
}
lp.parseSubscripts = function(base, start, noCalls, startIndent, line) {
for (;;) {
if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) {
if (this.tok.type == tt.dot && this.curIndent == startIndent)
--startIndent
else
return base
}
if (this.eat(tt.dot)) {
let node = this.startNodeAt(start)
node.object = base
if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine())
node.property = this.dummyIdent()
else
node.property = this.parsePropertyAccessor() || this.dummyIdent()
node.computed = false
base = this.finishNode(node, "MemberExpression")
} else if (this.tok.type == tt.bracketL) {
this.pushCx()
this.next()
let node = this.startNodeAt(start)
node.object = base
node.property = this.parseExpression()
node.computed = true
this.popCx()
this.expect(tt.bracketR)
base = this.finishNode(node, "MemberExpression")
} else if (!noCalls && this.tok.type == tt.parenL) {
let node = this.startNodeAt(start)
node.callee = base
node.arguments = this.parseExprList(tt.parenR)
base = this.finishNode(node, "CallExpression")
} else if (this.tok.type == tt.backQuote) {
let node = this.startNodeAt(start)
node.tag = base
node.quasi = this.parseTemplate()
base = this.finishNode(node, "TaggedTemplateExpression")
} else {
return base
}
}
}
lp.parseExprAtom = function() {
let node
switch (this.tok.type) {
case tt._this:
case tt._super:
let type = this.tok.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
return this.finishNode(node, type)
case tt.name:
let start = this.storeCurrentPos()
let id = this.parseIdent()
return this.eat(tt.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id]) : id
case tt.regexp:
node = this.startNode()
let val = this.tok.value
node.regex = {pattern: val.pattern, flags: val.flags}
node.value = val.value
node.raw = this.input.slice(this.tok.start, this.tok.end)
this.next()
return this.finishNode(node, "Literal")
case tt.num: case tt.string:
node = this.startNode()
node.value = this.tok.value
node.raw = this.input.slice(this.tok.start, this.tok.end)
this.next()
return this.finishNode(node, "Literal")
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.tok.type === tt._null ? null : this.tok.type === tt._true
node.raw = this.tok.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
let parenStart = this.storeCurrentPos()
this.next()
let inner = this.parseExpression()
this.expect(tt.parenR)
if (this.eat(tt.arrow)) {
return this.parseArrowExpression(this.startNodeAt(parenStart), inner.expressions || (isDummy(inner) ? [] : [inner]))
}
if (this.options.preserveParens) {
let par = this.startNodeAt(parenStart)
par.expression = inner
inner = this.finishNode(par, "ParenthesizedExpression")
}
return inner
case tt.bracketL:
node = this.startNode()
node.elements = this.parseExprList(tt.bracketR, true)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj()
case tt._class:
return this.parseClass()
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
default:
return this.dummyIdent()
}
}
lp.parseNew = function() {
let node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart
let meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
node.property = this.parseIdent(true)
return this.finishNode(node, "MetaProperty")
}
let start = this.storeCurrentPos()
node.callee = this.parseSubscripts(this.parseExprAtom(), start, true, startIndent, line)
if (this.tok.type == tt.parenL) {
node.arguments = this.parseExprList(tt.parenR)
} else {
node.arguments = []
}
return this.finishNode(node, "NewExpression")
}
lp.parseTemplateElement = function() {
let elem = this.startNode()
elem.value = {
raw: this.input.slice(this.tok.start, this.tok.end).replace(/\r\n?/g, '\n'),
cooked: this.tok.value
}
this.next()
elem.tail = this.tok.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
lp.parseTemplate = function() {
let node = this.startNode()
this.next()
node.expressions = []
let curElt = this.parseTemplateElement()
node.quasis = [curElt]
while (!curElt.tail) {
this.next()
node.expressions.push(this.parseExpression())
if (this.expect(tt.braceR)) {
curElt = this.parseTemplateElement()
} else {
curElt = this.startNode()
curElt.value = {cooked: '', raw: ''}
curElt.tail = true
}
node.quasis.push(curElt)
}
this.expect(tt.backQuote)
return this.finishNode(node, "TemplateLiteral")
}
lp.parseObj = function() {
let node = this.startNode()
node.properties = []
this.pushCx()
let indent = this.curIndent + 1, line = this.curLineStart
this.eat(tt.braceL)
if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart }
while (!this.closes(tt.braceR, indent, line)) {
let prop = this.startNode(), isGenerator, start
if (this.options.ecmaVersion >= 6) {
start = this.storeCurrentPos()
prop.method = false
prop.shorthand = false
isGenerator = this.eat(tt.star)
}
this.parsePropertyName(prop)
if (isDummy(prop.key)) { if (isDummy(this.parseMaybeAssign())) this.next(); this.eat(tt.comma); continue }
if (this.eat(tt.colon)) {
prop.kind = "init"
prop.value = this.parseMaybeAssign()
} else if (this.options.ecmaVersion >= 6 && (this.tok.type === tt.parenL || this.tok.type === tt.braceL)) {
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator)
} else if (this.options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
!prop.computed && (prop.key.name === "get" || prop.key.name === "set") &&
(this.tok.type != tt.comma && this.tok.type != tt.braceR)) {
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
} else {
prop.kind = "init"
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.eq)) {
let assign = this.startNodeAt(start)
assign.operator = "="
assign.left = prop.key
assign.right = this.parseMaybeAssign()
prop.value = this.finishNode(assign, "AssignmentExpression")
} else {
prop.value = prop.key
}
} else {
prop.value = this.dummyIdent()
}
prop.shorthand = true
}
node.properties.push(this.finishNode(prop, "Property"))
this.eat(tt.comma)
}
this.popCx()
if (!this.eat(tt.braceR)) {
// If there is no closing brace, make the node span to the start
// of the next token (this is useful for Tern)
this.last.end = this.tok.start
if (this.options.locations) this.last.loc.end = this.tok.loc.start
}
return this.finishNode(node, "ObjectExpression")
}
lp.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseExpression()
this.expect(tt.bracketR)
return
} else {
prop.computed = false
}
}
let key = (this.tok.type === tt.num || this.tok.type === tt.string) ? this.parseExprAtom() : this.parseIdent()
prop.key = key || this.dummyIdent()
}
lp.parsePropertyAccessor = function() {
if (this.tok.type === tt.name || this.tok.type.keyword) return this.parseIdent()
}
lp.parseIdent = function() {
let name = this.tok.type === tt.name ? this.tok.value : this.tok.type.keyword
if (!name) return this.dummyIdent()
let node = this.startNode()
this.next()
node.name = name
return this.finishNode(node, "Identifier")
}
lp.initFunction = function(node) {
node.id = null
node.params = []
if (this.options.ecmaVersion >= 6) {
node.generator = false
node.expression = false
}
}
// Convert existing expression atom to assignable pattern
// if possible.
lp.toAssignable = function(node, binding) {
if (!node || node.type == "Identifier" || (node.type == "MemberExpression" && !binding)) {
// Okay
} else if (node.type == "ParenthesizedExpression") {
node.expression = this.toAssignable(node.expression, binding)
} else if (this.options.ecmaVersion < 6) {
return this.dummyIdent()
} else if (node.type == "ObjectExpression") {
node.type = "ObjectPattern"
let props = node.properties
for (let i = 0; i < props.length; i++)
props[i].value = this.toAssignable(props[i].value, binding)
} else if (node.type == "ArrayExpression") {
node.type = "ArrayPattern"
this.toAssignableList(node.elements, binding)
} else if (node.type == "SpreadElement") {
node.type = "RestElement"
node.argument = this.toAssignable(node.argument, binding)
} else if (node.type == "AssignmentExpression") {
node.type = "AssignmentPattern"
delete node.operator
} else {
return this.dummyIdent()
}
return node
}
lp.toAssignableList = function(exprList, binding) {
for (let i = 0; i < exprList.length; i++)
exprList[i] = this.toAssignable(exprList[i], binding)
return exprList
}
lp.parseFunctionParams = function(params) {
params = this.parseExprList(tt.parenR)
return this.toAssignableList(params, true)
}
lp.parseMethod = function(isGenerator) {
let node = this.startNode()
this.initFunction(node)
node.params = this.parseFunctionParams()
node.generator = isGenerator || false
node.expression = this.options.ecmaVersion >= 6 && this.tok.type !== tt.braceL
node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock()
return this.finishNode(node, "FunctionExpression")
}
lp.parseArrowExpression = function(node, params) {
this.initFunction(node)
node.params = this.toAssignableList(params, true)
node.expression = this.tok.type !== tt.braceL
node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock()
return this.finishNode(node, "ArrowFunctionExpression")
}
lp.parseExprList = function(close, allowEmpty) {
this.pushCx()
let indent = this.curIndent, line = this.curLineStart, elts = []
this.next() // Opening bracket
while (!this.closes(close, indent + 1, line)) {
if (this.eat(tt.comma)) {
elts.push(allowEmpty ? null : this.dummyIdent())
continue
}
let elt = this.parseMaybeAssign()
if (isDummy(elt)) {
if (this.closes(close, indent, line)) break
this.next()
} else {
elts.push(elt)
}
this.eat(tt.comma)
}
this.popCx()
if (!this.eat(close)) {
// If there is no closing brace, make the node span to the start
// of the next token (this is useful for Tern)
this.last.end = this.tok.start
if (this.options.locations) this.last.loc.end = this.tok.loc.start
}
return elts
}
| eddyerburgh/free-code-camp-ziplines | react-projects/markdown-previewer/node_modules/is-expression/node_modules/acorn/src/loose/expression.js | JavaScript | mit | 16,264 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SolverFoundation.Plugin.Z3.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SolverFoundation.Plugin.Z3.Tests")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("27657eee-ca7b-4996-a905-86a3f4584988")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| seahorn/z3 | examples/msf/SolverFoundation.Plugin.Z3.Tests/Properties/AssemblyInfo.cs | C# | mit | 1,440 |
html, body {
color: rgba(0, 0, 0, 0.8);
min-height: 100vh;
}
@media (min-width: 992px) {
.content {
padding-left: 300px;
}
}
.hidden {
display: none !important;
}
.loading {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #fff;
color: #153d77;
z-index: 9999;
display: inline-block;
}
.loading > div {
top: 35%;
width: 80px;
margin: auto calc(50vw - 40px);
position: fixed;
text-align: center;
}
.loading img {
width: 100%;
}
.nonselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
}
.no-event {
pointer-events: none;
}
.due {
color: red;
}
.error {
margin: 0 0 20px 0;
color: red;
}
.clickable {
cursor: pointer;
}
.text-primary {
color: #153d77 !important;
}
.text-accent {
color: rgb(0,148,64) !important;
}
.primary {
background-color: #153d77 !important;
}
.primary.btn:hover, .primary.btn:active, .primary.btn:focus {
background-color: rgb(0,101,189) !important;
}
.accent{
background-color: rgb(0,148,64) !important;
}
.overlay {
width: 100%;
height: 100%;
position:
absolute;
top: 0;
left: 0;
z-index: 10;
}
.parrallax img {
background-image: url("/assets/meeting.jpg");
background-repeat: no-repeat;
background-position: top;
background-size: cover;
}
svg {
color: inherit;
fill: currentColor;
}
.toast {
background-color: #ff363e;
}
.section {
width: 100%;
}
.picker__date-display {
background-color: #153d77;
}
.picker__weekday-display {
background-color: #0e346b;
}
.picker__day.picker__day--today, .picker__close, .picker__today {
color: #153d77;
}
input:focus:not([readonly]), textarea:focus:not([readonly]), .chips.focus {
border-bottom: 1px solid #153d77 !important;
-webkit-box-shadow: 0 1px 0 0 #153d77 !important;
-moz-box-shadow: 0 1px 0 0 #153d77 !important;
box-shadow: 0 1px 0 0 #153d77 !important;
}
.subtle, .subtle:active, .subtle:focus {
border-bottom: 1px solid #153d77;
box-shadow: 0 1px 0 0 #153d77;
}
input[type=text].subtle {
border-bottom: 0 none white !important;
}
input[type=text]:focus:not([readonly]).subtle {
background: rgba(0, 0, 0, 0.05);
border-style: none !important;
border-width: 0 !important;
box-shadow: 0 0 0 0 white !important;
}
nav ul li a{
color: #153d77;
}
nav a i{
color: #153d77;
}
nav .nav-wrapper .brand-logo {
color: rgba(0, 0, 0, 0.8);
height: 64px;
text-align: center;
white-space: nowrap;
}
nav .nav-wrapper .brand-logo > span {
display: inline-block;
height: 95%;
margin-bottom: 5%;
vertical-align: middle;
font-size: 0.8em;
color: #153d77;
}
nav .nav-wrapper .brand-logo img {
height: 50px;
margin: 8px 8px 8px 8px;
vertical-align: middle;
}
@media (max-width: 600px) {
nav .nav-wrapper .brand-logo {
height: 56px;
}
nav .nav-wrapper .brand-logo img {
height: 40px;
}
}
.config-bar {
background: rgba(255,255,255,0.8);
position:relative;
z-index:1;
}
.config-bar > div:first-of-type {
height: 21.75px;
}
#port {
height:25px;
width:45px;
text-align:
right;
padding: 0 5px;
}
.input-card {
height: 70px;
margin: 0 0 1px 0;
}
.input-card input {
box-sizing: border-box;
font-size: inherit;
height: 70px;
padding: 0 20px;
}
.input-footer {
padding-top: 20px;
text-align: center;
color: rgba(0,0,0,0.4);
}
.input-footer a {
color: inherit;
}
.task-card {
font-size: 1.3em;
min-height: 70px;
margin: 0 0 1px 0;
}
.task-card.completed {
color: rgba(0,0,0,0.4);
text-decoration: line-through;
}
.task-card .checkbox {
width: 40px;
height: 40px;
margin: 0.75rem;
padding: 0;
background: url("/assets/icons/circle.svg");
background-repeat: no-repeat;
}
.task-card .duedate {
font-size: 0.65em;
width: 30%;
text-align: right;
}
.task-card .delete {
width: 24px;
height: 24px;
margin: 0.75rem;
margin-left: 0;
padding: 0;
padding-left: 10px;
background: rgba(0,0,0,0);
}
.task-card:hover .delete {
background: url("/assets/icons/delete.svg");
background-repeat: no-repeat;
}
.task-card .delete:hover {
background: url("/assets/icons/delete_now.svg");
background-repeat: no-repeat;
}
.task-card .edit {
width: 28px;
height: 22px;
margin: 0.75rem 0;
padding: 0;
padding-left: 10px;
background: rgba(0,0,0,0);
}
.task-card:hover .edit {
background: url("/assets/icons/edit.svg");
background-size: contain;
background-repeat: no-repeat;
}
.task-card .edit:hover {
background: url("/assets/icons/edit_filled.svg");
background-size: contain;
background-repeat: no-repeat;
}
.task-card img {
margin: auto auto;
padding: 0.5rem;
}
.task-card .checkbox img {
display: none;
}
.task-card.completed .checkbox img {
display: block;
}
.task-card .card-title {
/* Due date?? margins??*/
width: calc(100% - 4.5rem - 88px);
width: -webkit-calc(100% - 4.5rem - 88px);
width: -moz-calc(100% - 4.5rem - 88px);
}
.modal {
max-height: 80%;
}
.modal drop-zone#multifile-drop {
height: 100%;
padding: 12px;
margin: 12px;
width: calc(100% - 24px);
height: calc(100% - 56px - 24px);
}
.modal drop-zone#multifile-drop #drop-indicator {
/*Important: Cancel all pointer events on the overlay.*/
pointer-events: none;
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
display: none;
}
.modal drop-zone#multifile-drop.over #drop-indicator {
display: block;
background: rgba(255, 255, 255, 0.9);
border-style: dashed;
border-width: 4px;
border-color: rgb(150,150,150);
}
.modal drop-zone#multifile-drop #drop-indicator p{
color: rgb(150,150,150);
font-size: 24pt;
text-align: center;
margin-top: 40%;
}
.modal.modal-fixed-footer {
height: 80%;
}
@media (max-height: 720px) {
.modal .picker--opened .picker__frame {
top: 5%;
bottom: auto;
}
.modal {
top: 5% !important;
max-height: 90%;
}
.modal.modal-fixed-footer {
height: 90%;
}
}
.modal .card-title {
font-size: 32px;
font-weight: 300;
}
.modal .task-header {
text-decoration: none;
color: rgba(0, 0, 0, 0.8);
}
.modal .completed .task-header {
text-decoration: line-through;
color: rgba(0, 0, 0, 0.4);
}
.modal .task-header input {
box-sizing: border-box;
height: 70px;
padding: 0 20px;
margin-bottom: 0;
}
.modal .task-body {
width: 90%;
margin: 30px 5% 0 5%;
}
.modal .valign-wrapper {
margin: 0;
}
.modal hr {
width: 90%;
margin: 0 5%;
border-width: 0 0 0 0;
border-top: 1px solid rgba(0,0,0,0.1);
}
.modal h5 {
font-size: 18px;
}
.modal .description {
min-height: 10em;
}
.modal .attachment-field {
font-size: 11pt;
}
.modal .hint {
font-size: 10pt;
font-style: italic;
color: grey;
}
.modal .input-field {
margin-top: 0;
}
.modal .input-field h5 {
margin-top: 0;
}
.modal.list {
height: 400px;
}
.modal.list .edit-list-wrapper {
width: 90%;
margin: 15px 5% 0 5%;
}
.modal.list .task-card .card-title {
width: calc(100% - 3.0rem);
width: -webkit-calc(100% - 3.0rem);
width: -mozt-calc(100% - 3.0rem);
}
.modal.list.create {
margin-top: 100px;
height: 200px;
}
.modal.list.create .create-list-wrapper {
width: 90%;
margin: 15px 5% 0 5%;
}
.modal.list.create .create-list-wrapper .row {
margin: 0;
}
.waves-effect.waves-blue .waves-ripple {
background-color: rgba(21, 61, 119, 0.50);
}
.chip img {
padding: 4px 4px 4px 0;
}
h1 svg {
width: 60px;
vertical-align: middle;
}
.side-nav a {
height: 48px;
}
list-view .collection-item {
border-style: none !important;
padding: 0 !important;
}
list-view a {
padding:0 !important;
}
list-view .active a{
background: #153d77;
color: white;
}
list-view .active a:hover {
background: rgba(23,77,124, 1);
color: white;
}
list-view .list-title svg {
width: 25px;
vertical-align: middle;
margin-right: 5px;
fill: #153d77;
}
list-view .active .list-title svg {
fill: white;
}
list-view .list-title {
width:100%;
height:100%;
float: left;
padding-left: 10px;
background: inherit;
color: inherit;
}
list-view .active .list-title {
color: white
}
list-view .list-actions {
float: right;
height: 100%;
}
list-view .list-notifications {
width: 32px;
height:100%;
display: inline-block;
background: inherit;
color: inherit;
}
list-view .list-notifications .badge {
font-weight: 300;
}
list-view .active .list-notifications {
color: white
}
list-view .active .list-notifications .badge {
color: rgba(255, 255, 255, 0.7);
}
list-view .list-notifications .new.badge {
background-color: #153d77
}
list-view .active .list-notifications .new.badge {
color: #153d77;
background-color: rgba(255, 255, 255, 1.0);
}
list-view .active .list-notifications {
color: white
}
list-view .list-edit {
width: 28px;
height:100%;
display: inline-block;
background: inherit;
color: inherit;
}
list-view .list-edit .edit {
width: 28px;
height: 22px;
margin: 0.75rem 0;
padding: 0;
background: rgba(0,0,0,0);
}
list-view list-element:hover .edit {
background: url("/assets/icons/edit.svg");
background-size: contain;
background-repeat: no-repeat;
}
list-view list-element:hover .active .edit {
background: url("/assets/icons/edit_grey.svg");
background-size: contain;
background-repeat: no-repeat;
}
list-view .list-edit .edit:hover {
background: url("/assets/icons/edit_filled.svg");
background-size: contain;
background-repeat: no-repeat;
}
list-view list-element .active .edit:hover {
background: url("/assets/icons/edit_white.svg");
background-size: contain;
background-repeat: no-repeat;
}
/* BUG FIXES Materialize*/
.modal-overlay {
width: 100vw !important;
height: 100vh !important;
background: black !important;
position: absolute !important;
top: 0 !important;
}
/* ANIMATIONS */
.animated {
animation-duration: 0.5s;
animation-fill-mode: both;
animation-timing-function: ease-in-out;
}
.animated.long {
animation-duration: 1.0s;
}
@keyframes shake {
0%, 100% {transform: translateX(0);}
10%, 30%, 50%, 70%, 90% {transform: translateX(-10px);}
20%, 40%, 60%, 80% {transform: translateX(10px);}
}
.shake {
animation-name: shake;
}
@keyframes fadeOutUp {
from {
opacity: 1;
}
to {
opacity: 0;
transform: translate3d(0, -50%, 0);
}
}
.fadeOutUp {
animation-name: fadeOutUp;
}
| FroeMic/CDTM-Backend-Workshop-WT2016 | src/server/server/static/css/main.css | CSS | mit | 10,540 |
/*
* linux/include/linux/mmc/host.h
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Host driver specific definitions.
*/
#ifndef LINUX_MMC_HOST_H
#define LINUX_MMC_HOST_H
#include <linux/leds.h>
#include <linux/mmc/core.h>
struct mmc_ios {
unsigned int clock; /* clock rate */
unsigned short vdd;
/* vdd stores the bit number of the selected voltage range from below. */
unsigned char bus_mode; /* command output mode */
#define MMC_BUSMODE_OPENDRAIN 1
#define MMC_BUSMODE_PUSHPULL 2
unsigned char chip_select; /* SPI chip select */
#define MMC_CS_DONTCARE 0
#define MMC_CS_HIGH 1
#define MMC_CS_LOW 2
unsigned char power_mode; /* power supply mode */
#define MMC_POWER_OFF 0
#define MMC_POWER_UP 1
#define MMC_POWER_ON 2
unsigned char bus_width; /* data bus width */
#define MMC_BUS_WIDTH_1 0
#define MMC_BUS_WIDTH_4 2
unsigned char timing; /* timing specification used */
#define MMC_TIMING_LEGACY 0
#define MMC_TIMING_MMC_HS 1
#define MMC_TIMING_SD_HS 2
};
struct mmc_host_ops {
void (*request)(struct mmc_host *host, struct mmc_request *req);
/*
* Avoid calling these three functions too often or in a "fast path",
* since underlaying controller might implement them in an expensive
* and/or slow way.
*
* Also note that these functions might sleep, so don't call them
* in the atomic contexts!
*
* Return values for the get_ro callback should be:
* 0 for a read/write card
* 1 for a read-only card
* -ENOSYS when not supported (equal to NULL callback)
* or a negative errno value when something bad happened
*
* Return values for the get_cd callback should be:
* 0 for a absent card
* 1 for a present card
* -ENOSYS when not supported (equal to NULL callback)
* or a negative errno value when something bad happened
*/
void (*set_ios)(struct mmc_host *host, struct mmc_ios *ios);
int (*get_ro)(struct mmc_host *host);
int (*get_cd)(struct mmc_host *host);
void (*enable_sdio_irq)(struct mmc_host *host, int enable);
};
struct mmc_card;
struct device;
struct mmc_host {
struct device *parent;
struct device class_dev;
int index;
const struct mmc_host_ops *ops;
unsigned int f_min;
unsigned int f_max;
u32 ocr_avail;
#define MMC_VDD_165_195 0x00000080 /* VDD voltage 1.65 - 1.95 */
#define MMC_VDD_20_21 0x00000100 /* VDD voltage 2.0 ~ 2.1 */
#define MMC_VDD_21_22 0x00000200 /* VDD voltage 2.1 ~ 2.2 */
#define MMC_VDD_22_23 0x00000400 /* VDD voltage 2.2 ~ 2.3 */
#define MMC_VDD_23_24 0x00000800 /* VDD voltage 2.3 ~ 2.4 */
#define MMC_VDD_24_25 0x00001000 /* VDD voltage 2.4 ~ 2.5 */
#define MMC_VDD_25_26 0x00002000 /* VDD voltage 2.5 ~ 2.6 */
#define MMC_VDD_26_27 0x00004000 /* VDD voltage 2.6 ~ 2.7 */
#define MMC_VDD_27_28 0x00008000 /* VDD voltage 2.7 ~ 2.8 */
#define MMC_VDD_28_29 0x00010000 /* VDD voltage 2.8 ~ 2.9 */
#define MMC_VDD_29_30 0x00020000 /* VDD voltage 2.9 ~ 3.0 */
#define MMC_VDD_30_31 0x00040000 /* VDD voltage 3.0 ~ 3.1 */
#define MMC_VDD_31_32 0x00080000 /* VDD voltage 3.1 ~ 3.2 */
#define MMC_VDD_32_33 0x00100000 /* VDD voltage 3.2 ~ 3.3 */
#define MMC_VDD_33_34 0x00200000 /* VDD voltage 3.3 ~ 3.4 */
#define MMC_VDD_34_35 0x00400000 /* VDD voltage 3.4 ~ 3.5 */
#define MMC_VDD_35_36 0x00800000 /* VDD voltage 3.5 ~ 3.6 */
unsigned long caps; /* Host capabilities */
#define MMC_CAP_4_BIT_DATA (1 << 0) /* Can the host do 4 bit transfers */
#define MMC_CAP_MMC_HIGHSPEED (1 << 1) /* Can do MMC high-speed timing */
#define MMC_CAP_SD_HIGHSPEED (1 << 2) /* Can do SD high-speed timing */
#define MMC_CAP_SDIO_IRQ (1 << 3) /* Can signal pending SDIO IRQs */
#define MMC_CAP_SPI (1 << 4) /* Talks only SPI protocols */
#define MMC_CAP_NEEDS_POLL (1 << 5) /* Needs polling for card-detection */
/* host specific block data */
unsigned int max_seg_size; /* see blk_queue_max_segment_size */
unsigned short max_hw_segs; /* see blk_queue_max_hw_segments */
unsigned short max_phys_segs; /* see blk_queue_max_phys_segments */
unsigned short unused;
unsigned int max_req_size; /* maximum number of bytes in one req */
unsigned int max_blk_size; /* maximum size of one mmc block */
unsigned int max_blk_count; /* maximum number of blocks in one req */
/* private data */
spinlock_t lock; /* lock for claim and bus ops */
struct mmc_ios ios; /* current io bus settings */
u32 ocr; /* the current OCR setting */
/* group bitfields together to minimize padding */
unsigned int use_spi_crc:1;
unsigned int claimed:1; /* host exclusively claimed */
unsigned int bus_dead:1; /* bus has been released */
#ifdef CONFIG_MMC_DEBUG
unsigned int removed:1; /* host is being removed */
#endif
struct mmc_card *card; /* device attached to this host */
wait_queue_head_t wq;
struct delayed_work detect;
const struct mmc_bus_ops *bus_ops; /* current bus driver */
unsigned int bus_refs; /* reference counter */
unsigned int sdio_irqs;
struct task_struct *sdio_irq_thread;
atomic_t sdio_irq_thread_abort;
#ifdef CONFIG_LEDS_TRIGGERS
struct led_trigger *led; /* activity led */
#endif
struct dentry *debugfs_root;
unsigned long private[0] ____cacheline_aligned;
};
extern struct mmc_host *mmc_alloc_host(int extra, struct device *);
extern int mmc_add_host(struct mmc_host *);
extern void mmc_remove_host(struct mmc_host *);
extern void mmc_free_host(struct mmc_host *);
static inline void *mmc_priv(struct mmc_host *host)
{
return (void *)host->private;
}
#define mmc_host_is_spi(host) ((host)->caps & MMC_CAP_SPI)
#define mmc_dev(x) ((x)->parent)
#define mmc_classdev(x) (&(x)->class_dev)
#define mmc_hostname(x) (dev_name(&(x)->class_dev))
extern int mmc_suspend_host(struct mmc_host *, pm_message_t);
extern int mmc_resume_host(struct mmc_host *);
extern void mmc_detect_change(struct mmc_host *, unsigned long delay);
extern void mmc_request_done(struct mmc_host *, struct mmc_request *);
static inline void mmc_signal_sdio_irq(struct mmc_host *host)
{
host->ops->enable_sdio_irq(host, 0);
wake_up_process(host->sdio_irq_thread);
}
#endif
| broonie/sound-2.6 | include/linux/mmc/host.h | C | gpl-2.0 | 6,224 |
<?php
namespace Elasticsearch\Endpoints\Indices\Gateway;
use Elasticsearch\Endpoints\AbstractEndpoint;
/**
* Class Snapshot
*
* @category Elasticsearch
* @package Elasticsearch\Endpoints\Indices\Gateway
* @author Zachary Tong <zachary.tong@elasticsearch.com>
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache2
* @link http://elasticsearch.org
*/
class Snapshot extends AbstractEndpoint
{
/**
* @return string
*/
protected function getURI()
{
$index = $this->index;
$uri = "/_gateway/snapshot";
if (isset($index) === true) {
$uri = "/$index/_gateway/snapshot";
}
return $uri;
}
/**
* @return string[]
*/
protected function getParamWhitelist()
{
return [
'ignore_unavailable',
'allow_no_indices',
'expand_wildcards',
];
}
/**
* @return string
*/
protected function getMethod()
{
return 'POST';
}
}
| quitedensepoint/Devel1 | vendor/elasticsearch/elasticsearch/src/Elasticsearch/Endpoints/Indices/Gateway/Snapshot.php | PHP | gpl-2.0 | 1,020 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.